repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
seanbell/opensurfaces
server/normals/views.py
1
9087
import json from django.shortcuts import render, get_object_or_404 from django.db.models import F from django.http import HttpResponse from django.views.decorators.http import require_POST from django.core.urlresolvers import reverse from django.contrib.admin.views.decorators import staff_member_required from django.views.decorators.csrf import ensure_csrf_cookie from endless_pagination.decorators import page_template from common.utils import dict_union, prepare_votes_bar, \ json_success_response, json_error_response from normals.models import ShapeRectifiedNormalLabel def rectified_normal_detail(request, pk): entry = get_object_or_404(ShapeRectifiedNormalLabel, pk=pk) votes = [ prepare_votes_bar(entry, 'qualities', 'correct', 'correct', 'Quality'), ] data = { 'nav': 'browse/rectified-normal', 'entry': entry, 'votes': votes, } return render(request, 'rectified_normal_detail.html', data) @page_template('grid3_page.html') def rectified_normal_all(request, template='endless_list.html', extra_context=None): entries = ShapeRectifiedNormalLabel.objects.all().order_by('-id') if 'publishable' in request.GET: entries = entries.filter(shape__photo__license__publishable=True) context = dict_union({ 'nav': 'browse/rectified-normal', 'subnav': 'all', 'entries': entries, 'base_template': 'rectified_normal_base.html', 'thumb_template': 'rectified_normal_thumb.html', 'header': 'All submissions', 'header_small': 'sorted by submission time', #'enable_voting': False, }, extra_context) return render(request, template, context) @page_template('grid3_page.html') def rectified_normal_good(request, template='endless_list.html', extra_context=None): entries = ShapeRectifiedNormalLabel.objects \ .filter(shape__planar=True, correct=True, correct_score__isnull=False) \ .order_by('-correct_score') #.filter(admin_score__gt=0, shape__synthetic=False) \ #.order_by('-admin_score', '-shape__pixel_area') context = dict_union({ 'nav': 'browse/rectified-normal', 'subnav': 'good', 'entries': entries, 'base_template': 'rectified_normal_base.html', 'thumb_template': 'rectified_normal_thumb.html', 'header': 'High quality submissions' #'header_sub': 'These submissions were voted as high quality.' #'enable_voting': False, }, extra_context) return render(request, template, context) @page_template('grid3_page.html') def rectified_normal_bad(request, template='endless_list.html', extra_context=None): entries = ShapeRectifiedNormalLabel.objects \ .filter(shape__planar=True, correct=False, correct_score__isnull=False) \ .order_by('correct_score') #.filter(admin_score__lt=0, shape__synthetic=False) \ #.order_by('admin_score', 'shape__num_vertices') if 'publishable' in request.GET: entries = entries.filter(shape__photo__license__publishable=True) context = dict_union({ 'nav': 'browse/rectified-normal', 'subnav': 'bad', 'entries': entries, 'base_template': 'rectified_normal_base.html', 'thumb_template': 'rectified_normal_thumb.html', 'header': 'Low quality submissions', 'header_small': 'sorted by quality', #'enable_voting': False, }, extra_context) return render(request, template, context) @page_template('grid3_page.html') def rectified_normal_auto(request, template='endless_list.html', extra_context=None): entries = ShapeRectifiedNormalLabel.objects \ .filter(shape__planar=True, shape__correct=True, automatic=True) \ .order_by('-shape__num_vertices') if 'publishable' in request.GET: entries = entries.filter(shape__photo__license__publishable=True) context = dict_union({ 'nav': 'browse/rectified-normal', 'subnav': 'auto', 'entries': entries, 'base_template': 'rectified_normal_base.html', 'thumb_template': 'rectified_normal_thumb.html', 'header': 'Automatically rectified shapes', 'header_small': 'using vanishing points', }, extra_context) return render(request, template, context) @page_template('grid3_page.html') def rectified_normal_best(request, template='endless_list.html', extra_context=None): entries = ShapeRectifiedNormalLabel.objects \ .filter(shape__photo__inappropriate=False, shape__correct=True, shape__planar=True, shape__rectified_normal_id=F('id')) \ if 'by-id' in request.GET: header_small = 'sorted by id' entries = entries.order_by('-id') else: header_small = 'sorted by complexity' entries = entries.order_by('-shape__num_vertices') if 'publishable' in request.GET: entries = entries.filter(shape__photo__license__publishable=True) context = dict_union({ 'nav': 'browse/rectified-normal', 'subnav': 'best', 'entries': entries, 'base_template': 'rectified_normal_base.html', 'thumb_template': 'rectified_normal_thumb.html', 'header': 'High quality submissions', 'header_small': header_small, }, extra_context) return render(request, template, context) @staff_member_required @page_template('grid3_page.html') def rectified_normal_curate( request, template='endless_list_curate.html', extra_context=None): entries = ShapeRectifiedNormalLabel.objects \ .filter(shape__planar=True, correct=True) \ .order_by('-shape__num_vertices') if 'publishable' in request.GET: entries = entries.filter(shape__photo__license__publishable=True) context = dict_union({ 'nav': 'browse/rectified-normal', 'subnav': 'curate', 'entries': entries, 'base_template': 'rectified_normal_base.html', 'thumb_template': 'rectified_normal_thumb.html', 'header': 'Curate rectified textures', 'curate_post_url': reverse('rectified-normal-curate-post'), 'curate': True }, extra_context) return render(request, template, context) @require_POST @staff_member_required def rectified_normal_curate_post(request): if request.POST['model'] != "shapes/shaperectifiednormallabel": return json_error_response("invalid model") normal = ShapeRectifiedNormalLabel.objects.get(id=request.POST['id']) normal.quality_method = 'A' normal.correct = not normal.correct normal.save() normal.shape.update_entropy(save=True) return HttpResponse( json.dumps({'selected': not normal.correct}), mimetype='application/json') @ensure_csrf_cookie @page_template('grid3_page.html') def rectified_normal_voted_none(request, template='endless_list.html', extra_context=None): entries = ShapeRectifiedNormalLabel.objects \ .filter(admin_score=0, time_ms__gt=500, shape__dominant_delta__isnull=False) \ .order_by('-shape__synthetic', '?') context = dict_union({ 'nav': 'browse/rectified-normal', 'subnav': 'vote', 'entries': entries, 'base_template': 'rectified_normal_base.html', 'thumb_template': 'rectified_normal_thumb_vote.html', 'enable_voting': True, }, extra_context) return render(request, template, context) @ensure_csrf_cookie @page_template('grid3_page.html') def rectified_normal_voted_yes(request, template='endless_list.html', extra_context=None): entries = ShapeRectifiedNormalLabel.objects \ .filter(admin_score__gt=0) \ .order_by('-admin_score', '-shape__pixel_area') context = dict_union({ 'nav': 'browse/rectified-normal', 'subnav': 'voted-yes', 'entries': entries, 'base_template': 'rectified_normal_base.html', 'thumb_template': 'rectified_normal_thumb_vote.html', 'enable_voting': True, }, extra_context) return render(request, template, context) @ensure_csrf_cookie @page_template('grid3_page.html') def rectified_normal_voted_no(request, template='endless_list.html', extra_context=None): entries = ShapeRectifiedNormalLabel.objects \ .filter(admin_score__lt=0) \ .order_by('admin_score', '-shape__pixel_area') context = dict_union({ 'nav': 'browse/rectified-normal', 'subnav': 'voted-no', 'entries': entries, 'base_template': 'rectified_normal_base.html', 'thumb_template': 'rectified_normal_thumb_vote.html', 'enable_voting': True, }, extra_context) return render(request, template, context) @require_POST def rectified_normal_vote(request): id = request.POST['id'] score = request.POST['score'] ShapeRectifiedNormalLabel.objects.filter(id=id).update(admin_score=score) return json_success_response()
mit
steedos/odoo7
openerp/addons/l10n_be/__init__.py
430
1060
# -*- 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 wizard # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
mayblue9/scikit-learn
sklearn/decomposition/tests/test_online_lda.py
21
13171
import numpy as np from scipy.linalg import block_diag from scipy.sparse import csr_matrix from scipy.special import psi from sklearn.decomposition import LatentDirichletAllocation from sklearn.decomposition._online_lda import (_dirichlet_expectation_1d, _dirichlet_expectation_2d) from sklearn.utils.testing import assert_allclose from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_greater_equal from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import if_safe_multiprocessing_with_blas from sklearn.utils.validation import NotFittedError from sklearn.externals.six.moves import xrange def _build_sparse_mtx(): # Create 3 topics and each topic has 3 disticnt words. # (Each word only belongs to a single topic.) n_topics = 3 block = n_topics * np.ones((3, 3)) blocks = [block] * n_topics X = block_diag(*blocks) X = csr_matrix(X) return (n_topics, X) def test_lda_default_prior_params(): # default prior parameter should be `1 / topics` # and verbose params should not affect result n_topics, X = _build_sparse_mtx() prior = 1. / n_topics lda_1 = LatentDirichletAllocation(n_topics=n_topics, doc_topic_prior=prior, topic_word_prior=prior, random_state=0) lda_2 = LatentDirichletAllocation(n_topics=n_topics, random_state=0) topic_distr_1 = lda_1.fit_transform(X) topic_distr_2 = lda_2.fit_transform(X) assert_almost_equal(topic_distr_1, topic_distr_2) def test_lda_fit_batch(): # Test LDA batch learning_offset (`fit` method with 'batch' learning) rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, evaluate_every=1, learning_method='batch', random_state=rng) lda.fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for component in lda.components_: # Find top 3 words in each LDA component top_idx = set(component.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_fit_online(): # Test LDA online learning (`fit` method with 'online' learning) rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, learning_offset=10., evaluate_every=1, learning_method='online', random_state=rng) lda.fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for component in lda.components_: # Find top 3 words in each LDA component top_idx = set(component.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_partial_fit(): # Test LDA online learning (`partial_fit` method) # (same as test_lda_batch) rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, learning_offset=10., total_samples=100, random_state=rng) for i in xrange(3): lda.partial_fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for c in lda.components_: top_idx = set(c.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_dense_input(): # Test LDA with dense input. rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, learning_method='batch', random_state=rng) lda.fit(X.toarray()) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for component in lda.components_: # Find top 3 words in each LDA component top_idx = set(component.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_transform(): # Test LDA transform. # Transform result cannot be negative rng = np.random.RandomState(0) X = rng.randint(5, size=(20, 10)) n_topics = 3 lda = LatentDirichletAllocation(n_topics=n_topics, random_state=rng) X_trans = lda.fit_transform(X) assert_true((X_trans > 0.0).any()) def test_lda_fit_transform(): # Test LDA fit_transform & transform # fit_transform and transform result should be the same for method in ('online', 'batch'): rng = np.random.RandomState(0) X = rng.randint(10, size=(50, 20)) lda = LatentDirichletAllocation(n_topics=5, learning_method=method, random_state=rng) X_fit = lda.fit_transform(X) X_trans = lda.transform(X) assert_array_almost_equal(X_fit, X_trans, 4) def test_lda_partial_fit_dim_mismatch(): # test `n_features` mismatch in `partial_fit` rng = np.random.RandomState(0) n_topics = rng.randint(3, 6) n_col = rng.randint(6, 10) X_1 = np.random.randint(4, size=(10, n_col)) X_2 = np.random.randint(4, size=(10, n_col + 1)) lda = LatentDirichletAllocation(n_topics=n_topics, learning_offset=5., total_samples=20, random_state=rng) lda.partial_fit(X_1) assert_raises_regexp(ValueError, r"^The provided data has", lda.partial_fit, X_2) def test_invalid_params(): # test `_check_params` method X = np.ones((5, 10)) invalid_models = ( ('n_topics', LatentDirichletAllocation(n_topics=0)), ('learning_method', LatentDirichletAllocation(learning_method='unknown')), ('total_samples', LatentDirichletAllocation(total_samples=0)), ('learning_offset', LatentDirichletAllocation(learning_offset=-1)), ) for param, model in invalid_models: regex = r"^Invalid %r parameter" % param assert_raises_regexp(ValueError, regex, model.fit, X) def test_lda_negative_input(): # test pass dense matrix with sparse negative input. X = -np.ones((5, 10)) lda = LatentDirichletAllocation() regex = r"^Negative values in data passed" assert_raises_regexp(ValueError, regex, lda.fit, X) def test_lda_no_component_error(): # test `transform` and `perplexity` before `fit` rng = np.random.RandomState(0) X = rng.randint(4, size=(20, 10)) lda = LatentDirichletAllocation() regex = r"^no 'components_' attribute" assert_raises_regexp(NotFittedError, regex, lda.transform, X) assert_raises_regexp(NotFittedError, regex, lda.perplexity, X) def test_lda_transform_mismatch(): # test `n_features` mismatch in partial_fit and transform rng = np.random.RandomState(0) X = rng.randint(4, size=(20, 10)) X_2 = rng.randint(4, size=(10, 8)) n_topics = rng.randint(3, 6) lda = LatentDirichletAllocation(n_topics=n_topics, random_state=rng) lda.partial_fit(X) assert_raises_regexp(ValueError, r"^The provided data has", lda.partial_fit, X_2) @if_safe_multiprocessing_with_blas def test_lda_multi_jobs(): n_topics, X = _build_sparse_mtx() # Test LDA batch training with multi CPU for method in ('online', 'batch'): rng = np.random.RandomState(0) lda = LatentDirichletAllocation(n_topics=n_topics, n_jobs=2, learning_method=method, random_state=rng) lda.fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for c in lda.components_: top_idx = set(c.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) @if_safe_multiprocessing_with_blas def test_lda_partial_fit_multi_jobs(): # Test LDA online training with multi CPU rng = np.random.RandomState(0) n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, n_jobs=2, learning_offset=5., total_samples=30, random_state=rng) for i in range(2): lda.partial_fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for c in lda.components_: top_idx = set(c.argsort()[-3:][::-1]) assert_true(tuple(sorted(top_idx)) in correct_idx_grps) def test_lda_preplexity_mismatch(): # test dimension mismatch in `perplexity` method rng = np.random.RandomState(0) n_topics = rng.randint(3, 6) n_samples = rng.randint(6, 10) X = np.random.randint(4, size=(n_samples, 10)) lda = LatentDirichletAllocation(n_topics=n_topics, learning_offset=5., total_samples=20, random_state=rng) lda.fit(X) # invalid samples invalid_n_samples = rng.randint(4, size=(n_samples + 1, n_topics)) assert_raises_regexp(ValueError, r'Number of samples', lda.perplexity, X, invalid_n_samples) # invalid topic number invalid_n_topics = rng.randint(4, size=(n_samples, n_topics + 1)) assert_raises_regexp(ValueError, r'Number of topics', lda.perplexity, X, invalid_n_topics) def test_lda_perplexity(): # Test LDA perplexity for batch training # perplexity should be lower after each iteration n_topics, X = _build_sparse_mtx() for method in ('online', 'batch'): lda_1 = LatentDirichletAllocation(n_topics=n_topics, max_iter=1, learning_method=method, total_samples=100, random_state=0) lda_2 = LatentDirichletAllocation(n_topics=n_topics, max_iter=10, learning_method=method, total_samples=100, random_state=0) distr_1 = lda_1.fit_transform(X) perp_1 = lda_1.perplexity(X, distr_1, sub_sampling=False) distr_2 = lda_2.fit_transform(X) perp_2 = lda_2.perplexity(X, distr_2, sub_sampling=False) assert_greater_equal(perp_1, perp_2) perp_1_subsampling = lda_1.perplexity(X, distr_1, sub_sampling=True) perp_2_subsampling = lda_2.perplexity(X, distr_2, sub_sampling=True) assert_greater_equal(perp_1_subsampling, perp_2_subsampling) def test_lda_score(): # Test LDA score for batch training # score should be higher after each iteration n_topics, X = _build_sparse_mtx() for method in ('online', 'batch'): lda_1 = LatentDirichletAllocation(n_topics=n_topics, max_iter=1, learning_method=method, total_samples=100, random_state=0) lda_2 = LatentDirichletAllocation(n_topics=n_topics, max_iter=10, learning_method=method, total_samples=100, random_state=0) lda_1.fit_transform(X) score_1 = lda_1.score(X) lda_2.fit_transform(X) score_2 = lda_2.score(X) assert_greater_equal(score_2, score_1) def test_perplexity_input_format(): # Test LDA perplexity for sparse and dense input # score should be the same for both dense and sparse input n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=1, learning_method='batch', total_samples=100, random_state=0) distr = lda.fit_transform(X) perp_1 = lda.perplexity(X) perp_2 = lda.perplexity(X, distr) perp_3 = lda.perplexity(X.toarray(), distr) assert_almost_equal(perp_1, perp_2) assert_almost_equal(perp_1, perp_3) def test_lda_score_perplexity(): # Test the relationship between LDA score and perplexity n_topics, X = _build_sparse_mtx() lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=10, random_state=0) distr = lda.fit_transform(X) perplexity_1 = lda.perplexity(X, distr, sub_sampling=False) score = lda.score(X) perplexity_2 = np.exp(-1. * (score / np.sum(X.data))) assert_almost_equal(perplexity_1, perplexity_2) def test_lda_empty_docs(): """Test LDA on empty document (all-zero rows).""" Z = np.zeros((5, 4)) for X in [Z, csr_matrix(Z)]: lda = LatentDirichletAllocation(max_iter=750).fit(X) assert_almost_equal(lda.components_.sum(axis=0), np.ones(lda.components_.shape[1])) def test_dirichlet_expectation(): """Test Cython version of Dirichlet expectation calculation.""" x = np.logspace(-100, 10, 10000) expectation = np.empty_like(x) _dirichlet_expectation_1d(x, 0, expectation) assert_allclose(expectation, np.exp(psi(x) - psi(np.sum(x))), atol=1e-19) x = x.reshape(100, 100) assert_allclose(_dirichlet_expectation_2d(x), psi(x) - psi(np.sum(x, axis=1)[:, np.newaxis]), rtol=1e-11, atol=3e-9)
bsd-3-clause
Crossy147/java-design-patterns
_scripts/postPumlsToServer.py
10
2865
# # The MIT License # Copyright (c) 2014-2016 Ilkka Seppälä # # 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, 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: # # 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 MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS 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 IN # THE SOFTWARE. # import requests, glob, re, os # taken from here: http://stackoverflow.com/a/13641746 def replace(file, pattern, subst): # Read contents from file as a single string file_handle = open(file, 'r') file_string = file_handle.read() file_handle.close() # Use RE package to allow for replacement (also allowing for (multiline) REGEX) file_string = (re.sub(pattern, subst, file_string)) # Write contents to file. # Using mode 'w' truncates the file. file_handle = open(file, 'w') file_handle.write(file_string) file_handle.close() # list of all puml files fileList = glob.glob('*/etc/*.puml') for puml in fileList: pathSplit = puml.split("/") # parent folder parent = pathSplit[0] # individual artifact/project name artifact = pathSplit[2].replace(".urm.puml", "") print "parent: " + parent + "; artifact: " + artifact # do a POST to the official plantuml hosting site with a little trick "!includeurl" and raw github content data = { 'text': "!includeurl https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/" + puml } r = requests.post('http://plantuml.com/plantuml/uml', data=data) pumlId = r.url.replace("http://plantuml.com/plantuml/uml/", "") # the only thing needed to get a png/svg/ascii from the server back print "Puml Server ID: " + pumlId # add the id so jekyll/liquid can use it if (parent == artifact): replace("./" + parent + "/README.md", "categories:", "pumlid: {}\\ncategories:".format(pumlId)) else: print "I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file '" + puml + "'\npumlid: {}".format(pumlId)
mit
iradul/qtwebkit
Tools/Scripts/webkitpy/tool/bot/earlywarningsystemtask.py
127
2759
# Copyright (c) 2011 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. from webkitpy.tool.bot.patchanalysistask import PatchAnalysisTask, PatchAnalysisTaskDelegate, UnableToApplyPatch class EarlyWarningSystemTaskDelegate(PatchAnalysisTaskDelegate): pass class EarlyWarningSystemTask(PatchAnalysisTask): def __init__(self, delegate, patch, should_run_tests=True): PatchAnalysisTask.__init__(self, delegate, patch) self._should_run_tests = should_run_tests def validate(self): self._patch = self._delegate.refetch_patch(self._patch) if self._patch.is_obsolete(): return False if self._patch.bug().is_closed(): return False if self._patch.review() == "-": return False return True def run(self): if not self.validate(): return False if not self._clean(): return False if not self._update(): return False if not self._apply(): raise UnableToApplyPatch(self._patch) if not self._build(): if not self._build_without_patch(): return False return self.report_failure() if not self._should_run_tests: return True return self._test_patch()
gpl-2.0
deandunbar/html2bwml
venv/lib/python2.7/site-packages/django/contrib/gis/sitemaps/views.py
52
4914
from __future__ import unicode_literals import warnings from django.apps import apps from django.http import HttpResponse, Http404 from django.template import loader from django.contrib.sites.shortcuts import get_current_site from django.core import urlresolvers from django.core.paginator import EmptyPage, PageNotAnInteger from django.contrib.gis.db.models.fields import GeometryField from django.db import connections, DEFAULT_DB_ALIAS from django.db.models.fields import FieldDoesNotExist from django.utils import six from django.utils.deprecation import RemovedInDjango18Warning from django.utils.translation import ugettext as _ from django.contrib.gis.shortcuts import render_to_kml, render_to_kmz def index(request, sitemaps): """ This view generates a sitemap index that uses the proper view for resolving geographic section sitemap URLs. """ warnings.warn("Geo Sitemaps are deprecated. Use plain sitemaps from " "django.contrib.sitemaps instead", RemovedInDjango18Warning, stacklevel=2) current_site = get_current_site(request) sites = [] protocol = request.scheme for section, site in sitemaps.items(): if callable(site): pages = site().paginator.num_pages else: pages = site.paginator.num_pages sitemap_url = urlresolvers.reverse('django.contrib.gis.sitemaps.views.sitemap', kwargs={'section': section}) sites.append('%s://%s%s' % (protocol, current_site.domain, sitemap_url)) if pages > 1: for page in range(2, pages + 1): sites.append('%s://%s%s?p=%s' % (protocol, current_site.domain, sitemap_url, page)) xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites}) return HttpResponse(xml, content_type='application/xml') def sitemap(request, sitemaps, section=None): """ This view generates a sitemap with additional geographic elements defined by Google. """ warnings.warn("Geo Sitemaps are deprecated. Use plain sitemaps from " "django.contrib.sitemaps instead", RemovedInDjango18Warning, stacklevel=2) maps, urls = [], [] if section is not None: if section not in sitemaps: raise Http404(_("No sitemap available for section: %r") % section) maps.append(sitemaps[section]) else: maps = list(six.itervalues(sitemaps)) page = request.GET.get("p", 1) current_site = get_current_site(request) for site in maps: try: if callable(site): urls.extend(site().get_urls(page=page, site=current_site)) else: urls.extend(site.get_urls(page=page, site=current_site)) except EmptyPage: raise Http404(_("Page %s empty") % page) except PageNotAnInteger: raise Http404(_("No page '%s'") % page) xml = loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls}) return HttpResponse(xml, content_type='application/xml') def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS): """ This view generates KML for the given app label, model, and field name. The model's default manager must be GeoManager, and the field name must be that of a geographic field. """ placemarks = [] try: klass = apps.get_model(label, model) except LookupError: raise Http404('You must supply a valid app label and module name. Got "%s.%s"' % (label, model)) if field_name: try: field, _, _, _ = klass._meta.get_field_by_name(field_name) if not isinstance(field, GeometryField): raise FieldDoesNotExist except FieldDoesNotExist: raise Http404('Invalid geometry field.') connection = connections[using] if connection.ops.postgis: # PostGIS will take care of transformation. placemarks = klass._default_manager.using(using).kml(field_name=field_name) else: # There's no KML method on Oracle or MySQL, so we use the `kml` # attribute of the lazy geometry instead. placemarks = [] if connection.ops.oracle: qs = klass._default_manager.using(using).transform(4326, field_name=field_name) else: qs = klass._default_manager.using(using).all() for mod in qs: mod.kml = getattr(mod, field_name).kml placemarks.append(mod) # Getting the render function and rendering to the correct. if compress: render = render_to_kmz else: render = render_to_kml return render('gis/kml/placemarks.kml', {'places': placemarks}) def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS): """ This view returns KMZ for the given app label, model, and field name. """ return kml(request, label, model, field_name, compress=True, using=using)
mit
Coaxis-ASP/open-printing-tunnel
backend/api/tests/test_container_services.py
2
15694
import uuid import docker import docker.errors from django.conf import settings from rest_framework.test import APITestCase from api import container_services from api.tests import factories from api.tests import mock class ContainersTestCase(APITestCase): def setUp(self): self.docker_api = docker.Client(base_url='unix://var/run/docker.sock') self.client = factories.ClientFactory(name='Akema') self.client.uuid = uuid.uuid4() self.employee = factories.EmployeeFactory(clients=[self.client]) def test_create_network(self): number_networks = len(self.docker_api.networks()) network = container_services.create_network(data={'uuid': str(self.client.uuid), 'subnet': '10.48.0.0/16', 'gateway': '10.48.0.200'}, docker_client=self.docker_api) self.assertEqual(number_networks + 1, len(self.docker_api.networks())) self.docker_api.remove_network(network.get('Id')) def test_filter_network_return_only_opt_network(self): networks = [{"Name": "host", }, {"Name": "none", }, {"Name": "bridge", }, {"Name": "opt_default", }, {"Name": "opt_network_azertyuiop", }] filtered_networks = container_services.filter_opt_networks(networks) self.assertListEqual([{"Name": "opt_network_azertyuiop"}], filtered_networks) def test_network_use_macvlan_driver(self): network = container_services.create_network(data={'uuid': str(self.client.uuid), 'subnet': '10.48.0.0/16', 'gateway': '10.48.0.200'}, docker_client=self.docker_api) self.assertEqual('macvlan', self.docker_api.inspect_network(network.get('Id'))['Driver']) self.docker_api.remove_network(network.get('Id')) def test_network_use_custom_parent_interface_if_vlan_id(self): network = container_services.create_network(data={'uuid': str(self.client.uuid), 'subnet': '10.48.0.0/16', 'vlan': 100, 'gateway': '10.48.0.200'}, docker_client=self.docker_api) self.assertEqual('%s.100' % settings.DEFAULT_INTERFACE, self.docker_api.inspect_network(network.get('Id'))['Options']['parent']) self.docker_api.remove_network(network.get('Id')) def test_network_use_custom_parent_interface_if_not_vlan_id(self): network = container_services.create_network(data={'uuid': str(self.client.uuid), 'subnet': '10.48.0.0/16', 'vlan': 0, 'gateway': '10.48.0.200'}, docker_client=self.docker_api) self.assertEqual(settings.DEFAULT_INTERFACE, self.docker_api.inspect_network(network.get('Id'))['Options']['parent']) self.docker_api.remove_network(network.get('Id')) def test_can_get_container_network_infos(self): container_data = mock.get_one_container_data() network_data = container_services.get_container_network_infos(container_data) self.assertEqual(network_data.get('IPAddress'), '10.0.0.1') def test_can_get_container_ipaddress(self): container_data = mock.get_one_container_data() ipaddress = container_services.get_container_ipaddress(container_data) self.assertEqual(ipaddress, '10.0.0.1') def test_can_get_container_gateway(self): container_data = mock.get_one_container_data() gateway = container_services.get_container_gateway(container_data) self.assertEqual(gateway, '10.0.0.254') def test_can_get_container_volumes(self): container_data = mock.get_one_container_data() volumes = container_services.get_container_volumes(container_data) self.assertCountEqual(volumes, [ { "Type": "volume", "Name": "841d6a1709b365763c85fb4b7400c87f264d468eb1691a660fe81761da6e374f", "Source": "/var/lib/docker/volumes/841d6a1709b365763c85fb4b7400c87f264d468eb1691a660fe81761da6e374f/_data", "Destination": "/home/mast/.ssh", "Driver": "local", "Mode": "", "RW": True, "Propagation": "" }, { "Type": "volume", "Name": "002730cbb4dd9b37ad808915a60081508885d533fe003b529b8d0ab4fa46e92e", "Source": "/var/lib/docker/volumes/002730cbb4dd9b37ad808915a60081508885d533fe003b529b8d0ab4fa46e92e/_data", "Destination": "/etc/mast", "Driver": "local", "Mode": "", "RW": True, "Propagation": "" } ]) def test_can_get_container_hostname(self): container_data = mock.get_one_container_data() hostname = container_services.get_container_hostname(container_data) self.assertCountEqual(hostname, 'test-01') def test_can_get_container_image(self): container_data = mock.get_one_container_data() image = container_services.get_container_image(container_data) self.assertCountEqual(image, 'coaxisasp/coaxisopt_daemon:latest') def test_can_create_volume_config(self): container_data = mock.get_one_container_data() config = container_services.create_volumes_config(container_data) self.assertCountEqual(config, [ "/home/mast/.ssh", "/etc/mast" ]) def test_can_create_volume_bindings_config(self): container_data = mock.get_one_container_data() config = container_services.create_volumes_config_bindings(container_data) self.assertDictEqual(config, { "841d6a1709b365763c85fb4b7400c87f264d468eb1691a660fe81761da6e374f": { 'bind': "/home/mast/.ssh", 'mode': 'rw' }, "002730cbb4dd9b37ad808915a60081508885d533fe003b529b8d0ab4fa46e92e": { 'bind': "/etc/mast", 'mode': 'rw' } }) def test_can_get_network_config(self): container_data = mock.get_one_container_data() network_config = container_services.get_container_network_config(container_data) self.assertDictEqual(network_config, { 'EndpointsConfig': {'opt_network_508be7': {'IPAMConfig': {'IPv4Address': '10.0.0.1'}}}, 'IPv4Address': '10.0.0.1' }) def test_get_upgrade_image_change_version_tag(self): newImage = container_services.get_upgrade_image('docker.akema.fr:5000/coaxis/coaxisopt_daemon:v1.7.4', '1.7.11') self.assertEqual(newImage.split(':')[-1], '1.7.11') newImage = container_services.get_upgrade_image('coaxisasp/coaxisopt_daemon:latest', 'beta') self.assertEqual(newImage.split(':')[-1], 'beta') newImage = container_services.get_upgrade_image('coaxisasp/coaxisopt_backend:v1.6.1', 'latest') self.assertEqual(newImage.split(':')[-1], 'latest') newImage = container_services.get_upgrade_image('coaxisopt_backend:v1.6.1', 'latest') self.assertEqual(newImage.split(':')[-1], 'latest') def test_get_upgrade_image_change_registry(self): newImage = container_services.get_upgrade_image('docker.akema.fr:5000/coaxis/coaxisopt_daemon:v1.7.4', '1.7.11') self.assertEqual(newImage.split(':')[0], 'coaxisasp/coaxisopt_daemon') newImage = container_services.get_upgrade_image('coaxisasp/coaxisopt_daemon:latest', 'beta') self.assertEqual(newImage.split(':')[0], 'coaxisasp/coaxisopt_daemon') newImage = container_services.get_upgrade_image('coaxisasp/coaxisopt_backend:v1.6.1', 'latest') self.assertEqual(newImage.split(':')[0], 'coaxisasp/coaxisopt_backend') newImage = container_services.get_upgrade_image('coaxisopt_backend:v1.6.1', 'latest') self.assertEqual(newImage.split(':')[0], 'coaxisopt_backend') def test_can_get_data_to_upgrade_container(self): container_data = mock.get_one_container_data() creation_data = container_services.get_upgrade_data(container_data, version='beta') self.assertDictEqual(creation_data, { 'image': 'coaxisasp/coaxisopt_daemon:beta', 'hostname': 'test-01', 'volumes': [ '/home/mast/.ssh', '/etc/mast' ], 'volumes_bindings': { '841d6a1709b365763c85fb4b7400c87f264d468eb1691a660fe81761da6e374f': { 'bind': '/home/mast/.ssh', 'mode': 'rw' }, '002730cbb4dd9b37ad808915a60081508885d533fe003b529b8d0ab4fa46e92e': { 'bind': '/etc/mast', 'mode': 'rw' } }, 'networking_config': { 'EndpointsConfig': {'opt_network_508be7': {'IPAMConfig': {'IPv4Address': '10.0.0.1'}}}, 'IPv4Address': '10.0.0.1' }, 'labels': {'type': 'coaxisopt_daemon'} }) def test_create_network_config(self): number_networks = len(self.docker_api.networks()) network_config = container_services.create_network_config( data={ 'ip': '10.49.0.1', 'subnet': '10.49.0.0/16', 'gateway': '10.49.0.201', 'vlan': 101 }, docker_client=self.docker_api ) network_id = list(network_config.get('EndpointsConfig').keys())[0] self.assertEqual(number_networks + 1, len(self.docker_api.networks())) self.docker_api.remove_network(network_id) def purge(self, containers=[]): for container in containers: self.docker_api.stop(container['Id'], 0) for network in self.docker_api.inspect_container(container['Id'])['NetworkSettings']['Networks']: if 'opt_network' in network: self.docker_api.remove_network(network) self.docker_api.remove_container(container['Id']) def test_upgrade_container_pop_new_container(self): config = {'ip': '10.49.0.2', 'subnet': '10.49.0.0/16', 'gateway': '10.49.0.202', 'vlan': 102} container = container_services.pop_new_container(config, self.docker_api) new_container = container_services.upgrade_daemon_container(container.get('Id')) self.assertNotEqual(container.get('Id'), new_container.get('Id')) self.purge([new_container]) def test_upgrade_container_mount_volumes_from_old_to_new_container(self): config = {'ip': '10.49.0.2', 'subnet': '10.49.0.0/16', 'gateway': '10.49.0.202', 'vlan': 102} container = container_services.pop_new_container(config, self.docker_api) old_container_volumes = [volume['Name'] for volume in container_services.get_mounts(container['Id'])] new_container = container_services.upgrade_daemon_container(container.get('Id')) new_container_volumes = [volume['Name'] for volume in container_services.get_mounts(new_container['Id'])] self.assertSetEqual(set(old_container_volumes), set(new_container_volumes)) self.purge([new_container]) def test_upgrade_container_bind_to_old_network(self): config = {'ip': '10.49.0.2', 'subnet': '10.49.0.0/16', 'gateway': '10.49.0.202', 'vlan': 102} container = container_services.pop_new_container(config, self.docker_api) old_name, old_network = container_services.get_networks(container['Id']).popitem() new_container = container_services.upgrade_daemon_container(container.get('Id')) new_name, new_network = container_services.get_networks(new_container['Id']).popitem() self.assertEqual(old_name, new_name) self.assertEqual(old_network['IPAMConfig'], new_network['IPAMConfig']) self.assertEqual(old_network['IPAddress'], new_network['IPAddress']) self.assertEqual(old_network['Gateway'], new_network['Gateway']) self.assertEqual(old_network['MacAddress'], new_network['MacAddress']) self.assertEqual(old_network['NetworkID'], new_network['NetworkID']) self.purge([new_container]) def test_can_upgrade_to_different_version(self): config = {'ip': '10.49.0.2', 'subnet': '10.49.0.0/16', 'gateway': '10.49.0.202', 'vlan': 102, 'image': 'coaxisasp/coaxisopt_daemon:latest'} container = container_services.pop_new_container(config, self.docker_api) containers_count = len(self.docker_api.containers()) beta = 'beta' self.docker_api.tag('coaxisopt_daemon', 'coaxisasp/coaxisopt_daemon', tag=beta) new_container = container_services.upgrade_daemon_container(container.get('Id'), version=beta) self.assertEqual(container_services.get_tag(new_container.get('Image')), 'beta') self.purge([new_container]) def test_can_pop_new_container(self): config = {'ip': '10.49.0.2', 'subnet': '10.49.0.0/16', 'gateway': '10.49.0.202', 'vlan': 102} container = container_services.pop_new_container(config, self.docker_api) self.assertIsNotNone(container['Id']) self.purge([container]) def test_can_pop_new_container_with_specific_image(self): config = {'ip': '10.49.0.2', 'subnet': '10.49.0.0/16', 'gateway': '10.49.0.202', 'vlan': 102, 'image': 'coaxisasp/coaxisopt_daemon:latest'} container = container_services.pop_new_container(config, self.docker_api) self.assertIsNotNone(container['Id']) self.purge([container]) def test_can_restart_container(self): config = {'ip': '10.49.0.3', 'subnet': '10.49.0.0/16', 'gateway': '10.49.0.203', 'vlan': 103} container = container_services.pop_new_container(config, self.docker_api) data = self.docker_api.inspect_container(container['Id']) container_services.restart(container['Id'], self.docker_api) new_data = self.docker_api.inspect_container(container['Id']) self.assertGreater(new_data.get('State').get('StartedAt'), data.get('State').get('StartedAt')) self.purge([container]) def test_list_available_daemons_version(self): images = mock.get_images() versions = container_services.available_versions('coaxisasp/coaxisopt_daemon', images) self.assertEqual(len(versions), 3) self.assertCountEqual(set(versions), {'latest', 'v1.6.1', 'v1.6.0'}) def test_list_available_daemons_version_with_empty_repoTags(self): images = [ {'RepoTags': []}, {'RepoTags': ['node:argon-slim']}, {'RepoTags': ['coaxisasp/coaxisopt_daemon:v1.6.0']}, {"RepoTags": None} ] versions = container_services.available_versions('coaxisasp/coaxisopt_daemon', images) self.assertEqual(len(versions), 1) self.assertCountEqual(set(versions), {'v1.6.0'}) def test_can_get_tag(self): repo_tag = 'coaxisasp/coaxisopt_daemon:latest' tag = container_services.get_tag(repo_tag) self.assertEqual(tag, 'latest')
gpl-3.0
2hf/redis-in-action
python/ch07_listing_source.py
5
36913
import math import re import unittest import uuid import redis AVERAGE_PER_1K = {} # <start id="tokenize-and-index"/> STOP_WORDS = set('''able about across after all almost also am among an and any are as at be because been but by can cannot could dear did do does either else ever every for from get got had has have he her hers him his how however if in into is it its just least let like likely may me might most must my neither no nor not of off often on only or other our own rather said say says she should since so some than that the their them then there these they this tis to too twas us wants was we were what when where which while who whom why will with would yet you your'''.split()) #A WORDS_RE = re.compile("[a-z']{2,}") #B def tokenize(content): words = set() #C for match in WORDS_RE.finditer(content.lower()): #D word = match.group().strip("'") #E if len(word) >= 2: #F words.add(word) #F return words - STOP_WORDS #G def index_document(conn, docid, content): words = tokenize(content) #H pipeline = conn.pipeline(True) for word in words: #I pipeline.sadd('idx:' + word, docid) #I return len(pipeline.execute()) #J # <end id="tokenize-and-index"/> #A We pre-declare our known stop words, these were fetched from http://www.textfixer.com/resources/ #B A regular expression that extracts words as we defined them #C Our Python set of words that we have found in the document content #D Iterate over all of the words in the content #E Strip any leading or trailing single-quote characters #F Keep any words that are still at least 2 characters long #G Return the set of words that remain that are also not stop words #H Get the tokenized words for the content #I Add the documents to the appropriate inverted index entries #J Return the number of unique non-stop words that were added for the document #END # <start id="_1314_14473_9158"/> def _set_common(conn, method, names, ttl=30, execute=True): id = str(uuid.uuid4()) #A pipeline = conn.pipeline(True) if execute else conn #B names = ['idx:' + name for name in names] #C getattr(pipeline, method)('idx:' + id, *names) #D pipeline.expire('idx:' + id, ttl) #E if execute: pipeline.execute() #F return id #G def intersect(conn, items, ttl=30, _execute=True): #H return _set_common(conn, 'sinterstore', items, ttl, _execute) #H def union(conn, items, ttl=30, _execute=True): #I return _set_common(conn, 'sunionstore', items, ttl, _execute) #I def difference(conn, items, ttl=30, _execute=True): #J return _set_common(conn, 'sdiffstore', items, ttl, _execute) #J # <end id="_1314_14473_9158"/> #A Create a new temporary identifier #B Set up a transactional pipeline so that we have consistent results for each individual call #C Add the 'idx:' prefix to our terms #D Set up the call for one of the operations #E Instruct Redis to expire the SET in the future #F Actually execute the operation #G Return the id for the caller to process the results #H Helper function to perform SET intersections #I Helper function to perform SET unions #J Helper function to perform SET differences #END # <start id="parse-query"/> QUERY_RE = re.compile("[+-]?[a-z']{2,}") #A def parse(query): unwanted = set() #B all = [] #C current = set() #D for match in QUERY_RE.finditer(query.lower()): #E word = match.group() #F prefix = word[:1] #F if prefix in '+-': #F word = word[1:] #F else: #F prefix = None #F word = word.strip("'") #G if len(word) < 2 or word in STOP_WORDS: #G continue #G if prefix == '-': #H unwanted.add(word) #H continue #H if current and not prefix: #I all.append(list(current)) #I current = set() #I current.add(word) #J if current: #K all.append(list(current)) #K return all, list(unwanted) #L # <end id="parse-query"/> #A Our regular expression for finding wanted, unwanted, and synonym words #B A unique set of unwanted words #C Our final result of words that we are looking to intersect #D The current unique set of words to consider as synonyms #E Iterate over all words in the search query #F Discover +/- prefixes, if any #G Strip any leading or trailing single quotes, and skip anything that is a stop word #H If the word is unwanted, add it to the unwanted set #I Set up a new synonym set if we have no synonym prefix and we already have words #J Add the current word to the current set #K Add any remaining words to the final intersection #END # <start id="search-query"/> def parse_and_search(conn, query, ttl=30): all, unwanted = parse(query) #A if not all: #B return None #B to_intersect = [] for syn in all: #D if len(syn) > 1: #E to_intersect.append(union(conn, syn, ttl=ttl)) #E else: #F to_intersect.append(syn[0]) #F if len(to_intersect) > 1: #G intersect_result = intersect(conn, to_intersect, ttl=ttl) #G else: #H intersect_result = to_intersect[0] #H if unwanted: #I unwanted.insert(0, intersect_result) #I return difference(conn, unwanted, ttl=ttl) #I return intersect_result #J # <end id="search-query"/> #A Parse the query #B If there are no words in the query that are not stop words, we don't have a result #D Iterate over each list of synonyms #E If the synonym list is more than one word long, then perform the union operation #F Otherwise use the individual word directly #G If we have more than one word/result to intersect, intersect them #H Otherwise use the individual word/result directly #I If we have any unwanted words, remove them from our earlier result and return it #J Otherwise return the intersection result #END # <start id="sorted-searches"/> def search_and_sort(conn, query, id=None, ttl=300, sort="-updated", #A start=0, num=20): #A desc = sort.startswith('-') #B sort = sort.lstrip('-') #B by = "kb:doc:*->" + sort #B alpha = sort not in ('updated', 'id', 'created') #I if id and not conn.expire(id, ttl): #C id = None #C if not id: #D id = parse_and_search(conn, query, ttl=ttl) #D pipeline = conn.pipeline(True) pipeline.scard('idx:' + id) #E pipeline.sort('idx:' + id, by=by, alpha=alpha, #F desc=desc, start=start, num=num) #F results = pipeline.execute() return results[0], results[1], id #G # <end id="sorted-searches"/> #A We will optionally take an previous result id, a way to sort the results, and options for paginating over the results #B Determine which attribute to sort by, and whether to sort ascending or descending #I We need to tell Redis whether we are sorting by a number or alphabetically #C If there was a previous result, try to update its expiration time if it still exists #D Perform the search if we didn't have a past search id, or if our results expired #E Fetch the total number of results #F Sort the result list by the proper column and fetch only those results we want #G Return the number of items in the results, the results we wanted, and the id of the results so that we can fetch them again later #END # <start id="zset_scored_composite"/> def search_and_zsort(conn, query, id=None, ttl=300, update=1, vote=0, #A start=0, num=20, desc=True): #A if id and not conn.expire(id, ttl): #B id = None #B if not id: #C id = parse_and_search(conn, query, ttl=ttl) #C scored_search = { id: 0, #I 'sort:update': update, #D 'sort:votes': vote #D } id = zintersect(conn, scored_search, ttl) #E pipeline = conn.pipeline(True) pipeline.zcard('idx:' + id) #F if desc: #G pipeline.zrevrange('idx:' + id, start, start + num - 1) #G else: #G pipeline.zrange('idx:' + id, start, start + num - 1) #G results = pipeline.execute() return results[0], results[1], id #H # <end id="zset_scored_composite"/> #A Like before, we'll optionally take a previous result id for pagination if the result is still available #B We will refresh the search result's TTL if possible #C If our search result expired, or if this is the first time we've searched, perform the standard SET search #I We use the 'id' key for the intersection, but we don't want it to count towards weights #D Set up the scoring adjustments for balancing update time and votes. Remember: votes can be adjusted to 1, 10, 100, or higher depending on the sorting result desired. #E Intersect using our helper function that we define in listing 7.7 #F Fetch the size of the result ZSET #G Handle fetching a "page" of results #H Return the results and the id for pagination #END # <start id="zset_helpers"/> def _zset_common(conn, method, scores, ttl=30, **kw): id = str(uuid.uuid4()) #A execute = kw.pop('_execute', True) #J pipeline = conn.pipeline(True) if execute else conn #B for key in scores.keys(): #C scores['idx:' + key] = scores.pop(key) #C getattr(pipeline, method)('idx:' + id, scores, **kw) #D pipeline.expire('idx:' + id, ttl) #E if execute: #F pipeline.execute() #F return id #G def zintersect(conn, items, ttl=30, **kw): #H return _zset_common(conn, 'zinterstore', dict(items), ttl, **kw) #H def zunion(conn, items, ttl=30, **kw): #I return _zset_common(conn, 'zunionstore', dict(items), ttl, **kw) #I # <end id="zset_helpers"/> #A Create a new temporary identifier #B Set up a transactional pipeline so that we have consistent results for each individual call #C Add the 'idx:' prefix to our inputs #D Set up the call for one of the operations #E Instruct Redis to expire the ZSET in the future #F Actually execute the operation, unless explicitly instructed not to by the caller #G Return the id for the caller to process the results #H Helper function to perform ZSET intersections #I Helper function to perform ZSET unions #J Allow the passing of an argument to determine whether we should defer pipeline execution #END # <start id="string-to-score"/> def string_to_score(string, ignore_case=False): if ignore_case: #A string = string.lower() #A pieces = map(ord, string[:6]) #B while len(pieces) < 6: #C pieces.append(-1) #C score = 0 for piece in pieces: #D score = score * 257 + piece + 1 #D return score * 2 + (len(string) > 6) #E # <end id="string-to-score"/> #A We can handle optional case-insensitive indexes easily, so we will #B Convert the first 6 characters of the string into their numeric values, null being 0, tab being 9, capital A being 65, etc. #C For strings that aren't at least 6 characters long, we will add place-holder values to represent that the string was short #D For each value in the converted string values, we add it to the score, taking into consideration that a null is different from a place holder #E Because we have an extra bit, we can also signify whether the string is exactly 6 characters or more, allowing us to differentiate 'robber' and 'robbers', though not 'robbers' and 'robbery' #END def to_char_map(set): out = {} for pos, val in enumerate(sorted(set)): out[val] = pos-1 return out LOWER = to_char_map(set([-1]) | set(xrange(ord('a'), ord('z')+1))) ALPHA = to_char_map(set(LOWER) | set(xrange(ord('A'), ord('Z')+1))) LOWER_NUMERIC = to_char_map(set(LOWER) | set(xrange(ord('0'), ord('9')+1))) ALPHA_NUMERIC = to_char_map(set(LOWER_NUMERIC) | set(ALPHA)) def string_to_score_generic(string, mapping): length = int(52 / math.log(len(mapping), 2)) #A pieces = map(ord, string[:length]) #B while len(pieces) < length: #C pieces.append(-1) #C score = 0 for piece in pieces: #D value = mapping[piece] #D score = score * len(mapping) + value + 1 #D return score * 2 + (len(string) > length) #E # <start id="zadd-string"/> def zadd_string(conn, name, *args, **kwargs): pieces = list(args) #A for piece in kwargs.iteritems(): #A pieces.extend(piece) #A for i, v in enumerate(pieces): if i & 1: #B pieces[i] = string_to_score(v) #B return conn.zadd(name, *pieces) #C # <end id="zadd-string"/> #A Combine both types of arguments passed for later modification #B Convert string scores to integer scores #C Call the existing ZADD method #END # <start id="ecpm_helpers"/> def cpc_to_ecpm(views, clicks, cpc): return 1000. * cpc * clicks / views def cpa_to_ecpm(views, actions, cpa): return 1000. * cpa * actions / views #A # <end id="ecpm_helpers"/> #A Because click through rate is (clicks/views), and action rate is (actions/clicks), when we multiply them together we get (actions/views) #END # <start id="index_ad"/> TO_ECPM = { 'cpc': cpc_to_ecpm, 'cpa': cpa_to_ecpm, 'cpm': lambda *args:args[-1], } def index_ad(conn, id, locations, content, type, value): pipeline = conn.pipeline(True) #A for location in locations: pipeline.sadd('idx:req:'+location, id) #B words = tokenize(content) for word in tokenize(content): #H pipeline.zadd('idx:' + word, id, 0) #H rvalue = TO_ECPM[type]( #C 1000, AVERAGE_PER_1K.get(type, 1), value) #C pipeline.hset('type:', id, type) #D pipeline.zadd('idx:ad:value:', id, rvalue) #E pipeline.zadd('ad:base_value:', id, value) #F pipeline.sadd('terms:' + id, *list(words)) #G pipeline.execute() # <end id="index_ad"/> #A Set up the pipeline so that we only need a single round-trip to perform the full index operation #B Add the ad id to all of the relevant location SETs for targeting #H Index the words for the ad #C We will keep a dictionary that stores the average number of clicks or actions per 1000 views on our network, for estimating the performance of new ads #D Record what type of ad this is #E Add the ad's eCPM to a ZSET of all ads #F Add the ad's base value to a ZST of all ads #G Keep a record of the words that could be targeted for the ad #END # <start id="target_ad"/> def target_ads(conn, locations, content): pipeline = conn.pipeline(True) matched_ads, base_ecpm = match_location(pipeline, locations) #A words, targeted_ads = finish_scoring( #B pipeline, matched_ads, base_ecpm, content) #B pipeline.incr('ads:served:') #C pipeline.zrevrange('idx:' + targeted_ads, 0, 0) #D target_id, targeted_ad = pipeline.execute()[-2:] if not targeted_ad: #E return None, None #E ad_id = targeted_ad[0] record_targeting_result(conn, target_id, ad_id, words) #F return target_id, ad_id #G # <end id="target_ad"/> #A Find all ads that fit the location targeting parameter, and their eCPMs #B Finish any bonus scoring based on matching the content #C Get an id that can be used for reporting and recording of this particular ad target #D Fetch the top-eCPM ad id #E If there were no ads that matched the location targeting, return nothing #F Record the results of our targeting efforts as part of our learning process #G Return the target id and the ad id to the caller #END # <start id="location_target"/> def match_location(pipe, locations): required = ['req:' + loc for loc in locations] #A matched_ads = union(pipe, required, ttl=300, _execute=False) #B return matched_ads, zintersect(pipe, #C {matched_ads: 0, 'ad:value:': 1}, _execute=False) #C # <end id="location_target"/> #A Calculate the SET key names for all of the provided locations #B Calculate the SET of matched ads that are valid for this location #C Return the matched ads SET id, as well as the id of the ZSET that includes the base eCPM of all of the matched ads #END # <start id="finish_scoring"/> def finish_scoring(pipe, matched, base, content): bonus_ecpm = {} words = tokenize(content) #A for word in words: word_bonus = zintersect( #B pipe, {matched: 0, word: 1}, _execute=False) #B bonus_ecpm[word_bonus] = 1 #B if bonus_ecpm: minimum = zunion( #C pipe, bonus_ecpm, aggregate='MIN', _execute=False) #C maximum = zunion( #C pipe, bonus_ecpm, aggregate='MAX', _execute=False) #C return words, zunion( #D pipe, {base:1, minimum:.5, maximum:.5}, _execute=False) #D return words, base #E # <end id="finish_scoring"/> #A Tokenize the content for matching against ads #B Find the ads that are location-targeted, which also have one of the words in the content #C Find the minimum and maximum eCPM bonuses for each ad #D Compute the total of the base + half of the minimum eCPM bonus + half of the maximum eCPM bonus #E If there were no words in the content to match against, return just the known eCPM #END # <start id="record_targeting"/> def record_targeting_result(conn, target_id, ad_id, words): pipeline = conn.pipeline(True) terms = conn.smembers('terms:' + ad_id) #A matched = list(words & terms) #A if matched: matched_key = 'terms:matched:%s' % target_id pipeline.sadd(matched_key, *matched) #B pipeline.expire(matched_key, 900) #B type = conn.hget('type:', ad_id) #C pipeline.incr('type:%s:views:' % type) #C for word in matched: #D pipeline.zincrby('views:%s' % ad_id, word) #D pipeline.zincrby('views:%s' % ad_id, '') #D if not pipeline.execute()[-1] % 100: #E update_cpms(conn, ad_id) #E # <end id="record_targeting"/> #A Find the words in the content that matched with the words in the ad #B If any words in the ad matched the content, record that information and keep it for 15 minutes #C Keep a per-type count of the number of views that each ad received #D Record view information for each word in the ad, as well as the ad itself #E Every 100th time that the ad was shown, update the ad's eCPM #END # <start id="record_click"/> def record_click(conn, target_id, ad_id, action=False): pipeline = conn.pipeline(True) click_key = 'clicks:%s'%ad_id match_key = 'terms:matched:%s'%target_id type = conn.hget('type:', ad_id) if type == 'cpa': #A pipeline.expire(match_key, 900) #A if action: click_key = 'actions:%s' % ad_id #B if action and type == 'cpa': pipeline.incr('type:%s:actions:' % type) #C else: pipeline.incr('type:%s:clicks:' % type) #C matched = list(conn.smembers(match_key))#D matched.append('') #D for word in matched: #D pipeline.zincrby(click_key, word) #D pipeline.execute() update_cpms(conn, ad_id) #E # <end id="record_click"/> #A If the ad was a CPA ad, refresh the expiration time of the matched terms if it is still available #B Record actions instead of clicks #C Keep a global count of clicks/actions for ads based on the ad type #D Record clicks (or actions) for the ad and for all words that had been targeted in the ad #E Update the eCPM for all words that were seen in the ad #END # <start id="update_cpms"/> def update_cpms(conn, ad_id): pipeline = conn.pipeline(True) pipeline.hget('type:', ad_id) #A pipeline.zscore('ad:base_value:', ad_id) #A pipeline.smembers('terms:' + ad_id) #A type, base_value, words = pipeline.execute()#A which = 'clicks' #B if type == 'cpa': #B which = 'actions' #B pipeline.get('type:%s:views:' % type) #C pipeline.get('type:%s:%s' % (type, which)) #C type_views, type_clicks = pipeline.execute() #C AVERAGE_PER_1K[type] = ( #D 1000. * int(type_clicks or '1') / int(type_views or '1')) #D if type == 'cpm': #E return #E view_key = 'views:%s' % ad_id click_key = '%s:%s' % (which, ad_id) to_ecpm = TO_ECPM[type] pipeline.zscore(view_key, '') #G pipeline.zscore(click_key, '') #G ad_views, ad_clicks = pipeline.execute() #G if (ad_clicks or 0) < 1: #N ad_ecpm = conn.zscore('idx:ad:value:', ad_id) #N else: ad_ecpm = to_ecpm(ad_views or 1, ad_clicks or 0, base_value)#H pipeline.zadd('idx:ad:value:', ad_id, ad_ecpm) #H for word in words: pipeline.zscore(view_key, word) #I pipeline.zscore(click_key, word) #I views, clicks = pipeline.execute()[-2:] #I if (clicks or 0) < 1: #J continue #J word_ecpm = to_ecpm(views or 1, clicks or 0, base_value) #K bonus = word_ecpm - ad_ecpm #L pipeline.zadd('idx:' + word, ad_id, bonus) #M pipeline.execute() # <end id="update_cpms"/> #A Fetch the type and value of the ad, as well as all of the words in the ad #B Determine whether the eCPM of the ad should be based on clicks or actions #C Fetch the current number of views and clicks/actions for the given ad type #D Write back to our global dictionary the click-through rate or action rate for the ad #E If we are processing a CPM ad, then we don't update any of the eCPMs, as they are already updated #N Use the existing eCPM if the ad hasn't received any clicks yet #G Fetch the per-ad view and click/action scores and #H Calculate the ad's eCPM and update the ad's value #I Fetch the view and click/action scores for the word #J Don't update eCPMs when the ad has not received any clicks #K Calculate the word's eCPM #L Calculate the word's bonus #M Write the word's bonus back to the per-word per-ad ZSET #END # <start id="slow_job_search"/> def add_job(conn, job_id, required_skills): conn.sadd('job:' + job_id, *required_skills) #A def is_qualified(conn, job_id, candidate_skills): temp = str(uuid.uuid4()) pipeline = conn.pipeline(True) pipeline.sadd(temp, *candidate_skills) #B pipeline.expire(temp, 5) #B pipeline.sdiff('job:' + job_id, temp) #C return not pipeline.execute()[-1] #D # <end id="slow_job_search"/> #A Add all required job skills to the job's SET #B Add the candidate's skills to a temporary SET with an expiration time #C Calculate the SET of skills that the job requires that the user doesn't have #D Return True if there are no skills that the candidate does not have #END # <start id="job_search_index"/> def index_job(conn, job_id, skills): pipeline = conn.pipeline(True) for skill in skills: pipeline.sadd('idx:skill:' + skill, job_id) #A pipeline.zadd('idx:jobs:req', job_id, len(set(skills))) #B pipeline.execute() # <end id="job_search_index"/> #A Add the job id to all appropriate skill SETs #B Add the total required skill count to the required skills ZSET #END # <start id="job_search_results"/> def find_jobs(conn, candidate_skills): skills = {} #A for skill in set(candidate_skills): #A skills['skill:' + skill] = 1 #A job_scores = zunion(conn, skills) #B final_result = zintersect( #C conn, {job_scores:-1, 'jobs:req':1}) #C return conn.zrangebyscore('idx:' + final_result, 0, 0) #D # <end id="job_search_results"/> #A Set up the dictionary for scoring the jobs #B Calculate the scores for each of the jobs #C Calculate how many more skills the job requires than the candidate has #D Return the jobs that the candidate has the skills for #END # 0 is beginner, 1 is intermediate, 2 is expert SKILL_LEVEL_LIMIT = 2 def index_job_levels(conn, job_id, skill_levels): total_skills = len(set(skill for skill, level in skill_levels)) pipeline = conn.pipeline(True) for skill, level in skill_levels: level = min(level, SKILL_LEVEL_LIMIT) for wlevel in xrange(level, SKILL_LEVEL_LIMIT+1): pipeline.sadd('idx:skill:%s:%s'%(skill,wlevel), job_id) pipeline.zadd('idx:jobs:req', job_id, total_skills) pipeline.execute() def search_job_levels(conn, skill_levels): skills = {} for skill, level in skill_levels: level = min(level, SKILL_LEVEL_LIMIT) for wlevel in xrange(level, SKILL_LEVEL_LIMIT+1): skills['skill:%s:%s'%(skill,wlevel)] = 1 job_scores = zunion(conn, skills) final_result = zintersect(conn, {job_scores:-1, 'jobs:req':1}) return conn.zrangebyscore('idx:' + final_result, 0, 0) def index_job_years(conn, job_id, skill_years): total_skills = len(set(skill for skill, level in skill_years)) pipeline = conn.pipeline(True) for skill, years in skill_years: pipeline.zadd( 'idx:skill:%s:years'%skill, job_id, max(years, 0)) pipeline.sadd('idx:jobs:all', job_id) pipeline.zadd('idx:jobs:req', job_id, total_skills) def search_job_years(conn, skill_years): skill_years = dict(skill_years) pipeline = conn.pipeline(True) union = [] for skill, years in skill_years.iteritems(): sub_result = zintersect(pipeline, {'jobs:all':-years, 'skill:%s:years'%skill:1}, _execute=False) pipeline.zremrangebyscore('idx:' + sub_result, '(0', 'inf') union.append( zintersect(pipeline, {'jobs:all':1, sub_result:0}), _execute=False) job_scores = zunion(pipeline, dict((key, 1) for key in union), _execute=False) final_result = zintersect(pipeline, {job_scores:-1, 'jobs:req':1}, _execute=False) pipeline.zrange('idx:' + final_result, 0, 0) return pipeline.execute()[-1] class TestCh07(unittest.TestCase): content = 'this is some random content, look at how it is indexed.' def setUp(self): self.conn = redis.Redis(db=15) self.conn.flushdb() def tearDown(self): self.conn.flushdb() def test_index_document(self): print "We're tokenizing some content..." tokens = tokenize(self.content) print "Those tokens are:", tokens self.assertTrue(tokens) print "And now we are indexing that content..." r = index_document(self.conn, 'test', self.content) self.assertEquals(r, len(tokens)) for t in tokens: self.assertEquals(self.conn.smembers('idx:' + t), set(['test'])) def test_set_operations(self): index_document(self.conn, 'test', self.content) r = intersect(self.conn, ['content', 'indexed']) self.assertEquals(self.conn.smembers('idx:' + r), set(['test'])) r = intersect(self.conn, ['content', 'ignored']) self.assertEquals(self.conn.smembers('idx:' + r), set()) r = union(self.conn, ['content', 'ignored']) self.assertEquals(self.conn.smembers('idx:' + r), set(['test'])) r = difference(self.conn, ['content', 'ignored']) self.assertEquals(self.conn.smembers('idx:' + r), set(['test'])) r = difference(self.conn, ['content', 'indexed']) self.assertEquals(self.conn.smembers('idx:' + r), set()) def test_parse_query(self): query = 'test query without stopwords' self.assertEquals(parse(query), ([[x] for x in query.split()], [])) query = 'test +query without -stopwords' self.assertEquals(parse(query), ([['test', 'query'], ['without']], ['stopwords'])) def test_parse_and_search(self): print "And now we are testing search..." index_document(self.conn, 'test', self.content) r = parse_and_search(self.conn, 'content') self.assertEquals(self.conn.smembers('idx:' + r), set(['test'])) r = parse_and_search(self.conn, 'content indexed random') self.assertEquals(self.conn.smembers('idx:' + r), set(['test'])) r = parse_and_search(self.conn, 'content +indexed random') self.assertEquals(self.conn.smembers('idx:' + r), set(['test'])) r = parse_and_search(self.conn, 'content indexed +random') self.assertEquals(self.conn.smembers('idx:' + r), set(['test'])) r = parse_and_search(self.conn, 'content indexed -random') self.assertEquals(self.conn.smembers('idx:' + r), set()) r = parse_and_search(self.conn, 'content indexed +random') self.assertEquals(self.conn.smembers('idx:' + r), set(['test'])) print "Which passed!" def test_search_with_sort(self): print "And now let's test searching with sorting..." index_document(self.conn, 'test', self.content) index_document(self.conn, 'test2', self.content) self.conn.hmset('kb:doc:test', {'updated': 12345, 'id': 10}) self.conn.hmset('kb:doc:test2', {'updated': 54321, 'id': 1}) r = search_and_sort(self.conn, "content") self.assertEquals(r[1], ['test2', 'test']) r = search_and_sort(self.conn, "content", sort='-id') self.assertEquals(r[1], ['test', 'test2']) print "Which passed!" def test_search_with_zsort(self): print "And now let's test searching with sorting via zset..." index_document(self.conn, 'test', self.content) index_document(self.conn, 'test2', self.content) self.conn.zadd('idx:sort:update', 'test', 12345, 'test2', 54321) self.conn.zadd('idx:sort:votes', 'test', 10, 'test2', 1) r = search_and_zsort(self.conn, "content", desc=False) self.assertEquals(r[1], ['test', 'test2']) r = search_and_zsort(self.conn, "content", update=0, vote=1, desc=False) self.assertEquals(r[1], ['test2', 'test']) print "Which passed!" def test_string_to_score(self): words = 'these are some words that will be sorted'.split() pairs = [(word, string_to_score(word)) for word in words] pairs2 = list(pairs) pairs.sort() pairs2.sort(key=lambda x:x[1]) self.assertEquals(pairs, pairs2) words = 'these are some words that will be sorted'.split() pairs = [(word, string_to_score_generic(word, LOWER)) for word in words] pairs2 = list(pairs) pairs.sort() pairs2.sort(key=lambda x:x[1]) self.assertEquals(pairs, pairs2) zadd_string(self.conn, 'key', 'test', 'value', test2='other') self.assertTrue(self.conn.zscore('key', 'test'), string_to_score('value')) self.assertTrue(self.conn.zscore('key', 'test2'), string_to_score('other')) def test_index_and_target_ads(self): index_ad(self.conn, '1', ['USA', 'CA'], self.content, 'cpc', .25) index_ad(self.conn, '2', ['USA', 'VA'], self.content + ' wooooo', 'cpc', .125) for i in xrange(100): ro = target_ads(self.conn, ['USA'], self.content) self.assertEquals(ro[1], '1') r = target_ads(self.conn, ['VA'], 'wooooo') self.assertEquals(r[1], '2') self.assertEquals(self.conn.zrange('idx:ad:value:', 0, -1, withscores=True), [('2', 0.125), ('1', 0.25)]) self.assertEquals(self.conn.zrange('ad:base_value:', 0, -1, withscores=True), [('2', 0.125), ('1', 0.25)]) record_click(self.conn, ro[0], ro[1]) self.assertEquals(self.conn.zrange('idx:ad:value:', 0, -1, withscores=True), [('2', 0.125), ('1', 2.5)]) self.assertEquals(self.conn.zrange('ad:base_value:', 0, -1, withscores=True), [('2', 0.125), ('1', 0.25)]) def test_is_qualified_for_job(self): add_job(self.conn, 'test', ['q1', 'q2', 'q3']) self.assertTrue(is_qualified(self.conn, 'test', ['q1', 'q3', 'q2'])) self.assertFalse(is_qualified(self.conn, 'test', ['q1', 'q2'])) def test_index_and_find_jobs(self): index_job(self.conn, 'test1', ['q1', 'q2', 'q3']) index_job(self.conn, 'test2', ['q1', 'q3', 'q4']) index_job(self.conn, 'test3', ['q1', 'q3', 'q5']) self.assertEquals(find_jobs(self.conn, ['q1']), []) self.assertEquals(find_jobs(self.conn, ['q1', 'q3', 'q4']), ['test2']) self.assertEquals(find_jobs(self.conn, ['q1', 'q3', 'q5']), ['test3']) self.assertEquals(find_jobs(self.conn, ['q1', 'q2', 'q3', 'q4', 'q5']), ['test1', 'test2', 'test3']) if __name__ == '__main__': unittest.main()
mit
amazuelos/BitacleSymfony3
vendor/doctrine/orm/docs/en/_exts/configurationblock.py
2577
3506
#Copyright (c) 2010 Fabien Potencier # #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, 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: # #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 MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS 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 IN #THE SOFTWARE. from docutils.parsers.rst import Directive, directives from docutils import nodes from string import upper class configurationblock(nodes.General, nodes.Element): pass class ConfigurationBlock(Directive): has_content = True required_arguments = 0 optional_arguments = 0 final_argument_whitespace = True option_spec = {} formats = { 'html': 'HTML', 'xml': 'XML', 'php': 'PHP', 'yaml': 'YAML', 'jinja': 'Twig', 'html+jinja': 'Twig', 'jinja+html': 'Twig', 'php+html': 'PHP', 'html+php': 'PHP', 'ini': 'INI', 'php-annotations': 'Annotations', } def run(self): env = self.state.document.settings.env node = nodes.Element() node.document = self.state.document self.state.nested_parse(self.content, self.content_offset, node) entries = [] for i, child in enumerate(node): if isinstance(child, nodes.literal_block): # add a title (the language name) before each block #targetid = "configuration-block-%d" % env.new_serialno('configuration-block') #targetnode = nodes.target('', '', ids=[targetid]) #targetnode.append(child) innernode = nodes.emphasis(self.formats[child['language']], self.formats[child['language']]) para = nodes.paragraph() para += [innernode, child] entry = nodes.list_item('') entry.append(para) entries.append(entry) resultnode = configurationblock() resultnode.append(nodes.bullet_list('', *entries)) return [resultnode] def visit_configurationblock_html(self, node): self.body.append(self.starttag(node, 'div', CLASS='configuration-block')) def depart_configurationblock_html(self, node): self.body.append('</div>\n') def visit_configurationblock_latex(self, node): pass def depart_configurationblock_latex(self, node): pass def setup(app): app.add_node(configurationblock, html=(visit_configurationblock_html, depart_configurationblock_html), latex=(visit_configurationblock_latex, depart_configurationblock_latex)) app.add_directive('configuration-block', ConfigurationBlock)
mit
ericpp/hippyvm
testing/test_var_funcs.py
1
1346
import py.test from hippy.objects.floatobject import W_FloatObject from testing.test_interpreter import BaseTestInterpreter class TestVarFuncs(BaseTestInterpreter): def test_print_r(self): output = self.run(''' class A { private $y = 5; } $a = new A; $a->x = array($a); $a->zzz = array($a); $result = print_r($a, TRUE); echo str_replace("\\n", '\\n', $result); ''') expected = """\ A Object ( [y:A:private] => 5 [x] => Array ( [0] => A Object *RECURSION* ) [zzz] => Array ( [0] => A Object *RECURSION* ) ) """ assert self.space.str_w(output[0]) == '\\n'.join(expected.split('\n')) @py.test.mark.parametrize(['input', 'expected'], [["'xxx'", 0.], ["'3.4bcd'", 3.4], ['2e1', 20.], ['5', 5.], ['1.3', 1.3], ["array()", 0.]]) def test_floatval(self, input, expected): output, = self.run('echo floatval(%s);' % input) assert output == W_FloatObject(expected) def test_floatval_object(self): with self.warnings(['Notice: Object of class stdClass ' 'could not be converted to double']): output, = self.run('echo floatval(new stdClass);') assert output == W_FloatObject(1.)
mit
SravanthiSinha/edx-platform
openedx/core/djangoapps/user_api/accounts/tests/test_views.py
37
33316
# -*- coding: utf-8 -*- import datetime from copy import deepcopy import ddt import hashlib import json from mock import patch from pytz import UTC import unittest from django.conf import settings from django.core.urlresolvers import reverse from django.test.testcases import TransactionTestCase from django.test.utils import override_settings from rest_framework.test import APITestCase, APIClient from student.tests.factories import UserFactory from student.models import UserProfile, LanguageProficiency, PendingEmailChange from openedx.core.djangoapps.user_api.accounts import ACCOUNT_VISIBILITY_PREF_KEY from openedx.core.djangoapps.user_api.preferences.api import set_user_preference from .. import PRIVATE_VISIBILITY, ALL_USERS_VISIBILITY TEST_PROFILE_IMAGE_UPLOADED_AT = datetime.datetime(2002, 1, 9, 15, 43, 01, tzinfo=UTC) # this is used in one test to check the behavior of profile image url # generation with a relative url in the config. TEST_PROFILE_IMAGE_BACKEND = deepcopy(settings.PROFILE_IMAGE_BACKEND) TEST_PROFILE_IMAGE_BACKEND['options']['base_url'] = '/profile-images/' class UserAPITestCase(APITestCase): """ The base class for all tests of the User API """ test_password = "test" def setUp(self): super(UserAPITestCase, self).setUp() self.anonymous_client = APIClient() self.different_user = UserFactory.create(password=self.test_password) self.different_client = APIClient() self.staff_user = UserFactory(is_staff=True, password=self.test_password) self.staff_client = APIClient() self.user = UserFactory.create(password=self.test_password) # will be assigned to self.client by default def login_client(self, api_client, user): """Helper method for getting the client and user and logging in. Returns client. """ client = getattr(self, api_client) user = getattr(self, user) client.login(username=user.username, password=self.test_password) return client def send_patch(self, client, json_data, content_type="application/merge-patch+json", expected_status=204): """ Helper method for sending a patch to the server, defaulting to application/merge-patch+json content_type. Verifies the expected status and returns the response. """ # pylint: disable=no-member response = client.patch(self.url, data=json.dumps(json_data), content_type=content_type) self.assertEqual(expected_status, response.status_code) return response def send_get(self, client, query_parameters=None, expected_status=200): """ Helper method for sending a GET to the server. Verifies the expected status and returns the response. """ url = self.url + '?' + query_parameters if query_parameters else self.url # pylint: disable=no-member response = client.get(url) self.assertEqual(expected_status, response.status_code) return response def send_put(self, client, json_data, content_type="application/json", expected_status=204): """ Helper method for sending a PUT to the server. Verifies the expected status and returns the response. """ response = client.put(self.url, data=json.dumps(json_data), content_type=content_type) self.assertEqual(expected_status, response.status_code) return response def send_delete(self, client, expected_status=204): """ Helper method for sending a DELETE to the server. Verifies the expected status and returns the response. """ response = client.delete(self.url) self.assertEqual(expected_status, response.status_code) return response def create_mock_profile(self, user): """ Helper method that creates a mock profile for the specified user :return: """ legacy_profile = UserProfile.objects.get(id=user.id) legacy_profile.country = "US" legacy_profile.level_of_education = "m" legacy_profile.year_of_birth = 2000 legacy_profile.goals = "world peace" legacy_profile.mailing_address = "Park Ave" legacy_profile.gender = "f" legacy_profile.bio = "Tired mother of twins" legacy_profile.profile_image_uploaded_at = TEST_PROFILE_IMAGE_UPLOADED_AT legacy_profile.language_proficiencies.add(LanguageProficiency(code='en')) legacy_profile.save() @ddt.ddt @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Account APIs are only supported in LMS') @patch('openedx.core.djangoapps.user_api.accounts.image_helpers._PROFILE_IMAGE_SIZES', [50, 10]) @patch.dict( 'openedx.core.djangoapps.user_api.accounts.image_helpers.PROFILE_IMAGE_SIZES_MAP', {'full': 50, 'small': 10}, clear=True ) class TestAccountAPI(UserAPITestCase): """ Unit tests for the Account API. """ def setUp(self): super(TestAccountAPI, self).setUp() self.url = reverse("accounts_api", kwargs={'username': self.user.username}) def _verify_profile_image_data(self, data, has_profile_image): """ Verify the profile image data in a GET response for self.user corresponds to whether the user has or hasn't set a profile image. """ template = '{root}/{filename}_{{size}}.{extension}' if has_profile_image: url_root = 'http://example-storage.com/profile-images' filename = hashlib.md5('secret' + self.user.username).hexdigest() file_extension = 'jpg' template += '?v={}'.format(TEST_PROFILE_IMAGE_UPLOADED_AT.strftime("%s")) else: url_root = 'http://testserver/static' filename = 'default' file_extension = 'png' template = template.format(root=url_root, filename=filename, extension=file_extension) self.assertEqual( data['profile_image'], { 'has_image': has_profile_image, 'image_url_full': template.format(size=50), 'image_url_small': template.format(size=10), } ) def _verify_full_shareable_account_response(self, response): """ Verify that the shareable fields from the account are returned """ data = response.data self.assertEqual(6, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual("US", data["country"]) self._verify_profile_image_data(data, True) self.assertIsNone(data["time_zone"]) self.assertEqual([{"code": "en"}], data["language_proficiencies"]) self.assertEqual("Tired mother of twins", data["bio"]) def _verify_private_account_response(self, response, requires_parental_consent=False): """ Verify that only the public fields are returned if a user does not want to share account fields """ data = response.data self.assertEqual(2, len(data)) self.assertEqual(self.user.username, data["username"]) self._verify_profile_image_data(data, not requires_parental_consent) def _verify_full_account_response(self, response, requires_parental_consent=False): """ Verify that all account fields are returned (even those that are not shareable). """ data = response.data self.assertEqual(15, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"]) self.assertEqual("US", data["country"]) self.assertEqual("f", data["gender"]) self.assertEqual(2000, data["year_of_birth"]) self.assertEqual("m", data["level_of_education"]) self.assertEqual("world peace", data["goals"]) self.assertEqual("Park Ave", data['mailing_address']) self.assertEqual(self.user.email, data["email"]) self.assertTrue(data["is_active"]) self.assertIsNotNone(data["date_joined"]) self.assertEqual("Tired mother of twins", data["bio"]) self._verify_profile_image_data(data, not requires_parental_consent) self.assertEquals(requires_parental_consent, data["requires_parental_consent"]) self.assertEqual([{"code": "en"}], data["language_proficiencies"]) def test_anonymous_access(self): """ Test that an anonymous client (not logged in) cannot call GET or PATCH. """ self.send_get(self.anonymous_client, expected_status=401) self.send_patch(self.anonymous_client, {}, expected_status=401) def test_unsupported_methods(self): """ Test that DELETE, POST, and PUT are not supported. """ self.client.login(username=self.user.username, password=self.test_password) self.assertEqual(405, self.client.put(self.url).status_code) self.assertEqual(405, self.client.post(self.url).status_code) self.assertEqual(405, self.client.delete(self.url).status_code) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_get_account_unknown_user(self, api_client, user): """ Test that requesting a user who does not exist returns a 404. """ client = self.login_client(api_client, user) response = client.get(reverse("accounts_api", kwargs={'username': "does_not_exist"})) self.assertEqual(403 if user == "staff_user" else 404, response.status_code) # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "all_users"}) def test_get_account_different_user_visible(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "all_users". """ self.different_client.login(username=self.different_user.username, password=self.test_password) self.create_mock_profile(self.user) response = self.send_get(self.different_client) self._verify_full_shareable_account_response(response) # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "private"}) def test_get_account_different_user_private(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "private". """ self.different_client.login(username=self.different_user.username, password=self.test_password) self.create_mock_profile(self.user) response = self.send_get(self.different_client) self._verify_private_account_response(response) @ddt.data( ("client", "user", PRIVATE_VISIBILITY), ("different_client", "different_user", PRIVATE_VISIBILITY), ("staff_client", "staff_user", PRIVATE_VISIBILITY), ("client", "user", ALL_USERS_VISIBILITY), ("different_client", "different_user", ALL_USERS_VISIBILITY), ("staff_client", "staff_user", ALL_USERS_VISIBILITY), ) @ddt.unpack def test_get_account_private_visibility(self, api_client, requesting_username, preference_visibility): """ Test the return from GET based on user visibility setting. """ def verify_fields_visible_to_all_users(response): if preference_visibility == PRIVATE_VISIBILITY: self._verify_private_account_response(response) else: self._verify_full_shareable_account_response(response) client = self.login_client(api_client, requesting_username) # Update user account visibility setting. set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, preference_visibility) self.create_mock_profile(self.user) response = self.send_get(client) if requesting_username == "different_user": verify_fields_visible_to_all_users(response) else: self._verify_full_account_response(response) # Verify how the view parameter changes the fields that are returned. response = self.send_get(client, query_parameters='view=shared') verify_fields_visible_to_all_users(response) def test_get_account_default(self): """ Test that a client (logged in) can get her own account information (using default legacy profile information, as created by the test UserFactory). """ def verify_get_own_information(): response = self.send_get(self.client) data = response.data self.assertEqual(15, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"]) for empty_field in ("year_of_birth", "level_of_education", "mailing_address", "bio"): self.assertIsNone(data[empty_field]) self.assertIsNone(data["country"]) self.assertEqual("m", data["gender"]) self.assertEqual("Learn a lot", data["goals"]) self.assertEqual(self.user.email, data["email"]) self.assertIsNotNone(data["date_joined"]) self.assertEqual(self.user.is_active, data["is_active"]) self._verify_profile_image_data(data, False) self.assertTrue(data["requires_parental_consent"]) self.assertEqual([], data["language_proficiencies"]) self.client.login(username=self.user.username, password=self.test_password) verify_get_own_information() # Now make sure that the user can get the same information, even if not active self.user.is_active = False self.user.save() verify_get_own_information() def test_get_account_empty_string(self): """ Test the conversion of empty strings to None for certain fields. """ legacy_profile = UserProfile.objects.get(id=self.user.id) legacy_profile.country = "" legacy_profile.level_of_education = "" legacy_profile.gender = "" legacy_profile.bio = "" legacy_profile.save() self.client.login(username=self.user.username, password=self.test_password) response = self.send_get(self.client) for empty_field in ("level_of_education", "gender", "country", "bio"): self.assertIsNone(response.data[empty_field]) @ddt.data( ("different_client", "different_user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_disallowed_user(self, api_client, user): """ Test that a client cannot call PATCH on a different client's user account (even with is_staff access). """ client = self.login_client(api_client, user) self.send_patch(client, {}, expected_status=403 if user == "staff_user" else 404) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_unknown_user(self, api_client, user): """ Test that trying to update a user who does not exist returns a 404. """ client = self.login_client(api_client, user) response = client.patch( reverse("accounts_api", kwargs={'username': "does_not_exist"}), data=json.dumps({}), content_type="application/merge-patch+json" ) self.assertEqual(404, response.status_code) @ddt.data( ("gender", "f", "not a gender", u"Select a valid choice. not a gender is not one of the available choices."), ("level_of_education", "none", u"ȻħȺɍłɇs", u"Select a valid choice. ȻħȺɍłɇs is not one of the available choices."), ("country", "GB", "XY", u"Select a valid choice. XY is not one of the available choices."), ("year_of_birth", 2009, "not_an_int", u"Enter a whole number."), ("name", "bob", "z" * 256, u"Ensure this value has at most 255 characters (it has 256)."), ("name", u"ȻħȺɍłɇs", "z ", u"The name field must be at least 2 characters long."), ("goals", "Smell the roses"), ("mailing_address", "Sesame Street"), # Note that we store the raw data, so it is up to client to escape the HTML. ("bio", u"<html>Lacrosse-playing superhero 壓是進界推日不復女</html>", "z" * 3001, u"Ensure this value has at most 3000 characters (it has 3001)."), # Note that email is tested below, as it is not immediately updated. # Note that language_proficiencies is tested below as there are multiple error and success conditions. ) @ddt.unpack def test_patch_account(self, field, value, fails_validation_value=None, developer_validation_message=None): """ Test the behavior of patch, when using the correct content_type. """ client = self.login_client("client", "user") self.send_patch(client, {field: value}) get_response = self.send_get(client) self.assertEqual(value, get_response.data[field]) if fails_validation_value: error_response = self.send_patch(client, {field: fails_validation_value}, expected_status=400) self.assertEqual( u'This value is invalid.', error_response.data["field_errors"][field]["user_message"] ) self.assertEqual( u"Value '{value}' is not valid for field '{field}': {messages}".format( value=fails_validation_value, field=field, messages=[developer_validation_message] ), error_response.data["field_errors"][field]["developer_message"] ) else: # If there are no values that would fail validation, then empty string should be supported. self.send_patch(client, {field: ""}) get_response = self.send_get(client) self.assertEqual("", get_response.data[field]) def test_patch_inactive_user(self): """ Verify that a user can patch her own account, even if inactive. """ self.client.login(username=self.user.username, password=self.test_password) self.user.is_active = False self.user.save() self.send_patch(self.client, {"goals": "to not activate account"}) get_response = self.send_get(self.client) self.assertEqual("to not activate account", get_response.data["goals"]) @ddt.unpack def test_patch_account_noneditable(self): """ Tests the behavior of patch when a read-only field is attempted to be edited. """ client = self.login_client("client", "user") def verify_error_response(field_name, data): self.assertEqual( "This field is not editable via this API", data["field_errors"][field_name]["developer_message"] ) self.assertEqual( "The '{0}' field cannot be edited.".format(field_name), data["field_errors"][field_name]["user_message"] ) for field_name in ["username", "date_joined", "is_active", "profile_image", "requires_parental_consent"]: response = self.send_patch(client, {field_name: "will_error", "gender": "o"}, expected_status=400) verify_error_response(field_name, response.data) # Make sure that gender did not change. response = self.send_get(client) self.assertEqual("m", response.data["gender"]) # Test error message with multiple read-only items response = self.send_patch(client, {"username": "will_error", "date_joined": "xx"}, expected_status=400) self.assertEqual(2, len(response.data["field_errors"])) verify_error_response("username", response.data) verify_error_response("date_joined", response.data) def test_patch_bad_content_type(self): """ Test the behavior of patch when an incorrect content_type is specified. """ self.client.login(username=self.user.username, password=self.test_password) self.send_patch(self.client, {}, content_type="application/json", expected_status=415) self.send_patch(self.client, {}, content_type="application/xml", expected_status=415) def test_patch_account_empty_string(self): """ Tests the behavior of patch when attempting to set fields with a select list of options to the empty string. Also verifies the behaviour when setting to None. """ self.client.login(username=self.user.username, password=self.test_password) for field_name in ["gender", "level_of_education", "country"]: self.send_patch(self.client, {field_name: ""}) response = self.send_get(self.client) # Although throwing a 400 might be reasonable, the default DRF behavior with ModelSerializer # is to convert to None, which also seems acceptable (and is difficult to override). self.assertIsNone(response.data[field_name]) # Verify that the behavior is the same for sending None. self.send_patch(self.client, {field_name: ""}) response = self.send_get(self.client) self.assertIsNone(response.data[field_name]) def test_patch_name_metadata(self): """ Test the metadata stored when changing the name field. """ def get_name_change_info(expected_entries): legacy_profile = UserProfile.objects.get(id=self.user.id) name_change_info = legacy_profile.get_meta()["old_names"] self.assertEqual(expected_entries, len(name_change_info)) return name_change_info def verify_change_info(change_info, old_name, requester, new_name): self.assertEqual(3, len(change_info)) self.assertEqual(old_name, change_info[0]) self.assertEqual("Name change requested through account API by {}".format(requester), change_info[1]) self.assertIsNotNone(change_info[2]) # Verify the new name was also stored. get_response = self.send_get(self.client) self.assertEqual(new_name, get_response.data["name"]) self.client.login(username=self.user.username, password=self.test_password) legacy_profile = UserProfile.objects.get(id=self.user.id) self.assertEqual({}, legacy_profile.get_meta()) old_name = legacy_profile.name # First change the name as the user and verify meta information. self.send_patch(self.client, {"name": "Mickey Mouse"}) name_change_info = get_name_change_info(1) verify_change_info(name_change_info[0], old_name, self.user.username, "Mickey Mouse") # Now change the name again and verify meta information. self.send_patch(self.client, {"name": "Donald Duck"}) name_change_info = get_name_change_info(2) verify_change_info(name_change_info[0], old_name, self.user.username, "Donald Duck",) verify_change_info(name_change_info[1], "Mickey Mouse", self.user.username, "Donald Duck") def test_patch_email(self): """ Test that the user can request an email change through the accounts API. Full testing of the helper method used (do_email_change_request) exists in the package with the code. Here just do minimal smoke testing. """ client = self.login_client("client", "user") old_email = self.user.email new_email = "newemail@example.com" self.send_patch(client, {"email": new_email, "goals": "change my email"}) # Since request is multi-step, the email won't change on GET immediately (though goals will update). get_response = self.send_get(client) self.assertEqual(old_email, get_response.data["email"]) self.assertEqual("change my email", get_response.data["goals"]) # Now call the method that will be invoked with the user clicks the activation key in the received email. # First we must get the activation key that was sent. pending_change = PendingEmailChange.objects.filter(user=self.user) self.assertEqual(1, len(pending_change)) activation_key = pending_change[0].activation_key confirm_change_url = reverse( "student.views.confirm_email_change", kwargs={'key': activation_key} ) response = self.client.post(confirm_change_url) self.assertEqual(200, response.status_code) get_response = self.send_get(client) self.assertEqual(new_email, get_response.data["email"]) @ddt.data( ("not_an_email",), ("",), (None,), ) @ddt.unpack def test_patch_invalid_email(self, bad_email): """ Test a few error cases for email validation (full test coverage lives with do_email_change_request). """ client = self.login_client("client", "user") # Try changing to an invalid email to make sure error messages are appropriately returned. error_response = self.send_patch(client, {"email": bad_email}, expected_status=400) field_errors = error_response.data["field_errors"] self.assertEqual( "Error thrown from validate_new_email: 'Valid e-mail address required.'", field_errors["email"]["developer_message"] ) self.assertEqual("Valid e-mail address required.", field_errors["email"]["user_message"]) def test_patch_language_proficiencies(self): """ Verify that patching the language_proficiencies field of the user profile completely overwrites the previous value. """ client = self.login_client("client", "user") # Patching language_proficiencies exercises the # `LanguageProficiencySerializer.get_identity` method, which compares # identifies language proficiencies based on their language code rather # than django model id. for proficiencies in ([{"code": "en"}, {"code": "fr"}, {"code": "es"}], [{"code": "fr"}], [{"code": "aa"}], []): self.send_patch(client, {"language_proficiencies": proficiencies}) response = self.send_get(client) self.assertItemsEqual(response.data["language_proficiencies"], proficiencies) @ddt.data( (u"not_a_list", [{u'non_field_errors': [u'Expected a list of items.']}]), ([u"not_a_JSON_object"], [{u'non_field_errors': [u'Invalid data']}]), ([{}], [{"code": [u"This field is required."]}]), ([{u"code": u"invalid_language_code"}], [{'code': [u'Select a valid choice. invalid_language_code is not one of the available choices.']}]), ([{u"code": u"kw"}, {u"code": u"el"}, {u"code": u"kw"}], [u'The language_proficiencies field must consist of unique languages']), ) @ddt.unpack def test_patch_invalid_language_proficiencies(self, patch_value, expected_error_message): """ Verify we handle error cases when patching the language_proficiencies field. """ client = self.login_client("client", "user") response = self.send_patch(client, {"language_proficiencies": patch_value}, expected_status=400) self.assertEqual( response.data["field_errors"]["language_proficiencies"]["developer_message"], u"Value '{patch_value}' is not valid for field 'language_proficiencies': {error_message}".format(patch_value=patch_value, error_message=expected_error_message) ) @patch('openedx.core.djangoapps.user_api.accounts.serializers.AccountUserSerializer.save') def test_patch_serializer_save_fails(self, serializer_save): """ Test that AccountUpdateErrors are passed through to the response. """ serializer_save.side_effect = [Exception("bummer"), None] self.client.login(username=self.user.username, password=self.test_password) error_response = self.send_patch(self.client, {"goals": "save an account field"}, expected_status=400) self.assertEqual( "Error thrown when saving account updates: 'bummer'", error_response.data["developer_message"] ) self.assertIsNone(error_response.data["user_message"]) @override_settings(PROFILE_IMAGE_BACKEND=TEST_PROFILE_IMAGE_BACKEND) def test_convert_relative_profile_url(self): """ Test that when TEST_PROFILE_IMAGE_BACKEND['base_url'] begins with a '/', the API generates the full URL to profile images based on the URL of the request. """ self.client.login(username=self.user.username, password=self.test_password) response = self.send_get(self.client) self.assertEqual( response.data["profile_image"], { "has_image": False, "image_url_full": "http://testserver/static/default_50.png", "image_url_small": "http://testserver/static/default_10.png" } ) @ddt.data( ("client", "user", True), ("different_client", "different_user", False), ("staff_client", "staff_user", True), ) @ddt.unpack def test_parental_consent(self, api_client, requesting_username, has_full_access): """ Verifies that under thirteens never return a public profile. """ client = self.login_client(api_client, requesting_username) # Set the user to be ten years old with a public profile legacy_profile = UserProfile.objects.get(id=self.user.id) current_year = datetime.datetime.now().year legacy_profile.year_of_birth = current_year - 10 legacy_profile.save() set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, ALL_USERS_VISIBILITY) # Verify that the default view is still private (except for clients with full access) response = self.send_get(client) if has_full_access: data = response.data self.assertEqual(15, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"]) self.assertEqual(self.user.email, data["email"]) self.assertEqual(current_year - 10, data["year_of_birth"]) for empty_field in ("country", "level_of_education", "mailing_address", "bio"): self.assertIsNone(data[empty_field]) self.assertEqual("m", data["gender"]) self.assertEqual("Learn a lot", data["goals"]) self.assertTrue(data["is_active"]) self.assertIsNotNone(data["date_joined"]) self._verify_profile_image_data(data, False) self.assertTrue(data["requires_parental_consent"]) else: self._verify_private_account_response(response, requires_parental_consent=True) # Verify that the shared view is still private response = self.send_get(client, query_parameters='view=shared') self._verify_private_account_response(response, requires_parental_consent=True) @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class TestAccountAPITransactions(TransactionTestCase): """ Tests the transactional behavior of the account API """ test_password = "test" def setUp(self): super(TestAccountAPITransactions, self).setUp() self.client = APIClient() self.user = UserFactory.create(password=self.test_password) self.url = reverse("accounts_api", kwargs={'username': self.user.username}) @patch('student.views.do_email_change_request') def test_update_account_settings_rollback(self, mock_email_change): """ Verify that updating account settings is transactional when a failure happens. """ # Send a PATCH request with updates to both profile information and email. # Throw an error from the method that is used to process the email change request # (this is the last thing done in the api method). Verify that the profile did not change. mock_email_change.side_effect = [ValueError, "mock value error thrown"] self.client.login(username=self.user.username, password=self.test_password) old_email = self.user.email json_data = {"email": "foo@bar.com", "gender": "o"} response = self.client.patch(self.url, data=json.dumps(json_data), content_type="application/merge-patch+json") self.assertEqual(400, response.status_code) # Verify that GET returns the original preferences response = self.client.get(self.url) data = response.data self.assertEqual(old_email, data["email"]) self.assertEqual(u"m", data["gender"])
agpl-3.0
lduarte1991/edx-platform
lms/djangoapps/django_comment_client/permissions.py
5
9254
""" Module for checking permissions with the comment_client backend """ import logging from types import NoneType from opaque_keys.edx.keys import CourseKey from django_comment_common.models import CourseDiscussionSettings, all_permissions_for_user_in_course from django_comment_common.utils import get_course_discussion_settings from lms.djangoapps.teams.models import CourseTeam from lms.lib.comment_client import Thread from request_cache.middleware import RequestCache, request_cached def has_permission(user, permission, course_id=None): assert isinstance(course_id, (NoneType, CourseKey)) request_cache_dict = RequestCache.get_request_cache().data cache_key = "django_comment_client.permissions.has_permission.all_permissions.{}.{}".format( user.id, course_id ) if cache_key in request_cache_dict: all_permissions = request_cache_dict[cache_key] else: all_permissions = all_permissions_for_user_in_course(user, course_id) request_cache_dict[cache_key] = all_permissions return permission in all_permissions CONDITIONS = ['is_open', 'is_author', 'is_question_author', 'is_team_member_if_applicable'] @request_cached def get_team(commentable_id): """ Returns the team that the commentable_id belongs to if it exists. Returns None otherwise. """ try: team = CourseTeam.objects.get(discussion_topic_id=commentable_id) except CourseTeam.DoesNotExist: team = None return team def _check_condition(user, condition, content): """ Check whether or not the given condition applies for the given user and content. """ def check_open(_user, content): """ Check whether the content is open. """ try: return content and not content['closed'] except KeyError: return False def check_author(user, content): """ Check if the given user is the author of the content. """ try: return content and content['user_id'] == str(user.id) except KeyError: return False def check_question_author(user, content): """ Check if the given user is the author of the original question for both threads and comments. """ if not content: return False try: if content["type"] == "thread": return content["thread_type"] == "question" and content["user_id"] == str(user.id) else: # N.B. This will trigger a comments service query return check_question_author(user, Thread(id=content["thread_id"]).to_dict()) except KeyError: return False def check_team_member(user, content): """ If the content has a commentable_id, verifies that either it is not associated with a team, or if it is, that the user is a member of that team. """ if not content: return False try: commentable_id = content['commentable_id'] request_cache_dict = RequestCache.get_request_cache().data cache_key = u"django_comment_client.check_team_member.{}.{}".format(user.id, commentable_id) if cache_key in request_cache_dict: return request_cache_dict[cache_key] team = get_team(commentable_id) if team is None: passes_condition = True else: passes_condition = team.users.filter(id=user.id).exists() request_cache_dict[cache_key] = passes_condition except KeyError: # We do not expect KeyError in production-- it usually indicates an improper test mock. logging.warning("Did not find key commentable_id in content.") passes_condition = False return passes_condition handlers = { 'is_open': check_open, 'is_author': check_author, 'is_question_author': check_question_author, 'is_team_member_if_applicable': check_team_member } return handlers[condition](user, content) def _check_conditions_permissions(user, permissions, course_id, content, user_group_id=None, content_user_group=None): """ Accepts a list of permissions and proceed if any of the permission is valid. Note that ["can_view", "can_edit"] will proceed if the user has either "can_view" or "can_edit" permission. To use AND operator in between, wrap them in a list. """ def test(user, per, operator="or"): if isinstance(per, basestring): if per in CONDITIONS: return _check_condition(user, per, content) if 'group_' in per: # If a course does not have divided discussions # or a course has divided discussions, but the current user's content group does not equal # the content group of the commenter/poster, # then the current user does not have group edit permissions. division_scheme = get_course_discussion_settings(course_id).division_scheme if (division_scheme is CourseDiscussionSettings.NONE or user_group_id is None or content_user_group is None or user_group_id != content_user_group): return False return has_permission(user, per, course_id=course_id) elif isinstance(per, list) and operator in ["and", "or"]: results = [test(user, x, operator="and") for x in per] if operator == "or": return True in results elif operator == "and": return False not in results return test(user, permissions, operator="or") # Note: 'edit_content' is being used as a generic way of telling if someone is a privileged user # (forum Moderator/Admin/TA), because there is a desire that team membership does not impact privileged users. VIEW_PERMISSIONS = { 'update_thread': ['group_edit_content', 'edit_content', ['update_thread', 'is_open', 'is_author']], 'create_comment': ['group_edit_content', 'edit_content', ["create_comment", "is_open", "is_team_member_if_applicable"]], 'delete_thread': ['group_delete_thread', 'delete_thread', ['update_thread', 'is_author']], 'update_comment': ['group_edit_content', 'edit_content', ['update_comment', 'is_open', 'is_author']], 'endorse_comment': ['endorse_comment', 'is_question_author'], 'openclose_thread': ['group_openclose_thread', 'openclose_thread'], 'create_sub_comment': ['group_edit_content', 'edit_content', ['create_sub_comment', 'is_open', 'is_team_member_if_applicable']], 'delete_comment': ['group_delete_comment', 'delete_comment', ['update_comment', 'is_open', 'is_author']], 'vote_for_comment': ['group_edit_content', 'edit_content', ['vote', 'is_open', 'is_team_member_if_applicable']], 'undo_vote_for_comment': ['group_edit_content', 'edit_content', ['unvote', 'is_open', 'is_team_member_if_applicable']], 'vote_for_thread': ['group_edit_content', 'edit_content', ['vote', 'is_open', 'is_team_member_if_applicable']], 'flag_abuse_for_thread': ['group_edit_content', 'edit_content', ['vote', 'is_team_member_if_applicable']], 'un_flag_abuse_for_thread': ['group_edit_content', 'edit_content', ['vote', 'is_team_member_if_applicable']], 'flag_abuse_for_comment': ['group_edit_content', 'edit_content', ['vote', 'is_team_member_if_applicable']], 'un_flag_abuse_for_comment': ['group_edit_content', 'edit_content', ['vote', 'is_team_member_if_applicable']], 'undo_vote_for_thread': ['group_edit_content', 'edit_content', ['unvote', 'is_open', 'is_team_member_if_applicable']], 'pin_thread': ['group_openclose_thread', 'openclose_thread'], 'un_pin_thread': ['group_openclose_thread', 'openclose_thread'], 'follow_thread': ['group_edit_content', 'edit_content', ['follow_thread', 'is_team_member_if_applicable']], 'follow_commentable': ['group_edit_content', 'edit_content', ['follow_commentable', 'is_team_member_if_applicable']], 'unfollow_thread': ['group_edit_content', 'edit_content', ['unfollow_thread', 'is_team_member_if_applicable']], 'unfollow_commentable': ['group_edit_content', 'edit_content', ['unfollow_commentable', 'is_team_member_if_applicable']], 'create_thread': ['group_edit_content', 'edit_content', ['create_thread', 'is_team_member_if_applicable']], } def check_permissions_by_view(user, course_id, content, name, group_id=None, content_user_group=None): assert isinstance(course_id, CourseKey) p = None try: p = VIEW_PERMISSIONS[name] except KeyError: logging.warning("Permission for view named %s does not exist in permissions.py", name) return _check_conditions_permissions(user, p, course_id, content, group_id, content_user_group)
agpl-3.0
a25kk/bfa
src/bfa.sitecontent/bfa/sitecontent/widgets/content/video.py
1
4222
# -*- coding: utf-8 -*- """Module providing event filter widget""" import uuid as uuid_tool from Acquisition import aq_inner from Products.Five import BrowserView from plone import api from plone.i18n.normalizer import IIDNormalizer from wildcard.media.behavior import IVideo from zope.component import queryUtility class WidgetContentVideoCard(BrowserView): """ Basic context content card """ def __call__(self, widget_data=None, widget_mode="view", **kw): self.params = {"widget_mode": widget_mode, "widget_data": widget_data} return self.render() def render(self): return self.index() @staticmethod def can_edit(): return not api.user.is_anonymous() @property def record(self): return self.params['widget_data'] def has_content(self): if self.widget_content(): return True return False def widget_uid(self): try: widget_id = self.record['id'] except (KeyError, TypeError): widget_id = str(uuid_tool.uuid4()) return widget_id @staticmethod def normalizer(): return queryUtility(IIDNormalizer) def card_subject_classes(self, item): context = item subjects = context.Subject() class_list = [ "c-card-tag--{0}".format(self.normalizer().normalize(keyword)) for keyword in subjects ] return class_list def card_css_classes(self, item): class_list = self.card_subject_classes(item) if class_list: return " ".join(class_list) else: return "c-card-tag--all" @staticmethod def has_image(context): try: lead_img = context.image except AttributeError: lead_img = None if lead_img is not None: return True return False @staticmethod def has_animated_cover(context): try: animated_lead_img = context.image_animated except AttributeError: animated_lead_img = None if animated_lead_img is not None: return True return False @staticmethod def get_standalone_image_caption(context): try: caption = context.image_caption except AttributeError: caption = None return caption def get_embed_url(self): """ Try to guess video id from a various case of possible youtube urls and returns the correct url for embed. For example: - 'https://youtu.be/VIDEO_ID' - 'https://www.youtube.com/watch?v=VIDEO_ID' - 'https://www.youtube.com/embed/2Lb2BiUC898' """ video_behavior = IVideo(self.context) if not video_behavior: return "" video_id = video_behavior.get_youtube_id_from_url() if not video_id: return "" return "https://www.youtube.com/embed/" + video_id def get_edit_url(self): """ If the user can edit the video, returns the edit url. """ if not api.user.has_permission( 'Modify portal content', obj=self.context): return "" from plone.protect.utils import addTokenToUrl url = "%s/@@edit" % self.context.absolute_url() return addTokenToUrl(url) def widget_content(self): context = aq_inner(self.context) widget_data = self.params["widget_data"] if widget_data and "uuid" in widget_data: context = api.content.get(UID=widget_data["uuid"]) details = { "title": context.Title(), "description": context.Description(), "url": context.absolute_url(), "timestamp": context.Date, "uuid": context.UID(), "has_image": self.has_image(context), "has_animated_cover": self.has_animated_cover(context), "image_caption": self.get_standalone_image_caption(context), "css_classes": "c-card--{0} {1}".format( context.UID(), self.card_css_classes(context) ), "content_item": context, } return details
mit
damomeen/pox-datapath
pox/messenger/__init__.py
25
19645
# Copyright 2011,2012 James McCauley # # This file is part of POX. # # POX 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. # # POX 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 POX. If not, see <http://www.gnu.org/licenses/>. """ The POX Messenger system. The Messenger system is a way to build services in POX that can be consumed by external clients. Sometimes a controller might need to interact with the outside world. Sometimes you need to integrate with an existing piece of software and maybe you don't get to choose how you communicate with it. Other times, you have the opportunity and burden of rolling your own. The Messenger system is meant to help you with the latter case. In short, channels are a system for communicating between POX and external programs by exchanging messages encoded in JSON. It is intended to be quite general, both in the communication models it supports and in the transports is supports (as of this writing, it supports a straightforward TCP socket transport and an HTTP transport). Any service written to use the Messenger should theoretically be usable via any transport. *Connections* are somehow established when a client connects via some *Transport*. The server can individually send messages to a specific client. A client can send messages to a *Channel* on the server. A client can also become a member of a channel, after which it will receive any messages the server sends to that channel. There is always a default channel with no name. Channels can either be permanent or temporary. Temporary channels are automatically destroyed when they no longer contain any members. """ from pox.lib.revent.revent import * from pox.core import core as core import json import time import random import hashlib from base64 import b32encode log = core.getLogger() # JSON decoder used by default defaultDecoder = json.JSONDecoder() class ChannelJoin (Event): """ Fired on a channel when a client joins. """ def __init__ (self, connection, channel, msg = {}): Event.__init__(self) self.con = connection self.channel = channel self.msg = msg class ConnectionClosed (Event): """ Fired on a connection when it closes. """ def __init__ (self, connection): Event.__init__(self) self.con = connection class ChannelLeave (Event): """ Fired on a channel when a client leaves. """ def __init__ (self, connection, channel): Event.__init__(self) self.con = connection self.channel = channel class ChannelCreate (Event): """ Fired on a Nexus when a channel is created. """ def __init__ (self, channel): Event.__init__(self) self.channel = channel class ChannelDestroy (Event): """ Fired on the channel and its Nexus right before a channel is destroyed. Set .keep = True to keep the channel after all. """ def __init__ (self, channel): Event.__init__(self) self.channel = channel self.keep = False class ChannelDestroyed (Event): """ Fired on the channel and its Nexus right after a channel is destroyed. """ def __init__ (self, channel): Event.__init__(self) self.channel = channel class MissingChannel (Event): """ Fired on a Nexus when a message has been received to a non-existant channel. You can create the channel in response to this. """ def __init__ (self, connection, channel_name, msg): Event.__init__(self) self.con = connection self.channel_name = channel_name self.msg = msg class MessageReceived (Event): """ Fired by a channel when a message has been receieved. Always fired on the Connection itself. Also fired on the corresponding Channel object as specified by the CHANNEL key. The listener looks like: def _handle_MessageReceived (event, msg): """ def __init__ (self, connection, channel, msg): Event.__init__(self) self.con = connection self.msg = msg self.channel = channel def is_to_channel (self, channel): """ Returns True if this message is to the given channel """ if isinstance(channel, Channel): channel = channel.name if channel == self.channel: return True if channel in self.channel: return True return False def _invoke (self, handler, *args, **kw): # Special handling -- pass the message return handler(self, self.msg, *args, **kw) def _get_nexus (nexus): if nexus is None: nexus = "MessengerNexus" if isinstance(nexus, str): if not core.hasComponent(nexus): #TODO: Wait for channel Nexus s = "MessengerNexus %s is not available" % (nexus,) log.error(s) raise RuntimeError(s) return getattr(core, nexus) assert isinstance(nexus, MessengerNexus) return nexus class Transport (object): def __init__ (self, nexus): self._nexus = _get_nexus(nexus) def _forget (self, connection): """ Forget about a connection """ raise RuntimeError("Not implemented") class Connection (EventMixin): """ Superclass for Connections. This could actually be a bit thinner, if someone wants to clean it up. Maintains the state and handles message parsing and dispatch for a single connection. """ _eventMixin_events = set([ MessageReceived, ConnectionClosed, ]) def __init__ (self, transport): """ transport is the source of the connection (e.g, TCPTransport). """ EventMixin.__init__(self) self._is_connected = True self._transport = transport self._newlines = False # Transports that don't do their own encapsulation can use _recv_raw(), # which uses this. (Such should probably be broken into a subclass.) self._buf = bytes() key,num = self._transport._nexus.generate_session() self._session_id,self._session_num = key,num def _send_welcome (self): """ Send a message to a client so they know they're connected """ self.send({"CHANNEL":"","cmd":"welcome","session_id":self._session_id}) def _close (self): """ Called internally to shut the connection down. """ if self._is_connected is False: return self._transport._forget(self) self._is_connected = False for name,chan in self._transport._nexus._channels.items(): chan._remove_member(self) self.raiseEventNoErrors(ConnectionClosed, self) #self._transport._nexus.raiseEventNoErrors(ConnectionClosed, self) def send (self, whatever): """ Send data over the connection. It will first be encoded into JSON, and optionally followed with a newline. Ultimately, it will be passed to send_raw() to actually be sent. """ if self._is_connected is False: return False s = json.dumps(whatever, default=str) if self._newlines: s += "\n" self.send_raw(s) return True def send_raw (self, data): """ This method should actually send data out over the connection. Subclasses need to implement this. """ raise RuntimeError("Not implemented") @property def is_connected (self): """ True if this Connection is still connected. """ return self._is_connected def _rx_message (self, msg): """ Raises events when a complete message is available. Subclasses may want to call this when they have a new message available. See _recv_raw(). """ e = self.raiseEventNoErrors(MessageReceived,self,msg.get('CHANNEL'),msg) self._transport._nexus._rx_message(self, msg) def _rx_raw (self, data): """ If your subclass receives a stream instead of discrete messages, this method can parse out individual messages and call _recv_msg() when it has full messages. """ if len(data) == 0: return if len(self._buf) == 0: if data[0].isspace(): self._buf = data.lstrip() else: self._buf = data else: self._buf += data while len(self._buf) > 0: try: msg, l = defaultDecoder.raw_decode(self._buf) except: # Need more data before it's a valid message # (.. or the stream is corrupt and things will never be okay # ever again) return self._buf = self._buf[l:] if len(self._buf) != 0 and self._buf[0].isspace(): self._buf = self._buf.lstrip() self._rx_message(msg) def __str__ (self): """ Subclasses should implement better versions of this. """ return "<%s/%s/%i>" % (self.__class__.__name__, self._session_id, self._session_num) def close (self): """ Close the connection. """ self._close() class Channel (EventMixin): """ Allows one to easily listen to only messages that have a CHANNEL key with a specific name. Generally you will not create these classes directly, but by calling getChannel() on the ChannelNexus. """ _eventMixin_events = set([ MessageReceived, ChannelJoin, # Immedaitely when a connection goes up ChannelLeave, # When a connection goes down ChannelDestroy, ChannelDestroyed, ]) def __init__ (self, name, nexus = None, temporary = False): """ name is the name for the channel (i.e., the value for the messages' CHANNEL key). nexus is the specific MessengerNexus with which this channel is to be associated (defaults to core.MessengerNexus). """ EventMixin.__init__(self) assert isinstance(name, basestring) self._name = name self._nexus = _get_nexus(nexus) self._nexus._channels[name] = self self.temporary = temporary self._members = set() # Member Connections @property def name (self): return self._name def _destroy (self): """ Remove channel """ e = self.raiseEvent(ChannelDestroy, self) if e: if e.keep: return False self._nexus.raiseEvent(e) if e.keep: return False del self._nexus._channels[self._name] # We can't just do the follow because then listeners # can't tell if the channel is now empty... #for sub in set(self._members): # sub.raiseEvent(ChannelLeave, sub, self) # #self._members.clear() # .. so do the following really straightforward... for sub in set(self._members): self._remove_member(sub, allow_destroy = False) e = ChannelDestroyed(self) self.raiseEvent(e) self._nexus.raiseEvent(e) def _add_member (self, con, msg = {}): if con in self._members: return self._members.add(con) self.raiseEvent(ChannelJoin, con, self, msg) def _remove_member (self, con, allow_destroy = True): if con not in self._members: return self._members.remove(con) self.raiseEvent(ChannelLeave, con, self) if not allow_destroy: return if self.temporary is True: if len(self._members) == 0: self._destroy() def send (self, msg): d = dict(msg) d['CHANNEL'] = self._name for r in self._members: if not r.is_connected: continue r.send(d) def __str__ (self): return "<Channel " + self.name + ">" def reply (_msg, **kw): if not isinstance(_msg, dict): # We'll also take an event... _msg = _msg.msg kw['CHANNEL'] = _msg.get('CHANNEL') if 'XID' in _msg: kw['XID'] = _msg.get('XID') return kw class ChannelBot (object): """ A very simple framework for writing "bots" that respond to messages on a channel. """ def __str__ (self): return "<%s@%s>" % (self.__class__.__name__, self.channel) def __init__ (self, channel, nexus = None, weak = False, extra = {}): self._startup(channel, nexus, weak, extra) def _startup (self, channel, nexus = None, weak = False, extra = {}): self._nexus = _get_nexus(nexus) if isinstance(channel, Channel): self.channel = channel else: self.channel = self._nexus.get_channel(channel, create=True) self.listeners = self.channel.addListeners(self, weak = weak) self.prefixes = None self._init(extra) if self.prefixes is None: self.prefixes = [] for n in dir(self): if n.startswith("_exec_"): n = n.split("_")[2] self.prefixes.append(n) def _handle_ChannelDestroyed (self, event): self.channel.removeListeners(self.listeners) self._destroyed() def _handle_ChannelJoin (self, event): self._join(event, event.con, event.msg) def _handle_ChannelLeave (self, event): self._leave(event.con, len(self.channel._members) == 0) def _handle_MessageReceived (self, event, msg): for prefix in self.prefixes: if prefix in event.msg: cmd = "_exec_%s_%s" % (prefix, str(event.msg[prefix])) if hasattr(self, cmd): getattr(self, cmd)(event) return #TODO: Return val? for prefix in self.prefixes: if prefix in event.msg: cmd = "_exec_" + prefix if hasattr(self, cmd): getattr(self, cmd)(event, msg[prefix]) return #TODO: Return val? self._unhandled(event) def _unhandled (self, event): """ Called when no command found """ pass def _join (self, event, connection, msg): """ Called when a connection joins """ pass def _leave (self, connection, empty): """ Called when a connection leaves If channel now has no members, empty is True """ pass def _destroyed (self): """ Called when channel is destroyed """ pass def _init (self, extra): """ Called during initialization 'extra' is any additional information passed in when initializing the bot. In particular, this may be the message that goes along with its invitation into a channel. """ pass def reply (__self, __event, **kw): """ Unicast reply to a specific message. """ __event.con.send(reply(__event, **kw)) def send (__self, __msg={}, **kw): """ Send a message to all members of this channel. """ m = {} m.update(__msg) m.update(kw) __self.channel.send(m) class DefaultChannelBot (ChannelBot): def _init (self, extra): self._bots = {} def add_bot (self, bot, name = None): """ Registers a bot (an instance of ChannelBot) so that it can be invited to other channels. """ assert issubclass(bot, ChannelBot) if name is None: name = bot.__name__ self._bots[name] = bot def _exec_newlines_False (self, event): event.con._newlines = False def _exec_newlines_True (self, event): event.con._newlines = True def _exec_cmd_invite (self, event): """ Invites a bot that has been registered with add_bot() to a channel. Note that you can invite a bot to an empty (new) temporary channel. It will stay until the first member leaves. """ botname = event.msg.get('bot') botclass = self._bots.get(botname) channel = event.msg.get('channel') new_channel = False if channel is None: new_channel = True channel = self._gen_channel_name(event.msg.get("prefix", "temp")) chan = self._nexus.get_channel(channel, create=True, temporary=True) if chan is None: #TODO: send an error log.warning("A bot was invited to a nonexistent channel (%s)" % (channel,)) return if botclass is None: #TODO: send an error log.warning("A nonexistent bot (%s) was invited to a channel" % (botname,)) return bot = botclass(channel, self._nexus) if new_channel: self.reply(event, new_channel = new_channel) def _unhandled (self, event): log.warn("Default channel got unknown command: " + str(event.msg.get('cmd'))) def _gen_channel_name (self, prefix = "temp"): """ Makes up a channel name """ prefix += "_" import random while True: # Sloppy r = random.randint(1, 100000) n = prefix + str(r) if r not in self._nexus._channels: break return n def _exec_cmd_new_channel (self, event): """ Generates a new channel with random name """ prefix = event.msg.get('prefix', 'temp') n = self._gen_channel_name(prefix) ch = self._nexus.get_channel(n, create=True, temporary=True) ch._add_member(event.con, event.msg) self.reply(event, new_channel = n) def _exec_cmd_join_channel (self, event): """ Joins/creates a channel """ temp = event.msg.get('temporary', True) # Default temporary! ch = self._nexus.get_channel(event.msg['channel'], temporary=temp) if ch is None: return ch._add_member(event.con, event.msg) def _exec_cmd_leave_channel (self, event): ch = self._nexus.get_channel(event.msg['channel']) if ch is None: return ch._remove_member(event.con) def _exec_test (self, event, value): log.info("Default channel got: " + str(value)) self.reply(event, test = value.upper()) class MessengerNexus (EventMixin): """ Transports, Channels, etc. are all associated with a MessengerNexus. Typically, there is only one, and it is registered as pox.core.MessengerNexus """ _eventMixin_events = set([ MissingChannel, # When a msg arrives to nonexistent channel ChannelDestroy, ChannelDestroyed, ChannelCreate, ]) def __init__ (self): EventMixin.__init__(self) self._channels = {} # name -> Channel self.default_bot = DefaultChannelBot("", self) self._next_ses = 1 self._session_salt = str(time.time()) def generate_session (self): """ Return a new session ID tuple (key, num) The key is a unique and not-trivial-to-guess alphanumeric value associated with the session. The num is a unique numerical value associated with the session. """ r = self._next_ses self._next_ses += 1 key = str(random.random()) + str(time.time()) + str(r) key += str(id(key)) + self._session_salt key = b32encode(hashlib.md5(key).digest()).upper().replace('=','') def alphahex (r): """ base 16 on digits 'a' through 'p' """ r=hex(r)[2:].lower() return ''.join(chr((10 if ord(x) >= 97 else 49) + ord(x)) for x in r) key = alphahex(r) + key return key,r def get_channel (self, name, create = True, temporary = False): if name is None: name = "" if name in self._channels: return self._channels[name] elif create: c = Channel(name, self, temporary = temporary) self.raiseEvent(ChannelCreate, c) return c else: return None def _rx_message (self, con, msg): """ Dispatches messages to listeners of this nexus and to its Channels. Called by Connections. """ ret = False assert isinstance(msg, dict) if isinstance(msg, dict): channels = msg.get('CHANNEL') if channels is None: channels = [""] if not isinstance(channels, list): channels = [channels] for cname in channels: channel = self.get_channel(cname, create=False) if channel is None: e = self.raiseEvent(MissingChannel, con, cname, msg) if e is not None: cname = e.channel_name channel = self.get_channel(cname, create=False) if channel is not None: #print "raise on", channel channel.raiseEvent(MessageReceived, con, channel, msg) ret = True return ret def launch (): core.registerNew(MessengerNexus)
apache-2.0
lgarren/spack
var/spack/repos/builtin/packages/r-affycomp/package.py
1
1773
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser 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 ############################################################################## from spack import * class RAffycomp(RPackage): """The package contains functions that can be used to compare expression measures for Affymetrix Oligonucleotide Arrays.""" homepage = "https://www.bioconductor.org/packages/affycomp/" url = "https://git.bioconductor.org/packages/affycomp" version('1.52.0', git='https://git.bioconductor.org/packages/affycomp', commit='1b97a1cb21ec93bf1e5c88d5d55b988059612790') depends_on('r@3.4.0:3.4.9', when='@1.52.0') depends_on('r-biobase', type=('build', 'run'))
lgpl-2.1
lostdj/Jaklin-OpenJFX
modules/web/src/main/native/Tools/Scripts/webkitpy/tool/commands/newcommitbot.py
119
7612
# Copyright (c) 2012 Google Inc. All rights reserved. # Copyright (c) 2013 Apple 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. import logging import re from webkitpy.common.config.committers import CommitterList from webkitpy.common.system.executive import ScriptError from webkitpy.tool.bot.irc_command import IRCCommand from webkitpy.tool.bot.irc_command import Help from webkitpy.tool.bot.irc_command import Hi from webkitpy.tool.bot.irc_command import PingPong from webkitpy.tool.bot.irc_command import Restart from webkitpy.tool.bot.irc_command import YouThere from webkitpy.tool.bot.ircbot import IRCBot from webkitpy.tool.commands.queues import AbstractQueue from webkitpy.tool.commands.stepsequence import StepSequenceErrorHandler _log = logging.getLogger(__name__) class Agent(object): def __init__(self, tool, newcommitbot): self._tool = tool self._newcommitbot = newcommitbot def name(self): return 'WKR' class NewCommitBot(AbstractQueue, StepSequenceErrorHandler): name = "WKR" watchers = AbstractQueue.watchers + ["rniwa@webkit.org"] _commands = { "hi": Hi, "ping": PingPong, "restart": Restart, "yt?": YouThere, } _maximum_number_of_revisions_to_avoid_spamming_irc = 10 # AbstractQueue methods def begin_work_queue(self): AbstractQueue.begin_work_queue(self) self._last_svn_revision = int(self._tool.scm().head_svn_revision()) self._irc_bot = IRCBot(self.name, self._tool, Agent(self._tool, self), self._commands) self._tool.ensure_irc_connected(self._irc_bot.irc_delegate()) def work_item_log_path(self, failure_map): return None def next_work_item(self): self._irc_bot.process_pending_messages() _log.info('Last SVN revision: %d' % self._last_svn_revision) count = 0 while count < self._maximum_number_of_revisions_to_avoid_spamming_irc: new_revision = self._last_svn_revision + 1 try: commit_log = self._tool.executive.run_command(['svn', 'log', 'https://svn.webkit.org/repository/webkit/trunk', '--non-interactive', '--revision', self._tool.scm().strip_r_from_svn_revision(new_revision)]) except ScriptError: break self._last_svn_revision = new_revision if self._is_empty_log(commit_log): continue count += 1 _log.info('Found revision %d' % new_revision) self._tool.irc().post(self._summarize_commit_log(commit_log).encode('utf-8')) def _is_empty_log(self, commit_log): return re.match(r'^\-+$', commit_log) def process_work_item(self, failure_map): return True _patch_by_regex = re.compile(r'^Patch\s+by\s+(?P<author>.+?)\s+on(\s+\d{4}-\d{2}-\d{2})?\n?', re.MULTILINE | re.IGNORECASE) _rollout_regex = re.compile(r'(rolling out|reverting) (?P<revisions>r?\d+((,\s*|,?\s*and\s+)?r?\d+)*)\.?\s*', re.MULTILINE | re.IGNORECASE) _requested_by_regex = re.compile(r'^\"?(?P<reason>.+?)\"? \(Requested\s+by\s+(?P<author>.+?)\s+on\s+#webkit\)\.', re.MULTILINE | re.IGNORECASE) _bugzilla_url_regex = re.compile(r'http(s?)://bugs\.webkit\.org/show_bug\.cgi\?id=(?P<id>\d+)', re.MULTILINE) _trac_url_regex = re.compile(r'http(s?)://trac.webkit.org/changeset/(?P<revision>\d+)', re.MULTILINE) @classmethod def _summarize_commit_log(self, commit_log, committer_list=CommitterList()): patch_by = self._patch_by_regex.search(commit_log) commit_log = self._patch_by_regex.sub('', commit_log, count=1) rollout = self._rollout_regex.search(commit_log) commit_log = self._rollout_regex.sub('', commit_log, count=1) requested_by = self._requested_by_regex.search(commit_log) commit_log = self._bugzilla_url_regex.sub(r'https://webkit.org/b/\g<id>', commit_log) commit_log = self._trac_url_regex.sub(r'https://trac.webkit.org/r\g<revision>', commit_log) for contributor in committer_list.contributors(): if not contributor.irc_nicknames: continue name_with_nick = "%s (%s)" % (contributor.full_name, contributor.irc_nicknames[0]) if contributor.full_name in commit_log: commit_log = commit_log.replace(contributor.full_name, name_with_nick) for email in contributor.emails: commit_log = commit_log.replace(' <' + email + '>', '') else: for email in contributor.emails: commit_log = commit_log.replace(email, name_with_nick) lines = commit_log.split('\n')[1:-2] # Ignore lines with ----------. firstline = re.match(r'^(?P<revision>r\d+) \| (?P<email>[^\|]+) \| (?P<timestamp>[^|]+) \| [^\n]+', lines[0]) assert firstline author = firstline.group('email') if patch_by: author = patch_by.group('author') linkified_revision = 'https://trac.webkit.org/%s' % firstline.group('revision') lines[0] = '%s by %s' % (linkified_revision, author) if rollout: if requested_by: author = requested_by.group('author') contributor = committer_list.contributor_by_irc_nickname(author) if contributor: author = "%s (%s)" % (contributor.full_name, contributor.irc_nicknames[0]) return '%s rolled out %s in %s : %s' % (author, rollout.group('revisions'), linkified_revision, requested_by.group('reason')) lines[0] = '%s rolled out %s in %s' % (author, rollout.group('revisions'), linkified_revision) return ' '.join(filter(lambda line: len(line), lines)[0:4]) def handle_unexpected_error(self, failure_map, message): _log.error(message) # StepSequenceErrorHandler methods @classmethod def handle_script_error(cls, tool, state, script_error): # Ideally we would post some information to IRC about what went wrong # here, but we don't have the IRC password in the child process. pass
gpl-2.0
edx/edx-platform
openedx/core/djangoapps/enrollments/tests/fake_data_api.py
9
4333
""" A Fake Data API for testing purposes. """ import copy import datetime _DEFAULT_FAKE_MODE = { "slug": "honor", "name": "Honor Code Certificate", "min_price": 0, "suggested_prices": "", "currency": "usd", "expiration_datetime": None, "description": None } _ENROLLMENTS = [] _COURSES = [] _ENROLLMENT_ATTRIBUTES = [] _VERIFIED_MODE_EXPIRED = [] # pylint: disable=unused-argument def get_course_enrollments(student_id, include_inactive=False): """Stubbed out Enrollment data request.""" return _ENROLLMENTS def get_course_enrollment(student_id, course_id): """Stubbed out Enrollment data request.""" return _get_fake_enrollment(student_id, course_id) def create_course_enrollment(student_id, course_id, mode='honor', is_active=True): """Stubbed out Enrollment creation request. """ return add_enrollment(student_id, course_id, mode=mode, is_active=is_active) def update_course_enrollment(student_id, course_id, mode=None, is_active=None): """Stubbed out Enrollment data request.""" enrollment = _get_fake_enrollment(student_id, course_id) if enrollment and mode is not None: enrollment['mode'] = mode if enrollment and is_active is not None: enrollment['is_active'] = is_active return enrollment def get_course_enrollment_info(course_id, include_expired=False): """Stubbed out Enrollment data request.""" return _get_fake_course_info(course_id, include_expired) def _get_fake_enrollment(student_id, course_id): """Get an enrollment from the enrollments array.""" for enrollment in _ENROLLMENTS: if student_id == enrollment['student'] and course_id == enrollment['course']['course_id']: return enrollment def _get_fake_course_info(course_id, include_expired=False): """Get a course from the courses array.""" # if verified mode is expired and include expired is false # then remove the verified mode from the course. for course in _COURSES: if course_id == course['course_id']: if course_id in _VERIFIED_MODE_EXPIRED and not include_expired: course['course_modes'] = [mode for mode in course['course_modes'] if mode['slug'] != 'verified'] return course def add_enrollment(student_id, course_id, is_active=True, mode='honor'): """Append an enrollment to the enrollments array.""" enrollment = { "created": datetime.datetime.now(), "mode": mode, "is_active": is_active, "course": _get_fake_course_info(course_id), "student": student_id } _ENROLLMENTS.append(enrollment) return enrollment # pylint: disable=unused-argument def add_or_update_enrollment_attr(user_id, course_id, attributes): """Add or update enrollment attribute array""" for attribute in attributes: _ENROLLMENT_ATTRIBUTES.append({ 'namespace': attribute['namespace'], 'name': attribute['name'], 'value': attribute['value'] }) # pylint: disable=unused-argument def get_enrollment_attributes(user_id, course_id): """Retrieve enrollment attribute array""" return _ENROLLMENT_ATTRIBUTES def set_expired_mode(course_id): """Set course verified mode as expired.""" _VERIFIED_MODE_EXPIRED.append(course_id) def add_course(course_id, enrollment_start=None, enrollment_end=None, invite_only=False, course_modes=None): """Append course to the courses array.""" course_info = { "course_id": course_id, "enrollment_end": enrollment_end, "course_modes": [], "enrollment_start": enrollment_start, "invite_only": invite_only, } if not course_modes: course_info['course_modes'].append(_DEFAULT_FAKE_MODE) else: for mode in course_modes: new_mode = copy.deepcopy(_DEFAULT_FAKE_MODE) new_mode['slug'] = mode course_info['course_modes'].append(new_mode) _COURSES.append(course_info) def reset(): """Set the enrollments and courses arrays to be empty.""" global _COURSES # pylint: disable=global-statement _COURSES = [] global _ENROLLMENTS # pylint: disable=global-statement _ENROLLMENTS = [] global _VERIFIED_MODE_EXPIRED # pylint: disable=global-statement _VERIFIED_MODE_EXPIRED = []
agpl-3.0
JohnGriffiths/nipype
nipype/utils/misc.py
9
7047
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Miscellaneous utility functions """ from cPickle import dumps, loads import inspect from distutils.version import LooseVersion import numpy as np from textwrap import dedent import sys import re from nipype.external.six import Iterator def human_order_sorted(l): """Sorts string in human order (i.e. 'stat10' will go after 'stat2')""" def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): if isinstance(text, tuple): text = text[0] return [ atoi(c) for c in re.split('(\d+)', text) ] return sorted(l, key=natural_keys) def trim(docstring, marker=None): if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxint for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxint: for line in lines[1:]: # replace existing REST marker with doc level marker stripped = line.lstrip().strip().rstrip() if marker is not None and stripped and \ all([s==stripped[0] for s in stripped]) and \ stripped[0] not in [':']: line = line.replace(stripped[0], marker) trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed) def getsource(function): """Returns the source code of a function""" src = dumps(dedent(inspect.getsource(function))) return src def create_function_from_source(function_source, imports=None): """Return a function object from a function source Parameters ---------- function_source : pickled string string in pickled form defining a function imports : list of strings list of import statements in string form that allow the function to be executed in an otherwise empty namespace """ ns = {} import_keys = [] try: if imports is not None: for statement in imports: exec statement in ns import_keys = ns.keys() exec loads(function_source) in ns except Exception, msg: msg = str(msg) + '\nError executing function:\n %s\n'%function_source msg += '\n'.join(["Functions in connection strings have to be standalone.", "They cannot be declared either interactively or inside", "another function or inline in the connect string. Any", "imports should be done inside the function" ]) raise RuntimeError(msg) ns_funcs = list(set(ns) - set(import_keys + ['__builtins__'])) assert len(ns_funcs) == 1, "Function or inputs are ill-defined" funcname = ns_funcs[0] func = ns[funcname] return func def find_indices(condition): "Return the indices where ravel(condition) is true" res, = np.nonzero(np.ravel(condition)) return res def is_container(item): """Checks if item is a container (list, tuple, dict, set) Parameters ---------- item : object object to check for .__iter__ Returns ------- output : Boolean True if container False if not (eg string) """ if hasattr(item, '__iter__'): return True else: return False def container_to_string(cont): """Convert a container to a command line string. Elements of the container are joined with a space between them, suitable for a command line parameter. If the container `cont` is only a sequence, like a string and not a container, it is returned unmodified. Parameters ---------- cont : container A container object like a list, tuple, dict, or a set. Returns ------- cont_str : string Container elements joined into a string. """ if hasattr(cont, '__iter__'): return ' '.join(cont) else: return str(cont) # Dependency checks. Copied this from Nipy, with some modificiations # (added app as a parameter). def package_check(pkg_name, version=None, app=None, checker=LooseVersion, exc_failed_import=ImportError, exc_failed_check=RuntimeError): """Check that the minimal version of the required package is installed. Parameters ---------- pkg_name : string Name of the required package. version : string, optional Minimal version number for required package. app : string, optional Application that is performing the check. For instance, the name of the tutorial being executed that depends on specific packages. Default is *Nipype*. checker : object, optional The class that will perform the version checking. Default is distutils.version.LooseVersion. exc_failed_import : Exception, optional Class of the exception to be thrown if import failed. exc_failed_check : Exception, optional Class of the exception to be thrown if version check failed. Examples -------- package_check('numpy', '1.3') package_check('networkx', '1.0', 'tutorial1') """ if app: msg = '%s requires %s' % (app, pkg_name) else: msg = 'Nipype requires %s' % pkg_name if version: msg += ' with version >= %s' % (version,) try: mod = __import__(pkg_name) except ImportError: raise exc_failed_import(msg) if not version: return try: have_version = mod.__version__ except AttributeError: raise exc_failed_check('Cannot find version for %s' % pkg_name) if checker(have_version) < checker(version): raise exc_failed_check(msg) def str2bool(v): if isinstance(v, bool): return v lower = v.lower() if lower in ("yes", "true", "t", "1"): return True elif lower in ("no", "false", "n", "f", "0"): return False else: raise ValueError("%s cannot be converted to bool"%v) def flatten(S): if S == []: return S if isinstance(S[0], list): return flatten(S[0]) + flatten(S[1:]) return S[:1] + flatten(S[1:]) def unflatten(in_list, prev_structure): if not isinstance(in_list, Iterator): in_list = iter(in_list) if not isinstance(prev_structure, list): return in_list.next() else: out = [] for item in prev_structure: out.append(unflatten(in_list, item)) return out
bsd-3-clause
analogue/mythbox
resources/lib/twisted/twisted/python/test/test_release.py
56
95755
# Copyright (c) 2007-2010 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.python.release} and L{twisted.python._release}. All of these tests are skipped on platforms other than Linux, as the release is only ever performed on Linux. """ import warnings import operator import os, sys, signal from StringIO import StringIO import tarfile from xml.dom import minidom as dom from datetime import date from twisted.trial.unittest import TestCase from twisted.python.compat import set from twisted.python.procutils import which from twisted.python import release from twisted.python.filepath import FilePath from twisted.python.versions import Version from twisted.python._release import _changeVersionInFile, getNextVersion from twisted.python._release import findTwistedProjects, replaceInFile from twisted.python._release import replaceProjectVersion from twisted.python._release import updateTwistedVersionInformation, Project from twisted.python._release import generateVersionFileData from twisted.python._release import changeAllProjectVersions from twisted.python._release import VERSION_OFFSET, DocBuilder, ManBuilder from twisted.python._release import NoDocumentsFound, filePathDelta from twisted.python._release import CommandFailed, BookBuilder from twisted.python._release import DistributionBuilder, APIBuilder from twisted.python._release import BuildAPIDocsScript from twisted.python._release import buildAllTarballs, runCommand from twisted.python._release import UncleanWorkingDirectory, NotWorkingDirectory from twisted.python._release import ChangeVersionsScript, BuildTarballsScript from twisted.python._release import NewsBuilder if os.name != 'posix': skip = "Release toolchain only supported on POSIX." else: skip = None # Check a bunch of dependencies to skip tests if necessary. try: from twisted.lore.scripts import lore except ImportError: loreSkip = "Lore is not present." else: loreSkip = skip try: import pydoctor.driver # it might not be installed, or it might use syntax not available in # this version of Python. except (ImportError, SyntaxError): pydoctorSkip = "Pydoctor is not present." else: if getattr(pydoctor, "version_info", (0,)) < (0, 1): pydoctorSkip = "Pydoctor is too old." else: pydoctorSkip = skip if which("latex") and which("dvips") and which("ps2pdf13"): latexSkip = skip else: latexSkip = "LaTeX is not available." if which("svn") and which("svnadmin"): svnSkip = skip else: svnSkip = "svn or svnadmin is not present." def genVersion(*args, **kwargs): """ A convenience for generating _version.py data. @param args: Arguments to pass to L{Version}. @param kwargs: Keyword arguments to pass to L{Version}. """ return generateVersionFileData(Version(*args, **kwargs)) class StructureAssertingMixin(object): """ A mixin for L{TestCase} subclasses which provides some methods for asserting the structure and contents of directories and files on the filesystem. """ def createStructure(self, root, dirDict): """ Create a set of directories and files given a dict defining their structure. @param root: The directory in which to create the structure. It must already exist. @type root: L{FilePath} @param dirDict: The dict defining the structure. Keys should be strings naming files, values should be strings describing file contents OR dicts describing subdirectories. All files are written in binary mode. Any string values are assumed to describe text files and will have their newlines replaced with the platform-native newline convention. For example:: {"foofile": "foocontents", "bardir": {"barfile": "bar\ncontents"}} @type dirDict: C{dict} """ for x in dirDict: child = root.child(x) if isinstance(dirDict[x], dict): child.createDirectory() self.createStructure(child, dirDict[x]) else: child.setContent(dirDict[x].replace('\n', os.linesep)) def assertStructure(self, root, dirDict): """ Assert that a directory is equivalent to one described by a dict. @param root: The filesystem directory to compare. @type root: L{FilePath} @param dirDict: The dict that should describe the contents of the directory. It should be the same structure as the C{dirDict} parameter to L{createStructure}. @type dirDict: C{dict} """ children = [x.basename() for x in root.children()] for x in dirDict: child = root.child(x) if isinstance(dirDict[x], dict): self.assertTrue(child.isdir(), "%s is not a dir!" % (child.path,)) self.assertStructure(child, dirDict[x]) else: a = child.getContent().replace(os.linesep, '\n') self.assertEquals(a, dirDict[x], child.path) children.remove(x) if children: self.fail("There were extra children in %s: %s" % (root.path, children)) def assertExtractedStructure(self, outputFile, dirDict): """ Assert that a tarfile content is equivalent to one described by a dict. @param outputFile: The tar file built by L{DistributionBuilder}. @type outputFile: L{FilePath}. @param dirDict: The dict that should describe the contents of the directory. It should be the same structure as the C{dirDict} parameter to L{createStructure}. @type dirDict: C{dict} """ tarFile = tarfile.TarFile.open(outputFile.path, "r:bz2") extracted = FilePath(self.mktemp()) extracted.createDirectory() for info in tarFile: tarFile.extract(info, path=extracted.path) self.assertStructure(extracted.children()[0], dirDict) class ChangeVersionTest(TestCase, StructureAssertingMixin): """ Twisted has the ability to change versions. """ def makeFile(self, relativePath, content): """ Create a file with the given content relative to a temporary directory. @param relativePath: The basename of the file to create. @param content: The content that the file will have. @return: The filename. """ baseDirectory = FilePath(self.mktemp()) directory, filename = os.path.split(relativePath) directory = baseDirectory.preauthChild(directory) directory.makedirs() file = directory.child(filename) directory.child(filename).setContent(content) return file def test_getNextVersion(self): """ When calculating the next version to release when a release is happening in the same year as the last release, the minor version number is incremented. """ now = date.today() major = now.year - VERSION_OFFSET version = Version("twisted", major, 9, 0) self.assertEquals(getNextVersion(version, now=now), Version("twisted", major, 10, 0)) def test_getNextVersionAfterYearChange(self): """ When calculating the next version to release when a release is happening in a later year, the minor version number is reset to 0. """ now = date.today() major = now.year - VERSION_OFFSET version = Version("twisted", major - 1, 9, 0) self.assertEquals(getNextVersion(version, now=now), Version("twisted", major, 0, 0)) def test_changeVersionInFile(self): """ _changeVersionInFile replaces the old version information in a file with the given new version information. """ # The version numbers are arbitrary, the name is only kind of # arbitrary. packageName = 'foo' oldVersion = Version(packageName, 2, 5, 0) file = self.makeFile('README', "Hello and welcome to %s." % oldVersion.base()) newVersion = Version(packageName, 7, 6, 0) _changeVersionInFile(oldVersion, newVersion, file.path) self.assertEqual(file.getContent(), "Hello and welcome to %s." % newVersion.base()) def test_changeAllProjectVersions(self): """ L{changeAllProjectVersions} changes all version numbers in _version.py and README files for all projects as well as in the the top-level README file. """ root = FilePath(self.mktemp()) root.createDirectory() structure = { "README": "Hi this is 1.0.0.", "twisted": { "topfiles": { "README": "Hi this is 1.0.0"}, "_version.py": genVersion("twisted", 1, 0, 0), "web": { "topfiles": { "README": "Hi this is 1.0.0"}, "_version.py": genVersion("twisted.web", 1, 0, 0) }}} self.createStructure(root, structure) changeAllProjectVersions(root, Version("lol", 1, 0, 2)) outStructure = { "README": "Hi this is 1.0.2.", "twisted": { "topfiles": { "README": "Hi this is 1.0.2"}, "_version.py": genVersion("twisted", 1, 0, 2), "web": { "topfiles": { "README": "Hi this is 1.0.2"}, "_version.py": genVersion("twisted.web", 1, 0, 2), }}} self.assertStructure(root, outStructure) def test_changeAllProjectVersionsPreRelease(self): """ L{changeAllProjectVersions} changes all version numbers in _version.py and README files for all projects as well as in the the top-level README file. If the old version was a pre-release, it will change the version in NEWS files as well. """ root = FilePath(self.mktemp()) root.createDirectory() coreNews = ("Twisted Core 1.0.0 (2009-12-25)\n" "===============================\n" "\n") webNews = ("Twisted Web 1.0.0pre1 (2009-12-25)\n" "==================================\n" "\n") structure = { "README": "Hi this is 1.0.0.", "NEWS": coreNews + webNews, "twisted": { "topfiles": { "README": "Hi this is 1.0.0", "NEWS": coreNews}, "_version.py": genVersion("twisted", 1, 0, 0), "web": { "topfiles": { "README": "Hi this is 1.0.0pre1", "NEWS": webNews}, "_version.py": genVersion("twisted.web", 1, 0, 0, 1) }}} self.createStructure(root, structure) changeAllProjectVersions(root, Version("lol", 1, 0, 2), '2010-01-01') coreNews = ( "Twisted Core 1.0.0 (2009-12-25)\n" "===============================\n" "\n") webNews = ("Twisted Web 1.0.2 (2010-01-01)\n" "==============================\n" "\n") outStructure = { "README": "Hi this is 1.0.2.", "NEWS": coreNews + webNews, "twisted": { "topfiles": { "README": "Hi this is 1.0.2", "NEWS": coreNews}, "_version.py": genVersion("twisted", 1, 0, 2), "web": { "topfiles": { "README": "Hi this is 1.0.2", "NEWS": webNews}, "_version.py": genVersion("twisted.web", 1, 0, 2), }}} self.assertStructure(root, outStructure) class ProjectTest(TestCase): """ There is a first-class representation of a project. """ def assertProjectsEqual(self, observedProjects, expectedProjects): """ Assert that two lists of L{Project}s are equal. """ self.assertEqual(len(observedProjects), len(expectedProjects)) observedProjects = sorted(observedProjects, key=operator.attrgetter('directory')) expectedProjects = sorted(expectedProjects, key=operator.attrgetter('directory')) for observed, expected in zip(observedProjects, expectedProjects): self.assertEqual(observed.directory, expected.directory) def makeProject(self, version, baseDirectory=None): """ Make a Twisted-style project in the given base directory. @param baseDirectory: The directory to create files in (as a L{FilePath). @param version: The version information for the project. @return: L{Project} pointing to the created project. """ if baseDirectory is None: baseDirectory = FilePath(self.mktemp()) baseDirectory.createDirectory() segments = version.package.split('.') directory = baseDirectory for segment in segments: directory = directory.child(segment) if not directory.exists(): directory.createDirectory() directory.child('__init__.py').setContent('') directory.child('topfiles').createDirectory() directory.child('topfiles').child('README').setContent(version.base()) replaceProjectVersion( directory.child('_version.py').path, version) return Project(directory) def makeProjects(self, *versions): """ Create a series of projects underneath a temporary base directory. @return: A L{FilePath} for the base directory. """ baseDirectory = FilePath(self.mktemp()) baseDirectory.createDirectory() for version in versions: self.makeProject(version, baseDirectory) return baseDirectory def test_getVersion(self): """ Project objects know their version. """ version = Version('foo', 2, 1, 0) project = self.makeProject(version) self.assertEquals(project.getVersion(), version) def test_updateVersion(self): """ Project objects know how to update the version numbers in those projects. """ project = self.makeProject(Version("bar", 2, 1, 0)) newVersion = Version("bar", 3, 2, 9) project.updateVersion(newVersion) self.assertEquals(project.getVersion(), newVersion) self.assertEquals( project.directory.child("topfiles").child("README").getContent(), "3.2.9") def test_repr(self): """ The representation of a Project is Project(directory). """ foo = Project(FilePath('bar')) self.assertEqual( repr(foo), 'Project(%r)' % (foo.directory)) def test_findTwistedStyleProjects(self): """ findTwistedStyleProjects finds all projects underneath a particular directory. A 'project' is defined by the existence of a 'topfiles' directory and is returned as a Project object. """ baseDirectory = self.makeProjects( Version('foo', 2, 3, 0), Version('foo.bar', 0, 7, 4)) projects = findTwistedProjects(baseDirectory) self.assertProjectsEqual( projects, [Project(baseDirectory.child('foo')), Project(baseDirectory.child('foo').child('bar'))]) def test_updateTwistedVersionInformation(self): """ Update Twisted version information in the top-level project and all of the subprojects. """ baseDirectory = FilePath(self.mktemp()) baseDirectory.createDirectory() now = date.today() projectName = 'foo' oldVersion = Version(projectName, 2, 5, 0) newVersion = getNextVersion(oldVersion, now=now) project = self.makeProject(oldVersion, baseDirectory) updateTwistedVersionInformation(baseDirectory, now=now) self.assertEqual(project.getVersion(), newVersion) self.assertEqual( project.directory.child('topfiles').child('README').getContent(), newVersion.base()) class UtilityTest(TestCase): """ Tests for various utility functions for releasing. """ def test_chdir(self): """ Test that the runChdirSafe is actually safe, i.e., it still changes back to the original directory even if an error is raised. """ cwd = os.getcwd() def chAndBreak(): os.mkdir('releaseCh') os.chdir('releaseCh') 1/0 self.assertRaises(ZeroDivisionError, release.runChdirSafe, chAndBreak) self.assertEquals(cwd, os.getcwd()) def test_replaceInFile(self): """ L{replaceInFile} replaces data in a file based on a dict. A key from the dict that is found in the file is replaced with the corresponding value. """ in_ = 'foo\nhey hey $VER\nbar\n' outf = open('release.replace', 'w') outf.write(in_) outf.close() expected = in_.replace('$VER', '2.0.0') replaceInFile('release.replace', {'$VER': '2.0.0'}) self.assertEquals(open('release.replace').read(), expected) expected = expected.replace('2.0.0', '3.0.0') replaceInFile('release.replace', {'2.0.0': '3.0.0'}) self.assertEquals(open('release.replace').read(), expected) class VersionWritingTest(TestCase): """ Tests for L{replaceProjectVersion}. """ def test_replaceProjectVersion(self): """ L{replaceProjectVersion} writes a Python file that defines a C{version} variable that corresponds to the given name and version number. """ replaceProjectVersion("test_project", Version("twisted.test_project", 0, 82, 7)) ns = {'__name___': 'twisted.test_project'} execfile("test_project", ns) self.assertEquals(ns["version"].base(), "0.82.7") def test_replaceProjectVersionWithPrerelease(self): """ L{replaceProjectVersion} will write a Version instantiation that includes a prerelease parameter if necessary. """ replaceProjectVersion("test_project", Version("twisted.test_project", 0, 82, 7, prerelease=8)) ns = {'__name___': 'twisted.test_project'} execfile("test_project", ns) self.assertEquals(ns["version"].base(), "0.82.7pre8") class BuilderTestsMixin(object): """ A mixin class which provides various methods for creating sample Lore input and output. @cvar template: The lore template that will be used to prepare sample output. @type template: C{str} @ivar docCounter: A counter which is incremented every time input is generated and which is included in the documents. @type docCounter: C{int} """ template = ''' <html> <head><title>Yo:</title></head> <body> <div class="body" /> <a href="index.html">Index</a> <span class="version">Version: </span> </body> </html> ''' def setUp(self): """ Initialize the doc counter which ensures documents are unique. """ self.docCounter = 0 def assertXMLEqual(self, first, second): """ Verify that two strings represent the same XML document. """ self.assertEqual( dom.parseString(first).toxml(), dom.parseString(second).toxml()) def getArbitraryOutput(self, version, counter, prefix="", apiBaseURL="%s"): """ Get the correct HTML output for the arbitrary input returned by L{getArbitraryLoreInput} for the given parameters. @param version: The version string to include in the output. @type version: C{str} @param counter: A counter to include in the output. @type counter: C{int} """ document = """\ <?xml version="1.0"?><html> <head><title>Yo:Hi! Title: %(count)d</title></head> <body> <div class="content">Hi! %(count)d<div class="API"><a href="%(foobarLink)s" title="foobar">foobar</a></div></div> <a href="%(prefix)sindex.html">Index</a> <span class="version">Version: %(version)s</span> </body> </html>""" # Try to normalize irrelevant whitespace. return dom.parseString( document % {"count": counter, "prefix": prefix, "version": version, "foobarLink": apiBaseURL % ("foobar",)}).toxml('utf-8') def getArbitraryLoreInput(self, counter): """ Get an arbitrary, unique (for this test case) string of lore input. @param counter: A counter to include in the input. @type counter: C{int} """ template = ( '<html>' '<head><title>Hi! Title: %(count)s</title></head>' '<body>' 'Hi! %(count)s' '<div class="API">foobar</div>' '</body>' '</html>') return template % {"count": counter} def getArbitraryLoreInputAndOutput(self, version, prefix="", apiBaseURL="%s"): """ Get an input document along with expected output for lore run on that output document, assuming an appropriately-specified C{self.template}. @param version: A version string to include in the input and output. @type version: C{str} @param prefix: The prefix to include in the link to the index. @type prefix: C{str} @return: A two-tuple of input and expected output. @rtype: C{(str, str)}. """ self.docCounter += 1 return (self.getArbitraryLoreInput(self.docCounter), self.getArbitraryOutput(version, self.docCounter, prefix=prefix, apiBaseURL=apiBaseURL)) def getArbitraryManInput(self): """ Get an arbitrary man page content. """ return """.TH MANHOLE "1" "August 2001" "" "" .SH NAME manhole \- Connect to a Twisted Manhole service .SH SYNOPSIS .B manhole .SH DESCRIPTION manhole is a GTK interface to Twisted Manhole services. You can execute python code as if at an interactive Python console inside a running Twisted process with this.""" def getArbitraryManLoreOutput(self): """ Get an arbitrary lore input document which represents man-to-lore output based on the man page returned from L{getArbitraryManInput} """ return """\ <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head> <title>MANHOLE.1</title></head> <body> <h1>MANHOLE.1</h1> <h2>NAME</h2> <p>manhole - Connect to a Twisted Manhole service </p> <h2>SYNOPSIS</h2> <p><strong>manhole</strong> </p> <h2>DESCRIPTION</h2> <p>manhole is a GTK interface to Twisted Manhole services. You can execute python code as if at an interactive Python console inside a running Twisted process with this.</p> </body> </html> """ def getArbitraryManHTMLOutput(self, version, prefix=""): """ Get an arbitrary lore output document which represents the lore HTML output based on the input document returned from L{getArbitraryManLoreOutput}. @param version: A version string to include in the document. @type version: C{str} @param prefix: The prefix to include in the link to the index. @type prefix: C{str} """ # Try to normalize the XML a little bit. return dom.parseString("""\ <?xml version="1.0" ?><html> <head><title>Yo:MANHOLE.1</title></head> <body> <div class="content"> <span/> <h2>NAME<a name="auto0"/></h2> <p>manhole - Connect to a Twisted Manhole service </p> <h2>SYNOPSIS<a name="auto1"/></h2> <p><strong>manhole</strong> </p> <h2>DESCRIPTION<a name="auto2"/></h2> <p>manhole is a GTK interface to Twisted Manhole services. You can execute python code as if at an interactive Python console inside a running Twisted process with this.</p> </div> <a href="%(prefix)sindex.html">Index</a> <span class="version">Version: %(version)s</span> </body> </html>""" % { 'prefix': prefix, 'version': version}).toxml("utf-8") class DocBuilderTestCase(TestCase, BuilderTestsMixin): """ Tests for L{DocBuilder}. Note for future maintainers: The exact byte equality assertions throughout this suite may need to be updated due to minor differences in lore. They should not be taken to mean that Lore must maintain the same byte format forever. Feel free to update the tests when Lore changes, but please be careful. """ skip = loreSkip def setUp(self): """ Set up a few instance variables that will be useful. @ivar builder: A plain L{DocBuilder}. @ivar docCounter: An integer to be used as a counter by the C{getArbitrary...} methods. @ivar howtoDir: A L{FilePath} representing a directory to be used for containing Lore documents. @ivar templateFile: A L{FilePath} representing a file with C{self.template} as its content. """ BuilderTestsMixin.setUp(self) self.builder = DocBuilder() self.howtoDir = FilePath(self.mktemp()) self.howtoDir.createDirectory() self.templateFile = self.howtoDir.child("template.tpl") self.templateFile.setContent(self.template) def test_build(self): """ The L{DocBuilder} runs lore on all .xhtml files within a directory. """ version = "1.2.3" input1, output1 = self.getArbitraryLoreInputAndOutput(version) input2, output2 = self.getArbitraryLoreInputAndOutput(version) self.howtoDir.child("one.xhtml").setContent(input1) self.howtoDir.child("two.xhtml").setContent(input2) self.builder.build(version, self.howtoDir, self.howtoDir, self.templateFile) out1 = self.howtoDir.child('one.html') out2 = self.howtoDir.child('two.html') self.assertXMLEqual(out1.getContent(), output1) self.assertXMLEqual(out2.getContent(), output2) def test_noDocumentsFound(self): """ The C{build} method raises L{NoDocumentsFound} if there are no .xhtml files in the given directory. """ self.assertRaises( NoDocumentsFound, self.builder.build, "1.2.3", self.howtoDir, self.howtoDir, self.templateFile) def test_parentDocumentLinking(self): """ The L{DocBuilder} generates correct links from documents to template-generated links like stylesheets and index backreferences. """ input = self.getArbitraryLoreInput(0) tutoDir = self.howtoDir.child("tutorial") tutoDir.createDirectory() tutoDir.child("child.xhtml").setContent(input) self.builder.build("1.2.3", self.howtoDir, tutoDir, self.templateFile) outFile = tutoDir.child('child.html') self.assertIn('<a href="../index.html">Index</a>', outFile.getContent()) def test_siblingDirectoryDocumentLinking(self): """ It is necessary to generate documentation in a directory foo/bar where stylesheet and indexes are located in foo/baz. Such resources should be appropriately linked to. """ input = self.getArbitraryLoreInput(0) resourceDir = self.howtoDir.child("resources") docDir = self.howtoDir.child("docs") docDir.createDirectory() docDir.child("child.xhtml").setContent(input) self.builder.build("1.2.3", resourceDir, docDir, self.templateFile) outFile = docDir.child('child.html') self.assertIn('<a href="../resources/index.html">Index</a>', outFile.getContent()) def test_apiLinking(self): """ The L{DocBuilder} generates correct links from documents to API documentation. """ version = "1.2.3" input, output = self.getArbitraryLoreInputAndOutput(version) self.howtoDir.child("one.xhtml").setContent(input) self.builder.build(version, self.howtoDir, self.howtoDir, self.templateFile, "scheme:apilinks/%s.ext") out = self.howtoDir.child('one.html') self.assertIn( '<a href="scheme:apilinks/foobar.ext" title="foobar">foobar</a>', out.getContent()) def test_deleteInput(self): """ L{DocBuilder.build} can be instructed to delete the input files after generating the output based on them. """ input1 = self.getArbitraryLoreInput(0) self.howtoDir.child("one.xhtml").setContent(input1) self.builder.build("whatever", self.howtoDir, self.howtoDir, self.templateFile, deleteInput=True) self.assertTrue(self.howtoDir.child('one.html').exists()) self.assertFalse(self.howtoDir.child('one.xhtml').exists()) def test_doNotDeleteInput(self): """ Input will not be deleted by default. """ input1 = self.getArbitraryLoreInput(0) self.howtoDir.child("one.xhtml").setContent(input1) self.builder.build("whatever", self.howtoDir, self.howtoDir, self.templateFile) self.assertTrue(self.howtoDir.child('one.html').exists()) self.assertTrue(self.howtoDir.child('one.xhtml').exists()) def test_getLinkrelToSameDirectory(self): """ If the doc and resource directories are the same, the linkrel should be an empty string. """ linkrel = self.builder.getLinkrel(FilePath("/foo/bar"), FilePath("/foo/bar")) self.assertEquals(linkrel, "") def test_getLinkrelToParentDirectory(self): """ If the doc directory is a child of the resource directory, the linkrel should make use of '..'. """ linkrel = self.builder.getLinkrel(FilePath("/foo"), FilePath("/foo/bar")) self.assertEquals(linkrel, "../") def test_getLinkrelToSibling(self): """ If the doc directory is a sibling of the resource directory, the linkrel should make use of '..' and a named segment. """ linkrel = self.builder.getLinkrel(FilePath("/foo/howto"), FilePath("/foo/examples")) self.assertEquals(linkrel, "../howto/") def test_getLinkrelToUncle(self): """ If the doc directory is a sibling of the parent of the resource directory, the linkrel should make use of multiple '..'s and a named segment. """ linkrel = self.builder.getLinkrel(FilePath("/foo/howto"), FilePath("/foo/examples/quotes")) self.assertEquals(linkrel, "../../howto/") class APIBuilderTestCase(TestCase): """ Tests for L{APIBuilder}. """ skip = pydoctorSkip def test_build(self): """ L{APIBuilder.build} writes an index file which includes the name of the project specified. """ stdout = StringIO() self.patch(sys, 'stdout', stdout) projectName = "Foobar" packageName = "quux" projectURL = "scheme:project" sourceURL = "scheme:source" docstring = "text in docstring" privateDocstring = "should also appear in output" inputPath = FilePath(self.mktemp()).child(packageName) inputPath.makedirs() inputPath.child("__init__.py").setContent( "def foo():\n" " '%s'\n" "def _bar():\n" " '%s'" % (docstring, privateDocstring)) outputPath = FilePath(self.mktemp()) outputPath.makedirs() builder = APIBuilder() builder.build(projectName, projectURL, sourceURL, inputPath, outputPath) indexPath = outputPath.child("index.html") self.assertTrue( indexPath.exists(), "API index %r did not exist." % (outputPath.path,)) self.assertIn( '<a href="%s">%s</a>' % (projectURL, projectName), indexPath.getContent(), "Project name/location not in file contents.") quuxPath = outputPath.child("quux.html") self.assertTrue( quuxPath.exists(), "Package documentation file %r did not exist." % (quuxPath.path,)) self.assertIn( docstring, quuxPath.getContent(), "Docstring not in package documentation file.") self.assertIn( '<a href="%s/%s">View Source</a>' % (sourceURL, packageName), quuxPath.getContent()) self.assertIn( '<a href="%s/%s/__init__.py#L1" class="functionSourceLink">' % ( sourceURL, packageName), quuxPath.getContent()) self.assertIn(privateDocstring, quuxPath.getContent()) # There should also be a page for the foo function in quux. self.assertTrue(quuxPath.sibling('quux.foo.html').exists()) self.assertEqual(stdout.getvalue(), '') def test_buildWithPolicy(self): """ L{BuildAPIDocsScript.buildAPIDocs} builds the API docs with values appropriate for the Twisted project. """ stdout = StringIO() self.patch(sys, 'stdout', stdout) docstring = "text in docstring" projectRoot = FilePath(self.mktemp()) packagePath = projectRoot.child("twisted") packagePath.makedirs() packagePath.child("__init__.py").setContent( "def foo():\n" " '%s'\n" % (docstring,)) packagePath.child("_version.py").setContent( genVersion("twisted", 1, 0, 0)) outputPath = FilePath(self.mktemp()) script = BuildAPIDocsScript() script.buildAPIDocs(projectRoot, outputPath) indexPath = outputPath.child("index.html") self.assertTrue( indexPath.exists(), "API index %r did not exist." % (outputPath.path,)) self.assertIn( '<a href="http://twistedmatrix.com/">Twisted</a>', indexPath.getContent(), "Project name/location not in file contents.") twistedPath = outputPath.child("twisted.html") self.assertTrue( twistedPath.exists(), "Package documentation file %r did not exist." % (twistedPath.path,)) self.assertIn( docstring, twistedPath.getContent(), "Docstring not in package documentation file.") #Here we check that it figured out the correct version based on the #source code. self.assertIn( '<a href="http://twistedmatrix.com/trac/browser/tags/releases/' 'twisted-1.0.0/twisted">View Source</a>', twistedPath.getContent()) self.assertEqual(stdout.getvalue(), '') def test_apiBuilderScriptMainRequiresTwoArguments(self): """ SystemExit is raised when the incorrect number of command line arguments are passed to the API building script. """ script = BuildAPIDocsScript() self.assertRaises(SystemExit, script.main, []) self.assertRaises(SystemExit, script.main, ["foo"]) self.assertRaises(SystemExit, script.main, ["foo", "bar", "baz"]) def test_apiBuilderScriptMain(self): """ The API building script invokes the same code that L{test_buildWithPolicy} tests. """ script = BuildAPIDocsScript() calls = [] script.buildAPIDocs = lambda a, b: calls.append((a, b)) script.main(["hello", "there"]) self.assertEquals(calls, [(FilePath("hello"), FilePath("there"))]) class ManBuilderTestCase(TestCase, BuilderTestsMixin): """ Tests for L{ManBuilder}. """ skip = loreSkip def setUp(self): """ Set up a few instance variables that will be useful. @ivar builder: A plain L{ManBuilder}. @ivar manDir: A L{FilePath} representing a directory to be used for containing man pages. """ BuilderTestsMixin.setUp(self) self.builder = ManBuilder() self.manDir = FilePath(self.mktemp()) self.manDir.createDirectory() def test_noDocumentsFound(self): """ L{ManBuilder.build} raises L{NoDocumentsFound} if there are no .1 files in the given directory. """ self.assertRaises(NoDocumentsFound, self.builder.build, self.manDir) def test_build(self): """ Check that L{ManBuilder.build} find the man page in the directory, and successfully produce a Lore content. """ manContent = self.getArbitraryManInput() self.manDir.child('test1.1').setContent(manContent) self.builder.build(self.manDir) output = self.manDir.child('test1-man.xhtml').getContent() expected = self.getArbitraryManLoreOutput() # No-op on *nix, fix for windows expected = expected.replace('\n', os.linesep) self.assertEquals(output, expected) def test_toHTML(self): """ Check that the content output by C{build} is compatible as input of L{DocBuilder.build}. """ manContent = self.getArbitraryManInput() self.manDir.child('test1.1').setContent(manContent) self.builder.build(self.manDir) templateFile = self.manDir.child("template.tpl") templateFile.setContent(DocBuilderTestCase.template) docBuilder = DocBuilder() docBuilder.build("1.2.3", self.manDir, self.manDir, templateFile) output = self.manDir.child('test1-man.html').getContent() self.assertXMLEqual( output, """\ <?xml version="1.0" ?><html> <head><title>Yo:MANHOLE.1</title></head> <body> <div class="content"> <span/> <h2>NAME<a name="auto0"/></h2> <p>manhole - Connect to a Twisted Manhole service </p> <h2>SYNOPSIS<a name="auto1"/></h2> <p><strong>manhole</strong> </p> <h2>DESCRIPTION<a name="auto2"/></h2> <p>manhole is a GTK interface to Twisted Manhole services. You can execute python code as if at an interactive Python console inside a running Twisted process with this.</p> </div> <a href="index.html">Index</a> <span class="version">Version: 1.2.3</span> </body> </html>""") class BookBuilderTests(TestCase, BuilderTestsMixin): """ Tests for L{BookBuilder}. """ skip = latexSkip or loreSkip def setUp(self): """ Make a directory into which to place temporary files. """ self.docCounter = 0 self.howtoDir = FilePath(self.mktemp()) self.howtoDir.makedirs() self.oldHandler = signal.signal(signal.SIGCHLD, signal.SIG_DFL) def tearDown(self): signal.signal(signal.SIGCHLD, self.oldHandler) def getArbitraryOutput(self, version, counter, prefix="", apiBaseURL=None): """ Create and return a C{str} containing the LaTeX document which is expected as the output for processing the result of the document returned by C{self.getArbitraryLoreInput(counter)}. """ path = self.howtoDir.child("%d.xhtml" % (counter,)).path return ( r'\section{Hi! Title: %(count)s\label{%(path)s}}' '\n' r'Hi! %(count)sfoobar') % {'count': counter, 'path': path} def test_runSuccess(self): """ L{BookBuilder.run} executes the command it is passed and returns a string giving the stdout and stderr of the command if it completes successfully. """ builder = BookBuilder() self.assertEquals( builder.run([ sys.executable, '-c', 'import sys; ' 'sys.stdout.write("hi\\n"); ' 'sys.stdout.flush(); ' 'sys.stderr.write("bye\\n"); ' 'sys.stderr.flush()']), "hi\nbye\n") def test_runFailed(self): """ L{BookBuilder.run} executes the command it is passed and raises L{CommandFailed} if it completes unsuccessfully. """ builder = BookBuilder() exc = self.assertRaises( CommandFailed, builder.run, [sys.executable, '-c', 'print "hi"; raise SystemExit(1)']) self.assertEquals(exc.exitStatus, 1) self.assertEquals(exc.exitSignal, None) self.assertEquals(exc.output, "hi\n") def test_runSignaled(self): """ L{BookBuilder.run} executes the command it is passed and raises L{CommandFailed} if it exits due to a signal. """ builder = BookBuilder() exc = self.assertRaises( CommandFailed, builder.run, [sys.executable, '-c', 'import sys; print "hi"; sys.stdout.flush(); ' 'import os; os.kill(os.getpid(), 9)']) self.assertEquals(exc.exitSignal, 9) self.assertEquals(exc.exitStatus, None) self.assertEquals(exc.output, "hi\n") def test_buildTeX(self): """ L{BookBuilder.buildTeX} writes intermediate TeX files for all lore input files in a directory. """ version = "3.2.1" input1, output1 = self.getArbitraryLoreInputAndOutput(version) input2, output2 = self.getArbitraryLoreInputAndOutput(version) # Filenames are chosen by getArbitraryOutput to match the counter used # by getArbitraryLoreInputAndOutput. self.howtoDir.child("1.xhtml").setContent(input1) self.howtoDir.child("2.xhtml").setContent(input2) builder = BookBuilder() builder.buildTeX(self.howtoDir) self.assertEqual(self.howtoDir.child("1.tex").getContent(), output1) self.assertEqual(self.howtoDir.child("2.tex").getContent(), output2) def test_buildTeXRejectsInvalidDirectory(self): """ L{BookBuilder.buildTeX} raises L{ValueError} if passed a directory which does not exist. """ builder = BookBuilder() self.assertRaises( ValueError, builder.buildTeX, self.howtoDir.temporarySibling()) def test_buildTeXOnlyBuildsXHTML(self): """ L{BookBuilder.buildTeX} ignores files which which don't end with ".xhtml". """ # Hopefully ">" is always a parse error from microdom! self.howtoDir.child("not-input.dat").setContent(">") self.test_buildTeX() def test_stdout(self): """ L{BookBuilder.buildTeX} does not write to stdout. """ stdout = StringIO() self.patch(sys, 'stdout', stdout) # Suppress warnings so that if there are any old-style plugins that # lore queries for don't confuse the assertion below. See #3070. self.patch(warnings, 'warn', lambda *a, **kw: None) self.test_buildTeX() self.assertEqual(stdout.getvalue(), '') def test_buildPDFRejectsInvalidBookFilename(self): """ L{BookBuilder.buildPDF} raises L{ValueError} if the book filename does not end with ".tex". """ builder = BookBuilder() self.assertRaises( ValueError, builder.buildPDF, FilePath(self.mktemp()).child("foo"), None, None) def _setupTeXFiles(self): sections = range(3) self._setupTeXSections(sections) return self._setupTeXBook(sections) def _setupTeXSections(self, sections): for texSectionNumber in sections: texPath = self.howtoDir.child("%d.tex" % (texSectionNumber,)) texPath.setContent(self.getArbitraryOutput( "1.2.3", texSectionNumber)) def _setupTeXBook(self, sections): bookTeX = self.howtoDir.child("book.tex") bookTeX.setContent( r"\documentclass{book}" "\n" r"\begin{document}" "\n" + "\n".join([r"\input{%d.tex}" % (n,) for n in sections]) + r"\end{document}" "\n") return bookTeX def test_buildPDF(self): """ L{BookBuilder.buildPDF} creates a PDF given an index tex file and a directory containing .tex files. """ bookPath = self._setupTeXFiles() outputPath = FilePath(self.mktemp()) builder = BookBuilder() builder.buildPDF(bookPath, self.howtoDir, outputPath) self.assertTrue(outputPath.exists()) def test_buildPDFLongPath(self): """ L{BookBuilder.buildPDF} succeeds even if the paths it is operating on are very long. C{ps2pdf13} seems to have problems when path names are long. This test verifies that even if inputs have long paths, generation still succeeds. """ # Make it long. self.howtoDir = self.howtoDir.child("x" * 128).child("x" * 128).child("x" * 128) self.howtoDir.makedirs() # This will use the above long path. bookPath = self._setupTeXFiles() outputPath = FilePath(self.mktemp()) builder = BookBuilder() builder.buildPDF(bookPath, self.howtoDir, outputPath) self.assertTrue(outputPath.exists()) def test_buildPDFRunsLaTeXThreeTimes(self): """ L{BookBuilder.buildPDF} runs C{latex} three times. """ class InspectableBookBuilder(BookBuilder): def __init__(self): BookBuilder.__init__(self) self.commands = [] def run(self, command): """ Record the command and then execute it. """ self.commands.append(command) return BookBuilder.run(self, command) bookPath = self._setupTeXFiles() outputPath = FilePath(self.mktemp()) builder = InspectableBookBuilder() builder.buildPDF(bookPath, self.howtoDir, outputPath) # These string comparisons are very fragile. It would be better to # have a test which asserted the correctness of the contents of the # output files. I don't know how one could do that, though. -exarkun latex1, latex2, latex3, dvips, ps2pdf13 = builder.commands self.assertEquals(latex1, latex2) self.assertEquals(latex2, latex3) self.assertEquals( latex1[:1], ["latex"], "LaTeX command %r does not seem right." % (latex1,)) self.assertEquals( latex1[-1:], [bookPath.path], "LaTeX command %r does not end with the book path (%r)." % ( latex1, bookPath.path)) self.assertEquals( dvips[:1], ["dvips"], "dvips command %r does not seem right." % (dvips,)) self.assertEquals( ps2pdf13[:1], ["ps2pdf13"], "ps2pdf13 command %r does not seem right." % (ps2pdf13,)) def test_noSideEffects(self): """ The working directory is the same before and after a call to L{BookBuilder.buildPDF}. Also the contents of the directory containing the input book are the same before and after the call. """ startDir = os.getcwd() bookTeX = self._setupTeXFiles() startTeXSiblings = bookTeX.parent().children() startHowtoChildren = self.howtoDir.children() builder = BookBuilder() builder.buildPDF(bookTeX, self.howtoDir, FilePath(self.mktemp())) self.assertEqual(startDir, os.getcwd()) self.assertEqual(startTeXSiblings, bookTeX.parent().children()) self.assertEqual(startHowtoChildren, self.howtoDir.children()) def test_failedCommandProvidesOutput(self): """ If a subprocess fails, L{BookBuilder.buildPDF} raises L{CommandFailed} with the subprocess's output and leaves the temporary directory as a sibling of the book path. """ bookTeX = FilePath(self.mktemp() + ".tex") builder = BookBuilder() inputState = bookTeX.parent().children() exc = self.assertRaises( CommandFailed, builder.buildPDF, bookTeX, self.howtoDir, FilePath(self.mktemp())) self.assertTrue(exc.output) newOutputState = set(bookTeX.parent().children()) - set(inputState) self.assertEqual(len(newOutputState), 1) workPath = newOutputState.pop() self.assertTrue( workPath.isdir(), "Expected work path %r was not a directory." % (workPath.path,)) def test_build(self): """ L{BookBuilder.build} generates a pdf book file from some lore input files. """ sections = range(1, 4) for sectionNumber in sections: self.howtoDir.child("%d.xhtml" % (sectionNumber,)).setContent( self.getArbitraryLoreInput(sectionNumber)) bookTeX = self._setupTeXBook(sections) bookPDF = FilePath(self.mktemp()) builder = BookBuilder() builder.build(self.howtoDir, [self.howtoDir], bookTeX, bookPDF) self.assertTrue(bookPDF.exists()) def test_buildRemovesTemporaryLaTeXFiles(self): """ L{BookBuilder.build} removes the intermediate LaTeX files it creates. """ sections = range(1, 4) for sectionNumber in sections: self.howtoDir.child("%d.xhtml" % (sectionNumber,)).setContent( self.getArbitraryLoreInput(sectionNumber)) bookTeX = self._setupTeXBook(sections) bookPDF = FilePath(self.mktemp()) builder = BookBuilder() builder.build(self.howtoDir, [self.howtoDir], bookTeX, bookPDF) self.assertEqual( set(self.howtoDir.listdir()), set([bookTeX.basename()] + ["%d.xhtml" % (n,) for n in sections])) class FilePathDeltaTest(TestCase): """ Tests for L{filePathDelta}. """ def test_filePathDeltaSubdir(self): """ L{filePathDelta} can create a simple relative path to a child path. """ self.assertEquals(filePathDelta(FilePath("/foo/bar"), FilePath("/foo/bar/baz")), ["baz"]) def test_filePathDeltaSiblingDir(self): """ L{filePathDelta} can traverse upwards to create relative paths to siblings. """ self.assertEquals(filePathDelta(FilePath("/foo/bar"), FilePath("/foo/baz")), ["..", "baz"]) def test_filePathNoCommonElements(self): """ L{filePathDelta} can create relative paths to totally unrelated paths for maximum portability. """ self.assertEquals(filePathDelta(FilePath("/foo/bar"), FilePath("/baz/quux")), ["..", "..", "baz", "quux"]) def test_filePathDeltaSimilarEndElements(self): """ L{filePathDelta} doesn't take into account final elements when comparing 2 paths, but stops at the first difference. """ self.assertEquals(filePathDelta(FilePath("/foo/bar/bar/spam"), FilePath("/foo/bar/baz/spam")), ["..", "..", "baz", "spam"]) class NewsBuilderTests(TestCase, StructureAssertingMixin): """ Tests for L{NewsBuilder}. """ def setUp(self): """ Create a fake project and stuff some basic structure and content into it. """ self.builder = NewsBuilder() self.project = FilePath(self.mktemp()) self.project.createDirectory() self.existingText = 'Here is stuff which was present previously.\n' self.createStructure(self.project, { 'NEWS': self.existingText, '5.feature': 'We now support the web.\n', '12.feature': 'The widget is more robust.\n', '15.feature': ( 'A very long feature which takes many words to ' 'describe with any accuracy was introduced so that ' 'the line wrapping behavior of the news generating ' 'code could be verified.\n'), '16.feature': ( 'A simpler feature\ndescribed on multiple lines\n' 'was added.\n'), '23.bugfix': 'Broken stuff was fixed.\n', '25.removal': 'Stupid stuff was deprecated.\n', '30.misc': '', '35.misc': '', '40.doc': 'foo.bar.Baz.quux', '41.doc': 'writing Foo servers'}) def test_today(self): """ L{NewsBuilder._today} returns today's date in YYYY-MM-DD form. """ self.assertEquals( self.builder._today(), date.today().strftime('%Y-%m-%d')) def test_findFeatures(self): """ When called with L{NewsBuilder._FEATURE}, L{NewsBuilder._findChanges} returns a list of bugfix ticket numbers and descriptions as a list of two-tuples. """ features = self.builder._findChanges( self.project, self.builder._FEATURE) self.assertEquals( features, [(5, "We now support the web."), (12, "The widget is more robust."), (15, "A very long feature which takes many words to describe with " "any accuracy was introduced so that the line wrapping behavior " "of the news generating code could be verified."), (16, "A simpler feature described on multiple lines was added.")]) def test_findBugfixes(self): """ When called with L{NewsBuilder._BUGFIX}, L{NewsBuilder._findChanges} returns a list of bugfix ticket numbers and descriptions as a list of two-tuples. """ bugfixes = self.builder._findChanges( self.project, self.builder._BUGFIX) self.assertEquals( bugfixes, [(23, 'Broken stuff was fixed.')]) def test_findRemovals(self): """ When called with L{NewsBuilder._REMOVAL}, L{NewsBuilder._findChanges} returns a list of removal/deprecation ticket numbers and descriptions as a list of two-tuples. """ removals = self.builder._findChanges( self.project, self.builder._REMOVAL) self.assertEquals( removals, [(25, 'Stupid stuff was deprecated.')]) def test_findDocumentation(self): """ When called with L{NewsBuilder._DOC}, L{NewsBuilder._findChanges} returns a list of documentation ticket numbers and descriptions as a list of two-tuples. """ doc = self.builder._findChanges( self.project, self.builder._DOC) self.assertEquals( doc, [(40, 'foo.bar.Baz.quux'), (41, 'writing Foo servers')]) def test_findMiscellaneous(self): """ When called with L{NewsBuilder._MISC}, L{NewsBuilder._findChanges} returns a list of removal/deprecation ticket numbers and descriptions as a list of two-tuples. """ misc = self.builder._findChanges( self.project, self.builder._MISC) self.assertEquals( misc, [(30, ''), (35, '')]) def test_writeHeader(self): """ L{NewsBuilder._writeHeader} accepts a file-like object opened for writing and a header string and writes out a news file header to it. """ output = StringIO() self.builder._writeHeader(output, "Super Awesometastic 32.16") self.assertEquals( output.getvalue(), "Super Awesometastic 32.16\n" "=========================\n" "\n") def test_writeSection(self): """ L{NewsBuilder._writeSection} accepts a file-like object opened for writing, a section name, and a list of ticket information (as returned by L{NewsBuilder._findChanges}) and writes out a section header and all of the given ticket information. """ output = StringIO() self.builder._writeSection( output, "Features", [(3, "Great stuff."), (17, "Very long line which goes on and on and on, seemingly " "without end until suddenly without warning it does end.")]) self.assertEquals( output.getvalue(), "Features\n" "--------\n" " - Great stuff. (#3)\n" " - Very long line which goes on and on and on, seemingly without end\n" " until suddenly without warning it does end. (#17)\n" "\n") def test_writeMisc(self): """ L{NewsBuilder._writeMisc} accepts a file-like object opened for writing, a section name, and a list of ticket information (as returned by L{NewsBuilder._findChanges} and writes out a section header and all of the ticket numbers, but excludes any descriptions. """ output = StringIO() self.builder._writeMisc( output, "Other", [(x, "") for x in range(2, 50, 3)]) self.assertEquals( output.getvalue(), "Other\n" "-----\n" " - #2, #5, #8, #11, #14, #17, #20, #23, #26, #29, #32, #35, #38, #41,\n" " #44, #47\n" "\n") def test_build(self): """ L{NewsBuilder.build} updates a NEWS file with new features based on the I{<ticket>.feature} files found in the directory specified. """ self.builder.build( self.project, self.project.child('NEWS'), "Super Awesometastic 32.16") results = self.project.child('NEWS').getContent() self.assertEquals( results, 'Super Awesometastic 32.16\n' '=========================\n' '\n' 'Features\n' '--------\n' ' - We now support the web. (#5)\n' ' - The widget is more robust. (#12)\n' ' - A very long feature which takes many words to describe with any\n' ' accuracy was introduced so that the line wrapping behavior of the\n' ' news generating code could be verified. (#15)\n' ' - A simpler feature described on multiple lines was added. (#16)\n' '\n' 'Bugfixes\n' '--------\n' ' - Broken stuff was fixed. (#23)\n' '\n' 'Improved Documentation\n' '----------------------\n' ' - foo.bar.Baz.quux (#40)\n' ' - writing Foo servers (#41)\n' '\n' 'Deprecations and Removals\n' '-------------------------\n' ' - Stupid stuff was deprecated. (#25)\n' '\n' 'Other\n' '-----\n' ' - #30, #35\n' '\n\n' + self.existingText) def test_emptyProjectCalledOut(self): """ If no changes exist for a project, I{NEWS} gains a new section for that project that includes some helpful text about how there were no interesting changes. """ project = FilePath(self.mktemp()).child("twisted") project.makedirs() self.createStructure(project, { 'NEWS': self.existingText }) self.builder.build( project, project.child('NEWS'), "Super Awesometastic 32.16") results = project.child('NEWS').getContent() self.assertEquals( results, 'Super Awesometastic 32.16\n' '=========================\n' '\n' + self.builder._NO_CHANGES + '\n\n' + self.existingText) def test_preserveTicketHint(self): """ If a I{NEWS} file begins with the two magic lines which point readers at the issue tracker, those lines are kept at the top of the new file. """ news = self.project.child('NEWS') news.setContent( 'Ticket numbers in this file can be looked up by visiting\n' 'http://twistedmatrix.com/trac/ticket/<number>\n' '\n' 'Blah blah other stuff.\n') self.builder.build(self.project, news, "Super Awesometastic 32.16") self.assertEquals( news.getContent(), 'Ticket numbers in this file can be looked up by visiting\n' 'http://twistedmatrix.com/trac/ticket/<number>\n' '\n' 'Super Awesometastic 32.16\n' '=========================\n' '\n' 'Features\n' '--------\n' ' - We now support the web. (#5)\n' ' - The widget is more robust. (#12)\n' ' - A very long feature which takes many words to describe with any\n' ' accuracy was introduced so that the line wrapping behavior of the\n' ' news generating code could be verified. (#15)\n' ' - A simpler feature described on multiple lines was added. (#16)\n' '\n' 'Bugfixes\n' '--------\n' ' - Broken stuff was fixed. (#23)\n' '\n' 'Improved Documentation\n' '----------------------\n' ' - foo.bar.Baz.quux (#40)\n' ' - writing Foo servers (#41)\n' '\n' 'Deprecations and Removals\n' '-------------------------\n' ' - Stupid stuff was deprecated. (#25)\n' '\n' 'Other\n' '-----\n' ' - #30, #35\n' '\n\n' 'Blah blah other stuff.\n') def test_emptySectionsOmitted(self): """ If there are no changes of a particular type (feature, bugfix, etc), no section for that type is written by L{NewsBuilder.build}. """ for ticket in self.project.children(): if ticket.splitext()[1] in ('.feature', '.misc', '.doc'): ticket.remove() self.builder.build( self.project, self.project.child('NEWS'), 'Some Thing 1.2') self.assertEquals( self.project.child('NEWS').getContent(), 'Some Thing 1.2\n' '==============\n' '\n' 'Bugfixes\n' '--------\n' ' - Broken stuff was fixed. (#23)\n' '\n' 'Deprecations and Removals\n' '-------------------------\n' ' - Stupid stuff was deprecated. (#25)\n' '\n\n' 'Here is stuff which was present previously.\n') def test_duplicatesMerged(self): """ If two change files have the same contents, they are merged in the generated news entry. """ def feature(s): return self.project.child(s + '.feature') feature('5').copyTo(feature('15')) feature('5').copyTo(feature('16')) self.builder.build( self.project, self.project.child('NEWS'), 'Project Name 5.0') self.assertEquals( self.project.child('NEWS').getContent(), 'Project Name 5.0\n' '================\n' '\n' 'Features\n' '--------\n' ' - We now support the web. (#5, #15, #16)\n' ' - The widget is more robust. (#12)\n' '\n' 'Bugfixes\n' '--------\n' ' - Broken stuff was fixed. (#23)\n' '\n' 'Improved Documentation\n' '----------------------\n' ' - foo.bar.Baz.quux (#40)\n' ' - writing Foo servers (#41)\n' '\n' 'Deprecations and Removals\n' '-------------------------\n' ' - Stupid stuff was deprecated. (#25)\n' '\n' 'Other\n' '-----\n' ' - #30, #35\n' '\n\n' 'Here is stuff which was present previously.\n') def createFakeTwistedProject(self): """ Create a fake-looking Twisted project to build from. """ project = FilePath(self.mktemp()).child("twisted") project.makedirs() self.createStructure(project, { 'NEWS': 'Old boring stuff from the past.\n', '_version.py': genVersion("twisted", 1, 2, 3), 'topfiles': { 'NEWS': 'Old core news.\n', '3.feature': 'Third feature addition.\n', '5.misc': ''}, 'conch': { '_version.py': genVersion("twisted.conch", 3, 4, 5), 'topfiles': { 'NEWS': 'Old conch news.\n', '7.bugfix': 'Fixed that bug.\n'}}, 'vfs': { '_version.py': genVersion("twisted.vfs", 6, 7, 8), 'topfiles': { 'NEWS': 'Old vfs news.\n', '8.bugfix': 'Fixed bug 8.\n'}}}) return project def test_buildAll(self): """ L{NewsBuilder.buildAll} calls L{NewsBuilder.build} once for each subproject, passing that subproject's I{topfiles} directory as C{path}, the I{NEWS} file in that directory as C{output}, and the subproject's name as C{header}, and then again for each subproject with the top-level I{NEWS} file for C{output}. Blacklisted subprojects are skipped. """ builds = [] builder = NewsBuilder() builder.build = lambda path, output, header: builds.append(( path, output, header)) builder.blacklist = ['vfs'] builder._today = lambda: '2009-12-01' project = self.createFakeTwistedProject() builder.buildAll(project) coreTopfiles = project.child("topfiles") coreNews = coreTopfiles.child("NEWS") coreHeader = "Twisted Core 1.2.3 (2009-12-01)" conchTopfiles = project.child("conch").child("topfiles") conchNews = conchTopfiles.child("NEWS") conchHeader = "Twisted Conch 3.4.5 (2009-12-01)" aggregateNews = project.child("NEWS") self.assertEquals( builds, [(conchTopfiles, conchNews, conchHeader), (coreTopfiles, coreNews, coreHeader), (conchTopfiles, aggregateNews, conchHeader), (coreTopfiles, aggregateNews, coreHeader)]) def test_changeVersionInNews(self): """ L{NewsBuilder._changeVersions} gets the release date for a given version of a project as a string. """ builder = NewsBuilder() builder._today = lambda: '2009-12-01' project = self.createFakeTwistedProject() builder.buildAll(project) newVersion = Version('TEMPLATE', 7, 7, 14) coreNews = project.child('topfiles').child('NEWS') # twisted 1.2.3 is the old version. builder._changeNewsVersion( coreNews, "Core", Version("twisted", 1, 2, 3), newVersion, '2010-01-01') expectedCore = ( 'Twisted Core 7.7.14 (2010-01-01)\n' '================================\n' '\n' 'Features\n' '--------\n' ' - Third feature addition. (#3)\n' '\n' 'Other\n' '-----\n' ' - #5\n\n\n') self.assertEquals( expectedCore + 'Old core news.\n', coreNews.getContent()) class DistributionBuilderTestBase(BuilderTestsMixin, StructureAssertingMixin, TestCase): """ Base for tests of L{DistributionBuilder}. """ skip = loreSkip def setUp(self): BuilderTestsMixin.setUp(self) self.rootDir = FilePath(self.mktemp()) self.rootDir.createDirectory() self.outputDir = FilePath(self.mktemp()) self.outputDir.createDirectory() self.builder = DistributionBuilder(self.rootDir, self.outputDir) class DistributionBuilderTest(DistributionBuilderTestBase): def test_twistedDistribution(self): """ The Twisted tarball contains everything in the source checkout, with built documentation. """ loreInput, loreOutput = self.getArbitraryLoreInputAndOutput("10.0.0") manInput1 = self.getArbitraryManInput() manOutput1 = self.getArbitraryManHTMLOutput("10.0.0", "../howto/") manInput2 = self.getArbitraryManInput() manOutput2 = self.getArbitraryManHTMLOutput("10.0.0", "../howto/") coreIndexInput, coreIndexOutput = self.getArbitraryLoreInputAndOutput( "10.0.0", prefix="howto/") structure = { "README": "Twisted", "unrelated": "x", "LICENSE": "copyright!", "setup.py": "import toplevel", "bin": {"web": {"websetroot": "SET ROOT"}, "twistd": "TWISTD"}, "twisted": {"web": {"__init__.py": "import WEB", "topfiles": {"setup.py": "import WEBINSTALL", "README": "WEB!"}}, "words": {"__init__.py": "import WORDS"}, "plugins": {"twisted_web.py": "import WEBPLUG", "twisted_words.py": "import WORDPLUG"}}, "doc": {"web": {"howto": {"index.xhtml": loreInput}, "man": {"websetroot.1": manInput2}}, "core": {"howto": {"template.tpl": self.template}, "man": {"twistd.1": manInput1}, "index.xhtml": coreIndexInput}}} outStructure = { "README": "Twisted", "unrelated": "x", "LICENSE": "copyright!", "setup.py": "import toplevel", "bin": {"web": {"websetroot": "SET ROOT"}, "twistd": "TWISTD"}, "twisted": {"web": {"__init__.py": "import WEB", "topfiles": {"setup.py": "import WEBINSTALL", "README": "WEB!"}}, "words": {"__init__.py": "import WORDS"}, "plugins": {"twisted_web.py": "import WEBPLUG", "twisted_words.py": "import WORDPLUG"}}, "doc": {"web": {"howto": {"index.html": loreOutput}, "man": {"websetroot.1": manInput2, "websetroot-man.html": manOutput2}}, "core": {"howto": {"template.tpl": self.template}, "man": {"twistd.1": manInput1, "twistd-man.html": manOutput1}, "index.html": coreIndexOutput}}} self.createStructure(self.rootDir, structure) outputFile = self.builder.buildTwisted("10.0.0") self.assertExtractedStructure(outputFile, outStructure) def test_twistedDistributionExcludesWeb2AndVFSAndAdmin(self): """ The main Twisted distribution does not include web2 or vfs, or the bin/admin directory. """ loreInput, loreOutput = self.getArbitraryLoreInputAndOutput("10.0.0") coreIndexInput, coreIndexOutput = self.getArbitraryLoreInputAndOutput( "10.0.0", prefix="howto/") structure = { "README": "Twisted", "unrelated": "x", "LICENSE": "copyright!", "setup.py": "import toplevel", "bin": {"web2": {"websetroot": "SET ROOT"}, "vfs": {"vfsitup": "hee hee"}, "twistd": "TWISTD", "admin": {"build-a-thing": "yay"}}, "twisted": {"web2": {"__init__.py": "import WEB", "topfiles": {"setup.py": "import WEBINSTALL", "README": "WEB!"}}, "vfs": {"__init__.py": "import VFS", "blah blah": "blah blah"}, "words": {"__init__.py": "import WORDS"}, "plugins": {"twisted_web.py": "import WEBPLUG", "twisted_words.py": "import WORDPLUG", "twisted_web2.py": "import WEB2", "twisted_vfs.py": "import VFS"}}, "doc": {"web2": {"excluded!": "yay"}, "vfs": {"unrelated": "whatever"}, "core": {"howto": {"template.tpl": self.template}, "index.xhtml": coreIndexInput}}} outStructure = { "README": "Twisted", "unrelated": "x", "LICENSE": "copyright!", "setup.py": "import toplevel", "bin": {"twistd": "TWISTD"}, "twisted": {"words": {"__init__.py": "import WORDS"}, "plugins": {"twisted_web.py": "import WEBPLUG", "twisted_words.py": "import WORDPLUG"}}, "doc": {"core": {"howto": {"template.tpl": self.template}, "index.html": coreIndexOutput}}} self.createStructure(self.rootDir, structure) outputFile = self.builder.buildTwisted("10.0.0") self.assertExtractedStructure(outputFile, outStructure) def test_subProjectLayout(self): """ The subproject tarball includes files like so: 1. twisted/<subproject>/topfiles defines the files that will be in the top level in the tarball, except LICENSE, which comes from the real top-level directory. 2. twisted/<subproject> is included, but without the topfiles entry in that directory. No other twisted subpackages are included. 3. twisted/plugins/twisted_<subproject>.py is included, but nothing else in plugins is. """ structure = { "README": "HI!@", "unrelated": "x", "LICENSE": "copyright!", "setup.py": "import toplevel", "bin": {"web": {"websetroot": "SET ROOT"}, "words": {"im": "#!im"}}, "twisted": {"web": {"__init__.py": "import WEB", "topfiles": {"setup.py": "import WEBINSTALL", "README": "WEB!"}}, "words": {"__init__.py": "import WORDS"}, "plugins": {"twisted_web.py": "import WEBPLUG", "twisted_words.py": "import WORDPLUG"}}} outStructure = { "README": "WEB!", "LICENSE": "copyright!", "setup.py": "import WEBINSTALL", "bin": {"websetroot": "SET ROOT"}, "twisted": {"web": {"__init__.py": "import WEB"}, "plugins": {"twisted_web.py": "import WEBPLUG"}}} self.createStructure(self.rootDir, structure) outputFile = self.builder.buildSubProject("web", "0.3.0") self.assertExtractedStructure(outputFile, outStructure) def test_minimalSubProjectLayout(self): """ buildSubProject should work with minimal subprojects. """ structure = { "LICENSE": "copyright!", "bin": {}, "twisted": {"web": {"__init__.py": "import WEB", "topfiles": {"setup.py": "import WEBINSTALL"}}, "plugins": {}}} outStructure = { "setup.py": "import WEBINSTALL", "LICENSE": "copyright!", "twisted": {"web": {"__init__.py": "import WEB"}}} self.createStructure(self.rootDir, structure) outputFile = self.builder.buildSubProject("web", "0.3.0") self.assertExtractedStructure(outputFile, outStructure) def test_subProjectDocBuilding(self): """ When building a subproject release, documentation should be built with lore. """ loreInput, loreOutput = self.getArbitraryLoreInputAndOutput("0.3.0") manInput = self.getArbitraryManInput() manOutput = self.getArbitraryManHTMLOutput("0.3.0", "../howto/") structure = { "LICENSE": "copyright!", "twisted": {"web": {"__init__.py": "import WEB", "topfiles": {"setup.py": "import WEBINST"}}}, "doc": {"web": {"howto": {"index.xhtml": loreInput}, "man": {"twistd.1": manInput}}, "core": {"howto": {"template.tpl": self.template}} } } outStructure = { "LICENSE": "copyright!", "setup.py": "import WEBINST", "twisted": {"web": {"__init__.py": "import WEB"}}, "doc": {"howto": {"index.html": loreOutput}, "man": {"twistd.1": manInput, "twistd-man.html": manOutput}}} self.createStructure(self.rootDir, structure) outputFile = self.builder.buildSubProject("web", "0.3.0") self.assertExtractedStructure(outputFile, outStructure) def test_coreProjectLayout(self): """ The core tarball looks a lot like a subproject tarball, except it doesn't include: - Python packages from other subprojects - plugins from other subprojects - scripts from other subprojects """ indexInput, indexOutput = self.getArbitraryLoreInputAndOutput( "8.0.0", prefix="howto/") howtoInput, howtoOutput = self.getArbitraryLoreInputAndOutput("8.0.0") specInput, specOutput = self.getArbitraryLoreInputAndOutput( "8.0.0", prefix="../howto/") upgradeInput, upgradeOutput = self.getArbitraryLoreInputAndOutput( "8.0.0", prefix="../howto/") tutorialInput, tutorialOutput = self.getArbitraryLoreInputAndOutput( "8.0.0", prefix="../") structure = { "LICENSE": "copyright!", "twisted": {"__init__.py": "twisted", "python": {"__init__.py": "python", "roots.py": "roots!"}, "conch": {"__init__.py": "conch", "unrelated.py": "import conch"}, "plugin.py": "plugin", "plugins": {"twisted_web.py": "webplug", "twisted_whatever.py": "include!", "cred.py": "include!"}, "topfiles": {"setup.py": "import CORE", "README": "core readme"}}, "doc": {"core": {"howto": {"template.tpl": self.template, "index.xhtml": howtoInput, "tutorial": {"index.xhtml": tutorialInput}}, "specifications": {"index.xhtml": specInput}, "upgrades": {"index.xhtml": upgradeInput}, "examples": {"foo.py": "foo.py"}, "index.xhtml": indexInput}, "web": {"howto": {"index.xhtml": "webindex"}}}, "bin": {"twistd": "TWISTD", "web": {"websetroot": "websetroot"}} } outStructure = { "LICENSE": "copyright!", "setup.py": "import CORE", "README": "core readme", "twisted": {"__init__.py": "twisted", "python": {"__init__.py": "python", "roots.py": "roots!"}, "plugin.py": "plugin", "plugins": {"twisted_whatever.py": "include!", "cred.py": "include!"}}, "doc": {"howto": {"template.tpl": self.template, "index.html": howtoOutput, "tutorial": {"index.html": tutorialOutput}}, "specifications": {"index.html": specOutput}, "upgrades": {"index.html": upgradeOutput}, "examples": {"foo.py": "foo.py"}, "index.html": indexOutput}, "bin": {"twistd": "TWISTD"}, } self.createStructure(self.rootDir, structure) outputFile = self.builder.buildCore("8.0.0") self.assertExtractedStructure(outputFile, outStructure) def test_apiBaseURL(self): """ DistributionBuilder builds documentation with the specified API base URL. """ apiBaseURL = "http://%s" builder = DistributionBuilder(self.rootDir, self.outputDir, apiBaseURL=apiBaseURL) loreInput, loreOutput = self.getArbitraryLoreInputAndOutput( "0.3.0", apiBaseURL=apiBaseURL) structure = { "LICENSE": "copyright!", "twisted": {"web": {"__init__.py": "import WEB", "topfiles": {"setup.py": "import WEBINST"}}}, "doc": {"web": {"howto": {"index.xhtml": loreInput}}, "core": {"howto": {"template.tpl": self.template}} } } outStructure = { "LICENSE": "copyright!", "setup.py": "import WEBINST", "twisted": {"web": {"__init__.py": "import WEB"}}, "doc": {"howto": {"index.html": loreOutput}}} self.createStructure(self.rootDir, structure) outputFile = builder.buildSubProject("web", "0.3.0") self.assertExtractedStructure(outputFile, outStructure) class BuildAllTarballsTest(DistributionBuilderTestBase): """ Tests for L{DistributionBuilder.buildAllTarballs}. """ skip = svnSkip def setUp(self): self.oldHandler = signal.signal(signal.SIGCHLD, signal.SIG_DFL) DistributionBuilderTestBase.setUp(self) def tearDown(self): signal.signal(signal.SIGCHLD, self.oldHandler) DistributionBuilderTestBase.tearDown(self) def test_buildAllTarballs(self): """ L{buildAllTarballs} builds tarballs for Twisted and all of its subprojects based on an SVN checkout; the resulting tarballs contain no SVN metadata. This involves building documentation, which it will build with the correct API documentation reference base URL. """ repositoryPath = self.mktemp() repository = FilePath(repositoryPath) checkoutPath = self.mktemp() checkout = FilePath(checkoutPath) self.outputDir.remove() runCommand(["svnadmin", "create", repositoryPath]) runCommand(["svn", "checkout", "file://" + repository.path, checkout.path]) coreIndexInput, coreIndexOutput = self.getArbitraryLoreInputAndOutput( "1.2.0", prefix="howto/", apiBaseURL="http://twistedmatrix.com/documents/1.2.0/api/%s.html") structure = { "README": "Twisted", "unrelated": "x", "LICENSE": "copyright!", "setup.py": "import toplevel", "bin": {"web2": {"websetroot": "SET ROOT"}, "vfs": {"vfsitup": "hee hee"}, "words": {"im": "import im"}, "twistd": "TWISTD"}, "twisted": { "topfiles": {"setup.py": "import TOPINSTALL", "README": "CORE!"}, "_version.py": genVersion("twisted", 1, 2, 0), "web2": {"__init__.py": "import WEB", "topfiles": {"setup.py": "import WEBINSTALL", "README": "WEB!"}}, "vfs": {"__init__.py": "import VFS", "blah blah": "blah blah"}, "words": {"__init__.py": "import WORDS", "_version.py": genVersion("twisted.words", 1, 2, 0), "topfiles": {"setup.py": "import WORDSINSTALL", "README": "WORDS!"}, }, "plugins": {"twisted_web.py": "import WEBPLUG", "twisted_words.py": "import WORDPLUG", "twisted_web2.py": "import WEB2", "twisted_vfs.py": "import VFS", "twisted_yay.py": "import YAY"}}, "doc": {"web2": {"excluded!": "yay"}, "vfs": {"unrelated": "whatever"}, "core": {"howto": {"template.tpl": self.template}, "index.xhtml": coreIndexInput}}} twistedStructure = { "README": "Twisted", "unrelated": "x", "LICENSE": "copyright!", "setup.py": "import toplevel", "bin": {"twistd": "TWISTD", "words": {"im": "import im"}}, "twisted": { "topfiles": {"setup.py": "import TOPINSTALL", "README": "CORE!"}, "_version.py": genVersion("twisted", 1, 2, 0), "words": {"__init__.py": "import WORDS", "_version.py": genVersion("twisted.words", 1, 2, 0), "topfiles": {"setup.py": "import WORDSINSTALL", "README": "WORDS!"}, }, "plugins": {"twisted_web.py": "import WEBPLUG", "twisted_words.py": "import WORDPLUG", "twisted_yay.py": "import YAY"}}, "doc": {"core": {"howto": {"template.tpl": self.template}, "index.html": coreIndexOutput}}} coreStructure = { "setup.py": "import TOPINSTALL", "README": "CORE!", "LICENSE": "copyright!", "bin": {"twistd": "TWISTD"}, "twisted": { "_version.py": genVersion("twisted", 1, 2, 0), "plugins": {"twisted_yay.py": "import YAY"}}, "doc": {"howto": {"template.tpl": self.template}, "index.html": coreIndexOutput}} wordsStructure = { "README": "WORDS!", "LICENSE": "copyright!", "setup.py": "import WORDSINSTALL", "bin": {"im": "import im"}, "twisted": { "words": {"__init__.py": "import WORDS", "_version.py": genVersion("twisted.words", 1, 2, 0), }, "plugins": {"twisted_words.py": "import WORDPLUG"}}} self.createStructure(checkout, structure) childs = [x.path for x in checkout.children()] runCommand(["svn", "add"] + childs) runCommand(["svn", "commit", checkout.path, "-m", "yay"]) buildAllTarballs(checkout, self.outputDir) self.assertEquals( set(self.outputDir.children()), set([self.outputDir.child("Twisted-1.2.0.tar.bz2"), self.outputDir.child("TwistedCore-1.2.0.tar.bz2"), self.outputDir.child("TwistedWords-1.2.0.tar.bz2")])) self.assertExtractedStructure( self.outputDir.child("Twisted-1.2.0.tar.bz2"), twistedStructure) self.assertExtractedStructure( self.outputDir.child("TwistedCore-1.2.0.tar.bz2"), coreStructure) self.assertExtractedStructure( self.outputDir.child("TwistedWords-1.2.0.tar.bz2"), wordsStructure) def test_buildAllTarballsEnsuresCleanCheckout(self): """ L{UncleanWorkingDirectory} is raised by L{buildAllTarballs} when the SVN checkout provided has uncommitted changes. """ repositoryPath = self.mktemp() repository = FilePath(repositoryPath) checkoutPath = self.mktemp() checkout = FilePath(checkoutPath) runCommand(["svnadmin", "create", repositoryPath]) runCommand(["svn", "checkout", "file://" + repository.path, checkout.path]) checkout.child("foo").setContent("whatever") self.assertRaises(UncleanWorkingDirectory, buildAllTarballs, checkout, FilePath(self.mktemp())) def test_buildAllTarballsEnsuresExistingCheckout(self): """ L{NotWorkingDirectory} is raised by L{buildAllTarballs} when the checkout passed does not exist or is not an SVN checkout. """ checkout = FilePath(self.mktemp()) self.assertRaises(NotWorkingDirectory, buildAllTarballs, checkout, FilePath(self.mktemp())) checkout.createDirectory() self.assertRaises(NotWorkingDirectory, buildAllTarballs, checkout, FilePath(self.mktemp())) class ScriptTests(BuilderTestsMixin, StructureAssertingMixin, TestCase): """ Tests for the release script functionality. """ def _testVersionChanging(self, major, minor, micro, prerelease=None): """ Check that L{ChangeVersionsScript.main} calls the version-changing function with the appropriate version data and filesystem path. """ versionUpdates = [] def myVersionChanger(sourceTree, versionTemplate): versionUpdates.append((sourceTree, versionTemplate)) versionChanger = ChangeVersionsScript() versionChanger.changeAllProjectVersions = myVersionChanger version = "%d.%d.%d" % (major, minor, micro) if prerelease is not None: version += "pre%d" % (prerelease,) versionChanger.main([version]) self.assertEquals(len(versionUpdates), 1) self.assertEquals(versionUpdates[0][0], FilePath(".")) self.assertEquals(versionUpdates[0][1].major, major) self.assertEquals(versionUpdates[0][1].minor, minor) self.assertEquals(versionUpdates[0][1].micro, micro) self.assertEquals(versionUpdates[0][1].prerelease, prerelease) def test_changeVersions(self): """ L{ChangeVersionsScript.main} changes version numbers for all Twisted projects. """ self._testVersionChanging(8, 2, 3) def test_changeVersionsWithPrerelease(self): """ A prerelease can be specified to L{changeVersionsScript}. """ self._testVersionChanging(9, 2, 7, 38) def test_defaultChangeVersionsVersionChanger(self): """ The default implementation of C{changeAllProjectVersions} is L{changeAllProjectVersions}. """ versionChanger = ChangeVersionsScript() self.assertEquals(versionChanger.changeAllProjectVersions, changeAllProjectVersions) def test_badNumberOfArgumentsToChangeVersionsScript(self): """ L{changeVersionsScript} raises SystemExit when the wrong number of arguments are passed. """ versionChanger = ChangeVersionsScript() self.assertRaises(SystemExit, versionChanger.main, []) def test_tooManyDotsToChangeVersionsScript(self): """ L{changeVersionsScript} raises SystemExit when there are the wrong number of segments in the version number passed. """ versionChanger = ChangeVersionsScript() self.assertRaises(SystemExit, versionChanger.main, ["3.2.1.0"]) def test_nonIntPartsToChangeVersionsScript(self): """ L{changeVersionsScript} raises SystemExit when the version number isn't made out of numbers. """ versionChanger = ChangeVersionsScript() self.assertRaises(SystemExit, versionChanger.main, ["my united.states.of prewhatever"]) def test_buildTarballsScript(self): """ L{BuildTarballsScript.main} invokes L{buildAllTarballs} with L{FilePath} instances representing the paths passed to it. """ builds = [] def myBuilder(checkout, destination): builds.append((checkout, destination)) tarballBuilder = BuildTarballsScript() tarballBuilder.buildAllTarballs = myBuilder tarballBuilder.main(["checkoutDir", "destinationDir"]) self.assertEquals( builds, [(FilePath("checkoutDir"), FilePath("destinationDir"))]) def test_defaultBuildTarballsScriptBuilder(self): """ The default implementation of L{BuildTarballsScript.buildAllTarballs} is L{buildAllTarballs}. """ tarballBuilder = BuildTarballsScript() self.assertEquals(tarballBuilder.buildAllTarballs, buildAllTarballs) def test_badNumberOfArgumentsToBuildTarballs(self): """ L{BuildTarballsScript.main} raises SystemExit when the wrong number of arguments are passed. """ tarballBuilder = BuildTarballsScript() self.assertRaises(SystemExit, tarballBuilder.main, []) def test_badNumberOfArgumentsToBuildNews(self): """ L{NewsBuilder.main} raises L{SystemExit} when other than 1 argument is passed to it. """ newsBuilder = NewsBuilder() self.assertRaises(SystemExit, newsBuilder.main, []) self.assertRaises(SystemExit, newsBuilder.main, ["hello", "world"]) def test_buildNews(self): """ L{NewsBuilder.main} calls L{NewsBuilder.buildAll} with a L{FilePath} instance constructed from the path passed to it. """ builds = [] newsBuilder = NewsBuilder() newsBuilder.buildAll = builds.append newsBuilder.main(["/foo/bar/baz"]) self.assertEquals(builds, [FilePath("/foo/bar/baz")])
gpl-2.0
robinro/ansible
contrib/inventory/libvirt_lxc.py
196
1357
#!/usr/bin/env python # (c) 2013, Michael Scherer <misc@zarb.org> # # 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 subprocess import Popen, PIPE import sys import json result = {} result['all'] = {} pipe = Popen(['virsh', '-q', '-c', 'lxc:///', 'list', '--name', '--all'], stdout=PIPE, universal_newlines=True) result['all']['hosts'] = [x[:-1] for x in pipe.stdout.readlines()] result['all']['vars'] = {} result['all']['vars']['ansible_connection'] = 'libvirt_lxc' if len(sys.argv) == 2 and sys.argv[1] == '--list': print(json.dumps(result)) elif len(sys.argv) == 3 and sys.argv[1] == '--host': print(json.dumps({'ansible_connection': 'libvirt_lxc'})) else: sys.stderr.write("Need an argument, either --list or --host <host>\n")
gpl-3.0
simonemurzilli/geonode
geonode/contrib/slack/utils.py
10
7977
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2012 OpenPlans # # 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 copy from slugify import Slugify from httplib import HTTPSConnection from urlparse import urlsplit from django.conf import settings from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.http import HttpResponse from django.utils import simplejson as json from .enumerations import SLACK_MESSAGE_TEMPLATES from geonode.base.models import Link custom_slugify = Slugify(separator='_') def _build_state_resourcebase(resource): site = Site.objects.get_current() thumbnail_url = resource.get_thumbnail_url() owner_url = "{base}{context}".format(base=settings.SITEURL[:-1], context=resource.owner.get_absolute_url()) state = { 'title': resource.title, 'type': resource.polymorphic_ctype, 'sitename': site.name, 'baseurl': settings.SITEURL, 'owner_name': (resource.owner.get_full_name() or resource.owner.username), 'owner_url': owner_url, 'thumbnail_url': thumbnail_url } return state def _build_state_layer(layer): state = _build_state_resourcebase(layer) url_detail = "{base}{context}".format(base=settings.SITEURL[:-1], context=layer.detail_url) link_shp = Link.objects.get(resource=layer.get_self_resource(), name='Zipped Shapefile') link_geojson = Link.objects.get(resource=layer.get_self_resource(), name='GeoJSON') link_netkml = Link.objects.get(resource=layer.get_self_resource(), name='View in Google Earth') url_map = "{base}{context}".format( base=settings.SITEURL[:-1], context=reverse("new_map")+"?layer="+layer.service_typename) state['url_detail'] = url_detail state['url_shp'] = link_shp.url if link_shp else '' state['url_geojson'] = link_geojson.url if link_geojson else '' state['url_netkml'] = link_netkml.url if link_netkml else '' state['url_map'] = url_map return state def _build_state_map(map): state = _build_state_resourcebase(map) url_detail = "{base}{context}".format( base=settings.SITEURL[:-1], context=reverse('map_detail', args=(map.id,))) url_view = "{base}{context}".format( base=settings.SITEURL[:-1], context=reverse('map_view', args=(map.id,))) url_download = "{base}{context}".format( base=settings.SITEURL[:-1], context=reverse('map_download', args=(map.id,))) state['url_detail'] = url_detail state['url_view'] = url_view state['url_download'] = url_download return state def _build_state_document(document): state = _build_state_resourcebase(document) url_detail = "{base}{context}".format( base=settings.SITEURL[:-1], context=reverse('document_detail', args=(document.id,))) url_download = "{base}{context}".format( base=settings.SITEURL[:-1], context=reverse('document_download', args=(document.id,))) state['url_detail'] = url_detail state['url_download'] = url_download return state def _render_attachment(a, state): for k in ["title", "title_link", "fallback", "text", "thumb_url"]: if k in a: a[k] = a[k].format(** state) if "fields" in a: for j in range(len(a["fields"])): f = a["fields"][j] if "title" in f: f["title"] = f["title"].format(** state) if "value" in f: f["value"] = f["value"].format(** state) a["fields"][j].update(f) return copy.deepcopy(a) def _render_message_plain(template, resource): state = _build_state_resourcebase(resource) message = None try: message = {} if "text" in template: message["text"] = template["text"].format(** state) if "icon_url" in template: message["icon_url"] = template["icon_url"].format(** state) except: print "Could not build plain slack message for resource" message = None return message def build_slack_message_layer(event, layer): message = None try: if event.lower() in SLACK_MESSAGE_TEMPLATES: event_lc = event.lower() if "attachments" in SLACK_MESSAGE_TEMPLATES[event_lc]: state = _build_state_layer(layer) message = copy.deepcopy(SLACK_MESSAGE_TEMPLATES[event_lc]) for i in range(len(message["attachments"])): a = _render_attachment(message["attachments"][i], state) message["attachments"][i] = a else: message = _render_message_plain(SLACK_MESSAGE_TEMPLATES[event_lc], layer) else: print "Slack template not found." except: print "Could not build slack message for layer." message = None return message def build_slack_message_map(event, map_obj): message = None try: if event.lower() in SLACK_MESSAGE_TEMPLATES: event_lc = event.lower() if "attachments" in SLACK_MESSAGE_TEMPLATES[event_lc]: state = _build_state_map(map_obj) message = copy.deepcopy(SLACK_MESSAGE_TEMPLATES[event_lc]) for i in range(len(message["attachments"])): a = _render_attachment(message["attachments"][i], state) message["attachments"][i] = a else: message = _render_message_plain(SLACK_MESSAGE_TEMPLATES[event_lc], map_obj) else: print "Slack template not found." except: print "Could not build slack message for map." message = None return message def build_slack_message_document(event, document): message = None try: if event.lower() in SLACK_MESSAGE_TEMPLATES: event_lc = event.lower() if "attachments" in SLACK_MESSAGE_TEMPLATES[event_lc]: state = _build_state_document(document) message = copy.deepcopy(SLACK_MESSAGE_TEMPLATES[event_lc]) for i in range(len(message["attachments"])): a = _render_attachment(message["attachments"][i], state) message["attachments"][i] = a else: message = _render_message_plain(SLACK_MESSAGE_TEMPLATES[event_lc], document) else: print "Slack template not found." except: print "Could not build slack message for document." message = None return message def send_slack_messages(message): if message and settings.SLACK_WEBHOOK_URLS: for url in settings.SLACK_WEBHOOK_URLS: _post_slack_message(message, url) else: print "Slack message is None." return None def _post_slack_message(message, webhook_endpoint): url = urlsplit(webhook_endpoint) headers = {} conn = HTTPSConnection(url.hostname, url.port) conn.request("POST", str(url.path), json.dumps(message), headers) result = conn.getresponse() response = HttpResponse( result.read(), status=result.status, content_type=result.getheader("Content-Type", "text/plain")) return response
gpl-3.0
redshiftzero/pgpbuddy
tests/test_crypto.py
1
10432
from unittest.mock import patch from unittest import TestCase from nose.tools import assert_list_equal from pgpbuddy.crypto import * from tests.mock_gpg import * class TestCheckEncryptionAndSignature(TestCase): @patch('gnupg.GPG', decrypt=mock_decrypt(Encryption.missing, Signature.missing)) def test_plain(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.missing assert signature_status == Signature.missing assert not reason @patch('gnupg.GPG', decrypt=mock_decrypt(Encryption.missing, Signature.incorrect)) def test_not_encrypted_incorrect_signature(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.missing assert signature_status == Signature.incorrect assert reason @patch('gnupg.GPG', decrypt=mock_decrypt(Encryption.missing, Signature.correct)) def test_not_encrypted_correct_signature(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.missing assert signature_status == Signature.correct assert not reason @patch('gnupg.GPG', decrypt=mock_decrypt(Encryption.correct, Signature.missing)) def test_correct_encrypted_no_sig(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.correct assert signature_status == Signature.missing assert not reason @patch('gnupg.GPG', decrypt=mock_decrypt(Encryption.correct, Signature.incorrect)) def test_correct_encrypted_incorrect_sig(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.correct assert signature_status == Signature.incorrect assert reason @patch('gnupg.GPG', decrypt=mock_decrypt(Encryption.correct, Signature.correct)) def test_correct_encrypted_correct_sig(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.correct assert signature_status == Signature.correct assert not reason @patch('gnupg.GPG', decrypt=mock_decrypt(Encryption.incorrect, Signature.correct)) def test_incorrect_encrypted_sig_correct(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.incorrect assert signature_status == Signature.missing # with incorrect encryption can not check the sig assert reason @patch('gnupg.GPG', decrypt=mock_decrypt(Encryption.incorrect, Signature.missing)) def test_incorrect_encrypted_sig_missing(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.incorrect assert signature_status == Signature.missing # with incorrect encryption can not check the sig assert reason @patch('gnupg.GPG', decrypt=mock_decrypt(Encryption.incorrect, Signature.incorrect)) def test_incorrect_encrypted_sig_incorrect(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.incorrect assert signature_status == Signature.missing # with incorrect encryption can not check the sig assert reason @patch('gnupg.GPG', decrypt=mock_decrypt_unexpected_output()) def test_fallback(self, gpg): encryption_status, signature_status, reason = check_encryption_and_signature(gpg, "blabla") assert encryption_status == Encryption.incorrect assert signature_status == Signature.incorrect assert reason class TestImportKeysFromAttachments(TestCase): def _mock_key(self, content): return "-----BEGIN PGP PUBLIC KEY BLOCK-----\n{}\n-----END PGP PUBLIC KEY BLOCK-----\n".format(content) @patch('gnupg.GPG') def test_no_attachments(self, gpg): attachments = [] remaining_attachments = import_public_keys_from_attachments(gpg, attachments) assert remaining_attachments == [] assert not gpg.import_keys.called @patch('gnupg.GPG') def test_plain_attachment(self, gpg): attachments = [("blabla", None)] remaining_attachments = import_public_keys_from_attachments(gpg, attachments) assert_list_equal(attachments, remaining_attachments) assert not gpg.import_keys.called @patch('gnupg.GPG', import_keys=mock_import_keys(True)) def test_key_attachment(self, gpg): key = self._mock_key("PRETEND THIS IS A KEY") attachments = [(key, None)] remaining_attachments = import_public_keys_from_attachments(gpg, attachments) expected = [] assert_list_equal(expected, remaining_attachments) gpg.import_keys.assert_called_once_with(self.__format_key(key)) @patch('gnupg.GPG', import_keys=mock_import_keys(False)) def test_key_attachment_import_fails(self, gpg): key = self._mock_key("PRETEND THIS IS A KEY") attachments = [(key, None)] remaining_attachments = import_public_keys_from_attachments(gpg, attachments) expected = attachments assert_list_equal(expected, remaining_attachments) gpg.import_keys.assert_called_once_with(self.__format_key(key)) @patch('gnupg.GPG') def test_binary_attachment(self, gpg): attachments = [(self._mock_key("This will be binary so not considered a key").encode(), None)] remaining_attachments = import_public_keys_from_attachments(gpg, attachments) expected = attachments assert_list_equal(expected, remaining_attachments) assert not gpg.import_keys.called @patch('gnupg.GPG', import_keys=mock_import_keys([False, True, True])) def test_mixture_of_everything(self, gpg): key1 = self._mock_key("Failing key") key2 = self._mock_key("Succeeding key") key3 = self._mock_key("Another succeeding key") attachments = [("blabla", None), (key1, None), (b"binary", None), (key2, None), ("ladida", None), (key3, None)] remaining_attachments = import_public_keys_from_attachments(gpg, attachments) expected = [attachments[0], attachments[1], attachments[2], attachments[4]] assert_list_equal(expected, remaining_attachments) gpg.import_keys.assert_any_call(self.__format_key(key1)) gpg.import_keys.assert_any_call(self.__format_key(key2)) gpg.import_keys.assert_any_call(self.__format_key(key3)) @patch('gnupg.GPG') def test_preserve_encryption_status(self, gpg): attachments = [("bla", Encryption.missing), ("blu", Encryption.correct), ("ble", Encryption.incorrect)] remaining_attachments = import_public_keys_from_attachments(gpg, attachments) expected = attachments assert_list_equal(expected, remaining_attachments) assert not gpg.import_keys.called @staticmethod def __format_key(key): return key.strip().split("\n") class TestImportFromKeyServer(): server = 'pgp.mit.edu' @patch('gnupg.GPG', search_keys=mock_search_keys([]), recv_keys=mock_recv_keys()) def test_no_key_found(self, gpg): sender = "sender@plain.txt" import_public_keys_from_server(gpg, sender) gpg.search_keys.assert_called_once_with(sender, self.server) assert not gpg.recv_keys.called @patch('gnupg.GPG', search_keys=mock_search_keys(["key1"]), recv_keys=mock_recv_keys()) def test_one_key_found(self, gpg): sender = "sender@plain.txt" import_public_keys_from_server(gpg, sender) gpg.search_keys.assert_called_once_with(sender, self.server) gpg.recv_keys.assert_called_once_with(self.server, "key1") @patch('gnupg.GPG', search_keys=mock_search_keys(["key1", "key2"]), recv_keys=mock_recv_keys()) def test_two_keys_found(self, gpg): sender = "sender@plain.txt" import_public_keys_from_server(gpg, sender) gpg.search_keys.assert_called_once_with(sender, self.server) gpg.recv_keys.assert_any_call(self.server, "key1") gpg.recv_keys.assert_any_call(self.server, "key2") class TestPublicKeyAvailable(TestCase): @patch('gnupg.GPG', encrypt=mock_encrypt(success=True)) def test_available(self, gpg): sender = "sender@plain.text" result = check_public_key_available(gpg, sender) assert result == PublicKey.available @patch('gnupg.GPG', encrypt=mock_encrypt(success=False)) def test_not_available(self, gpg): sender = "sender@plain.text" result = check_public_key_available(gpg, sender) assert result == PublicKey.not_available class TestVerifyExternalSig(TestCase): @patch('gnupg.GPG', verify_data=mock_verify(Signature.correct)) def test_good_sig(self, gpg): sig = b"good sig" data = "to be signed" signature_status, reason = verify_external_sig(gpg, data, sig) assert signature_status == Signature.correct assert not reason @patch('gnupg.GPG', verify_data=mock_verify(Signature.incorrect, PublicKey.not_available)) def test_no_public_key(self, gpg): sig = b"bad sig" data = "to be signed" signature_status, reason = verify_external_sig(gpg, data, sig) assert signature_status == Signature.incorrect assert reason @patch('gnupg.GPG', verify_data=mock_verify(Signature.incorrect, PublicKey.available)) def test_bad_sig(self, gpg): sig = b"bad sig" data = "to be signed" signature_status, reason = verify_external_sig(gpg, data, sig) assert signature_status == Signature.incorrect assert reason @patch('gnupg.GPG', verify_data=mock_verify(Signature.missing)) def test_no_sig(self, gpg): sig = b"bad sig" data = "to be signed" signature_status, reason = verify_external_sig(gpg, data, sig) assert signature_status == Signature.missing assert not reason
gpl-2.0
ProfessionalIT/professionalit-webiste
sdk/google_appengine/lib/django-1.4/django/contrib/gis/gdal/srs.py
80
11683
""" The Spatial Reference class, represensents OGR Spatial Reference objects. Example: >>> from django.contrib.gis.gdal import SpatialReference >>> srs = SpatialReference('WGS84') >>> print srs GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], TOWGS84[0,0,0,0,0,0,0], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]] >>> print srs.proj +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs >>> print srs.ellipsoid (6378137.0, 6356752.3142451793, 298.25722356300003) >>> print srs.projected, srs.geographic False True >>> srs.import_epsg(32140) >>> print srs.name NAD83 / Texas South Central """ from ctypes import byref, c_char_p, c_int # Getting the error checking routine and exceptions from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import SRSException from django.contrib.gis.gdal.prototypes import srs as capi #### Spatial Reference class. #### class SpatialReference(GDALBase): """ A wrapper for the OGRSpatialReference object. According to the GDAL Web site, the SpatialReference object "provide[s] services to represent coordinate systems (projections and datums) and to transform between them." """ #### Python 'magic' routines #### def __init__(self, srs_input=''): """ Creates a GDAL OSR Spatial Reference object from the given input. The input may be string of OGC Well Known Text (WKT), an integer EPSG code, a PROJ.4 string, and/or a projection "well known" shorthand string (one of 'WGS84', 'WGS72', 'NAD27', 'NAD83'). """ buf = c_char_p('') srs_type = 'user' if isinstance(srs_input, basestring): # Encoding to ASCII if unicode passed in. if isinstance(srs_input, unicode): srs_input = srs_input.encode('ascii') try: # If SRID is a string, e.g., '4326', then make acceptable # as user input. srid = int(srs_input) srs_input = 'EPSG:%d' % srid except ValueError: pass elif isinstance(srs_input, (int, long)): # EPSG integer code was input. srs_type = 'epsg' elif isinstance(srs_input, self.ptr_type): srs = srs_input srs_type = 'ogr' else: raise TypeError('Invalid SRS type "%s"' % srs_type) if srs_type == 'ogr': # Input is already an SRS pointer. srs = srs_input else: # Creating a new SRS pointer, using the string buffer. srs = capi.new_srs(buf) # If the pointer is NULL, throw an exception. if not srs: raise SRSException('Could not create spatial reference from: %s' % srs_input) else: self.ptr = srs # Importing from either the user input string or an integer SRID. if srs_type == 'user': self.import_user_input(srs_input) elif srs_type == 'epsg': self.import_epsg(srs_input) def __del__(self): "Destroys this spatial reference." if self._ptr: capi.release_srs(self._ptr) def __getitem__(self, target): """ Returns the value of the given string attribute node, None if the node doesn't exist. Can also take a tuple as a parameter, (target, child), where child is the index of the attribute in the WKT. For example: >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]') >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326 >>> print srs['GEOGCS'] WGS 84 >>> print srs['DATUM'] WGS_1984 >>> print srs['AUTHORITY'] EPSG >>> print srs['AUTHORITY', 1] # The authority value 4326 >>> print srs['TOWGS84', 4] # the fourth value in this wkt 0 >>> print srs['UNIT|AUTHORITY'] # For the units authority, have to use the pipe symbole. EPSG >>> print srs['UNIT|AUTHORITY', 1] # The authority value for the untis 9122 """ if isinstance(target, tuple): return self.attr_value(*target) else: return self.attr_value(target) def __str__(self): "The string representation uses 'pretty' WKT." return self.pretty_wkt #### SpatialReference Methods #### def attr_value(self, target, index=0): """ The attribute value for the given target node (e.g. 'PROJCS'). The index keyword specifies an index of the child node to return. """ if not isinstance(target, basestring) or not isinstance(index, int): raise TypeError return capi.get_attr_value(self.ptr, target, index) def auth_name(self, target): "Returns the authority name for the given string target node." return capi.get_auth_name(self.ptr, target) def auth_code(self, target): "Returns the authority code for the given string target node." return capi.get_auth_code(self.ptr, target) def clone(self): "Returns a clone of this SpatialReference object." return SpatialReference(capi.clone_srs(self.ptr)) def from_esri(self): "Morphs this SpatialReference from ESRI's format to EPSG." capi.morph_from_esri(self.ptr) def identify_epsg(self): """ This method inspects the WKT of this SpatialReference, and will add EPSG authority nodes where an EPSG identifier is applicable. """ capi.identify_epsg(self.ptr) def to_esri(self): "Morphs this SpatialReference to ESRI's format." capi.morph_to_esri(self.ptr) def validate(self): "Checks to see if the given spatial reference is valid." capi.srs_validate(self.ptr) #### Name & SRID properties #### @property def name(self): "Returns the name of this Spatial Reference." if self.projected: return self.attr_value('PROJCS') elif self.geographic: return self.attr_value('GEOGCS') elif self.local: return self.attr_value('LOCAL_CS') else: return None @property def srid(self): "Returns the SRID of top-level authority, or None if undefined." try: return int(self.attr_value('AUTHORITY', 1)) except (TypeError, ValueError): return None #### Unit Properties #### @property def linear_name(self): "Returns the name of the linear units." units, name = capi.linear_units(self.ptr, byref(c_char_p())) return name @property def linear_units(self): "Returns the value of the linear units." units, name = capi.linear_units(self.ptr, byref(c_char_p())) return units @property def angular_name(self): "Returns the name of the angular units." units, name = capi.angular_units(self.ptr, byref(c_char_p())) return name @property def angular_units(self): "Returns the value of the angular units." units, name = capi.angular_units(self.ptr, byref(c_char_p())) return units @property def units(self): """ Returns a 2-tuple of the units value and the units name, and will automatically determines whether to return the linear or angular units. """ if self.projected or self.local: return capi.linear_units(self.ptr, byref(c_char_p())) elif self.geographic: return capi.angular_units(self.ptr, byref(c_char_p())) else: return (None, None) #### Spheroid/Ellipsoid Properties #### @property def ellipsoid(self): """ Returns a tuple of the ellipsoid parameters: (semimajor axis, semiminor axis, and inverse flattening) """ return (self.semi_major, self.semi_minor, self.inverse_flattening) @property def semi_major(self): "Returns the Semi Major Axis for this Spatial Reference." return capi.semi_major(self.ptr, byref(c_int())) @property def semi_minor(self): "Returns the Semi Minor Axis for this Spatial Reference." return capi.semi_minor(self.ptr, byref(c_int())) @property def inverse_flattening(self): "Returns the Inverse Flattening for this Spatial Reference." return capi.invflattening(self.ptr, byref(c_int())) #### Boolean Properties #### @property def geographic(self): """ Returns True if this SpatialReference is geographic (root node is GEOGCS). """ return bool(capi.isgeographic(self.ptr)) @property def local(self): "Returns True if this SpatialReference is local (root node is LOCAL_CS)." return bool(capi.islocal(self.ptr)) @property def projected(self): """ Returns True if this SpatialReference is a projected coordinate system (root node is PROJCS). """ return bool(capi.isprojected(self.ptr)) #### Import Routines ##### def import_epsg(self, epsg): "Imports the Spatial Reference from the EPSG code (an integer)." capi.from_epsg(self.ptr, epsg) def import_proj(self, proj): "Imports the Spatial Reference from a PROJ.4 string." capi.from_proj(self.ptr, proj) def import_user_input(self, user_input): "Imports the Spatial Reference from the given user input string." capi.from_user_input(self.ptr, user_input) def import_wkt(self, wkt): "Imports the Spatial Reference from OGC WKT (string)" capi.from_wkt(self.ptr, byref(c_char_p(wkt))) def import_xml(self, xml): "Imports the Spatial Reference from an XML string." capi.from_xml(self.ptr, xml) #### Export Properties #### @property def wkt(self): "Returns the WKT representation of this Spatial Reference." return capi.to_wkt(self.ptr, byref(c_char_p())) @property def pretty_wkt(self, simplify=0): "Returns the 'pretty' representation of the WKT." return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify) @property def proj(self): "Returns the PROJ.4 representation for this Spatial Reference." return capi.to_proj(self.ptr, byref(c_char_p())) @property def proj4(self): "Alias for proj()." return self.proj @property def xml(self, dialect=''): "Returns the XML representation of this Spatial Reference." return capi.to_xml(self.ptr, byref(c_char_p()), dialect) class CoordTransform(GDALBase): "The coordinate system transformation object." def __init__(self, source, target): "Initializes on a source and target SpatialReference objects." if not isinstance(source, SpatialReference) or not isinstance(target, SpatialReference): raise TypeError('source and target must be of type SpatialReference') self.ptr = capi.new_ct(source._ptr, target._ptr) self._srs1_name = source.name self._srs2_name = target.name def __del__(self): "Deletes this Coordinate Transformation object." if self._ptr: capi.destroy_ct(self._ptr) def __str__(self): return 'Transform from "%s" to "%s"' % (self._srs1_name, self._srs2_name)
lgpl-3.0
CoderDuan/mantaflow
scenes/simpleplume.py
2
1414
# # Simple example scene (hello world) # Simulation of a buoyant smoke density plume (with noise texture as smoke source) # #import pdb; pdb.set_trace() from manta import * # solver params res = 64 gs = vec3(res, int(1.5*res), res) s = FluidSolver(name='main', gridSize = gs) # prepare grids flags = s.create(FlagGrid) vel = s.create(MACGrid) density = s.create(RealGrid) pressure = s.create(RealGrid) # noise field, tweak a bit for smoke source noise = s.create(NoiseField, loadFromFile=True) noise.posScale = vec3(45) noise.clamp = True noise.clampNeg = 0 noise.clampPos = 1 noise.valOffset = 0.75 noise.timeAnim = 0.2 source = s.create(Cylinder, center=gs*vec3(0.5,0.1,0.5), radius=res*0.14, z=gs*vec3(0, 0.02, 0)) flags.initDomain() flags.fillGrid() if (GUI): gui = Gui() gui.show() #main loop for t in range(250): mantaMsg('\nFrame %i' % (s.frame)) if t<100: densityInflow(flags=flags, density=density, noise=noise, shape=source, scale=1, sigma=0.5) # optionally, enforce inflow velocity #source.applyToGrid(grid=vel, value=vec3(0.1,0,0)) advectSemiLagrange(flags=flags, vel=vel, grid=density, order=2) advectSemiLagrange(flags=flags, vel=vel, grid=vel , order=2, strength=1.0) setWallBcs(flags=flags, vel=vel) addBuoyancy(density=density, vel=vel, gravity=vec3(0,-6e-4,0), flags=flags) solvePressure( flags=flags, vel=vel, pressure=pressure ) s.step()
gpl-3.0
ramanajee/phantomjs
src/qt/qtwebkit/Source/WebCore/inspector/CodeGeneratorInspector.py
117
97853
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Copyright (c) 2012 Intel Corporation. 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. import os.path import sys import string import optparse import re try: import json except ImportError: import simplejson as json import CodeGeneratorInspectorStrings DOMAIN_DEFINE_NAME_MAP = { "Database": "SQL_DATABASE", "Debugger": "JAVASCRIPT_DEBUGGER", "DOMDebugger": "JAVASCRIPT_DEBUGGER", "FileSystem": "FILE_SYSTEM", "IndexedDB": "INDEXED_DATABASE", "Profiler": "JAVASCRIPT_DEBUGGER", "Worker": "WORKERS", } # Manually-filled map of type name replacements. TYPE_NAME_FIX_MAP = { "RGBA": "Rgba", # RGBA is reported to be conflicting with a define name in Windows CE. "": "Empty", } TYPES_WITH_RUNTIME_CAST_SET = frozenset(["Runtime.RemoteObject", "Runtime.PropertyDescriptor", "Runtime.InternalPropertyDescriptor", "Debugger.FunctionDetails", "Debugger.CallFrame", "Canvas.TraceLog", "Canvas.ResourceInfo", "Canvas.ResourceState", # This should be a temporary hack. TimelineEvent should be created via generated C++ API. "Timeline.TimelineEvent"]) TYPES_WITH_OPEN_FIELD_LIST_SET = frozenset(["Timeline.TimelineEvent", # InspectorStyleSheet not only creates this property but wants to read it and modify it. "CSS.CSSProperty", # InspectorResourceAgent needs to update mime-type. "Network.Response"]) EXACTLY_INT_SUPPORTED = False cmdline_parser = optparse.OptionParser() cmdline_parser.add_option("--output_h_dir") cmdline_parser.add_option("--output_cpp_dir") cmdline_parser.add_option("--write_always", action="store_true") try: arg_options, arg_values = cmdline_parser.parse_args() if (len(arg_values) != 1): raise Exception("Exactly one plain argument expected (found %s)" % len(arg_values)) input_json_filename = arg_values[0] output_header_dirname = arg_options.output_h_dir output_cpp_dirname = arg_options.output_cpp_dir write_always = arg_options.write_always if not output_header_dirname: raise Exception("Output .h directory must be specified") if not output_cpp_dirname: raise Exception("Output .cpp directory must be specified") except Exception: # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.html exc = sys.exc_info()[1] sys.stderr.write("Failed to parse command-line arguments: %s\n\n" % exc) sys.stderr.write("Usage: <script> Inspector.json --output_h_dir <output_header_dir> --output_cpp_dir <output_cpp_dir> [--write_always]\n") exit(1) def dash_to_camelcase(word): return ''.join(x.capitalize() or '-' for x in word.split('-')) def fix_camel_case(name): refined = re.sub(r'-(\w)', lambda pat: pat.group(1).upper(), name) refined = to_title_case(refined) return re.sub(r'(?i)HTML|XML|WML|API', lambda pat: pat.group(0).upper(), refined) def to_title_case(name): return name[:1].upper() + name[1:] class Capitalizer: @staticmethod def lower_camel_case_to_upper(str): if len(str) > 0 and str[0].islower(): str = str[0].upper() + str[1:] return str @staticmethod def upper_camel_case_to_lower(str): pos = 0 while pos < len(str) and str[pos].isupper(): pos += 1 if pos == 0: return str if pos == 1: return str[0].lower() + str[1:] if pos < len(str): pos -= 1 possible_abbreviation = str[0:pos] if possible_abbreviation not in Capitalizer.ABBREVIATION: raise Exception("Unknown abbreviation %s" % possible_abbreviation) str = possible_abbreviation.lower() + str[pos:] return str @staticmethod def camel_case_to_capitalized_with_underscores(str): if len(str) == 0: return str output = Capitalizer.split_camel_case_(str) return "_".join(output).upper() @staticmethod def split_camel_case_(str): output = [] pos_being = 0 pos = 1 has_oneletter = False while pos < len(str): if str[pos].isupper(): output.append(str[pos_being:pos].upper()) if pos - pos_being == 1: has_oneletter = True pos_being = pos pos += 1 output.append(str[pos_being:]) if has_oneletter: array_pos = 0 while array_pos < len(output) - 1: if len(output[array_pos]) == 1: array_pos_end = array_pos + 1 while array_pos_end < len(output) and len(output[array_pos_end]) == 1: array_pos_end += 1 if array_pos_end - array_pos > 1: possible_abbreviation = "".join(output[array_pos:array_pos_end]) if possible_abbreviation.upper() in Capitalizer.ABBREVIATION: output[array_pos:array_pos_end] = [possible_abbreviation] else: array_pos = array_pos_end - 1 array_pos += 1 return output ABBREVIATION = frozenset(["XHR", "DOM", "CSS"]) VALIDATOR_IFDEF_NAME = "!ASSERT_DISABLED" class DomainNameFixes: @classmethod def get_fixed_data(cls, domain_name): field_name_res = Capitalizer.upper_camel_case_to_lower(domain_name) + "Agent" class Res(object): skip_js_bind = domain_name in cls.skip_js_bind_domains agent_field_name = field_name_res @staticmethod def get_guard(): if domain_name in DOMAIN_DEFINE_NAME_MAP: define_name = DOMAIN_DEFINE_NAME_MAP[domain_name] class Guard: @staticmethod def generate_open(output): output.append("#if ENABLE(%s)\n" % define_name) @staticmethod def generate_close(output): output.append("#endif // ENABLE(%s)\n" % define_name) return Guard return Res skip_js_bind_domains = set(["DOMDebugger"]) class RawTypes(object): @staticmethod def get(json_type): if json_type == "boolean": return RawTypes.Bool elif json_type == "string": return RawTypes.String elif json_type == "array": return RawTypes.Array elif json_type == "object": return RawTypes.Object elif json_type == "integer": return RawTypes.Int elif json_type == "number": return RawTypes.Number elif json_type == "any": return RawTypes.Any else: raise Exception("Unknown type: %s" % json_type) # For output parameter all values are passed by pointer except RefPtr-based types. class OutputPassModel: class ByPointer: @staticmethod def get_argument_prefix(): return "&" @staticmethod def get_parameter_type_suffix(): return "*" class ByReference: @staticmethod def get_argument_prefix(): return "" @staticmethod def get_parameter_type_suffix(): return "&" class BaseType(object): need_internal_runtime_cast_ = False @classmethod def request_raw_internal_runtime_cast(cls): if not cls.need_internal_runtime_cast_: cls.need_internal_runtime_cast_ = True @classmethod def get_raw_validator_call_text(cls): return "RuntimeCastHelper::assertType<InspectorValue::Type%s>" % cls.get_validate_method_params().template_type class String(BaseType): @staticmethod def get_getter_name(): return "String" get_setter_name = get_getter_name @staticmethod def get_c_initializer(): return "\"\"" @staticmethod def get_js_bind_type(): return "string" @staticmethod def get_validate_method_params(): class ValidateMethodParams: template_type = "String" return ValidateMethodParams @staticmethod def get_output_pass_model(): return RawTypes.OutputPassModel.ByPointer @staticmethod def is_heavy_value(): return True @staticmethod def get_array_item_raw_c_type_text(): return "String" @staticmethod def get_raw_type_model(): return TypeModel.String class Int(BaseType): @staticmethod def get_getter_name(): return "Int" @staticmethod def get_setter_name(): return "Number" @staticmethod def get_c_initializer(): return "0" @staticmethod def get_js_bind_type(): return "number" @classmethod def get_raw_validator_call_text(cls): return "RuntimeCastHelper::assertInt" @staticmethod def get_output_pass_model(): return RawTypes.OutputPassModel.ByPointer @staticmethod def is_heavy_value(): return False @staticmethod def get_array_item_raw_c_type_text(): return "int" @staticmethod def get_raw_type_model(): return TypeModel.Int class Number(BaseType): @staticmethod def get_getter_name(): return "Double" @staticmethod def get_setter_name(): return "Number" @staticmethod def get_c_initializer(): return "0" @staticmethod def get_js_bind_type(): return "number" @staticmethod def get_validate_method_params(): class ValidateMethodParams: template_type = "Number" return ValidateMethodParams @staticmethod def get_output_pass_model(): return RawTypes.OutputPassModel.ByPointer @staticmethod def is_heavy_value(): return False @staticmethod def get_array_item_raw_c_type_text(): return "double" @staticmethod def get_raw_type_model(): return TypeModel.Number class Bool(BaseType): @staticmethod def get_getter_name(): return "Boolean" get_setter_name = get_getter_name @staticmethod def get_c_initializer(): return "false" @staticmethod def get_js_bind_type(): return "boolean" @staticmethod def get_validate_method_params(): class ValidateMethodParams: template_type = "Boolean" return ValidateMethodParams @staticmethod def get_output_pass_model(): return RawTypes.OutputPassModel.ByPointer @staticmethod def is_heavy_value(): return False @staticmethod def get_array_item_raw_c_type_text(): return "bool" @staticmethod def get_raw_type_model(): return TypeModel.Bool class Object(BaseType): @staticmethod def get_getter_name(): return "Object" @staticmethod def get_setter_name(): return "Value" @staticmethod def get_c_initializer(): return "InspectorObject::create()" @staticmethod def get_js_bind_type(): return "object" @staticmethod def get_output_argument_prefix(): return "" @staticmethod def get_validate_method_params(): class ValidateMethodParams: template_type = "Object" return ValidateMethodParams @staticmethod def get_output_pass_model(): return RawTypes.OutputPassModel.ByReference @staticmethod def is_heavy_value(): return True @staticmethod def get_array_item_raw_c_type_text(): return "InspectorObject" @staticmethod def get_raw_type_model(): return TypeModel.Object class Any(BaseType): @staticmethod def get_getter_name(): return "Value" get_setter_name = get_getter_name @staticmethod def get_c_initializer(): raise Exception("Unsupported") @staticmethod def get_js_bind_type(): raise Exception("Unsupported") @staticmethod def get_raw_validator_call_text(): return "RuntimeCastHelper::assertAny" @staticmethod def get_output_pass_model(): return RawTypes.OutputPassModel.ByReference @staticmethod def is_heavy_value(): return True @staticmethod def get_array_item_raw_c_type_text(): return "InspectorValue" @staticmethod def get_raw_type_model(): return TypeModel.Any class Array(BaseType): @staticmethod def get_getter_name(): return "Array" @staticmethod def get_setter_name(): return "Value" @staticmethod def get_c_initializer(): return "InspectorArray::create()" @staticmethod def get_js_bind_type(): return "object" @staticmethod def get_output_argument_prefix(): return "" @staticmethod def get_validate_method_params(): class ValidateMethodParams: template_type = "Array" return ValidateMethodParams @staticmethod def get_output_pass_model(): return RawTypes.OutputPassModel.ByReference @staticmethod def is_heavy_value(): return True @staticmethod def get_array_item_raw_c_type_text(): return "InspectorArray" @staticmethod def get_raw_type_model(): return TypeModel.Array def replace_right_shift(input_str): return input_str.replace(">>", "> >") class CommandReturnPassModel: class ByReference: def __init__(self, var_type, set_condition): self.var_type = var_type self.set_condition = set_condition def get_return_var_type(self): return self.var_type @staticmethod def get_output_argument_prefix(): return "" @staticmethod def get_output_to_raw_expression(): return "%s" def get_output_parameter_type(self): return self.var_type + "&" def get_set_return_condition(self): return self.set_condition class ByPointer: def __init__(self, var_type): self.var_type = var_type def get_return_var_type(self): return self.var_type @staticmethod def get_output_argument_prefix(): return "&" @staticmethod def get_output_to_raw_expression(): return "%s" def get_output_parameter_type(self): return self.var_type + "*" @staticmethod def get_set_return_condition(): return None class OptOutput: def __init__(self, var_type): self.var_type = var_type def get_return_var_type(self): return "TypeBuilder::OptOutput<%s>" % self.var_type @staticmethod def get_output_argument_prefix(): return "&" @staticmethod def get_output_to_raw_expression(): return "%s.getValue()" def get_output_parameter_type(self): return "TypeBuilder::OptOutput<%s>*" % self.var_type @staticmethod def get_set_return_condition(): return "%s.isAssigned()" class TypeModel: class RefPtrBased(object): def __init__(self, class_name): self.class_name = class_name self.optional = False def get_optional(self): result = TypeModel.RefPtrBased(self.class_name) result.optional = True return result def get_command_return_pass_model(self): if self.optional: set_condition = "%s" else: set_condition = None return CommandReturnPassModel.ByReference(replace_right_shift("RefPtr<%s>" % self.class_name), set_condition) def get_input_param_type_text(self): return replace_right_shift("PassRefPtr<%s>" % self.class_name) @staticmethod def get_event_setter_expression_pattern(): return "%s" class Enum(object): def __init__(self, base_type_name): self.type_name = base_type_name + "::Enum" def get_optional(base_self): class EnumOptional: @classmethod def get_optional(cls): return cls @staticmethod def get_command_return_pass_model(): return CommandReturnPassModel.OptOutput(base_self.type_name) @staticmethod def get_input_param_type_text(): return base_self.type_name + "*" @staticmethod def get_event_setter_expression_pattern(): raise Exception("TODO") return EnumOptional def get_command_return_pass_model(self): return CommandReturnPassModel.ByPointer(self.type_name) def get_input_param_type_text(self): return self.type_name @staticmethod def get_event_setter_expression_pattern(): return "%s" class ValueType(object): def __init__(self, type_name, is_heavy): self.type_name = type_name self.is_heavy = is_heavy def get_optional(self): return self.ValueOptional(self) def get_command_return_pass_model(self): return CommandReturnPassModel.ByPointer(self.type_name) def get_input_param_type_text(self): if self.is_heavy: return "const %s&" % self.type_name else: return self.type_name def get_opt_output_type_(self): return self.type_name @staticmethod def get_event_setter_expression_pattern(): return "%s" class ValueOptional: def __init__(self, base): self.base = base def get_optional(self): return self def get_command_return_pass_model(self): return CommandReturnPassModel.OptOutput(self.base.get_opt_output_type_()) def get_input_param_type_text(self): return "const %s* const" % self.base.type_name @staticmethod def get_event_setter_expression_pattern(): return "*%s" class ExactlyInt(ValueType): def __init__(self): TypeModel.ValueType.__init__(self, "int", False) def get_input_param_type_text(self): return "TypeBuilder::ExactlyInt" def get_opt_output_type_(self): return "TypeBuilder::ExactlyInt" @classmethod def init_class(cls): cls.Bool = cls.ValueType("bool", False) if EXACTLY_INT_SUPPORTED: cls.Int = cls.ExactlyInt() else: cls.Int = cls.ValueType("int", False) cls.Number = cls.ValueType("double", False) cls.String = cls.ValueType("String", True,) cls.Object = cls.RefPtrBased("InspectorObject") cls.Array = cls.RefPtrBased("InspectorArray") cls.Any = cls.RefPtrBased("InspectorValue") TypeModel.init_class() # Collection of InspectorObject class methods that are likely to be overloaded in generated class. # We must explicitly import all overloaded methods or they won't be available to user. INSPECTOR_OBJECT_SETTER_NAMES = frozenset(["setValue", "setBoolean", "setNumber", "setString", "setValue", "setObject", "setArray"]) def fix_type_name(json_name): if json_name in TYPE_NAME_FIX_MAP: fixed = TYPE_NAME_FIX_MAP[json_name] class Result(object): class_name = fixed @staticmethod def output_comment(writer): writer.newline("// Type originally was named '%s'.\n" % json_name) else: class Result(object): class_name = json_name @staticmethod def output_comment(writer): pass return Result class Writer: def __init__(self, output, indent): self.output = output self.indent = indent def newline(self, str): if (self.indent): self.output.append(self.indent) self.output.append(str) def append(self, str): self.output.append(str) def newline_multiline(self, str): parts = str.split('\n') self.newline(parts[0]) for p in parts[1:]: self.output.append('\n') if p: self.newline(p) def append_multiline(self, str): parts = str.split('\n') self.append(parts[0]) for p in parts[1:]: self.output.append('\n') if p: self.newline(p) def get_indent(self): return self.indent def get_indented(self, additional_indent): return Writer(self.output, self.indent + additional_indent) def insert_writer(self, additional_indent): new_output = [] self.output.append(new_output) return Writer(new_output, self.indent + additional_indent) class EnumConstants: map_ = {} constants_ = [] @classmethod def add_constant(cls, value): if value in cls.map_: return cls.map_[value] else: pos = len(cls.map_) cls.map_[value] = pos cls.constants_.append(value) return pos @classmethod def get_enum_constant_code(cls): output = [] for item in cls.constants_: output.append(" \"" + item + "\"") return ",\n".join(output) + "\n" # Typebuilder code is generated in several passes: first typedefs, then other classes. # Manual pass management is needed because we cannot have forward declarations for typedefs. class TypeBuilderPass: TYPEDEF = "typedef" MAIN = "main" class TypeBindings: @staticmethod def create_named_type_declaration(json_typable, context_domain_name, type_data): json_type = type_data.get_json_type() class Helper: is_ad_hoc = False full_name_prefix_for_use = "TypeBuilder::" + context_domain_name + "::" full_name_prefix_for_impl = "TypeBuilder::" + context_domain_name + "::" @staticmethod def write_doc(writer): if "description" in json_type: writer.newline("/* ") writer.append(json_type["description"]) writer.append(" */\n") @staticmethod def add_to_forward_listener(forward_listener): forward_listener.add_type_data(type_data) fixed_type_name = fix_type_name(json_type["id"]) return TypeBindings.create_type_declaration_(json_typable, context_domain_name, fixed_type_name, Helper) @staticmethod def create_ad_hoc_type_declaration(json_typable, context_domain_name, ad_hoc_type_context): class Helper: is_ad_hoc = True full_name_prefix_for_use = ad_hoc_type_context.container_relative_name_prefix full_name_prefix_for_impl = ad_hoc_type_context.container_full_name_prefix @staticmethod def write_doc(writer): pass @staticmethod def add_to_forward_listener(forward_listener): pass fixed_type_name = ad_hoc_type_context.get_type_name_fix() return TypeBindings.create_type_declaration_(json_typable, context_domain_name, fixed_type_name, Helper) @staticmethod def create_type_declaration_(json_typable, context_domain_name, fixed_type_name, helper): if json_typable["type"] == "string": if "enum" in json_typable: class EnumBinding: need_user_runtime_cast_ = False need_internal_runtime_cast_ = False @classmethod def resolve_inner(cls, resolve_context): pass @classmethod def request_user_runtime_cast(cls, request): if request: cls.need_user_runtime_cast_ = True request.acknowledge() @classmethod def request_internal_runtime_cast(cls): cls.need_internal_runtime_cast_ = True @classmethod def get_code_generator(enum_binding_cls): #FIXME: generate ad-hoc enums too once we figure out how to better implement them in C++. comment_out = helper.is_ad_hoc class CodeGenerator: @staticmethod def generate_type_builder(writer, generate_context): enum = json_typable["enum"] helper.write_doc(writer) enum_name = fixed_type_name.class_name fixed_type_name.output_comment(writer) writer.newline("struct ") writer.append(enum_name) writer.append(" {\n") writer.newline(" enum Enum {\n") for enum_item in enum: enum_pos = EnumConstants.add_constant(enum_item) item_c_name = enum_item.replace('-', '_') item_c_name = Capitalizer.lower_camel_case_to_upper(item_c_name) if item_c_name in TYPE_NAME_FIX_MAP: item_c_name = TYPE_NAME_FIX_MAP[item_c_name] writer.newline(" ") writer.append(item_c_name) writer.append(" = ") writer.append("%s" % enum_pos) writer.append(",\n") writer.newline(" };\n") if enum_binding_cls.need_user_runtime_cast_: raise Exception("Not yet implemented") if enum_binding_cls.need_internal_runtime_cast_: writer.append("#if %s\n" % VALIDATOR_IFDEF_NAME) writer.newline(" static void assertCorrectValue(InspectorValue* value);\n") writer.append("#endif // %s\n" % VALIDATOR_IFDEF_NAME) validator_writer = generate_context.validator_writer domain_fixes = DomainNameFixes.get_fixed_data(context_domain_name) domain_guard = domain_fixes.get_guard() if domain_guard: domain_guard.generate_open(validator_writer) validator_writer.newline("void %s%s::assertCorrectValue(InspectorValue* value)\n" % (helper.full_name_prefix_for_impl, enum_name)) validator_writer.newline("{\n") validator_writer.newline(" WTF::String s;\n") validator_writer.newline(" bool cast_res = value->asString(&s);\n") validator_writer.newline(" ASSERT(cast_res);\n") if len(enum) > 0: condition_list = [] for enum_item in enum: enum_pos = EnumConstants.add_constant(enum_item) condition_list.append("s == \"%s\"" % enum_item) validator_writer.newline(" ASSERT(%s);\n" % " || ".join(condition_list)) validator_writer.newline("}\n") if domain_guard: domain_guard.generate_close(validator_writer) validator_writer.newline("\n\n") writer.newline("}; // struct ") writer.append(enum_name) writer.append("\n\n") @staticmethod def register_use(forward_listener): pass @staticmethod def get_generate_pass_id(): return TypeBuilderPass.MAIN return CodeGenerator @classmethod def get_validator_call_text(cls): return helper.full_name_prefix_for_use + fixed_type_name.class_name + "::assertCorrectValue" @classmethod def get_array_item_c_type_text(cls): return helper.full_name_prefix_for_use + fixed_type_name.class_name + "::Enum" @staticmethod def get_setter_value_expression_pattern(): return "TypeBuilder::getEnumConstantValue(%s)" @staticmethod def reduce_to_raw_type(): return RawTypes.String @staticmethod def get_type_model(): return TypeModel.Enum(helper.full_name_prefix_for_use + fixed_type_name.class_name) return EnumBinding else: if helper.is_ad_hoc: class PlainString: @classmethod def resolve_inner(cls, resolve_context): pass @staticmethod def request_user_runtime_cast(request): raise Exception("Unsupported") @staticmethod def request_internal_runtime_cast(): pass @staticmethod def get_code_generator(): return None @classmethod def get_validator_call_text(cls): return RawTypes.String.get_raw_validator_call_text() @staticmethod def reduce_to_raw_type(): return RawTypes.String @staticmethod def get_type_model(): return TypeModel.String @staticmethod def get_setter_value_expression_pattern(): return None @classmethod def get_array_item_c_type_text(cls): return cls.reduce_to_raw_type().get_array_item_raw_c_type_text() return PlainString else: class TypedefString: @classmethod def resolve_inner(cls, resolve_context): pass @staticmethod def request_user_runtime_cast(request): raise Exception("Unsupported") @staticmethod def request_internal_runtime_cast(): RawTypes.String.request_raw_internal_runtime_cast() @staticmethod def get_code_generator(): class CodeGenerator: @staticmethod def generate_type_builder(writer, generate_context): helper.write_doc(writer) fixed_type_name.output_comment(writer) writer.newline("typedef String ") writer.append(fixed_type_name.class_name) writer.append(";\n\n") @staticmethod def register_use(forward_listener): pass @staticmethod def get_generate_pass_id(): return TypeBuilderPass.TYPEDEF return CodeGenerator @classmethod def get_validator_call_text(cls): return RawTypes.String.get_raw_validator_call_text() @staticmethod def reduce_to_raw_type(): return RawTypes.String @staticmethod def get_type_model(): return TypeModel.ValueType("%s%s" % (helper.full_name_prefix_for_use, fixed_type_name.class_name), True) @staticmethod def get_setter_value_expression_pattern(): return None @classmethod def get_array_item_c_type_text(cls): return "const %s%s&" % (helper.full_name_prefix_for_use, fixed_type_name.class_name) return TypedefString elif json_typable["type"] == "object": if "properties" in json_typable: class ClassBinding: resolve_data_ = None need_user_runtime_cast_ = False need_internal_runtime_cast_ = False @classmethod def resolve_inner(cls, resolve_context): if cls.resolve_data_: return properties = json_typable["properties"] main = [] optional = [] ad_hoc_type_list = [] for prop in properties: prop_name = prop["name"] ad_hoc_type_context = cls.AdHocTypeContextImpl(prop_name, fixed_type_name.class_name, resolve_context, ad_hoc_type_list, helper.full_name_prefix_for_impl) binding = resolve_param_type(prop, context_domain_name, ad_hoc_type_context) code_generator = binding.get_code_generator() if code_generator: code_generator.register_use(resolve_context.forward_listener) class PropertyData: param_type_binding = binding p = prop if prop.get("optional"): optional.append(PropertyData) else: main.append(PropertyData) class ResolveData: main_properties = main optional_properties = optional ad_hoc_types = ad_hoc_type_list cls.resolve_data_ = ResolveData for ad_hoc in ad_hoc_type_list: ad_hoc.resolve_inner(resolve_context) @classmethod def request_user_runtime_cast(cls, request): if not request: return cls.need_user_runtime_cast_ = True request.acknowledge() cls.request_internal_runtime_cast() @classmethod def request_internal_runtime_cast(cls): if cls.need_internal_runtime_cast_: return cls.need_internal_runtime_cast_ = True for p in cls.resolve_data_.main_properties: p.param_type_binding.request_internal_runtime_cast() for p in cls.resolve_data_.optional_properties: p.param_type_binding.request_internal_runtime_cast() @classmethod def get_code_generator(class_binding_cls): class CodeGenerator: @classmethod def generate_type_builder(cls, writer, generate_context): resolve_data = class_binding_cls.resolve_data_ helper.write_doc(writer) class_name = fixed_type_name.class_name is_open_type = (context_domain_name + "." + class_name) in TYPES_WITH_OPEN_FIELD_LIST_SET fixed_type_name.output_comment(writer) writer.newline("class ") writer.append(class_name) writer.append(" : public ") if is_open_type: writer.append("InspectorObject") else: writer.append("InspectorObjectBase") writer.append(" {\n") writer.newline("public:\n") ad_hoc_type_writer = writer.insert_writer(" ") for ad_hoc_type in resolve_data.ad_hoc_types: code_generator = ad_hoc_type.get_code_generator() if code_generator: code_generator.generate_type_builder(ad_hoc_type_writer, generate_context) writer.newline_multiline( """ enum { NoFieldsSet = 0, """) state_enum_items = [] if len(resolve_data.main_properties) > 0: pos = 0 for prop_data in resolve_data.main_properties: item_name = Capitalizer.lower_camel_case_to_upper(prop_data.p["name"]) + "Set" state_enum_items.append(item_name) writer.newline(" %s = 1 << %s,\n" % (item_name, pos)) pos += 1 all_fields_set_value = "(" + (" | ".join(state_enum_items)) + ")" else: all_fields_set_value = "0" writer.newline_multiline(CodeGeneratorInspectorStrings.class_binding_builder_part_1 % (all_fields_set_value, class_name, class_name)) pos = 0 for prop_data in resolve_data.main_properties: prop_name = prop_data.p["name"] param_type_binding = prop_data.param_type_binding param_raw_type = param_type_binding.reduce_to_raw_type() writer.newline_multiline(CodeGeneratorInspectorStrings.class_binding_builder_part_2 % (state_enum_items[pos], Capitalizer.lower_camel_case_to_upper(prop_name), param_type_binding.get_type_model().get_input_param_type_text(), state_enum_items[pos], prop_name, param_raw_type.get_setter_name(), prop_name, format_setter_value_expression(param_type_binding, "value"), state_enum_items[pos])) pos += 1 writer.newline_multiline(CodeGeneratorInspectorStrings.class_binding_builder_part_3 % (class_name, class_name, class_name, class_name, class_name)) writer.newline(" /*\n") writer.newline(" * Synthetic constructor:\n") writer.newline(" * RefPtr<%s> result = %s::create()" % (class_name, class_name)) for prop_data in resolve_data.main_properties: writer.append_multiline("\n * .set%s(...)" % Capitalizer.lower_camel_case_to_upper(prop_data.p["name"])) writer.append_multiline(";\n */\n") writer.newline_multiline(CodeGeneratorInspectorStrings.class_binding_builder_part_4) writer.newline(" typedef TypeBuilder::StructItemTraits ItemTraits;\n") for prop_data in resolve_data.optional_properties: prop_name = prop_data.p["name"] param_type_binding = prop_data.param_type_binding setter_name = "set%s" % Capitalizer.lower_camel_case_to_upper(prop_name) writer.append_multiline("\n void %s" % setter_name) writer.append("(%s value)\n" % param_type_binding.get_type_model().get_input_param_type_text()) writer.newline(" {\n") writer.newline(" this->set%s(\"%s\", %s);\n" % (param_type_binding.reduce_to_raw_type().get_setter_name(), prop_data.p["name"], format_setter_value_expression(param_type_binding, "value"))) writer.newline(" }\n") if setter_name in INSPECTOR_OBJECT_SETTER_NAMES: writer.newline(" using InspectorObjectBase::%s;\n\n" % setter_name) if class_binding_cls.need_user_runtime_cast_: writer.newline(" static PassRefPtr<%s> runtimeCast(PassRefPtr<InspectorValue> value)\n" % class_name) writer.newline(" {\n") writer.newline(" RefPtr<InspectorObject> object;\n") writer.newline(" bool castRes = value->asObject(&object);\n") writer.newline(" ASSERT_UNUSED(castRes, castRes);\n") writer.append("#if %s\n" % VALIDATOR_IFDEF_NAME) writer.newline(" assertCorrectValue(object.get());\n") writer.append("#endif // %s\n" % VALIDATOR_IFDEF_NAME) writer.newline(" COMPILE_ASSERT(sizeof(%s) == sizeof(InspectorObjectBase), type_cast_problem);\n" % class_name) writer.newline(" return static_cast<%s*>(static_cast<InspectorObjectBase*>(object.get()));\n" % class_name) writer.newline(" }\n") writer.append("\n") if class_binding_cls.need_internal_runtime_cast_: writer.append("#if %s\n" % VALIDATOR_IFDEF_NAME) writer.newline(" static void assertCorrectValue(InspectorValue* value);\n") writer.append("#endif // %s\n" % VALIDATOR_IFDEF_NAME) closed_field_set = (context_domain_name + "." + class_name) not in TYPES_WITH_OPEN_FIELD_LIST_SET validator_writer = generate_context.validator_writer domain_fixes = DomainNameFixes.get_fixed_data(context_domain_name) domain_guard = domain_fixes.get_guard() if domain_guard: domain_guard.generate_open(validator_writer) validator_writer.newline("void %s%s::assertCorrectValue(InspectorValue* value)\n" % (helper.full_name_prefix_for_impl, class_name)) validator_writer.newline("{\n") validator_writer.newline(" RefPtr<InspectorObject> object;\n") validator_writer.newline(" bool castRes = value->asObject(&object);\n") validator_writer.newline(" ASSERT_UNUSED(castRes, castRes);\n") for prop_data in resolve_data.main_properties: validator_writer.newline(" {\n") it_name = "%sPos" % prop_data.p["name"] validator_writer.newline(" InspectorObject::iterator %s;\n" % it_name) validator_writer.newline(" %s = object->find(\"%s\");\n" % (it_name, prop_data.p["name"])) validator_writer.newline(" ASSERT(%s != object->end());\n" % it_name) validator_writer.newline(" %s(%s->value.get());\n" % (prop_data.param_type_binding.get_validator_call_text(), it_name)) validator_writer.newline(" }\n") if closed_field_set: validator_writer.newline(" int foundPropertiesCount = %s;\n" % len(resolve_data.main_properties)) for prop_data in resolve_data.optional_properties: validator_writer.newline(" {\n") it_name = "%sPos" % prop_data.p["name"] validator_writer.newline(" InspectorObject::iterator %s;\n" % it_name) validator_writer.newline(" %s = object->find(\"%s\");\n" % (it_name, prop_data.p["name"])) validator_writer.newline(" if (%s != object->end()) {\n" % it_name) validator_writer.newline(" %s(%s->value.get());\n" % (prop_data.param_type_binding.get_validator_call_text(), it_name)) if closed_field_set: validator_writer.newline(" ++foundPropertiesCount;\n") validator_writer.newline(" }\n") validator_writer.newline(" }\n") if closed_field_set: validator_writer.newline(" if (foundPropertiesCount != object->size()) {\n") validator_writer.newline(" FATAL(\"Unexpected properties in object: %s\\n\", object->toJSONString().ascii().data());\n") validator_writer.newline(" }\n") validator_writer.newline("}\n") if domain_guard: domain_guard.generate_close(validator_writer) validator_writer.newline("\n\n") if is_open_type: cpp_writer = generate_context.cpp_writer writer.append("\n") writer.newline(" // Property names for type generated as open.\n") for prop_data in resolve_data.main_properties + resolve_data.optional_properties: prop_name = prop_data.p["name"] prop_field_name = Capitalizer.lower_camel_case_to_upper(prop_name) writer.newline(" static const char* %s;\n" % (prop_field_name)) cpp_writer.newline("const char* %s%s::%s = \"%s\";\n" % (helper.full_name_prefix_for_impl, class_name, prop_field_name, prop_name)) writer.newline("};\n\n") @staticmethod def generate_forward_declaration(writer): class_name = fixed_type_name.class_name writer.newline("class ") writer.append(class_name) writer.append(";\n") @staticmethod def register_use(forward_listener): helper.add_to_forward_listener(forward_listener) @staticmethod def get_generate_pass_id(): return TypeBuilderPass.MAIN return CodeGenerator @staticmethod def get_validator_call_text(): return helper.full_name_prefix_for_use + fixed_type_name.class_name + "::assertCorrectValue" @classmethod def get_array_item_c_type_text(cls): return helper.full_name_prefix_for_use + fixed_type_name.class_name @staticmethod def get_setter_value_expression_pattern(): return None @staticmethod def reduce_to_raw_type(): return RawTypes.Object @staticmethod def get_type_model(): return TypeModel.RefPtrBased(helper.full_name_prefix_for_use + fixed_type_name.class_name) class AdHocTypeContextImpl: def __init__(self, property_name, class_name, resolve_context, ad_hoc_type_list, parent_full_name_prefix): self.property_name = property_name self.class_name = class_name self.resolve_context = resolve_context self.ad_hoc_type_list = ad_hoc_type_list self.container_full_name_prefix = parent_full_name_prefix + class_name + "::" self.container_relative_name_prefix = "" def get_type_name_fix(self): class NameFix: class_name = Capitalizer.lower_camel_case_to_upper(self.property_name) @staticmethod def output_comment(writer): writer.newline("// Named after property name '%s' while generating %s.\n" % (self.property_name, self.class_name)) return NameFix def add_type(self, binding): self.ad_hoc_type_list.append(binding) return ClassBinding else: class PlainObjectBinding: @classmethod def resolve_inner(cls, resolve_context): pass @staticmethod def request_user_runtime_cast(request): pass @staticmethod def request_internal_runtime_cast(): RawTypes.Object.request_raw_internal_runtime_cast() @staticmethod def get_code_generator(): pass @staticmethod def get_validator_call_text(): return "RuntimeCastHelper::assertType<InspectorValue::TypeObject>" @classmethod def get_array_item_c_type_text(cls): return cls.reduce_to_raw_type().get_array_item_raw_c_type_text() @staticmethod def get_setter_value_expression_pattern(): return None @staticmethod def reduce_to_raw_type(): return RawTypes.Object @staticmethod def get_type_model(): return TypeModel.Object return PlainObjectBinding elif json_typable["type"] == "array": if "items" in json_typable: ad_hoc_types = [] class AdHocTypeContext: container_full_name_prefix = "<not yet defined>" container_relative_name_prefix = "" @staticmethod def get_type_name_fix(): return fixed_type_name @staticmethod def add_type(binding): ad_hoc_types.append(binding) item_binding = resolve_param_type(json_typable["items"], context_domain_name, AdHocTypeContext) class ArrayBinding: resolve_data_ = None need_internal_runtime_cast_ = False @classmethod def resolve_inner(cls, resolve_context): if cls.resolve_data_: return class ResolveData: item_type_binding = item_binding ad_hoc_type_list = ad_hoc_types cls.resolve_data_ = ResolveData for t in ad_hoc_types: t.resolve_inner(resolve_context) @classmethod def request_user_runtime_cast(cls, request): raise Exception("Not implemented yet") @classmethod def request_internal_runtime_cast(cls): if cls.need_internal_runtime_cast_: return cls.need_internal_runtime_cast_ = True cls.resolve_data_.item_type_binding.request_internal_runtime_cast() @classmethod def get_code_generator(array_binding_cls): class CodeGenerator: @staticmethod def generate_type_builder(writer, generate_context): ad_hoc_type_writer = writer resolve_data = array_binding_cls.resolve_data_ for ad_hoc_type in resolve_data.ad_hoc_type_list: code_generator = ad_hoc_type.get_code_generator() if code_generator: code_generator.generate_type_builder(ad_hoc_type_writer, generate_context) @staticmethod def generate_forward_declaration(writer): pass @staticmethod def register_use(forward_listener): item_code_generator = item_binding.get_code_generator() if item_code_generator: item_code_generator.register_use(forward_listener) @staticmethod def get_generate_pass_id(): return TypeBuilderPass.MAIN return CodeGenerator @classmethod def get_validator_call_text(cls): return cls.get_array_item_c_type_text() + "::assertCorrectValue" @classmethod def get_array_item_c_type_text(cls): return replace_right_shift("TypeBuilder::Array<%s>" % cls.resolve_data_.item_type_binding.get_array_item_c_type_text()) @staticmethod def get_setter_value_expression_pattern(): return None @staticmethod def reduce_to_raw_type(): return RawTypes.Array @classmethod def get_type_model(cls): return TypeModel.RefPtrBased(cls.get_array_item_c_type_text()) return ArrayBinding else: # Fall-through to raw type. pass raw_type = RawTypes.get(json_typable["type"]) return RawTypeBinding(raw_type) class RawTypeBinding: def __init__(self, raw_type): self.raw_type_ = raw_type def resolve_inner(self, resolve_context): pass def request_user_runtime_cast(self, request): raise Exception("Unsupported") def request_internal_runtime_cast(self): self.raw_type_.request_raw_internal_runtime_cast() def get_code_generator(self): return None def get_validator_call_text(self): return self.raw_type_.get_raw_validator_call_text() def get_array_item_c_type_text(self): return self.raw_type_.get_array_item_raw_c_type_text() def get_setter_value_expression_pattern(self): return None def reduce_to_raw_type(self): return self.raw_type_ def get_type_model(self): return self.raw_type_.get_raw_type_model() class TypeData(object): def __init__(self, json_type, json_domain, domain_data): self.json_type_ = json_type self.json_domain_ = json_domain self.domain_data_ = domain_data if "type" not in json_type: raise Exception("Unknown type") json_type_name = json_type["type"] raw_type = RawTypes.get(json_type_name) self.raw_type_ = raw_type self.binding_being_resolved_ = False self.binding_ = None def get_raw_type(self): return self.raw_type_ def get_binding(self): if not self.binding_: if self.binding_being_resolved_: raise Error("Type %s is already being resolved" % self.json_type_["type"]) # Resolve only lazily, because resolving one named type may require resolving some other named type. self.binding_being_resolved_ = True try: self.binding_ = TypeBindings.create_named_type_declaration(self.json_type_, self.json_domain_["domain"], self) finally: self.binding_being_resolved_ = False return self.binding_ def get_json_type(self): return self.json_type_ def get_name(self): return self.json_type_["id"] def get_domain_name(self): return self.json_domain_["domain"] class DomainData: def __init__(self, json_domain): self.json_domain = json_domain self.types_ = [] def add_type(self, type_data): self.types_.append(type_data) def name(self): return self.json_domain["domain"] def types(self): return self.types_ class TypeMap: def __init__(self, api): self.map_ = {} self.domains_ = [] for json_domain in api["domains"]: domain_name = json_domain["domain"] domain_map = {} self.map_[domain_name] = domain_map domain_data = DomainData(json_domain) self.domains_.append(domain_data) if "types" in json_domain: for json_type in json_domain["types"]: type_name = json_type["id"] type_data = TypeData(json_type, json_domain, domain_data) domain_map[type_name] = type_data domain_data.add_type(type_data) def domains(self): return self.domains_ def get(self, domain_name, type_name): return self.map_[domain_name][type_name] def resolve_param_type(json_parameter, scope_domain_name, ad_hoc_type_context): if "$ref" in json_parameter: json_ref = json_parameter["$ref"] type_data = get_ref_data(json_ref, scope_domain_name) return type_data.get_binding() elif "type" in json_parameter: result = TypeBindings.create_ad_hoc_type_declaration(json_parameter, scope_domain_name, ad_hoc_type_context) ad_hoc_type_context.add_type(result) return result else: raise Exception("Unknown type") def resolve_param_raw_type(json_parameter, scope_domain_name): if "$ref" in json_parameter: json_ref = json_parameter["$ref"] type_data = get_ref_data(json_ref, scope_domain_name) return type_data.get_raw_type() elif "type" in json_parameter: json_type = json_parameter["type"] return RawTypes.get(json_type) else: raise Exception("Unknown type") def get_ref_data(json_ref, scope_domain_name): dot_pos = json_ref.find(".") if dot_pos == -1: domain_name = scope_domain_name type_name = json_ref else: domain_name = json_ref[:dot_pos] type_name = json_ref[dot_pos + 1:] return type_map.get(domain_name, type_name) input_file = open(input_json_filename, "r") json_string = input_file.read() json_api = json.loads(json_string) class Templates: def get_this_script_path_(absolute_path): absolute_path = os.path.abspath(absolute_path) components = [] def fill_recursive(path_part, depth): if depth <= 0 or path_part == '/': return fill_recursive(os.path.dirname(path_part), depth - 1) components.append(os.path.basename(path_part)) # Typical path is /Source/WebCore/inspector/CodeGeneratorInspector.py # Let's take 4 components from the real path then. fill_recursive(absolute_path, 4) return "/".join(components) file_header_ = ("// File is generated by %s\n\n" % get_this_script_path_(sys.argv[0]) + """// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. """) frontend_domain_class = string.Template(CodeGeneratorInspectorStrings.frontend_domain_class) backend_method = string.Template(CodeGeneratorInspectorStrings.backend_method) frontend_method = string.Template(CodeGeneratorInspectorStrings.frontend_method) callback_method = string.Template(CodeGeneratorInspectorStrings.callback_method) frontend_h = string.Template(file_header_ + CodeGeneratorInspectorStrings.frontend_h) backend_h = string.Template(file_header_ + CodeGeneratorInspectorStrings.backend_h) backend_cpp = string.Template(file_header_ + CodeGeneratorInspectorStrings.backend_cpp) frontend_cpp = string.Template(file_header_ + CodeGeneratorInspectorStrings.frontend_cpp) typebuilder_h = string.Template(file_header_ + CodeGeneratorInspectorStrings.typebuilder_h) typebuilder_cpp = string.Template(file_header_ + CodeGeneratorInspectorStrings.typebuilder_cpp) backend_js = string.Template(file_header_ + CodeGeneratorInspectorStrings.backend_js) param_container_access_code = CodeGeneratorInspectorStrings.param_container_access_code type_map = TypeMap(json_api) class NeedRuntimeCastRequest: def __init__(self): self.ack_ = None def acknowledge(self): self.ack_ = True def is_acknowledged(self): return self.ack_ def resolve_all_types(): runtime_cast_generate_requests = {} for type_name in TYPES_WITH_RUNTIME_CAST_SET: runtime_cast_generate_requests[type_name] = NeedRuntimeCastRequest() class ForwardListener: type_data_set = set() already_declared_set = set() @classmethod def add_type_data(cls, type_data): if type_data not in cls.already_declared_set: cls.type_data_set.add(type_data) class ResolveContext: forward_listener = ForwardListener for domain_data in type_map.domains(): for type_data in domain_data.types(): # Do not generate forwards for this type any longer. ForwardListener.already_declared_set.add(type_data) binding = type_data.get_binding() binding.resolve_inner(ResolveContext) for domain_data in type_map.domains(): for type_data in domain_data.types(): full_type_name = "%s.%s" % (type_data.get_domain_name(), type_data.get_name()) request = runtime_cast_generate_requests.pop(full_type_name, None) binding = type_data.get_binding() if request: binding.request_user_runtime_cast(request) if request and not request.is_acknowledged(): raise Exception("Failed to generate runtimeCast in " + full_type_name) for full_type_name in runtime_cast_generate_requests: raise Exception("Failed to generate runtimeCast. Type " + full_type_name + " not found") return ForwardListener global_forward_listener = resolve_all_types() def get_annotated_type_text(raw_type, annotated_type): if annotated_type != raw_type: return "/*%s*/ %s" % (annotated_type, raw_type) else: return raw_type def format_setter_value_expression(param_type_binding, value_ref): pattern = param_type_binding.get_setter_value_expression_pattern() if pattern: return pattern % value_ref else: return value_ref class Generator: frontend_class_field_lines = [] frontend_domain_class_lines = [] method_name_enum_list = [] backend_method_declaration_list = [] backend_method_implementation_list = [] backend_method_name_declaration_list = [] method_handler_list = [] frontend_method_list = [] backend_js_domain_initializer_list = [] backend_virtual_setters_list = [] backend_agent_interface_list = [] backend_setters_list = [] backend_constructor_init_list = [] backend_field_list = [] frontend_constructor_init_list = [] type_builder_fragments = [] type_builder_forwards = [] validator_impl_list = [] type_builder_impl_list = [] @staticmethod def go(): Generator.process_types(type_map) first_cycle_guardable_list_list = [ Generator.backend_method_declaration_list, Generator.backend_method_implementation_list, Generator.backend_method_name_declaration_list, Generator.backend_agent_interface_list, Generator.frontend_class_field_lines, Generator.frontend_constructor_init_list, Generator.frontend_domain_class_lines, Generator.frontend_method_list, Generator.method_handler_list, Generator.method_name_enum_list, Generator.backend_constructor_init_list, Generator.backend_virtual_setters_list, Generator.backend_setters_list, Generator.backend_field_list] for json_domain in json_api["domains"]: domain_name = json_domain["domain"] domain_name_lower = domain_name.lower() domain_fixes = DomainNameFixes.get_fixed_data(domain_name) domain_guard = domain_fixes.get_guard() if domain_guard: for l in first_cycle_guardable_list_list: domain_guard.generate_open(l) agent_field_name = domain_fixes.agent_field_name frontend_method_declaration_lines = [] Generator.backend_js_domain_initializer_list.append("// %s.\n" % domain_name) if not domain_fixes.skip_js_bind: Generator.backend_js_domain_initializer_list.append("InspectorBackend.register%sDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, \"%s\");\n" % (domain_name, domain_name)) if "types" in json_domain: for json_type in json_domain["types"]: if "type" in json_type and json_type["type"] == "string" and "enum" in json_type: enum_name = "%s.%s" % (domain_name, json_type["id"]) Generator.process_enum(json_type, enum_name) elif json_type["type"] == "object": if "properties" in json_type: for json_property in json_type["properties"]: if "type" in json_property and json_property["type"] == "string" and "enum" in json_property: enum_name = "%s.%s%s" % (domain_name, json_type["id"], to_title_case(json_property["name"])) Generator.process_enum(json_property, enum_name) if "events" in json_domain: for json_event in json_domain["events"]: Generator.process_event(json_event, domain_name, frontend_method_declaration_lines) Generator.frontend_class_field_lines.append(" %s m_%s;\n" % (domain_name, domain_name_lower)) if Generator.frontend_constructor_init_list: Generator.frontend_constructor_init_list.append(" , ") Generator.frontend_constructor_init_list.append("m_%s(inspectorFrontendChannel)\n" % domain_name_lower) Generator.frontend_domain_class_lines.append(Templates.frontend_domain_class.substitute(None, domainClassName=domain_name, domainFieldName=domain_name_lower, frontendDomainMethodDeclarations="".join(flatten_list(frontend_method_declaration_lines)))) agent_interface_name = Capitalizer.lower_camel_case_to_upper(domain_name) + "CommandHandler" Generator.backend_agent_interface_list.append(" class %s {\n" % agent_interface_name) Generator.backend_agent_interface_list.append(" public:\n") if "commands" in json_domain: for json_command in json_domain["commands"]: Generator.process_command(json_command, domain_name, agent_field_name, agent_interface_name) Generator.backend_agent_interface_list.append("\n protected:\n") Generator.backend_agent_interface_list.append(" virtual ~%s() { }\n" % agent_interface_name) Generator.backend_agent_interface_list.append(" };\n\n") Generator.backend_constructor_init_list.append(" , m_%s(0)" % agent_field_name) Generator.backend_virtual_setters_list.append(" virtual void registerAgent(%s* %s) = 0;" % (agent_interface_name, agent_field_name)) Generator.backend_setters_list.append(" virtual void registerAgent(%s* %s) { ASSERT(!m_%s); m_%s = %s; }" % (agent_interface_name, agent_field_name, agent_field_name, agent_field_name, agent_field_name)) Generator.backend_field_list.append(" %s* m_%s;" % (agent_interface_name, agent_field_name)) if domain_guard: for l in reversed(first_cycle_guardable_list_list): domain_guard.generate_close(l) Generator.backend_js_domain_initializer_list.append("\n") @staticmethod def process_enum(json_enum, enum_name): enum_members = [] for member in json_enum["enum"]: enum_members.append("%s: \"%s\"" % (fix_camel_case(member), member)) Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerEnum(\"%s\", {%s});\n" % ( enum_name, ", ".join(enum_members))) @staticmethod def process_event(json_event, domain_name, frontend_method_declaration_lines): event_name = json_event["name"] ad_hoc_type_output = [] frontend_method_declaration_lines.append(ad_hoc_type_output) ad_hoc_type_writer = Writer(ad_hoc_type_output, " ") decl_parameter_list = [] json_parameters = json_event.get("parameters") Generator.generate_send_method(json_parameters, event_name, domain_name, ad_hoc_type_writer, decl_parameter_list, Generator.EventMethodStructTemplate, Generator.frontend_method_list, Templates.frontend_method, {"eventName": event_name}) backend_js_event_param_list = [] if json_parameters: for parameter in json_parameters: parameter_name = parameter["name"] backend_js_event_param_list.append("\"%s\"" % parameter_name) frontend_method_declaration_lines.append( " void %s(%s);\n" % (event_name, ", ".join(decl_parameter_list))) Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerEvent(\"%s.%s\", [%s]);\n" % ( domain_name, event_name, ", ".join(backend_js_event_param_list))) class EventMethodStructTemplate: @staticmethod def append_prolog(line_list): line_list.append(" RefPtr<InspectorObject> paramsObject = InspectorObject::create();\n") @staticmethod def append_epilog(line_list): line_list.append(" jsonMessage->setObject(\"params\", paramsObject);\n") container_name = "paramsObject" @staticmethod def process_command(json_command, domain_name, agent_field_name, agent_interface_name): json_command_name = json_command["name"] cmd_enum_name = "k%s_%sCmd" % (domain_name, json_command["name"]) Generator.method_name_enum_list.append(" %s," % cmd_enum_name) Generator.method_handler_list.append(" &InspectorBackendDispatcherImpl::%s_%s," % (domain_name, json_command_name)) Generator.backend_method_declaration_list.append(" void %s_%s(long callId, InspectorObject* requestMessageObject);" % (domain_name, json_command_name)) ad_hoc_type_output = [] Generator.backend_agent_interface_list.append(ad_hoc_type_output) ad_hoc_type_writer = Writer(ad_hoc_type_output, " ") Generator.backend_agent_interface_list.append(" virtual void %s(ErrorString*" % json_command_name) method_in_code = "" method_out_code = "" agent_call_param_list = [] response_cook_list = [] request_message_param = "" js_parameters_text = "" if "parameters" in json_command: json_params = json_command["parameters"] method_in_code += Templates.param_container_access_code request_message_param = " requestMessageObject" js_param_list = [] for json_parameter in json_params: json_param_name = json_parameter["name"] param_raw_type = resolve_param_raw_type(json_parameter, domain_name) getter_name = param_raw_type.get_getter_name() optional = json_parameter.get("optional") non_optional_type_model = param_raw_type.get_raw_type_model() if optional: type_model = non_optional_type_model.get_optional() else: type_model = non_optional_type_model if optional: code = (" bool %s_valueFound = false;\n" " %s in_%s = get%s(paramsContainerPtr, \"%s\", &%s_valueFound, protocolErrorsPtr);\n" % (json_param_name, non_optional_type_model.get_command_return_pass_model().get_return_var_type(), json_param_name, getter_name, json_param_name, json_param_name)) param = ", %s_valueFound ? &in_%s : 0" % (json_param_name, json_param_name) # FIXME: pass optional refptr-values as PassRefPtr formal_param_type_pattern = "const %s*" else: code = (" %s in_%s = get%s(paramsContainerPtr, \"%s\", 0, protocolErrorsPtr);\n" % (non_optional_type_model.get_command_return_pass_model().get_return_var_type(), json_param_name, getter_name, json_param_name)) param = ", in_%s" % json_param_name # FIXME: pass not-optional refptr-values as NonNullPassRefPtr if param_raw_type.is_heavy_value(): formal_param_type_pattern = "const %s&" else: formal_param_type_pattern = "%s" method_in_code += code agent_call_param_list.append(param) Generator.backend_agent_interface_list.append(", %s in_%s" % (formal_param_type_pattern % non_optional_type_model.get_command_return_pass_model().get_return_var_type(), json_param_name)) js_bind_type = param_raw_type.get_js_bind_type() js_param_text = "{\"name\": \"%s\", \"type\": \"%s\", \"optional\": %s}" % ( json_param_name, js_bind_type, ("true" if ("optional" in json_parameter and json_parameter["optional"]) else "false")) js_param_list.append(js_param_text) js_parameters_text = ", ".join(js_param_list) response_cook_text = "" if json_command.get("async") == True: callback_name = Capitalizer.lower_camel_case_to_upper(json_command_name) + "Callback" callback_output = [] callback_writer = Writer(callback_output, ad_hoc_type_writer.get_indent()) decl_parameter_list = [] Generator.generate_send_method(json_command.get("returns"), json_command_name, domain_name, ad_hoc_type_writer, decl_parameter_list, Generator.CallbackMethodStructTemplate, Generator.backend_method_implementation_list, Templates.callback_method, {"callbackName": callback_name, "agentName": agent_interface_name}) callback_writer.newline("class " + callback_name + " : public CallbackBase {\n") callback_writer.newline("public:\n") callback_writer.newline(" " + callback_name + "(PassRefPtr<InspectorBackendDispatcherImpl>, int id);\n") callback_writer.newline(" void sendSuccess(" + ", ".join(decl_parameter_list) + ");\n") callback_writer.newline("};\n") ad_hoc_type_output.append(callback_output) method_out_code += " RefPtr<" + agent_interface_name + "::" + callback_name + "> callback = adoptRef(new " + agent_interface_name + "::" + callback_name + "(this, callId));\n" agent_call_param_list.append(", callback") response_cook_text += " if (!error.length()) \n" response_cook_text += " return;\n" response_cook_text += " callback->disable();\n" Generator.backend_agent_interface_list.append(", PassRefPtr<%s> callback" % callback_name) else: if "returns" in json_command: method_out_code += "\n" for json_return in json_command["returns"]: json_return_name = json_return["name"] optional = bool(json_return.get("optional")) return_type_binding = Generator.resolve_type_and_generate_ad_hoc(json_return, json_command_name, domain_name, ad_hoc_type_writer, agent_interface_name + "::") raw_type = return_type_binding.reduce_to_raw_type() setter_type = raw_type.get_setter_name() initializer = raw_type.get_c_initializer() type_model = return_type_binding.get_type_model() if optional: type_model = type_model.get_optional() code = " %s out_%s;\n" % (type_model.get_command_return_pass_model().get_return_var_type(), json_return_name) param = ", %sout_%s" % (type_model.get_command_return_pass_model().get_output_argument_prefix(), json_return_name) var_name = "out_%s" % json_return_name setter_argument = type_model.get_command_return_pass_model().get_output_to_raw_expression() % var_name if return_type_binding.get_setter_value_expression_pattern(): setter_argument = return_type_binding.get_setter_value_expression_pattern() % setter_argument cook = " result->set%s(\"%s\", %s);\n" % (setter_type, json_return_name, setter_argument) set_condition_pattern = type_model.get_command_return_pass_model().get_set_return_condition() if set_condition_pattern: cook = (" if (%s)\n " % (set_condition_pattern % var_name)) + cook annotated_type = type_model.get_command_return_pass_model().get_output_parameter_type() param_name = "out_%s" % json_return_name if optional: param_name = "opt_" + param_name Generator.backend_agent_interface_list.append(", %s %s" % (annotated_type, param_name)) response_cook_list.append(cook) method_out_code += code agent_call_param_list.append(param) response_cook_text = "".join(response_cook_list) if len(response_cook_text) != 0: response_cook_text = " if (!error.length()) {\n" + response_cook_text + " }" backend_js_reply_param_list = [] if "returns" in json_command: for json_return in json_command["returns"]: json_return_name = json_return["name"] backend_js_reply_param_list.append("\"%s\"" % json_return_name) js_reply_list = "[%s]" % ", ".join(backend_js_reply_param_list) Generator.backend_method_implementation_list.append(Templates.backend_method.substitute(None, domainName=domain_name, methodName=json_command_name, agentField="m_" + agent_field_name, methodInCode=method_in_code, methodOutCode=method_out_code, agentCallParams="".join(agent_call_param_list), requestMessageObject=request_message_param, responseCook=response_cook_text, commandNameIndex=cmd_enum_name)) Generator.backend_method_name_declaration_list.append(" \"%s.%s\"," % (domain_name, json_command_name)) Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerCommand(\"%s.%s\", [%s], %s);\n" % (domain_name, json_command_name, js_parameters_text, js_reply_list)) Generator.backend_agent_interface_list.append(") = 0;\n") class CallbackMethodStructTemplate: @staticmethod def append_prolog(line_list): pass @staticmethod def append_epilog(line_list): pass container_name = "jsonMessage" # Generates common code for event sending and callback response data sending. @staticmethod def generate_send_method(parameters, event_name, domain_name, ad_hoc_type_writer, decl_parameter_list, method_struct_template, generator_method_list, method_template, template_params): method_line_list = [] if parameters: method_struct_template.append_prolog(method_line_list) for json_parameter in parameters: parameter_name = json_parameter["name"] param_type_binding = Generator.resolve_type_and_generate_ad_hoc(json_parameter, event_name, domain_name, ad_hoc_type_writer, "") raw_type = param_type_binding.reduce_to_raw_type() raw_type_binding = RawTypeBinding(raw_type) optional = bool(json_parameter.get("optional")) setter_type = raw_type.get_setter_name() type_model = param_type_binding.get_type_model() raw_type_model = raw_type_binding.get_type_model() if optional: type_model = type_model.get_optional() raw_type_model = raw_type_model.get_optional() annotated_type = type_model.get_input_param_type_text() mode_type_binding = param_type_binding decl_parameter_list.append("%s %s" % (annotated_type, parameter_name)) setter_argument = raw_type_model.get_event_setter_expression_pattern() % parameter_name if mode_type_binding.get_setter_value_expression_pattern(): setter_argument = mode_type_binding.get_setter_value_expression_pattern() % setter_argument setter_code = " %s->set%s(\"%s\", %s);\n" % (method_struct_template.container_name, setter_type, parameter_name, setter_argument) if optional: setter_code = (" if (%s)\n " % parameter_name) + setter_code method_line_list.append(setter_code) method_struct_template.append_epilog(method_line_list) generator_method_list.append(method_template.substitute(None, domainName=domain_name, parameters=", ".join(decl_parameter_list), code="".join(method_line_list), **template_params)) @staticmethod def resolve_type_and_generate_ad_hoc(json_param, method_name, domain_name, ad_hoc_type_writer, container_relative_name_prefix_param): param_name = json_param["name"] ad_hoc_type_list = [] class AdHocTypeContext: container_full_name_prefix = "<not yet defined>" container_relative_name_prefix = container_relative_name_prefix_param @staticmethod def get_type_name_fix(): class NameFix: class_name = Capitalizer.lower_camel_case_to_upper(param_name) @staticmethod def output_comment(writer): writer.newline("// Named after parameter '%s' while generating command/event %s.\n" % (param_name, method_name)) return NameFix @staticmethod def add_type(binding): ad_hoc_type_list.append(binding) type_binding = resolve_param_type(json_param, domain_name, AdHocTypeContext) class InterfaceForwardListener: @staticmethod def add_type_data(type_data): pass class InterfaceResolveContext: forward_listener = InterfaceForwardListener for type in ad_hoc_type_list: type.resolve_inner(InterfaceResolveContext) class InterfaceGenerateContext: validator_writer = "not supported in InterfaceGenerateContext" cpp_writer = validator_writer for type in ad_hoc_type_list: generator = type.get_code_generator() if generator: generator.generate_type_builder(ad_hoc_type_writer, InterfaceGenerateContext) return type_binding @staticmethod def process_types(type_map): output = Generator.type_builder_fragments class GenerateContext: validator_writer = Writer(Generator.validator_impl_list, "") cpp_writer = Writer(Generator.type_builder_impl_list, "") def generate_all_domains_code(out, type_data_callback): writer = Writer(out, "") for domain_data in type_map.domains(): domain_fixes = DomainNameFixes.get_fixed_data(domain_data.name()) domain_guard = domain_fixes.get_guard() namespace_declared = [] def namespace_lazy_generator(): if not namespace_declared: if domain_guard: domain_guard.generate_open(out) writer.newline("namespace ") writer.append(domain_data.name()) writer.append(" {\n") # What is a better way to change value from outer scope? namespace_declared.append(True) return writer for type_data in domain_data.types(): type_data_callback(type_data, namespace_lazy_generator) if namespace_declared: writer.append("} // ") writer.append(domain_data.name()) writer.append("\n\n") if domain_guard: domain_guard.generate_close(out) def create_type_builder_caller(generate_pass_id): def call_type_builder(type_data, writer_getter): code_generator = type_data.get_binding().get_code_generator() if code_generator and generate_pass_id == code_generator.get_generate_pass_id(): writer = writer_getter() code_generator.generate_type_builder(writer, GenerateContext) return call_type_builder generate_all_domains_code(output, create_type_builder_caller(TypeBuilderPass.MAIN)) Generator.type_builder_forwards.append("// Forward declarations.\n") def generate_forward_callback(type_data, writer_getter): if type_data in global_forward_listener.type_data_set: binding = type_data.get_binding() binding.get_code_generator().generate_forward_declaration(writer_getter()) generate_all_domains_code(Generator.type_builder_forwards, generate_forward_callback) Generator.type_builder_forwards.append("// End of forward declarations.\n\n") Generator.type_builder_forwards.append("// Typedefs.\n") generate_all_domains_code(Generator.type_builder_forwards, create_type_builder_caller(TypeBuilderPass.TYPEDEF)) Generator.type_builder_forwards.append("// End of typedefs.\n\n") def flatten_list(input): res = [] def fill_recursive(l): for item in l: if isinstance(item, list): fill_recursive(item) else: res.append(item) fill_recursive(input) return res # A writer that only updates file if it actually changed to better support incremental build. class SmartOutput: def __init__(self, file_name): self.file_name_ = file_name self.output_ = "" def write(self, text): self.output_ += text def close(self): text_changed = True try: read_file = open(self.file_name_, "r") old_text = read_file.read() read_file.close() text_changed = old_text != self.output_ except: # Ignore, just overwrite by default pass if text_changed or write_always: out_file = open(self.file_name_, "w") out_file.write(self.output_) out_file.close() Generator.go() backend_h_file = SmartOutput(output_header_dirname + "/InspectorBackendDispatcher.h") backend_cpp_file = SmartOutput(output_cpp_dirname + "/InspectorBackendDispatcher.cpp") frontend_h_file = SmartOutput(output_header_dirname + "/InspectorFrontend.h") frontend_cpp_file = SmartOutput(output_cpp_dirname + "/InspectorFrontend.cpp") typebuilder_h_file = SmartOutput(output_header_dirname + "/InspectorTypeBuilder.h") typebuilder_cpp_file = SmartOutput(output_cpp_dirname + "/InspectorTypeBuilder.cpp") backend_js_file = SmartOutput(output_cpp_dirname + "/InspectorBackendCommands.js") backend_h_file.write(Templates.backend_h.substitute(None, virtualSetters="\n".join(Generator.backend_virtual_setters_list), agentInterfaces="".join(flatten_list(Generator.backend_agent_interface_list)), methodNamesEnumContent="\n".join(Generator.method_name_enum_list))) backend_cpp_file.write(Templates.backend_cpp.substitute(None, constructorInit="\n".join(Generator.backend_constructor_init_list), setters="\n".join(Generator.backend_setters_list), fieldDeclarations="\n".join(Generator.backend_field_list), methodNameDeclarations="\n".join(Generator.backend_method_name_declaration_list), methods="\n".join(Generator.backend_method_implementation_list), methodDeclarations="\n".join(Generator.backend_method_declaration_list), messageHandlers="\n".join(Generator.method_handler_list))) frontend_h_file.write(Templates.frontend_h.substitute(None, fieldDeclarations="".join(Generator.frontend_class_field_lines), domainClassList="".join(Generator.frontend_domain_class_lines))) frontend_cpp_file.write(Templates.frontend_cpp.substitute(None, constructorInit="".join(Generator.frontend_constructor_init_list), methods="\n".join(Generator.frontend_method_list))) typebuilder_h_file.write(Templates.typebuilder_h.substitute(None, typeBuilders="".join(flatten_list(Generator.type_builder_fragments)), forwards="".join(Generator.type_builder_forwards), validatorIfdefName=VALIDATOR_IFDEF_NAME)) typebuilder_cpp_file.write(Templates.typebuilder_cpp.substitute(None, enumConstantValues=EnumConstants.get_enum_constant_code(), implCode="".join(flatten_list(Generator.type_builder_impl_list)), validatorCode="".join(flatten_list(Generator.validator_impl_list)), validatorIfdefName=VALIDATOR_IFDEF_NAME)) backend_js_file.write(Templates.backend_js.substitute(None, domainInitializers="".join(Generator.backend_js_domain_initializer_list))) backend_h_file.close() backend_cpp_file.close() frontend_h_file.close() frontend_cpp_file.close() typebuilder_h_file.close() typebuilder_cpp_file.close() backend_js_file.close()
bsd-3-clause
jorge-marques/shoop
shoop_tests/core/test_product_caching_object.py
7
2090
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import pytest from shoop.core.models import Product from shoop.core.utils.product_caching_object import ProductCachingObject from shoop.testing.factories import get_default_shop_product, create_product def test_product_caching_object_nulling(): pco = ProductCachingObject() pco.product = None assert not pco.product assert not pco.product_id pco = ProductCachingObject() pco.product = None assert not pco.product_id pco = ProductCachingObject() pco.product_id = None assert not pco.product def test_product_caching_object_type_validation(): with pytest.raises(TypeError): pco = ProductCachingObject() pco.product_id = "yeah" with pytest.raises(TypeError): pco = ProductCachingObject() pco.product = "yeahhh" with pytest.raises(ValueError): pco = ProductCachingObject() pco.product = Product() @pytest.mark.django_db def test_product_caching_object(): shop_product = get_default_shop_product() product = shop_product.product another_product = create_product("PCOTestProduct") pco = ProductCachingObject() pco.product = product assert pco.product is product assert pco.product_id == product.pk assert ProductCachingObject().product != pco.product # Assert PCOs are separate assert pco._product_cache == pco.product # This private property is courtesy of ModelCachingDescriptor pco = ProductCachingObject() pco.product_id = product.pk assert pco.product == product assert pco.product_id == product.pk # Not creating a new PCO here pco.product = another_product assert pco.product == another_product assert pco.product_id == another_product.pk # Nor here pco.product_id = product.pk assert pco.product == product assert pco.product_id == product.pk
agpl-3.0
BaseBot/Triangula
src/python/setup.py
1
1035
__author__ = 'tom' from setuptools import setup # Makes use of the sphinx and sphinx-pypi-upload packages. To build for local development # use 'python setup.py develop'. To upload a version to pypi use 'python setup.py clean sdist upload'. # To build docs use 'python setup.py build_sphinx' and to upload docs to pythonhosted.org use # 'python setup.py upload_sphinx'. Both uploads require 'python setup.py register' to be run, and will # only work for Tom as they need the pypi account credentials. setup( name='triangula', version='0.3.1', description='Code for Triangula', classifiers=['Programming Language :: Python :: 2.7'], url='https://github.com/tomoinn/triangula/', author='Tom Oinn', author_email='tomoinn@gmail.com', license='ASL2.0', packages=['triangula'], install_requires=['evdev==0.5.0', 'euclid==0.1', 'pyserial==2.7', 'numpy==1.10.1'], include_package_data=True, test_suite='nose.collector', tests_require=['nose'], dependency_links=[], zip_safe=False)
apache-2.0
eyohansa/django
tests/gis_tests/geoapp/test_regress.py
318
3857
# -*- encoding: utf-8 -*- from __future__ import unicode_literals from datetime import datetime from django.contrib.gis.db.models import Extent from django.contrib.gis.shortcuts import render_to_kmz from django.db.models import Count, Min from django.test import TestCase, skipUnlessDBFeature from ..utils import no_oracle from .models import City, PennsylvaniaCity, State, Truth @skipUnlessDBFeature("gis_enabled") class GeoRegressionTests(TestCase): fixtures = ['initial'] def test_update(self): "Testing GeoQuerySet.update(). See #10411." pnt = City.objects.get(name='Pueblo').point bak = pnt.clone() pnt.y += 0.005 pnt.x += 0.005 City.objects.filter(name='Pueblo').update(point=pnt) self.assertEqual(pnt, City.objects.get(name='Pueblo').point) City.objects.filter(name='Pueblo').update(point=bak) self.assertEqual(bak, City.objects.get(name='Pueblo').point) def test_kmz(self): "Testing `render_to_kmz` with non-ASCII data. See #11624." name = "Åland Islands" places = [{ 'name': name, 'description': name, 'kml': '<Point><coordinates>5.0,23.0</coordinates></Point>' }] render_to_kmz('gis/kml/placemarks.kml', {'places': places}) @skipUnlessDBFeature("supports_extent_aggr") def test_extent(self): "Testing `extent` on a table with a single point. See #11827." pnt = City.objects.get(name='Pueblo').point ref_ext = (pnt.x, pnt.y, pnt.x, pnt.y) extent = City.objects.filter(name='Pueblo').aggregate(Extent('point'))['point__extent'] for ref_val, val in zip(ref_ext, extent): self.assertAlmostEqual(ref_val, val, 4) def test_unicode_date(self): "Testing dates are converted properly, even on SpatiaLite. See #16408." founded = datetime(1857, 5, 23) PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)', founded=founded) self.assertEqual(founded, PennsylvaniaCity.objects.datetimes('founded', 'day')[0]) self.assertEqual(founded, PennsylvaniaCity.objects.aggregate(Min('founded'))['founded__min']) def test_empty_count(self): "Testing that PostGISAdapter.__eq__ does check empty strings. See #13670." # contrived example, but need a geo lookup paired with an id__in lookup pueblo = City.objects.get(name='Pueblo') state = State.objects.filter(poly__contains=pueblo.point) cities_within_state = City.objects.filter(id__in=state) # .count() should not throw TypeError in __eq__ self.assertEqual(cities_within_state.count(), 1) # TODO: fix on Oracle -- get the following error because the SQL is ordered # by a geometry object, which Oracle apparently doesn't like: # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type @no_oracle def test_defer_or_only_with_annotate(self): "Regression for #16409. Make sure defer() and only() work with annotate()" self.assertIsInstance(list(City.objects.annotate(Count('point')).defer('name')), list) self.assertIsInstance(list(City.objects.annotate(Count('point')).only('name')), list) def test_boolean_conversion(self): "Testing Boolean value conversion with the spatial backend, see #15169." t1 = Truth.objects.create(val=True) t2 = Truth.objects.create(val=False) val1 = Truth.objects.get(pk=t1.pk).val val2 = Truth.objects.get(pk=t2.pk).val # verify types -- shouldn't be 0/1 self.assertIsInstance(val1, bool) self.assertIsInstance(val2, bool) # verify values self.assertEqual(val1, True) self.assertEqual(val2, False)
bsd-3-clause
dariemp/odoo
addons/hr_payroll_account/wizard/__init__.py
433
1116
#-*- coding:utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # d$ # # 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 hr_payroll_payslips_by_employees # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
libAtoms/matscipy
scripts/fracture_mechanics/run_crack_thin_strip.py
1
4618
#! /usr/bin/env python # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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, see <http://www.gnu.org/licenses/>. # ====================================================================== """ Script to run classical molecular dynamics for a crack slab, incrementing the load in small steps until fracture starts. James Kermode <james.kermode@kcl.ac.uk> August 2013 """ import numpy as np import ase.io import ase.units as units from ase.constraints import FixAtoms from ase.md.verlet import VelocityVerlet from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase.io.netcdftrajectory import NetCDFTrajectory from matscipy.fracture_mechanics.crack import (get_strain, get_energy_release_rate, ConstantStrainRate, find_tip_stress_field) import sys sys.path.insert(0, '.') import params # ********** Read input file ************ print 'Loading atoms from file "crack.xyz"' atoms = ase.io.read('crack.xyz') orig_height = atoms.info['OrigHeight'] orig_crack_pos = atoms.info['CrackPos'].copy() # ***** Setup constraints ******* top = atoms.positions[:, 1].max() bottom = atoms.positions[:, 1].min() left = atoms.positions[:, 0].min() right = atoms.positions[:, 0].max() # fix atoms in the top and bottom rows fixed_mask = ((abs(atoms.positions[:, 1] - top) < 1.0) | (abs(atoms.positions[:, 1] - bottom) < 1.0)) fix_atoms = FixAtoms(mask=fixed_mask) print('Fixed %d atoms\n' % fixed_mask.sum()) # Increase epsilon_yy applied to all atoms at constant strain rate strain_atoms = ConstantStrainRate(orig_height, params.strain_rate*params.timestep) atoms.set_constraint(fix_atoms) atoms.set_calculator(params.calc) # ********* Setup and run MD *********** # Set the initial temperature to 2*simT: it will then equilibriate to # simT, by the virial theorem MaxwellBoltzmannDistribution(atoms, 2.0*params.sim_T) # Initialise the dynamical system dynamics = VelocityVerlet(atoms, params.timestep) # Print some information every time step def printstatus(): if dynamics.nsteps == 1: print """ State Time/fs Temp/K Strain G/(J/m^2) CrackPos/A D(CrackPos)/A ---------------------------------------------------------------------------------""" log_format = ('%(label)-4s%(time)12.1f%(temperature)12.6f'+ '%(strain)12.5f%(G)12.4f%(crack_pos_x)12.2f (%(d_crack_pos_x)+5.2f)') atoms.info['label'] = 'D' # Label for the status line atoms.info['time'] = dynamics.get_time()/units.fs atoms.info['temperature'] = (atoms.get_kinetic_energy() / (1.5*units.kB*len(atoms))) atoms.info['strain'] = get_strain(atoms) atoms.info['G'] = get_energy_release_rate(atoms)/(units.J/units.m**2) crack_pos = find_tip_stress_field(atoms) atoms.info['crack_pos_x'] = crack_pos[0] atoms.info['d_crack_pos_x'] = crack_pos[0] - orig_crack_pos[0] print log_format % atoms.info dynamics.attach(printstatus) # Check if the crack has advanced enough and apply strain if it has not def check_if_crack_advanced(atoms): crack_pos = find_tip_stress_field(atoms) # strain if crack has not advanced more than tip_move_tol if crack_pos[0] - orig_crack_pos[0] < params.tip_move_tol: strain_atoms.apply_strain(atoms) dynamics.attach(check_if_crack_advanced, 1, atoms) # Save frames to the trajectory every `traj_interval` time steps trajectory = NetCDFTrajectory(params.traj_file, mode='w') def write_frame(atoms): trajectory.write(atoms) dynamics.attach(write_frame, params.traj_interval, atoms) # Start running! dynamics.run(params.nsteps)
gpl-2.0
tdtrask/ansible
test/units/modules/network/onyx/onyx_module.py
66
2691
# (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 import json import os from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except: pass fixture_data[path] = data return data class TestOnyxModule(ModuleTestCase): def execute_module(self, failed=False, changed=False, commands=None, is_updates=False, sort=True, transport='cli'): self.load_fixtures(commands, transport=transport) if failed: result = self.failed() self.assertTrue(result['failed'], result) else: result = self.changed(changed) self.assertEqual(result['changed'], changed, result) if commands is not None: if is_updates: commands_res = result.get('updates') else: commands_res = result.get('commands') if sort: self.assertEqual(sorted(commands), sorted(commands_res), commands_res) else: self.assertEqual(commands, commands_res, commands_res) return result def failed(self): with self.assertRaises(AnsibleFailJson) as exc: self.module.main() result = exc.exception.args[0] self.assertTrue(result['failed'], result) return result def changed(self, changed=False): with self.assertRaises(AnsibleExitJson) as exc: self.module.main() result = exc.exception.args[0] self.assertEqual(result['changed'], changed, result) return result def load_fixtures(self, commands=None, transport='cli'): pass
gpl-3.0
qedi-r/home-assistant
tests/components/ring/test_switch.py
4
2734
"""The tests for the Ring switch platform.""" from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from tests.common import load_fixture from .common import setup_platform async def test_entity_registry(hass, requests_mock): """Tests that the devices are registed in the entity registry.""" await setup_platform(hass, SWITCH_DOMAIN) entity_registry = await hass.helpers.entity_registry.async_get_registry() entry = entity_registry.async_get("switch.front_siren") assert entry.unique_id == "aacdef123-siren" entry = entity_registry.async_get("switch.internal_siren") assert entry.unique_id == "aacdef124-siren" async def test_siren_off_reports_correctly(hass, requests_mock): """Tests that the initial state of a device that should be off is correct.""" await setup_platform(hass, SWITCH_DOMAIN) state = hass.states.get("switch.front_siren") assert state.state == "off" assert state.attributes.get("friendly_name") == "Front siren" async def test_siren_on_reports_correctly(hass, requests_mock): """Tests that the initial state of a device that should be on is correct.""" await setup_platform(hass, SWITCH_DOMAIN) state = hass.states.get("switch.internal_siren") assert state.state == "on" assert state.attributes.get("friendly_name") == "Internal siren" assert state.attributes.get("icon") == "mdi:alarm-bell" async def test_siren_can_be_turned_on(hass, requests_mock): """Tests the siren turns on correctly.""" await setup_platform(hass, SWITCH_DOMAIN) # Mocks the response for turning a siren on requests_mock.put( "https://api.ring.com/clients_api/doorbots/987652/siren_on", text=load_fixture("ring_doorbot_siren_on_response.json"), ) state = hass.states.get("switch.front_siren") assert state.state == "off" await hass.services.async_call( "switch", "turn_on", {"entity_id": "switch.front_siren"}, blocking=True ) await hass.async_block_till_done() state = hass.states.get("switch.front_siren") assert state.state == "on" async def test_updates_work(hass, requests_mock): """Tests the update service works correctly.""" await setup_platform(hass, SWITCH_DOMAIN) state = hass.states.get("switch.front_siren") assert state.state == "off" # Changes the return to indicate that the siren is now on. requests_mock.get( "https://api.ring.com/clients_api/ring_devices", text=load_fixture("ring_devices_updated.json"), ) await hass.services.async_call("ring", "update", {}, blocking=True) await hass.async_block_till_done() state = hass.states.get("switch.front_siren") assert state.state == "on"
apache-2.0
Zerknechterer/pyload
module/setup.py
35
18929
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 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/>. @author: RaNaN """ from getpass import getpass import module.common.pylgettext as gettext import os from os import makedirs from os.path import abspath from os.path import dirname from os.path import exists from os.path import join from subprocess import PIPE from subprocess import call import sys from sys import exit from module.utils import get_console_encoding class Setup(): """ pyLoads initial setup configuration assistent """ def __init__(self, path, config): self.path = path self.config = config self.stdin_encoding = get_console_encoding(sys.stdin.encoding) def start(self): langs = self.config.getMetaData("general", "language")["type"].split(";") lang = self.ask(u"Choose your Language / Wähle deine Sprache", "en", langs) gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) translation = gettext.translation("setup", join(self.path, "locale"), languages=[lang, "en"], fallback=True) translation.install(True) #Input shorthand for yes self.yes = _("y") #Input shorthand for no self.no = _("n") # print "" # print _("Would you like to configure pyLoad via Webinterface?") # print _("You need a Browser and a connection to this PC for it.") # viaweb = self.ask(_("Start initial webinterface for configuration?"), "y", bool=True) # if viaweb: # try: # from module.web import ServerThread # ServerThread.setup = self # from module.web import webinterface # webinterface.run_simple() # return False # except Exception, e: # print "Setup failed with this error: ", e # print "Falling back to commandline setup." print "" print _("Welcome to the pyLoad Configuration Assistent.") print _("It will check your system and make a basic setup in order to run pyLoad.") print "" print _("The value in brackets [] always is the default value,") print _("in case you don't want to change it or you are unsure what to choose, just hit enter.") print _( "Don't forget: You can always rerun this assistent with --setup or -s parameter, when you start pyLoadCore.") print _("If you have any problems with this assistent hit STRG-C,") print _("to abort and don't let him start with pyLoadCore automatically anymore.") print "" print _("When you are ready for system check, hit enter.") raw_input() basic, ssl, captcha, gui, web, js = self.system_check() print "" if not basic: print _("You need pycurl, sqlite and python 2.5, 2.6 or 2.7 to run pyLoad.") print _("Please correct this and re-run pyLoad.") print _("Setup will now close.") raw_input() return False raw_input(_("System check finished, hit enter to see your status report.")) print "" print _("## Status ##") print "" avail = [] if self.check_module("Crypto"): avail.append(_("container decrypting")) if ssl: avail.append(_("ssl connection")) if captcha: avail.append(_("automatic captcha decryption")) if gui: avail.append(_("GUI")) if web: avail.append(_("Webinterface")) if js: avail.append(_("extended Click'N'Load")) string = "" for av in avail: string += ", " + av print _("Features available:") + string[1:] print "" if len(avail) < 5: print _("Featues missing: ") print if not self.check_module("Crypto"): print _("no py-crypto available") print _("You need this if you want to decrypt container files.") print "" if not ssl: print _("no SSL available") print _("This is needed if you want to establish a secure connection to core or webinterface.") print _("If you only want to access locally to pyLoad ssl is not usefull.") print "" if not captcha: print _("no Captcha Recognition available") print _("Only needed for some hosters and as freeuser.") print "" if not gui: print _("Gui not available") print _("The Graphical User Interface.") print "" if not js: print _("no JavaScript engine found") print _("You will need this for some Click'N'Load links. Install Spidermonkey, ossp-js, pyv8 or rhino") print _("You can abort the setup now and fix some dependicies if you want.") con = self.ask(_("Continue with setup?"), self.yes, bool=True) if not con: return False print "" print _("Do you want to change the config path? Current is %s") % abspath("") print _( "If you use pyLoad on a server or the home partition lives on an iternal flash it may be a good idea to change it.") path = self.ask(_("Change config path?"), self.no, bool=True) if path: self.conf_path() #calls exit when changed print "" print _("Do you want to configure login data and basic settings?") print _("This is recommend for first run.") con = self.ask(_("Make basic setup?"), self.yes, bool=True) if con: self.conf_basic() if ssl: print "" print _("Do you want to configure ssl?") ssl = self.ask(_("Configure ssl?"), self.no, bool=True) if ssl: self.conf_ssl() if web: print "" print _("Do you want to configure webinterface?") web = self.ask(_("Configure webinterface?"), self.yes, bool=True) if web: self.conf_web() print "" print _("Setup finished successfully.") print _("Hit enter to exit and restart pyLoad") raw_input() return True def system_check(self): """ make a systemcheck and return the results""" print _("## System Check ##") if sys.version_info[:2] > (2, 7): print _("Your python version is to new, Please use Python 2.6/2.7") python = False elif sys.version_info[:2] < (2, 5): print _("Your python version is to old, Please use at least Python 2.5") python = False else: print _("Python Version: OK") python = True curl = self.check_module("pycurl") self.print_dep("pycurl", curl) sqlite = self.check_module("sqlite3") self.print_dep("sqlite3", sqlite) basic = python and curl and sqlite print "" crypto = self.check_module("Crypto") self.print_dep("pycrypto", crypto) ssl = self.check_module("OpenSSL") self.print_dep("py-OpenSSL", ssl) print "" pil = self.check_module("Image") self.print_dep("py-imaging", pil) if os.name == "nt": tesser = self.check_prog([join(pypath, "tesseract", "tesseract.exe"), "-v"]) else: tesser = self.check_prog(["tesseract", "-v"]) self.print_dep("tesseract", tesser) captcha = pil and tesser print "" gui = self.check_module("PyQt4") self.print_dep("PyQt4", gui) print "" jinja = True try: import jinja2 v = jinja2.__version__ if v and "unknown" not in v: if not v.startswith("2.5") and not v.startswith("2.6"): print _("Your installed jinja2 version %s seems too old.") % jinja2.__version__ print _("You can safely continue but if the webinterface is not working,") print _("please upgrade or deinstall it, pyLoad includes a sufficient jinja2 libary.") print jinja = False except: pass self.print_dep("jinja2", jinja) beaker = self.check_module("beaker") self.print_dep("beaker", beaker) web = sqlite and beaker from module.common import JsEngine js = True if JsEngine.ENGINE else False self.print_dep(_("JS engine"), js) return basic, ssl, captcha, gui, web, js def conf_basic(self): print "" print _("## Basic Setup ##") print "" print _("The following logindata is valid for CLI, GUI and webinterface.") from module.database import DatabaseBackend db = DatabaseBackend(None) db.setup() username = self.ask(_("Username"), "User") password = self.ask("", "", password=True) db.addUser(username, password) db.shutdown() print "" print _("External clients (GUI, CLI or other) need remote access to work over the network.") print _("However, if you only want to use the webinterface you may disable it to save ram.") self.config["remote"]["activated"] = self.ask(_("Enable remote access"), self.yes, bool=True) print "" langs = self.config.getMetaData("general", "language") self.config["general"]["language"] = self.ask(_("Language"), "en", langs["type"].split(";")) self.config["general"]["download_folder"] = self.ask(_("Downloadfolder"), "Downloads") self.config["download"]["max_downloads"] = self.ask(_("Max parallel downloads"), "3") #print _("You should disable checksum proofing, if you have low hardware requirements.") #self.config["general"]["checksum"] = self.ask(_("Proof checksum?"), "y", bool=True) reconnect = self.ask(_("Use Reconnect?"), self.no, bool=True) self.config["reconnect"]["activated"] = reconnect if reconnect: self.config["reconnect"]["method"] = self.ask(_("Reconnect script location"), "./reconnect.sh") def conf_web(self): print "" print _("## Webinterface Setup ##") print "" self.config["webinterface"]["activated"] = self.ask(_("Activate webinterface?"), self.yes, bool=True) print "" print _("Listen address, if you use 127.0.0.1 or localhost, the webinterface will only accessible locally.") self.config["webinterface"]["host"] = self.ask(_("Address"), "0.0.0.0") self.config["webinterface"]["port"] = self.ask(_("Port"), "8000") print "" print _("pyLoad offers several server backends, now following a short explanation.") print "builtin:", _("Default server, best choice if you dont know which one to choose.") print "threaded:", _("This server offers SSL and is a good alternative to builtin.") print "fastcgi:", _( "Can be used by apache, lighttpd, requires you to configure them, which is not too easy job.") print "lightweight:", _("Very fast alternative written in C, requires libev and linux knowlegde.") print "\t", _("Get it from here: https://github.com/jonashaag/bjoern, compile it") print "\t", _("and copy bjoern.so to module/lib") print print _( "Attention: In some rare cases the builtin server is not working, if you notice problems with the webinterface") print _("come back here and change the builtin server to the threaded one here.") self.config["webinterface"]["server"] = self.ask(_("Server"), "builtin", ["builtin", "threaded", "fastcgi", "lightweight"]) def conf_ssl(self): print "" print _("## SSL Setup ##") print "" print _("Execute these commands from pyLoad config folder to make ssl certificates:") print "" print "openssl genrsa -out ssl.key 1024" print "openssl req -new -key ssl.key -out ssl.csr" print "openssl req -days 36500 -x509 -key ssl.key -in ssl.csr > ssl.crt " print "" print _("If you're done and everything went fine, you can activate ssl now.") self.config["ssl"]["activated"] = self.ask(_("Activate SSL?"), self.yes, bool=True) def set_user(self): gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) translation = gettext.translation("setup", join(self.path, "locale"), languages=[self.config["general"]["language"], "en"], fallback=True) translation.install(True) from module.database import DatabaseBackend db = DatabaseBackend(None) db.setup() noaction = True try: while True: print _("Select action") print _("1 - Create/Edit user") print _("2 - List users") print _("3 - Remove user") print _("4 - Quit") action = raw_input("[1]/2/3/4: ") if not action in ("1", "2", "3", "4"): continue elif action == "1": print "" username = self.ask(_("Username"), "User") password = self.ask("", "", password=True) db.addUser(username, password) noaction = False elif action == "2": print "" print _("Users") print "-----" users = db.listUsers() noaction = False for user in users: print user print "-----" print "" elif action == "3": print "" username = self.ask(_("Username"), "") if username: db.removeUser(username) noaction = False elif action == "4": break finally: if not noaction: db.shutdown() def conf_path(self, trans=False): if trans: gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) translation = gettext.translation("setup", join(self.path, "locale"), languages=[self.config["general"]["language"], "en"], fallback=True) translation.install(True) print _("Setting new configpath, current configuration will not be transfered!") path = self.ask(_("Configpath"), abspath("")) try: path = join(pypath, path) if not exists(path): makedirs(path) f = open(join(pypath, "module", "config", "configdir"), "wb") f.write(path) f.close() print _("Configpath changed, setup will now close, please restart to go on.") print _("Press Enter to exit.") raw_input() exit() except Exception, e: print _("Setting config path failed: %s") % str(e) def print_dep(self, name, value): """Print Status of dependency""" if value: print _("%s: OK") % name else: print _("%s: missing") % name def check_module(self, module): try: __import__(module) return True except: return False def check_prog(self, command): pipe = PIPE try: call(command, stdout=pipe, stderr=pipe) return True except: return False def ask(self, qst, default, answers=[], bool=False, password=False): """produce one line to asking for input""" if answers: info = "(" for i, answer in enumerate(answers): info += (", " if i != 0 else "") + str((answer == default and "[%s]" % answer) or answer) info += ")" elif bool: if default == self.yes: info = "([%s]/%s)" % (self.yes, self.no) else: info = "(%s/[%s])" % (self.yes, self.no) else: info = "[%s]" % default if password: p1 = True p2 = False while p1 != p2: # getpass(_("Password: ")) will crash on systems with broken locales (Win, NAS) sys.stdout.write(_("Password: ")) p1 = getpass("") if len(p1) < 4: print _("Password too short. Use at least 4 symbols.") continue sys.stdout.write(_("Password (again): ")) p2 = getpass("") if p1 == p2: return p1 else: print _("Passwords did not match.") while True: try: input = raw_input(qst + " %s: " % info) except KeyboardInterrupt: print "\nSetup interrupted" exit() input = input.decode(self.stdin_encoding) if input.strip() == "": input = default if bool: # yes, true,t are inputs for booleans with value true if input.lower().strip() in [self.yes, _("yes"), _("true"), _("t"), "yes"]: return True # no, false,f are inputs for booleans with value false elif input.lower().strip() in [self.no, _("no"), _("false"), _("f"), "no"]: return False else: print _("Invalid Input") continue if not answers: return input else: if input in answers: return input else: print _("Invalid Input") if __name__ == "__main__": test = Setup(join(abspath(dirname(__file__)), ".."), None) test.start()
gpl-3.0
Vixionar/django
tests/gis_tests/geo3d/models.py
302
1294
from django.utils.encoding import python_2_unicode_compatible from ..models import models @python_2_unicode_compatible class NamedModel(models.Model): name = models.CharField(max_length=30) objects = models.GeoManager() class Meta: abstract = True required_db_features = ['gis_enabled'] def __str__(self): return self.name class City3D(NamedModel): point = models.PointField(dim=3) class Interstate2D(NamedModel): line = models.LineStringField(srid=4269) class Interstate3D(NamedModel): line = models.LineStringField(dim=3, srid=4269) class InterstateProj2D(NamedModel): line = models.LineStringField(srid=32140) class InterstateProj3D(NamedModel): line = models.LineStringField(dim=3, srid=32140) class Polygon2D(NamedModel): poly = models.PolygonField(srid=32140) class Polygon3D(NamedModel): poly = models.PolygonField(dim=3, srid=32140) class SimpleModel(models.Model): objects = models.GeoManager() class Meta: abstract = True required_db_features = ['gis_enabled'] class Point2D(SimpleModel): point = models.PointField() class Point3D(SimpleModel): point = models.PointField(dim=3) class MultiPoint3D(SimpleModel): mpoint = models.MultiPointField(dim=3)
bsd-3-clause
msiedlarek/qtwebkit
Source/WebCore/inspector/CodeGeneratorInspectorStrings.py
119
29621
# Copyright (c) 2013 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. # THis file contains string resources for CodeGeneratorInspector. # Its syntax is a Python syntax subset, suitable for manual parsing. frontend_domain_class = ( """ class $domainClassName { public: $domainClassName(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { } ${frontendDomainMethodDeclarations} void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; } InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; } private: InspectorFrontendChannel* m_inspectorFrontendChannel; }; $domainClassName* $domainFieldName() { return &m_$domainFieldName; } """) backend_method = ( """void InspectorBackendDispatcherImpl::${domainName}_$methodName(long callId, InspectorObject*$requestMessageObject) { RefPtr<InspectorArray> protocolErrors = InspectorArray::create(); if (!$agentField) protocolErrors->pushString("${domainName} handler is not available."); $methodOutCode $methodInCode RefPtr<InspectorObject> result = InspectorObject::create(); ErrorString error; if (!protocolErrors->length()) { $agentField->$methodName(&error$agentCallParams); ${responseCook} } sendResponse(callId, result, commandNames[$commandNameIndex], protocolErrors, error); } """) frontend_method = ("""void InspectorFrontend::$domainName::$eventName($parameters) { RefPtr<InspectorObject> jsonMessage = InspectorObject::create(); jsonMessage->setString("method", "$domainName.$eventName"); $code if (m_inspectorFrontendChannel) m_inspectorFrontendChannel->sendMessageToFrontend(jsonMessage->toJSONString()); } """) callback_method = ( """InspectorBackendDispatcher::$agentName::$callbackName::$callbackName(PassRefPtr<InspectorBackendDispatcherImpl> backendImpl, int id) : CallbackBase(backendImpl, id) {} void InspectorBackendDispatcher::$agentName::$callbackName::sendSuccess($parameters) { RefPtr<InspectorObject> jsonMessage = InspectorObject::create(); $code sendIfActive(jsonMessage, ErrorString()); } """) frontend_h = ( """#ifndef InspectorFrontend_h #define InspectorFrontend_h #include "InspectorTypeBuilder.h" #include "InspectorValues.h" #include <wtf/PassRefPtr.h> #include <wtf/text/WTFString.h> namespace WebCore { class InspectorFrontendChannel; // Both InspectorObject and InspectorArray may or may not be declared at this point as defined by ENABLED_INSPECTOR. // Double-check we have them at least as forward declaration. class InspectorArray; class InspectorObject; typedef String ErrorString; #if ENABLE(INSPECTOR) class InspectorFrontend { public: InspectorFrontend(InspectorFrontendChannel*); $domainClassList private: ${fieldDeclarations}}; #endif // ENABLE(INSPECTOR) } // namespace WebCore #endif // !defined(InspectorFrontend_h) """) backend_h = ( """#ifndef InspectorBackendDispatcher_h #define InspectorBackendDispatcher_h #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> #include <wtf/text/WTFString.h> #include "InspectorTypeBuilder.h" namespace WebCore { class InspectorAgent; class InspectorObject; class InspectorArray; class InspectorFrontendChannel; typedef String ErrorString; class InspectorBackendDispatcherImpl; class InspectorBackendDispatcher: public RefCounted<InspectorBackendDispatcher> { public: static PassRefPtr<InspectorBackendDispatcher> create(InspectorFrontendChannel* inspectorFrontendChannel); virtual ~InspectorBackendDispatcher() { } class CallbackBase: public RefCounted<CallbackBase> { public: CallbackBase(PassRefPtr<InspectorBackendDispatcherImpl> backendImpl, int id); virtual ~CallbackBase(); void sendFailure(const ErrorString&); bool isActive(); protected: void sendIfActive(PassRefPtr<InspectorObject> partialMessage, const ErrorString& invocationError); private: void disable() { m_alreadySent = true; } RefPtr<InspectorBackendDispatcherImpl> m_backendImpl; int m_id; bool m_alreadySent; friend class InspectorBackendDispatcherImpl; }; $agentInterfaces $virtualSetters virtual void clearFrontend() = 0; enum CommonErrorCode { ParseError = 0, InvalidRequest, MethodNotFound, InvalidParams, InternalError, ServerError, LastEntry, }; void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage) const; virtual void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage, PassRefPtr<InspectorArray> data) const = 0; virtual void dispatch(const String& message) = 0; static bool getCommandName(const String& message, String* result); enum MethodNames { $methodNamesEnumContent kMethodNamesEnumSize }; static const char* commandNames[]; }; } // namespace WebCore #endif // !defined(InspectorBackendDispatcher_h) """) backend_cpp = ( """ #include "config.h" #if ENABLE(INSPECTOR) #include "InspectorBackendDispatcher.h" #include <wtf/text/WTFString.h> #include <wtf/text/CString.h> #include "InspectorAgent.h" #include "InspectorValues.h" #include "InspectorFrontendChannel.h" #include <wtf/text/WTFString.h> namespace WebCore { const char* InspectorBackendDispatcher::commandNames[] = { $methodNameDeclarations }; class InspectorBackendDispatcherImpl : public InspectorBackendDispatcher { public: InspectorBackendDispatcherImpl(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) $constructorInit { } virtual void clearFrontend() { m_inspectorFrontendChannel = 0; } virtual void dispatch(const String& message); virtual void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage, PassRefPtr<InspectorArray> data) const; using InspectorBackendDispatcher::reportProtocolError; void sendResponse(long callId, PassRefPtr<InspectorObject> result, const ErrorString& invocationError); bool isActive() { return m_inspectorFrontendChannel; } $setters private: $methodDeclarations InspectorFrontendChannel* m_inspectorFrontendChannel; $fieldDeclarations template<typename R, typename V, typename V0> static R getPropertyValueImpl(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors, V0 initial_value, bool (*as_method)(InspectorValue*, V*), const char* type_name); static int getInt(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors); static double getDouble(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors); static String getString(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors); static bool getBoolean(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors); static PassRefPtr<InspectorObject> getObject(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors); static PassRefPtr<InspectorArray> getArray(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors); void sendResponse(long callId, PassRefPtr<InspectorObject> result, const char* commandName, PassRefPtr<InspectorArray> protocolErrors, ErrorString invocationError); }; $methods PassRefPtr<InspectorBackendDispatcher> InspectorBackendDispatcher::create(InspectorFrontendChannel* inspectorFrontendChannel) { return adoptRef(new InspectorBackendDispatcherImpl(inspectorFrontendChannel)); } void InspectorBackendDispatcherImpl::dispatch(const String& message) { RefPtr<InspectorBackendDispatcher> protect = this; typedef void (InspectorBackendDispatcherImpl::*CallHandler)(long callId, InspectorObject* messageObject); typedef HashMap<String, CallHandler> DispatchMap; DEFINE_STATIC_LOCAL(DispatchMap, dispatchMap, ); long callId = 0; if (dispatchMap.isEmpty()) { static CallHandler handlers[] = { $messageHandlers }; size_t length = WTF_ARRAY_LENGTH(commandNames); for (size_t i = 0; i < length; ++i) dispatchMap.add(commandNames[i], handlers[i]); } RefPtr<InspectorValue> parsedMessage = InspectorValue::parseJSON(message); if (!parsedMessage) { reportProtocolError(0, ParseError, "Message must be in JSON format"); return; } RefPtr<InspectorObject> messageObject = parsedMessage->asObject(); if (!messageObject) { reportProtocolError(0, InvalidRequest, "Message must be a JSONified object"); return; } RefPtr<InspectorValue> callIdValue = messageObject->get("id"); if (!callIdValue) { reportProtocolError(0, InvalidRequest, "'id' property was not found"); return; } if (!callIdValue->asNumber(&callId)) { reportProtocolError(0, InvalidRequest, "The type of 'id' property must be number"); return; } RefPtr<InspectorValue> methodValue = messageObject->get("method"); if (!methodValue) { reportProtocolError(&callId, InvalidRequest, "'method' property wasn't found"); return; } String method; if (!methodValue->asString(&method)) { reportProtocolError(&callId, InvalidRequest, "The type of 'method' property must be string"); return; } HashMap<String, CallHandler>::iterator it = dispatchMap.find(method); if (it == dispatchMap.end()) { reportProtocolError(&callId, MethodNotFound, "'" + method + "' wasn't found"); return; } ((*this).*it->value)(callId, messageObject.get()); } void InspectorBackendDispatcherImpl::sendResponse(long callId, PassRefPtr<InspectorObject> result, const char* commandName, PassRefPtr<InspectorArray> protocolErrors, ErrorString invocationError) { if (protocolErrors->length()) { String errorMessage = String::format("Some arguments of method '%s' can't be processed", commandName); reportProtocolError(&callId, InvalidParams, errorMessage, protocolErrors); return; } sendResponse(callId, result, invocationError); } void InspectorBackendDispatcherImpl::sendResponse(long callId, PassRefPtr<InspectorObject> result, const ErrorString& invocationError) { if (invocationError.length()) { reportProtocolError(&callId, ServerError, invocationError); return; } RefPtr<InspectorObject> responseMessage = InspectorObject::create(); responseMessage->setObject("result", result); responseMessage->setNumber("id", callId); if (m_inspectorFrontendChannel) m_inspectorFrontendChannel->sendMessageToFrontend(responseMessage->toJSONString()); } void InspectorBackendDispatcher::reportProtocolError(const long* const callId, CommonErrorCode code, const String& errorMessage) const { reportProtocolError(callId, code, errorMessage, 0); } void InspectorBackendDispatcherImpl::reportProtocolError(const long* const callId, CommonErrorCode code, const String& errorMessage, PassRefPtr<InspectorArray> data) const { DEFINE_STATIC_LOCAL(Vector<int>,s_commonErrors,); if (!s_commonErrors.size()) { s_commonErrors.insert(ParseError, -32700); s_commonErrors.insert(InvalidRequest, -32600); s_commonErrors.insert(MethodNotFound, -32601); s_commonErrors.insert(InvalidParams, -32602); s_commonErrors.insert(InternalError, -32603); s_commonErrors.insert(ServerError, -32000); } ASSERT(code >=0); ASSERT((unsigned)code < s_commonErrors.size()); ASSERT(s_commonErrors[code]); RefPtr<InspectorObject> error = InspectorObject::create(); error->setNumber("code", s_commonErrors[code]); error->setString("message", errorMessage); ASSERT(error); if (data) error->setArray("data", data); RefPtr<InspectorObject> message = InspectorObject::create(); message->setObject("error", error); if (callId) message->setNumber("id", *callId); else message->setValue("id", InspectorValue::null()); if (m_inspectorFrontendChannel) m_inspectorFrontendChannel->sendMessageToFrontend(message->toJSONString()); } template<typename R, typename V, typename V0> R InspectorBackendDispatcherImpl::getPropertyValueImpl(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors, V0 initial_value, bool (*as_method)(InspectorValue*, V*), const char* type_name) { ASSERT(protocolErrors); if (valueFound) *valueFound = false; V value = initial_value; if (!object) { if (!valueFound) { // Required parameter in missing params container. protocolErrors->pushString(String::format("'params' object must contain required parameter '%s' with type '%s'.", name.utf8().data(), type_name)); } return value; } InspectorObject::const_iterator end = object->end(); InspectorObject::const_iterator valueIterator = object->find(name); if (valueIterator == end) { if (!valueFound) protocolErrors->pushString(String::format("Parameter '%s' with type '%s' was not found.", name.utf8().data(), type_name)); return value; } if (!as_method(valueIterator->value.get(), &value)) protocolErrors->pushString(String::format("Parameter '%s' has wrong type. It must be '%s'.", name.utf8().data(), type_name)); else if (valueFound) *valueFound = true; return value; } struct AsMethodBridges { static bool asInt(InspectorValue* value, int* output) { return value->asNumber(output); } static bool asDouble(InspectorValue* value, double* output) { return value->asNumber(output); } static bool asString(InspectorValue* value, String* output) { return value->asString(output); } static bool asBoolean(InspectorValue* value, bool* output) { return value->asBoolean(output); } static bool asObject(InspectorValue* value, RefPtr<InspectorObject>* output) { return value->asObject(output); } static bool asArray(InspectorValue* value, RefPtr<InspectorArray>* output) { return value->asArray(output); } }; int InspectorBackendDispatcherImpl::getInt(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) { return getPropertyValueImpl<int, int, int>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asInt, "Number"); } double InspectorBackendDispatcherImpl::getDouble(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) { return getPropertyValueImpl<double, double, double>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asDouble, "Number"); } String InspectorBackendDispatcherImpl::getString(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) { return getPropertyValueImpl<String, String, String>(object, name, valueFound, protocolErrors, "", AsMethodBridges::asString, "String"); } bool InspectorBackendDispatcherImpl::getBoolean(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) { return getPropertyValueImpl<bool, bool, bool>(object, name, valueFound, protocolErrors, false, AsMethodBridges::asBoolean, "Boolean"); } PassRefPtr<InspectorObject> InspectorBackendDispatcherImpl::getObject(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) { return getPropertyValueImpl<PassRefPtr<InspectorObject>, RefPtr<InspectorObject>, InspectorObject*>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asObject, "Object"); } PassRefPtr<InspectorArray> InspectorBackendDispatcherImpl::getArray(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors) { return getPropertyValueImpl<PassRefPtr<InspectorArray>, RefPtr<InspectorArray>, InspectorArray*>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asArray, "Array"); } bool InspectorBackendDispatcher::getCommandName(const String& message, String* result) { RefPtr<InspectorValue> value = InspectorValue::parseJSON(message); if (!value) return false; RefPtr<InspectorObject> object = value->asObject(); if (!object) return false; if (!object->getString("method", result)) return false; return true; } InspectorBackendDispatcher::CallbackBase::CallbackBase(PassRefPtr<InspectorBackendDispatcherImpl> backendImpl, int id) : m_backendImpl(backendImpl), m_id(id), m_alreadySent(false) {} InspectorBackendDispatcher::CallbackBase::~CallbackBase() {} void InspectorBackendDispatcher::CallbackBase::sendFailure(const ErrorString& error) { ASSERT(error.length()); sendIfActive(0, error); } bool InspectorBackendDispatcher::CallbackBase::isActive() { return !m_alreadySent && m_backendImpl->isActive(); } void InspectorBackendDispatcher::CallbackBase::sendIfActive(PassRefPtr<InspectorObject> partialMessage, const ErrorString& invocationError) { if (m_alreadySent) return; m_backendImpl->sendResponse(m_id, partialMessage, invocationError); m_alreadySent = true; } COMPILE_ASSERT(static_cast<int>(InspectorBackendDispatcher::kMethodNamesEnumSize) == WTF_ARRAY_LENGTH(InspectorBackendDispatcher::commandNames), command_name_array_problem); } // namespace WebCore #endif // ENABLE(INSPECTOR) """) frontend_cpp = ( """ #include "config.h" #if ENABLE(INSPECTOR) #include "InspectorFrontend.h" #include <wtf/text/WTFString.h> #include <wtf/text/CString.h> #include "InspectorFrontendChannel.h" #include "InspectorValues.h" #include <wtf/text/WTFString.h> namespace WebCore { InspectorFrontend::InspectorFrontend(InspectorFrontendChannel* inspectorFrontendChannel) : $constructorInit{ } $methods } // namespace WebCore #endif // ENABLE(INSPECTOR) """) typebuilder_h = ( """ #ifndef InspectorTypeBuilder_h #define InspectorTypeBuilder_h #if ENABLE(INSPECTOR) #include "InspectorValues.h" #include <wtf/Assertions.h> #include <wtf/PassRefPtr.h> namespace WebCore { namespace TypeBuilder { template<typename T> class OptOutput { public: OptOutput() : m_assigned(false) { } void operator=(T value) { m_value = value; m_assigned = true; } bool isAssigned() { return m_assigned; } T getValue() { ASSERT(isAssigned()); return m_value; } private: T m_value; bool m_assigned; WTF_MAKE_NONCOPYABLE(OptOutput); }; // A small transient wrapper around int type, that can be used as a funciton parameter type // cleverly disallowing C++ implicit casts from float or double. class ExactlyInt { public: template<typename T> ExactlyInt(T t) : m_value(cast_to_int<T>(t)) {} ExactlyInt() {} operator int() { return m_value; } private: int m_value; template<typename T> static int cast_to_int(T) { return T::default_case_cast_is_not_supported(); } }; template<> inline int ExactlyInt::cast_to_int<int>(int i) { return i; } template<> inline int ExactlyInt::cast_to_int<unsigned int>(unsigned int i) { return i; } class RuntimeCastHelper { public: #if $validatorIfdefName template<InspectorValue::Type TYPE> static void assertType(InspectorValue* value) { ASSERT(value->type() == TYPE); } static void assertAny(InspectorValue*); static void assertInt(InspectorValue* value); #endif }; // This class provides "Traits" type for the input type T. It is programmed using C++ template specialization // technique. By default it simply takes "ItemTraits" type from T, but it doesn't work with the base types. template<typename T> struct ArrayItemHelper { typedef typename T::ItemTraits Traits; }; template<typename T> class Array : public InspectorArrayBase { private: Array() { } InspectorArray* openAccessors() { COMPILE_ASSERT(sizeof(InspectorArray) == sizeof(Array<T>), cannot_cast); return static_cast<InspectorArray*>(static_cast<InspectorArrayBase*>(this)); } public: void addItem(PassRefPtr<T> value) { ArrayItemHelper<T>::Traits::pushRefPtr(this->openAccessors(), value); } void addItem(T value) { ArrayItemHelper<T>::Traits::pushRaw(this->openAccessors(), value); } static PassRefPtr<Array<T> > create() { return adoptRef(new Array<T>()); } static PassRefPtr<Array<T> > runtimeCast(PassRefPtr<InspectorValue> value) { RefPtr<InspectorArray> array; bool castRes = value->asArray(&array); ASSERT_UNUSED(castRes, castRes); #if $validatorIfdefName assertCorrectValue(array.get()); #endif // $validatorIfdefName COMPILE_ASSERT(sizeof(Array<T>) == sizeof(InspectorArray), type_cast_problem); return static_cast<Array<T>*>(static_cast<InspectorArrayBase*>(array.get())); } #if $validatorIfdefName static void assertCorrectValue(InspectorValue* value) { RefPtr<InspectorArray> array; bool castRes = value->asArray(&array); ASSERT_UNUSED(castRes, castRes); for (unsigned i = 0; i < array->length(); i++) ArrayItemHelper<T>::Traits::template assertCorrectValue<T>(array->get(i).get()); } #endif // $validatorIfdefName }; struct StructItemTraits { static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorValue> value) { array->pushValue(value); } #if $validatorIfdefName template<typename T> static void assertCorrectValue(InspectorValue* value) { T::assertCorrectValue(value); } #endif // $validatorIfdefName }; template<> struct ArrayItemHelper<String> { struct Traits { static void pushRaw(InspectorArray* array, const String& value) { array->pushString(value); } #if $validatorIfdefName template<typename T> static void assertCorrectValue(InspectorValue* value) { RuntimeCastHelper::assertType<InspectorValue::TypeString>(value); } #endif // $validatorIfdefName }; }; template<> struct ArrayItemHelper<int> { struct Traits { static void pushRaw(InspectorArray* array, int value) { array->pushInt(value); } #if $validatorIfdefName template<typename T> static void assertCorrectValue(InspectorValue* value) { RuntimeCastHelper::assertInt(value); } #endif // $validatorIfdefName }; }; template<> struct ArrayItemHelper<double> { struct Traits { static void pushRaw(InspectorArray* array, double value) { array->pushNumber(value); } #if $validatorIfdefName template<typename T> static void assertCorrectValue(InspectorValue* value) { RuntimeCastHelper::assertType<InspectorValue::TypeNumber>(value); } #endif // $validatorIfdefName }; }; template<> struct ArrayItemHelper<bool> { struct Traits { static void pushRaw(InspectorArray* array, bool value) { array->pushBoolean(value); } #if $validatorIfdefName template<typename T> static void assertCorrectValue(InspectorValue* value) { RuntimeCastHelper::assertType<InspectorValue::TypeBoolean>(value); } #endif // $validatorIfdefName }; }; template<> struct ArrayItemHelper<InspectorValue> { struct Traits { static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorValue> value) { array->pushValue(value); } #if $validatorIfdefName template<typename T> static void assertCorrectValue(InspectorValue* value) { RuntimeCastHelper::assertAny(value); } #endif // $validatorIfdefName }; }; template<> struct ArrayItemHelper<InspectorObject> { struct Traits { static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorValue> value) { array->pushValue(value); } #if $validatorIfdefName template<typename T> static void assertCorrectValue(InspectorValue* value) { RuntimeCastHelper::assertType<InspectorValue::TypeObject>(value); } #endif // $validatorIfdefName }; }; template<> struct ArrayItemHelper<InspectorArray> { struct Traits { static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorArray> value) { array->pushArray(value); } #if $validatorIfdefName template<typename T> static void assertCorrectValue(InspectorValue* value) { RuntimeCastHelper::assertType<InspectorValue::TypeArray>(value); } #endif // $validatorIfdefName }; }; template<typename T> struct ArrayItemHelper<TypeBuilder::Array<T> > { struct Traits { static void pushRefPtr(InspectorArray* array, PassRefPtr<TypeBuilder::Array<T> > value) { array->pushValue(value); } #if $validatorIfdefName template<typename S> static void assertCorrectValue(InspectorValue* value) { S::assertCorrectValue(value); } #endif // $validatorIfdefName }; }; ${forwards} String getEnumConstantValue(int code); ${typeBuilders} } // namespace TypeBuilder } // namespace WebCore #endif // ENABLE(INSPECTOR) #endif // !defined(InspectorTypeBuilder_h) """) typebuilder_cpp = ( """ #include "config.h" #if ENABLE(INSPECTOR) #include "InspectorTypeBuilder.h" #include <wtf/text/CString.h> namespace WebCore { namespace TypeBuilder { const char* const enum_constant_values[] = { $enumConstantValues}; String getEnumConstantValue(int code) { return enum_constant_values[code]; } } // namespace TypeBuilder $implCode #if $validatorIfdefName void TypeBuilder::RuntimeCastHelper::assertAny(InspectorValue*) { // No-op. } void TypeBuilder::RuntimeCastHelper::assertInt(InspectorValue* value) { double v; bool castRes = value->asNumber(&v); ASSERT_UNUSED(castRes, castRes); ASSERT(static_cast<double>(static_cast<int>(v)) == v); } $validatorCode #endif // $validatorIfdefName } // namespace WebCore #endif // ENABLE(INSPECTOR) """) backend_js = ( """ $domainInitializers """) param_container_access_code = """ RefPtr<InspectorObject> paramsContainer = requestMessageObject->getObject("params"); InspectorObject* paramsContainerPtr = paramsContainer.get(); InspectorArray* protocolErrorsPtr = protocolErrors.get(); """ class_binding_builder_part_1 = ( """ AllFieldsSet = %s }; template<int STATE> class Builder { private: RefPtr<InspectorObject> m_result; template<int STEP> Builder<STATE | STEP>& castState() { return *reinterpret_cast<Builder<STATE | STEP>*>(this); } Builder(PassRefPtr</*%s*/InspectorObject> ptr) { COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state); m_result = ptr; } friend class %s; public: """) class_binding_builder_part_2 = (""" Builder<STATE | %s>& set%s(%s value) { COMPILE_ASSERT(!(STATE & %s), property_%s_already_set); m_result->set%s("%s", %s); return castState<%s>(); } """) class_binding_builder_part_3 = (""" operator RefPtr<%s>& () { COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready); COMPILE_ASSERT(sizeof(%s) == sizeof(InspectorObject), cannot_cast); return *reinterpret_cast<RefPtr<%s>*>(&m_result); } PassRefPtr<%s> release() { return RefPtr<%s>(*this).release(); } }; """) class_binding_builder_part_4 = ( """ static Builder<NoFieldsSet> create() { return Builder<NoFieldsSet>(InspectorObject::create()); } """)
lgpl-3.0
fener06/pyload
module/plugins/accounts/HotfileCom.py
2
3111
# -*- coding: utf-8 -*- """ 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/>. @author: mkaay, JoKoT3 """ from module.plugins.Account import Account from time import strptime, mktime import hashlib class HotfileCom(Account): __name__ = "HotfileCom" __version__ = "0.2" __type__ = "account" __description__ = """hotfile.com account plugin""" __author_name__ = ("mkaay","JoKoT3") __author_mail__ = ("mkaay@mkaay.de","jokot3@gmail.com") def loadAccountInfo(self, user, req): resp = self.apiCall("getuserinfo", user=user) if resp.startswith("."): self.core.debug("HotfileCom API Error: %s" % resp) raise Exception info = {} for p in resp.split("&"): key, value = p.split("=") info[key] = value if info['is_premium'] == '1': info["premium_until"] = info["premium_until"].replace("T"," ") zone = info["premium_until"][19:] info["premium_until"] = info["premium_until"][:19] zone = int(zone[:3]) validuntil = int(mktime(strptime(info["premium_until"], "%Y-%m-%d %H:%M:%S"))) + (zone*3600) tmp = {"validuntil":validuntil, "trafficleft":-1, "premium":True} elif info['is_premium'] == '0': tmp = {"premium":False} return tmp def apiCall(self, method, post={}, user=None): if user: data = self.getAccountData(user) else: user, data = self.selectAccount() req = self.getAccountRequest(user) digest = req.load("http://api.hotfile.com/", post={"action":"getdigest"}) h = hashlib.md5() h.update(data["password"]) hp = h.hexdigest() h = hashlib.md5() h.update(hp) h.update(digest) pwhash = h.hexdigest() post.update({"action": method}) post.update({"username":user, "passwordmd5dig":pwhash, "digest":digest}) resp = req.load("http://api.hotfile.com/", post=post) req.close() return resp def login(self, user, data, req): cj = self.getAccountCookies(user) cj.setCookie("hotfile.com", "lang", "en") req.load("http://hotfile.com/", cookies=True) page = req.load("http://hotfile.com/login.php", post={"returnto": "/", "user": user, "pass": data["password"]}, cookies=True) if "Bad username/password" in page: self.wrongPassword()
gpl-3.0
pymedusa/Medusa
ext/boto/elasticache/__init__.py
22
1753
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # 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. # from boto.regioninfo import RegionInfo, get_regions from boto.regioninfo import connect def regions(): """ Get all available regions for the AWS ElastiCache service. :rtype: list :return: A list of :class:`boto.regioninfo.RegionInfo` """ from boto.elasticache.layer1 import ElastiCacheConnection return get_regions('elasticache', connection_cls=ElastiCacheConnection) def connect_to_region(region_name, **kw_params): from boto.elasticache.layer1 import ElastiCacheConnection return connect('elasticache', region_name, connection_cls=ElastiCacheConnection, **kw_params)
gpl-3.0
mvaled/sentry
src/sentry/api/endpoints/group_integration_details.py
1
11884
from __future__ import absolute_import from django.db import IntegrityError, transaction from rest_framework.response import Response from sentry import features from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.serializers.models.integration import IntegrationIssueConfigSerializer from sentry.integrations import IntegrationFeatures from sentry.integrations.exceptions import IntegrationError, IntegrationFormError from sentry.models import Activity, ExternalIssue, GroupLink, Integration from sentry.signals import integration_issue_created, integration_issue_linked MISSING_FEATURE_MESSAGE = "Your organization does not have access to this feature." class GroupIntegrationDetailsEndpoint(GroupEndpoint): def _has_issue_feature(self, organization, user): has_issue_basic = features.has( "organizations:integrations-issue-basic", organization, actor=user ) has_issue_sync = features.has( "organizations:integrations-issue-sync", organization, actor=user ) return has_issue_sync or has_issue_basic def create_issue_activity(self, request, group, installation, external_issue): issue_information = { "title": external_issue.title, "provider": installation.model.get_provider().name, "location": installation.get_issue_url(external_issue.key), "label": installation.get_issue_display_name(external_issue) or external_issue.key, } Activity.objects.create( project=group.project, group=group, type=Activity.CREATE_ISSUE, user=request.user, data=issue_information, ) def get(self, request, group, integration_id): if not self._has_issue_feature(group.organization, request.user): return Response({"detail": MISSING_FEATURE_MESSAGE}, status=400) # Keep link/create separate since create will likely require # many external API calls that aren't necessary if the user is # just linking action = request.GET.get("action") if action not in {"link", "create"}: return Response({"detail": "Action is required and should be either link or create"}) organization_id = group.project.organization_id try: integration = Integration.objects.get(id=integration_id, organizations=organization_id) except Integration.DoesNotExist: return Response(status=404) if not ( integration.has_feature(IntegrationFeatures.ISSUE_BASIC) or integration.has_feature(IntegrationFeatures.ISSUE_SYNC) ): return Response( {"detail": "This feature is not supported for this integration."}, status=400 ) try: return Response( serialize( integration, request.user, IntegrationIssueConfigSerializer(group, action, params=request.GET), organization_id=organization_id, ) ) except IntegrationError as exc: return Response({"detail": exc.message}, status=400) # was thinking put for link an existing issue, post for create new issue? def put(self, request, group, integration_id): if not self._has_issue_feature(group.organization, request.user): return Response({"detail": MISSING_FEATURE_MESSAGE}, status=400) external_issue_id = request.data.get("externalIssue") if not external_issue_id: return Response({"externalIssue": ["Issue ID is required"]}, status=400) organization_id = group.project.organization_id try: integration = Integration.objects.get(id=integration_id, organizations=organization_id) except Integration.DoesNotExist: return Response(status=404) if not ( integration.has_feature(IntegrationFeatures.ISSUE_BASIC) or integration.has_feature(IntegrationFeatures.ISSUE_SYNC) ): return Response( {"detail": "This feature is not supported for this integration."}, status=400 ) installation = integration.get_installation(organization_id) try: data = installation.get_issue(external_issue_id, data=request.data) except IntegrationFormError as exc: return Response(exc.field_errors, status=400) except IntegrationError as exc: return Response({"non_field_errors": [exc.message]}, status=400) defaults = { "title": data.get("title"), "description": data.get("description"), "metadata": data.get("metadata"), } external_issue_key = installation.make_external_key(data) external_issue, created = ExternalIssue.objects.get_or_create( organization_id=organization_id, integration_id=integration.id, key=external_issue_key, defaults=defaults, ) if created: integration_issue_linked.send_robust( integration=integration, organization=group.project.organization, user=request.user, sender=self.__class__, ) else: external_issue.update(**defaults) installation.store_issue_last_defaults(group.project_id, request.data) try: installation.after_link_issue(external_issue, data=request.data) except IntegrationFormError as exc: return Response(exc.field_errors, status=400) except IntegrationError as exc: return Response({"non_field_errors": [exc.message]}, status=400) try: with transaction.atomic(): GroupLink.objects.create( group_id=group.id, project_id=group.project_id, linked_type=GroupLink.LinkedType.issue, linked_id=external_issue.id, relationship=GroupLink.Relationship.references, ) except IntegrityError: return Response({"non_field_errors": ["That issue is already linked"]}, status=400) self.create_issue_activity(request, group, installation, external_issue) # TODO(jess): would be helpful to return serialized external issue # once we have description, title, etc url = data.get("url") or installation.get_issue_url(external_issue.key) context = { "id": external_issue.id, "key": external_issue.key, "url": url, "integrationId": external_issue.integration_id, "displayName": installation.get_issue_display_name(external_issue), } return Response(context, status=201) def post(self, request, group, integration_id): if not self._has_issue_feature(group.organization, request.user): return Response({"detail": MISSING_FEATURE_MESSAGE}, status=400) organization_id = group.project.organization_id try: integration = Integration.objects.get(id=integration_id, organizations=organization_id) except Integration.DoesNotExist: return Response(status=404) if not ( integration.has_feature(IntegrationFeatures.ISSUE_BASIC) or integration.has_feature(IntegrationFeatures.ISSUE_SYNC) ): return Response( {"detail": "This feature is not supported for this integration."}, status=400 ) installation = integration.get_installation(organization_id) try: data = installation.create_issue(request.data) except IntegrationFormError as exc: return Response(exc.field_errors, status=400) except IntegrationError as exc: return Response({"non_field_errors": [exc.message]}, status=400) external_issue_key = installation.make_external_key(data) external_issue, created = ExternalIssue.objects.get_or_create( organization_id=organization_id, integration_id=integration.id, key=external_issue_key, defaults={ "title": data.get("title"), "description": data.get("description"), "metadata": data.get("metadata"), }, ) try: with transaction.atomic(): GroupLink.objects.create( group_id=group.id, project_id=group.project_id, linked_type=GroupLink.LinkedType.issue, linked_id=external_issue.id, relationship=GroupLink.Relationship.references, ) except IntegrityError: return Response({"detail": "That issue is already linked"}, status=400) if created: integration_issue_created.send_robust( integration=integration, organization=group.project.organization, user=request.user, sender=self.__class__, ) installation.store_issue_last_defaults(group.project_id, request.data) self.create_issue_activity(request, group, installation, external_issue) # TODO(jess): return serialized issue url = data.get("url") or installation.get_issue_url(external_issue.key) context = { "id": external_issue.id, "key": external_issue.key, "url": url, "integrationId": external_issue.integration_id, "displayName": installation.get_issue_display_name(external_issue), } return Response(context, status=201) def delete(self, request, group, integration_id): if not self._has_issue_feature(group.organization, request.user): return Response({"detail": MISSING_FEATURE_MESSAGE}, status=400) # note here externalIssue refers to `ExternalIssue.id` wheras above # it refers to the id from the provider external_issue_id = request.GET.get("externalIssue") if not external_issue_id: return Response({"detail": "External ID required"}, status=400) organization_id = group.project.organization_id try: integration = Integration.objects.get(id=integration_id, organizations=organization_id) except Integration.DoesNotExist: return Response(status=404) if not ( integration.has_feature(IntegrationFeatures.ISSUE_BASIC) or integration.has_feature(IntegrationFeatures.ISSUE_SYNC) ): return Response( {"detail": "This feature is not supported for this integration."}, status=400 ) try: external_issue = ExternalIssue.objects.get( organization_id=organization_id, integration_id=integration.id, id=external_issue_id ) except ExternalIssue.DoesNotExist: return Response(status=404) with transaction.atomic(): GroupLink.objects.filter( group_id=group.id, project_id=group.project_id, linked_type=GroupLink.LinkedType.issue, linked_id=external_issue_id, relationship=GroupLink.Relationship.references, ).delete() # check if other groups reference this external issue # and delete if not if not GroupLink.objects.filter( linked_type=GroupLink.LinkedType.issue, linked_id=external_issue_id ).exists(): external_issue.delete() return Response(status=204)
bsd-3-clause
sophiavanvalkenburg/coala
tests/misc/DictUtilitiesTest.py
28
2055
import unittest from collections import OrderedDict from coalib.misc.DictUtilities import inverse_dicts, update_ordered_dict_key class DictUtilitiesTest(unittest.TestCase): def test_inverse_dicts(self): self.dict1 = {1: [1, 2, 3], 2: [3, 4, 5]} self.dict2 = {2: [1], 3: [2], 4: [3, 4]} self.dict3 = {1: 2, 3: 4, 4: 4, 5: 4} self.dict4 = {2: 3, 4: 4} result = inverse_dicts(self.dict3) self.assertEqual({2: [1], 4: [3, 4, 5]}, result) result = inverse_dicts(self.dict1) self.assertEqual({1: [1], 2: [1], 3: [1, 2], 4: [2], 5: [2]}, result) result = inverse_dicts(self.dict3, self.dict4) self.assertEqual({2: [1], 3: [2], 4: [3, 4, 5, 4]}, result) result = inverse_dicts(self.dict1, self.dict2) self.assertEqual({1: [1, 2], 2: [1, 3], 3: [1, 2, 4], 4: [2, 4], 5: [2]}, result) def test_update_ordered_dict_key(self): self.ordered_dict = OrderedDict() self.ordered_dict["default"] = "Some stuff" self.ordered_dict["pythoncheck"] = "Somemore stuff" self.ordered_dict = update_ordered_dict_key(self.ordered_dict, "default", "coala") self.assertTrue("coala" in self.ordered_dict) self.assertEqual("OrderedDict([('coala', 'Some stuff'), " "('pythoncheck', 'Somemore stuff')])", self.ordered_dict.__str__()) self.ordered_dict = update_ordered_dict_key(self.ordered_dict, "coala", "section") self.assertTrue("section" in self.ordered_dict) self.assertEqual("OrderedDict([('section', 'Some stuff'), " "('pythoncheck', 'Somemore stuff')])", self.ordered_dict.__str__())
agpl-3.0
disqus/django-old
django/middleware/csrf.py
5
8962
""" Cross Site Request Forgery Middleware. This module provides a middleware that implements protection against request forgeries from other sites. """ import hashlib import re import random from django.conf import settings from django.core.urlresolvers import get_callable from django.utils.cache import patch_vary_headers from django.utils.http import same_origin from django.utils.log import getLogger from django.utils.crypto import constant_time_compare logger = getLogger('django.request') # Use the system (hardware-based) random number generator if it exists. if hasattr(random, 'SystemRandom'): randrange = random.SystemRandom().randrange else: randrange = random.randrange _MAX_CSRF_KEY = 18446744073709551616L # 2 << 63 REASON_NO_REFERER = "Referer checking failed - no Referer." REASON_BAD_REFERER = "Referer checking failed - %s does not match %s." REASON_NO_CSRF_COOKIE = "CSRF cookie not set." REASON_BAD_TOKEN = "CSRF token missing or incorrect." def _get_failure_view(): """ Returns the view to be used for CSRF rejections """ return get_callable(settings.CSRF_FAILURE_VIEW) def _get_new_csrf_key(): return hashlib.md5("%s%s" % (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest() def get_token(request): """ Returns the the CSRF token required for a POST form. The token is an alphanumeric value. A side effect of calling this function is to make the the csrf_protect decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie' header to the outgoing response. For this reason, you may need to use this function lazily, as is done by the csrf context processor. """ request.META["CSRF_COOKIE_USED"] = True return request.META.get("CSRF_COOKIE", None) def _sanitize_token(token): # Allow only alphanum, and ensure we return a 'str' for the sake of the post # processing middleware. token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore'))) if token == "": # In case the cookie has been truncated to nothing at some point. return _get_new_csrf_key() else: return token class CsrfViewMiddleware(object): """ Middleware that requires a present and correct csrfmiddlewaretoken for POST requests that have a CSRF cookie, and sets an outgoing CSRF cookie. This middleware should be used in conjunction with the csrf_token template tag. """ # The _accept and _reject methods currently only exist for the sake of the # requires_csrf_token decorator. def _accept(self, request): # Avoid checking the request twice by adding a custom attribute to # request. This will be relevant when both decorator and middleware # are used. request.csrf_processing_done = True return None def _reject(self, request, reason): return _get_failure_view()(request, reason=reason) def process_view(self, request, callback, callback_args, callback_kwargs): if getattr(request, 'csrf_processing_done', False): return None try: csrf_token = _sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME]) # Use same token next time request.META['CSRF_COOKIE'] = csrf_token except KeyError: csrf_token = None # Generate token and store it in the request, so it's available to the view. request.META["CSRF_COOKIE"] = _get_new_csrf_key() # Wait until request.META["CSRF_COOKIE"] has been manipulated before # bailing out, so that get_token still works if getattr(callback, 'csrf_exempt', False): return None # Assume that anything not defined as 'safe' by RC2616 needs protection. if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): if getattr(request, '_dont_enforce_csrf_checks', False): # Mechanism to turn off CSRF checks for test suite. It comes after # the creation of CSRF cookies, so that everything else continues to # work exactly the same (e.g. cookies are sent etc), but before the # any branches that call reject() return self._accept(request) if request.is_secure(): # Suppose user visits http://example.com/ # An active network attacker,(man-in-the-middle, MITM) sends a # POST form which targets https://example.com/detonate-bomb/ and # submits it via javascript. # # The attacker will need to provide a CSRF cookie and token, but # that is no problem for a MITM and the session independent # nonce we are using. So the MITM can circumvent the CSRF # protection. This is true for any HTTP connection, but anyone # using HTTPS expects better! For this reason, for # https://example.com/ we need additional protection that treats # http://example.com/ as completely untrusted. Under HTTPS, # Barth et al. found that the Referer header is missing for # same-domain requests in only about 0.2% of cases or less, so # we can use strict Referer checking. referer = request.META.get('HTTP_REFERER') if referer is None: logger.warning('Forbidden (%s): %s' % (REASON_NO_REFERER, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, REASON_NO_REFERER) # Note that request.get_host() includes the port good_referer = 'https://%s/' % request.get_host() if not same_origin(referer, good_referer): reason = REASON_BAD_REFERER % (referer, good_referer) logger.warning('Forbidden (%s): %s' % (reason, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, reason) if csrf_token is None: # No CSRF cookie. For POST requests, we insist on a CSRF cookie, # and in this way we can avoid all CSRF attacks, including login # CSRF. logger.warning('Forbidden (%s): %s' % (REASON_NO_CSRF_COOKIE, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, REASON_NO_CSRF_COOKIE) # check non-cookie token for match request_csrf_token = "" if request.method == "POST": request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') if request_csrf_token == "": # Fall back to X-CSRFToken, to make things easier for AJAX, # and possible for PUT/DELETE request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') if not constant_time_compare(request_csrf_token, csrf_token): logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, REASON_BAD_TOKEN) return self._accept(request) def process_response(self, request, response): if getattr(response, 'csrf_processing_done', False): return response # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was # never called, probaby because a request middleware returned a response # (for example, contrib.auth redirecting to a login page). if request.META.get("CSRF_COOKIE") is None: return response if not request.META.get("CSRF_COOKIE_USED", False): return response # Set the CSRF cookie even if it's already set, so we renew the expiry timer. response.set_cookie(settings.CSRF_COOKIE_NAME, request.META["CSRF_COOKIE"], max_age = 60 * 60 * 24 * 7 * 52, domain=settings.CSRF_COOKIE_DOMAIN, path=settings.CSRF_COOKIE_PATH, secure=settings.CSRF_COOKIE_SECURE ) # Content varies with the CSRF cookie, so set the Vary header. patch_vary_headers(response, ('Cookie',)) response.csrf_processing_done = True return response
bsd-3-clause
madmatah/lapurge
lapurge/types.py
1
3448
# Copyright (c) 2013 Matthieu Huguet # 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, 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: # 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 MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS 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 IN THE # SOFTWARE. from collections import OrderedDict from datetime import datetime import os import sys class Backup: """ A Backup represents a file in the backup directory """ def __init__(self, mtime, filepath): self.mtime = mtime self.filepath = filepath def remove(self, simulate=True): if (simulate): print ("REMOVE " + str(self)) return True else: try: os.remove(self.filepath) return True except OSError as info: sys.stderr.write("ERROR : %s\n" % info) return False def __key(self): return (self.mtime, self.filepath) def __eq__(x, y): return x.__key() == y.__key() def __hash__(self): return hash(self.__key()) def __str__(self): return self.filepath + " (" + str(self.mtime.date().isoformat()) + ")" @classmethod def from_path(cls, filepath): stats = os.lstat(filepath) mtime = datetime.utcfromtimestamp(stats.st_mtime) return cls(mtime, filepath) class BackupCollection: """ Collection of Backup elements grouped by date """ def __init__(self, backups={}): self.backups = dict(backups) def add(self, backup): """ add a backup to the collection """ date = backup.mtime.date() if date not in self.backups: s = set() s.add(backup) self.backups[date] = s else: self.backups[date].add(backup) def days(self, recent_first=True): """ returns the list of days having backups, ordered by modification date (most recent backups first by default) """ return sorted(self.backups.keys(), reverse=recent_first) def except_days(self, days): """ returns a copy of the BackupCollection without the specified days """ filtered_backups = {day: self.backups[day] for day in self.days() if day not in days} return BackupCollection(filtered_backups) def remove_all(self, simulate=True): """ remove every backups of this collection """ errors = False for days in self.days(recent_first=False): for backup in self.backups[days]: if not backup.remove(simulate): errors = True return not errors
mit
jmwright/cadquery-x
gui/libs/pyqode/qt/QtCore.py
2
1137
""" Provides QtCore classes and functions. """ import os from pyqode.qt import QT_API from pyqode.qt import PYQT5_API from pyqode.qt import PYQT4_API from pyqode.qt import PYSIDE_API if os.environ[QT_API] == PYQT5_API: from PyQt5.QtCore import * # compatibility with pyside from PyQt5.QtCore import pyqtSignal as Signal from PyQt5.QtCore import pyqtSlot as Slot from PyQt5.QtCore import pyqtProperty as Property # use a common __version__ from PyQt5.QtCore import QT_VERSION_STR as __version__ elif os.environ[QT_API] == PYQT4_API: from PyQt4.QtCore import * # compatibility with pyside from PyQt4.QtCore import pyqtSignal as Signal from PyQt4.QtCore import pyqtSlot as Slot from PyQt4.QtCore import pyqtProperty as Property from PyQt4.QtGui import QSortFilterProxyModel # use a common __version__ from PyQt4.QtCore import QT_VERSION_STR as __version__ elif os.environ[QT_API] == PYSIDE_API: from PySide.QtCore import * from PySide.QtGui import QSortFilterProxyModel # use a common __version__ import PySide.QtCore __version__ = PySide.QtCore.__version__
lgpl-3.0
Krossom/python-for-android
python-modules/twisted/twisted/lore/docbook.py
53
2418
# Copyright (c) 2001-2009 Twisted Matrix Laboratories. # See LICENSE for details. """ DocBook output support for Lore. """ import os, cgi from xml.dom import minidom as dom from twisted.lore import latex class DocbookSpitter(latex.BaseLatexSpitter): currentLevel = 1 def writeNodeData(self, node): self.writer(node.data) def visitNode_body(self, node): self.visitNodeDefault(node) self.writer('</section>'*self.currentLevel) def visitNodeHeader(self, node): level = int(node.tagName[1]) difference, self.currentLevel = level-self.currentLevel, level self.writer('<section>'*difference+'</section>'*-difference) if difference<=0: self.writer('</section>\n<section>') self.writer('<title>') self.visitNodeDefault(node) def visitNode_a_listing(self, node): fileName = os.path.join(self.currDir, node.getAttribute('href')) self.writer('<programlisting>\n') self.writer(cgi.escape(open(fileName).read())) self.writer('</programlisting>\n') def visitNode_a_href(self, node): self.visitNodeDefault(node) def visitNode_a_name(self, node): self.visitNodeDefault(node) def visitNode_li(self, node): for child in node.childNodes: if getattr(child, 'tagName', None) != 'p': new = dom.Element('p') new.childNodes = [child] node.replaceChild(new, child) self.visitNodeDefault(node) visitNode_h2 = visitNode_h3 = visitNode_h4 = visitNodeHeader end_h2 = end_h3 = end_h4 = '</title><para />' start_title, end_title = '<section><title>', '</title><para />' start_p, end_p = '<para>', '</para>' start_strong, end_strong = start_em, end_em = '<emphasis>', '</emphasis>' start_span_footnote, end_span_footnote = '<footnote><para>', '</para></footnote>' start_q = end_q = '"' start_pre, end_pre = '<programlisting>', '</programlisting>' start_div_note, end_div_note = '<note>', '</note>' start_li, end_li = '<listitem>', '</listitem>' start_ul, end_ul = '<itemizedlist>', '</itemizedlist>' start_ol, end_ol = '<orderedlist>', '</orderedlist>' start_dl, end_dl = '<variablelist>', '</variablelist>' start_dt, end_dt = '<varlistentry><term>', '</term>' start_dd, end_dd = '<listitem><para>', '</para></listitem></varlistentry>'
apache-2.0
ftkghost/SuperSaver
supersaver/core/decorator.py
1
1206
from functools import wraps from .exception import UnauthorizedUser, UnsupportedHttpMethod ß def login_required(func): @wraps(func) def check_user_login(request, *args, **kwargs): if not request.user.is_authenticated(): raise UnauthorizedUser() return func(request, *args, **kwargs) return check_user_login def allow_http_methods(method_list): """ A clone of Django's require_http_methods decoration. We want a customized Exception. https://github.com/django/django/blob/master/django/views/decorators/http.py#L19 Note: method list should be upper case. """ def decorator(func): @wraps(func) def inner(request, *args, **kwargs): if request.method not in method_list: raise UnsupportedHttpMethod(request.method) return func(request, *args, **kwargs) return inner return decorator def redirect_after_signin(func): @wraps(func) def inner(request, *args, **kwargs): resp = func(request, *args, **kwargs) if not request.user.is_authenticated(): resp.set_cookie('next', request.get_full_path()) return resp return inner
bsd-2-clause
wjchen84/baxter_examples
scripts/joint_position_waypoints.py
6
6819
#!/usr/bin/env python # Copyright (c) 2013-2015, Rethink Robotics # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the Rethink Robotics 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. """ Baxter RSDK Joint Position Waypoints Example """ import argparse import sys import rospy import baxter_interface class Waypoints(object): def __init__(self, limb, speed, accuracy): # Create baxter_interface limb instance self._arm = limb self._limb = baxter_interface.Limb(self._arm) # Parameters which will describe joint position moves self._speed = speed self._accuracy = accuracy # Recorded waypoints self._waypoints = list() # Recording state self._is_recording = False # Verify robot is enabled print("Getting robot state... ") self._rs = baxter_interface.RobotEnable() self._init_state = self._rs.state().enabled print("Enabling robot... ") self._rs.enable() # Create Navigator I/O self._navigator_io = baxter_interface.Navigator(self._arm) def _record_waypoint(self, value): """ Stores joint position waypoints Navigator 'OK/Wheel' button callback """ if value: print("Waypoint Recorded") self._waypoints.append(self._limb.joint_angles()) def _stop_recording(self, value): """ Sets is_recording to false Navigator 'Rethink' button callback """ # On navigator Rethink button press, stop recording if value: self._is_recording = False def record(self): """ Records joint position waypoints upon each Navigator 'OK/Wheel' button press. """ rospy.loginfo("Waypoint Recording Started") print("Press Navigator 'OK/Wheel' button to record a new joint " "joint position waypoint.") print("Press Navigator 'Rethink' button when finished recording " "waypoints to begin playback") # Connect Navigator I/O signals # Navigator scroll wheel button press self._navigator_io.button0_changed.connect(self._record_waypoint) # Navigator Rethink button press self._navigator_io.button2_changed.connect(self._stop_recording) # Set recording flag self._is_recording = True # Loop until waypoints are done being recorded ('Rethink' Button Press) while self._is_recording and not rospy.is_shutdown(): rospy.sleep(1.0) # We are now done with the navigator I/O signals, disconnecting them self._navigator_io.button0_changed.disconnect(self._record_waypoint) self._navigator_io.button2_changed.disconnect(self._stop_recording) def playback(self): """ Loops playback of recorded joint position waypoints until program is exited """ rospy.sleep(1.0) rospy.loginfo("Waypoint Playback Started") print(" Press Ctrl-C to stop...") # Set joint position speed ratio for execution self._limb.set_joint_position_speed(self._speed) # Loop until program is exited loop = 0 while not rospy.is_shutdown(): loop += 1 print("Waypoint playback loop #%d " % (loop,)) for waypoint in self._waypoints: if rospy.is_shutdown(): break self._limb.move_to_joint_positions(waypoint, timeout=20.0, threshold=self._accuracy) # Sleep for a few seconds between playback loops rospy.sleep(3.0) # Set joint position speed back to default self._limb.set_joint_position_speed(0.3) def clean_shutdown(self): print("\nExiting example...") if not self._init_state: print("Disabling robot...") self._rs.disable() return True def main(): """RSDK Joint Position Waypoints Example Records joint positions each time the navigator 'OK/wheel' button is pressed. Upon pressing the navigator 'Rethink' button, the recorded joint positions will begin playing back in a loop. """ arg_fmt = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(formatter_class=arg_fmt, description=main.__doc__) required = parser.add_argument_group('required arguments') required.add_argument( '-l', '--limb', required=True, choices=['left', 'right'], help='limb to record/playback waypoints' ) parser.add_argument( '-s', '--speed', default=0.3, type=float, help='joint position motion speed ratio [0.0-1.0] (default:= 0.3)' ) parser.add_argument( '-a', '--accuracy', default=baxter_interface.settings.JOINT_ANGLE_TOLERANCE, type=float, help='joint position accuracy (rad) at which waypoints must achieve' ) args = parser.parse_args(rospy.myargv()[1:]) print("Initializing node... ") rospy.init_node("rsdk_joint_position_waypoints_%s" % (args.limb,)) waypoints = Waypoints(args.limb, args.speed, args.accuracy) # Register clean shutdown rospy.on_shutdown(waypoints.clean_shutdown) # Begin example program waypoints.record() waypoints.playback() if __name__ == '__main__': main()
bsd-3-clause
cogeorg/black_rhino
examples/firesales_SA/networkx/algorithms/centrality/tests/test_load_centrality.py
72
8408
#!/usr/bin/env python from nose.tools import * import networkx as nx class TestLoadCentrality: def setUp(self): G=nx.Graph(); G.add_edge(0,1,weight=3) G.add_edge(0,2,weight=2) G.add_edge(0,3,weight=6) G.add_edge(0,4,weight=4) G.add_edge(1,3,weight=5) G.add_edge(1,5,weight=5) G.add_edge(2,4,weight=1) G.add_edge(3,4,weight=2) G.add_edge(3,5,weight=1) G.add_edge(4,5,weight=4) self.G=G self.exact_weighted={0: 4.0, 1: 0.0, 2: 8.0, 3: 6.0, 4: 8.0, 5: 0.0} self.K = nx.krackhardt_kite_graph() self.P3 = nx.path_graph(3) self.P4 = nx.path_graph(4) self.K5 = nx.complete_graph(5) self.C4=nx.cycle_graph(4) self.T=nx.balanced_tree(r=2, h=2) self.Gb = nx.Graph() self.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) self.F = nx.florentine_families_graph() self.D = nx.cycle_graph(3, create_using=nx.DiGraph()) self.D.add_edges_from([(3, 0), (4, 3)]) def test_not_strongly_connected(self): b = nx.load_centrality(self.D) result = {0: 5./12, 1: 1./4, 2: 1./12, 3: 1./4, 4: 0.000} for n in sorted(self.D): assert_almost_equal(result[n], b[n], places=3) assert_almost_equal(result[n], nx.load_centrality(self.D, n), places=3) def test_weighted_load(self): b=nx.load_centrality(self.G,weight='weight',normalized=False) for n in sorted(self.G): assert_equal(b[n],self.exact_weighted[n]) def test_k5_load(self): G=self.K5 c=nx.load_centrality(G) d={0: 0.000, 1: 0.000, 2: 0.000, 3: 0.000, 4: 0.000} for n in sorted(G): assert_almost_equal(c[n],d[n],places=3) def test_p3_load(self): G=self.P3 c=nx.load_centrality(G) d={0: 0.000, 1: 1.000, 2: 0.000} for n in sorted(G): assert_almost_equal(c[n],d[n],places=3) c=nx.load_centrality(G,v=1) assert_almost_equal(c,1.0) c=nx.load_centrality(G,v=1,normalized=True) assert_almost_equal(c,1.0) def test_p2_load(self): G=nx.path_graph(2) c=nx.load_centrality(G) d={0: 0.000, 1: 0.000} for n in sorted(G): assert_almost_equal(c[n],d[n],places=3) def test_krackhardt_load(self): G=self.K c=nx.load_centrality(G) d={0: 0.023, 1: 0.023, 2: 0.000, 3: 0.102, 4: 0.000, 5: 0.231, 6: 0.231, 7: 0.389, 8: 0.222, 9: 0.000} for n in sorted(G): assert_almost_equal(c[n],d[n],places=3) def test_florentine_families_load(self): G=self.F c=nx.load_centrality(G) d={'Acciaiuoli': 0.000, 'Albizzi': 0.211, 'Barbadori': 0.093, 'Bischeri': 0.104, 'Castellani': 0.055, 'Ginori': 0.000, 'Guadagni': 0.251, 'Lamberteschi': 0.000, 'Medici': 0.522, 'Pazzi': 0.000, 'Peruzzi': 0.022, 'Ridolfi': 0.117, 'Salviati': 0.143, 'Strozzi': 0.106, 'Tornabuoni': 0.090} for n in sorted(G): assert_almost_equal(c[n],d[n],places=3) def test_unnormalized_k5_load(self): G=self.K5 c=nx.load_centrality(G,normalized=False) d={0: 0.000, 1: 0.000, 2: 0.000, 3: 0.000, 4: 0.000} for n in sorted(G): assert_almost_equal(c[n],d[n],places=3) def test_unnormalized_p3_load(self): G=self.P3 c=nx.load_centrality(G,normalized=False) d={0: 0.000, 1: 2.000, 2: 0.000} for n in sorted(G): assert_almost_equal(c[n],d[n],places=3) def test_unnormalized_krackhardt_load(self): G=self.K c=nx.load_centrality(G,normalized=False) d={0: 1.667, 1: 1.667, 2: 0.000, 3: 7.333, 4: 0.000, 5: 16.667, 6: 16.667, 7: 28.000, 8: 16.000, 9: 0.000} for n in sorted(G): assert_almost_equal(c[n],d[n],places=3) def test_unnormalized_florentine_families_load(self): G=self.F c=nx.load_centrality(G,normalized=False) d={'Acciaiuoli': 0.000, 'Albizzi': 38.333, 'Barbadori': 17.000, 'Bischeri': 19.000, 'Castellani': 10.000, 'Ginori': 0.000, 'Guadagni': 45.667, 'Lamberteschi': 0.000, 'Medici': 95.000, 'Pazzi': 0.000, 'Peruzzi': 4.000, 'Ridolfi': 21.333, 'Salviati': 26.000, 'Strozzi': 19.333, 'Tornabuoni': 16.333} for n in sorted(G): assert_almost_equal(c[n],d[n],places=3) def test_load_betweenness_difference(self): # Difference Between Load and Betweenness # --------------------------------------- The smallest graph # that shows the difference between load and betweenness is # G=ladder_graph(3) (Graph B below) # Graph A and B are from Tao Zhou, Jian-Guo Liu, Bing-Hong # Wang: Comment on ``Scientific collaboration # networks. II. Shortest paths, weighted networks, and # centrality". http://arxiv.org/pdf/physics/0511084 # Notice that unlike here, their calculation adds to 1 to the # betweennes of every node i for every path from i to every # other node. This is exactly what it should be, based on # Eqn. (1) in their paper: the eqn is B(v) = \sum_{s\neq t, # s\neq v}{\frac{\sigma_{st}(v)}{\sigma_{st}}}, therefore, # they allow v to be the target node. # We follow Brandes 2001, who follows Freeman 1977 that make # the sum for betweenness of v exclude paths where v is either # the source or target node. To agree with their numbers, we # must additionally, remove edge (4,8) from the graph, see AC # example following (there is a mistake in the figure in their # paper - personal communication). # A = nx.Graph() # A.add_edges_from([(0,1), (1,2), (1,3), (2,4), # (3,5), (4,6), (4,7), (4,8), # (5,8), (6,9), (7,9), (8,9)]) B = nx.Graph() # ladder_graph(3) B.add_edges_from([(0,1), (0,2), (1,3), (2,3), (2,4), (4,5), (3,5)]) c = nx.load_centrality(B,normalized=False) d={0: 1.750, 1: 1.750, 2: 6.500, 3: 6.500, 4: 1.750, 5: 1.750} for n in sorted(B): assert_almost_equal(c[n],d[n],places=3) def test_c4_edge_load(self): G=self.C4 c = nx.edge_load(G) d={(0, 1): 6.000, (0, 3): 6.000, (1, 2): 6.000, (2, 3): 6.000} for n in G.edges(): assert_almost_equal(c[n],d[n],places=3) def test_p4_edge_load(self): G=self.P4 c = nx.edge_load(G) d={(0, 1): 6.000, (1, 2): 8.000, (2, 3): 6.000} for n in G.edges(): assert_almost_equal(c[n],d[n],places=3) def test_k5_edge_load(self): G=self.K5 c = nx.edge_load(G) d={(0, 1): 5.000, (0, 2): 5.000, (0, 3): 5.000, (0, 4): 5.000, (1, 2): 5.000, (1, 3): 5.000, (1, 4): 5.000, (2, 3): 5.000, (2, 4): 5.000, (3, 4): 5.000} for n in G.edges(): assert_almost_equal(c[n],d[n],places=3) def test_tree_edge_load(self): G=self.T c = nx.edge_load(G) d={(0, 1): 24.000, (0, 2): 24.000, (1, 3): 12.000, (1, 4): 12.000, (2, 5): 12.000, (2, 6): 12.000} for n in G.edges(): assert_almost_equal(c[n],d[n],places=3)
gpl-3.0
martinbuc/missionplanner
packages/IronPython.StdLib.2.7.4/content/Lib/encodings/mac_greek.py
93
14284
""" Python Character Mapping Codec mac_greek generated from 'MAPPINGS/VENDORS/APPLE/GREEK.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='mac-greek', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> CONTROL CHARACTER u'\x01' # 0x01 -> CONTROL CHARACTER u'\x02' # 0x02 -> CONTROL CHARACTER u'\x03' # 0x03 -> CONTROL CHARACTER u'\x04' # 0x04 -> CONTROL CHARACTER u'\x05' # 0x05 -> CONTROL CHARACTER u'\x06' # 0x06 -> CONTROL CHARACTER u'\x07' # 0x07 -> CONTROL CHARACTER u'\x08' # 0x08 -> CONTROL CHARACTER u'\t' # 0x09 -> CONTROL CHARACTER u'\n' # 0x0A -> CONTROL CHARACTER u'\x0b' # 0x0B -> CONTROL CHARACTER u'\x0c' # 0x0C -> CONTROL CHARACTER u'\r' # 0x0D -> CONTROL CHARACTER u'\x0e' # 0x0E -> CONTROL CHARACTER u'\x0f' # 0x0F -> CONTROL CHARACTER u'\x10' # 0x10 -> CONTROL CHARACTER u'\x11' # 0x11 -> CONTROL CHARACTER u'\x12' # 0x12 -> CONTROL CHARACTER u'\x13' # 0x13 -> CONTROL CHARACTER u'\x14' # 0x14 -> CONTROL CHARACTER u'\x15' # 0x15 -> CONTROL CHARACTER u'\x16' # 0x16 -> CONTROL CHARACTER u'\x17' # 0x17 -> CONTROL CHARACTER u'\x18' # 0x18 -> CONTROL CHARACTER u'\x19' # 0x19 -> CONTROL CHARACTER u'\x1a' # 0x1A -> CONTROL CHARACTER u'\x1b' # 0x1B -> CONTROL CHARACTER u'\x1c' # 0x1C -> CONTROL CHARACTER u'\x1d' # 0x1D -> CONTROL CHARACTER u'\x1e' # 0x1E -> CONTROL CHARACTER u'\x1f' # 0x1F -> CONTROL CHARACTER u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> CONTROL CHARACTER u'\xc4' # 0x80 -> LATIN CAPITAL LETTER A WITH DIAERESIS u'\xb9' # 0x81 -> SUPERSCRIPT ONE u'\xb2' # 0x82 -> SUPERSCRIPT TWO u'\xc9' # 0x83 -> LATIN CAPITAL LETTER E WITH ACUTE u'\xb3' # 0x84 -> SUPERSCRIPT THREE u'\xd6' # 0x85 -> LATIN CAPITAL LETTER O WITH DIAERESIS u'\xdc' # 0x86 -> LATIN CAPITAL LETTER U WITH DIAERESIS u'\u0385' # 0x87 -> GREEK DIALYTIKA TONOS u'\xe0' # 0x88 -> LATIN SMALL LETTER A WITH GRAVE u'\xe2' # 0x89 -> LATIN SMALL LETTER A WITH CIRCUMFLEX u'\xe4' # 0x8A -> LATIN SMALL LETTER A WITH DIAERESIS u'\u0384' # 0x8B -> GREEK TONOS u'\xa8' # 0x8C -> DIAERESIS u'\xe7' # 0x8D -> LATIN SMALL LETTER C WITH CEDILLA u'\xe9' # 0x8E -> LATIN SMALL LETTER E WITH ACUTE u'\xe8' # 0x8F -> LATIN SMALL LETTER E WITH GRAVE u'\xea' # 0x90 -> LATIN SMALL LETTER E WITH CIRCUMFLEX u'\xeb' # 0x91 -> LATIN SMALL LETTER E WITH DIAERESIS u'\xa3' # 0x92 -> POUND SIGN u'\u2122' # 0x93 -> TRADE MARK SIGN u'\xee' # 0x94 -> LATIN SMALL LETTER I WITH CIRCUMFLEX u'\xef' # 0x95 -> LATIN SMALL LETTER I WITH DIAERESIS u'\u2022' # 0x96 -> BULLET u'\xbd' # 0x97 -> VULGAR FRACTION ONE HALF u'\u2030' # 0x98 -> PER MILLE SIGN u'\xf4' # 0x99 -> LATIN SMALL LETTER O WITH CIRCUMFLEX u'\xf6' # 0x9A -> LATIN SMALL LETTER O WITH DIAERESIS u'\xa6' # 0x9B -> BROKEN BAR u'\u20ac' # 0x9C -> EURO SIGN # before Mac OS 9.2.2, was SOFT HYPHEN u'\xf9' # 0x9D -> LATIN SMALL LETTER U WITH GRAVE u'\xfb' # 0x9E -> LATIN SMALL LETTER U WITH CIRCUMFLEX u'\xfc' # 0x9F -> LATIN SMALL LETTER U WITH DIAERESIS u'\u2020' # 0xA0 -> DAGGER u'\u0393' # 0xA1 -> GREEK CAPITAL LETTER GAMMA u'\u0394' # 0xA2 -> GREEK CAPITAL LETTER DELTA u'\u0398' # 0xA3 -> GREEK CAPITAL LETTER THETA u'\u039b' # 0xA4 -> GREEK CAPITAL LETTER LAMDA u'\u039e' # 0xA5 -> GREEK CAPITAL LETTER XI u'\u03a0' # 0xA6 -> GREEK CAPITAL LETTER PI u'\xdf' # 0xA7 -> LATIN SMALL LETTER SHARP S u'\xae' # 0xA8 -> REGISTERED SIGN u'\xa9' # 0xA9 -> COPYRIGHT SIGN u'\u03a3' # 0xAA -> GREEK CAPITAL LETTER SIGMA u'\u03aa' # 0xAB -> GREEK CAPITAL LETTER IOTA WITH DIALYTIKA u'\xa7' # 0xAC -> SECTION SIGN u'\u2260' # 0xAD -> NOT EQUAL TO u'\xb0' # 0xAE -> DEGREE SIGN u'\xb7' # 0xAF -> MIDDLE DOT u'\u0391' # 0xB0 -> GREEK CAPITAL LETTER ALPHA u'\xb1' # 0xB1 -> PLUS-MINUS SIGN u'\u2264' # 0xB2 -> LESS-THAN OR EQUAL TO u'\u2265' # 0xB3 -> GREATER-THAN OR EQUAL TO u'\xa5' # 0xB4 -> YEN SIGN u'\u0392' # 0xB5 -> GREEK CAPITAL LETTER BETA u'\u0395' # 0xB6 -> GREEK CAPITAL LETTER EPSILON u'\u0396' # 0xB7 -> GREEK CAPITAL LETTER ZETA u'\u0397' # 0xB8 -> GREEK CAPITAL LETTER ETA u'\u0399' # 0xB9 -> GREEK CAPITAL LETTER IOTA u'\u039a' # 0xBA -> GREEK CAPITAL LETTER KAPPA u'\u039c' # 0xBB -> GREEK CAPITAL LETTER MU u'\u03a6' # 0xBC -> GREEK CAPITAL LETTER PHI u'\u03ab' # 0xBD -> GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA u'\u03a8' # 0xBE -> GREEK CAPITAL LETTER PSI u'\u03a9' # 0xBF -> GREEK CAPITAL LETTER OMEGA u'\u03ac' # 0xC0 -> GREEK SMALL LETTER ALPHA WITH TONOS u'\u039d' # 0xC1 -> GREEK CAPITAL LETTER NU u'\xac' # 0xC2 -> NOT SIGN u'\u039f' # 0xC3 -> GREEK CAPITAL LETTER OMICRON u'\u03a1' # 0xC4 -> GREEK CAPITAL LETTER RHO u'\u2248' # 0xC5 -> ALMOST EQUAL TO u'\u03a4' # 0xC6 -> GREEK CAPITAL LETTER TAU u'\xab' # 0xC7 -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbb' # 0xC8 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\u2026' # 0xC9 -> HORIZONTAL ELLIPSIS u'\xa0' # 0xCA -> NO-BREAK SPACE u'\u03a5' # 0xCB -> GREEK CAPITAL LETTER UPSILON u'\u03a7' # 0xCC -> GREEK CAPITAL LETTER CHI u'\u0386' # 0xCD -> GREEK CAPITAL LETTER ALPHA WITH TONOS u'\u0388' # 0xCE -> GREEK CAPITAL LETTER EPSILON WITH TONOS u'\u0153' # 0xCF -> LATIN SMALL LIGATURE OE u'\u2013' # 0xD0 -> EN DASH u'\u2015' # 0xD1 -> HORIZONTAL BAR u'\u201c' # 0xD2 -> LEFT DOUBLE QUOTATION MARK u'\u201d' # 0xD3 -> RIGHT DOUBLE QUOTATION MARK u'\u2018' # 0xD4 -> LEFT SINGLE QUOTATION MARK u'\u2019' # 0xD5 -> RIGHT SINGLE QUOTATION MARK u'\xf7' # 0xD6 -> DIVISION SIGN u'\u0389' # 0xD7 -> GREEK CAPITAL LETTER ETA WITH TONOS u'\u038a' # 0xD8 -> GREEK CAPITAL LETTER IOTA WITH TONOS u'\u038c' # 0xD9 -> GREEK CAPITAL LETTER OMICRON WITH TONOS u'\u038e' # 0xDA -> GREEK CAPITAL LETTER UPSILON WITH TONOS u'\u03ad' # 0xDB -> GREEK SMALL LETTER EPSILON WITH TONOS u'\u03ae' # 0xDC -> GREEK SMALL LETTER ETA WITH TONOS u'\u03af' # 0xDD -> GREEK SMALL LETTER IOTA WITH TONOS u'\u03cc' # 0xDE -> GREEK SMALL LETTER OMICRON WITH TONOS u'\u038f' # 0xDF -> GREEK CAPITAL LETTER OMEGA WITH TONOS u'\u03cd' # 0xE0 -> GREEK SMALL LETTER UPSILON WITH TONOS u'\u03b1' # 0xE1 -> GREEK SMALL LETTER ALPHA u'\u03b2' # 0xE2 -> GREEK SMALL LETTER BETA u'\u03c8' # 0xE3 -> GREEK SMALL LETTER PSI u'\u03b4' # 0xE4 -> GREEK SMALL LETTER DELTA u'\u03b5' # 0xE5 -> GREEK SMALL LETTER EPSILON u'\u03c6' # 0xE6 -> GREEK SMALL LETTER PHI u'\u03b3' # 0xE7 -> GREEK SMALL LETTER GAMMA u'\u03b7' # 0xE8 -> GREEK SMALL LETTER ETA u'\u03b9' # 0xE9 -> GREEK SMALL LETTER IOTA u'\u03be' # 0xEA -> GREEK SMALL LETTER XI u'\u03ba' # 0xEB -> GREEK SMALL LETTER KAPPA u'\u03bb' # 0xEC -> GREEK SMALL LETTER LAMDA u'\u03bc' # 0xED -> GREEK SMALL LETTER MU u'\u03bd' # 0xEE -> GREEK SMALL LETTER NU u'\u03bf' # 0xEF -> GREEK SMALL LETTER OMICRON u'\u03c0' # 0xF0 -> GREEK SMALL LETTER PI u'\u03ce' # 0xF1 -> GREEK SMALL LETTER OMEGA WITH TONOS u'\u03c1' # 0xF2 -> GREEK SMALL LETTER RHO u'\u03c3' # 0xF3 -> GREEK SMALL LETTER SIGMA u'\u03c4' # 0xF4 -> GREEK SMALL LETTER TAU u'\u03b8' # 0xF5 -> GREEK SMALL LETTER THETA u'\u03c9' # 0xF6 -> GREEK SMALL LETTER OMEGA u'\u03c2' # 0xF7 -> GREEK SMALL LETTER FINAL SIGMA u'\u03c7' # 0xF8 -> GREEK SMALL LETTER CHI u'\u03c5' # 0xF9 -> GREEK SMALL LETTER UPSILON u'\u03b6' # 0xFA -> GREEK SMALL LETTER ZETA u'\u03ca' # 0xFB -> GREEK SMALL LETTER IOTA WITH DIALYTIKA u'\u03cb' # 0xFC -> GREEK SMALL LETTER UPSILON WITH DIALYTIKA u'\u0390' # 0xFD -> GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS u'\u03b0' # 0xFE -> GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS u'\xad' # 0xFF -> SOFT HYPHEN # before Mac OS 9.2.2, was undefined ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
gpl-3.0
nwalters512/the-blue-alliance
tests/test_usfirst_event_awards_parser_03_04.py
7
5085
import unittest2 import json from consts.award_type import AwardType from datafeeds.usfirst_event_awards_parser_03_04 import UsfirstEventAwardsParser_03_04 def convert_to_comparable(data): """ Converts jsons to dicts so that elements can be more easily compared """ if type(data) == list: return [convert_to_comparable(e) for e in data] elif type(data) == dict: to_return = {} for key, value in data.items(): to_return[key] = convert_to_comparable(value) return to_return elif type(data) == str or type(data) == unicode: try: return json.loads(data) except ValueError: return data else: return data class TestUsfirstEventAwardsParser_03_04(unittest2.TestCase): def test_parse_regional_2004(self): with open('test_data/usfirst_html/usfirst_event_awards_2004sj.html', 'r') as f: awards, _ = UsfirstEventAwardsParser_03_04.parse(f.read()) # Check number of parsed awards num_awards = 0 for award in awards: num_awards += len(award['recipient_json_list']) self.assertEqual(num_awards, 26) self.assertEqual(len(awards), 21) awards = convert_to_comparable(awards) # Test Team Award team_award = { 'name_str': u"Regional Chairman\u2019s Award", 'award_type_enum': AwardType.CHAIRMANS, 'team_number_list': [254], 'recipient_json_list': [{'team_number': 254, 'awardee': None}], } self.assertTrue(team_award in awards) # Test Multi Team Award multi_team_award = { 'name_str': "Regional Winner", 'award_type_enum': AwardType.WINNER, 'team_number_list': [971, 254, 852], 'recipient_json_list': [{'team_number': 971, 'awardee': None}, {'team_number': 254, 'awardee': None}, {'team_number': 852, 'awardee': None}], } self.assertTrue(multi_team_award in awards) # Test Individual Award individual_award = { 'name_str': "Regional Woodie Flowers Award", 'award_type_enum': AwardType.WOODIE_FLOWERS, 'team_number_list': [115], 'recipient_json_list': [{'team_number': 115, 'awardee': u"Ted Shinta"}], } self.assertTrue(individual_award in awards) def test_parse_regional_2003(self): with open('test_data/usfirst_html/usfirst_event_awards_2003sj.html', 'r') as f: awards, _ = UsfirstEventAwardsParser_03_04.parse(f.read()) # Check number of parsed awards num_awards = 0 for award in awards: num_awards += len(award['recipient_json_list']) self.assertEqual(num_awards, 25) self.assertEqual(len(awards), 18) awards = convert_to_comparable(awards) # Test Team Award team_award = { 'name_str': u"Regional Chairman\u2019s Award", 'award_type_enum': AwardType.CHAIRMANS, 'team_number_list': [359], 'recipient_json_list': [{'team_number': 359, 'awardee': None}], } self.assertTrue(team_award in awards) # Test Multi Team Award multi_team_award = { 'name_str': "Regional Winner", 'award_type_enum': AwardType.WINNER, 'team_number_list': [115, 254, 852], 'recipient_json_list': [{'team_number': 115, 'awardee': None}, {'team_number': 254, 'awardee': None}, {'team_number': 852, 'awardee': None}], } self.assertTrue(multi_team_award in awards) # Test Individual Award individual_award = { 'name_str': "Silicon Valley Regional Volunteer of the Year", 'award_type_enum': AwardType.VOLUNTEER, 'team_number_list': [], 'recipient_json_list': [{'team_number': None, 'awardee': u"Ken Krieger"}, {'team_number': None, 'awardee': u"Ken Leung"},], } self.assertTrue(individual_award in awards) def test_parse_cmp_2003(self): with open('test_data/usfirst_html/usfirst_event_awards_2003cmp.html', 'r') as f: awards, _ = UsfirstEventAwardsParser_03_04.parse(f.read()) # Check number of parsed awards num_awards = 0 for award in awards: num_awards += len(award['recipient_json_list']) self.assertEqual(num_awards, 26) self.assertEqual(len(awards), 20) awards = convert_to_comparable(awards) team_award = { 'name_str': u"Rookie All Star Award", 'award_type_enum': AwardType.ROOKIE_ALL_STAR, 'team_number_list': [1108, 1023], 'recipient_json_list': [{'team_number': 1108, 'awardee': None}, {'team_number': 1023, 'awardee': None}], } self.assertTrue(team_award in awards)
mit
joshbohde/scikit-learn
sklearn/linear_model/sparse/logistic.py
2
3922
""" Sparse Logistic Regression module This module has the same API as sklearn.linear_model.logistic, but is designed to handle efficiently data in sparse matrix format. """ import numpy as np import scipy.sparse as sp from ...base import ClassifierMixin from ...svm.sparse.base import SparseBaseLibLinear from ...linear_model.sparse.base import CoefSelectTransformerMixin from ...svm.liblinear import csr_predict_prob class LogisticRegression(SparseBaseLibLinear, ClassifierMixin, CoefSelectTransformerMixin): """ Logistic Regression. Implements L1 and L2 regularized logistic regression. Parameters ---------- penalty : string, 'l1' or 'l2' Used to specify the norm used in the penalization dual : boolean Dual or primal formulation. Dual formulation is only implemented for l2 penalty. C : float Specifies the strength of the regularization. The smaller it is the bigger in the regularization. fit_intercept : bool, default: True Specifies if a constant (a.k.a. bias or intercept) should be added the decision function intercept_scaling : float, default: 1 when self.fit_intercept is True, instance vector x becomes [x, self.intercept_scaling], i.e. a "synthetic" feature with constant value equals to intercept_scaling is appended to the instance vector. The intercept becomes intercept_scaling * synthetic feature weight Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased tol: float, optional tolerance for stopping criteria Attributes ---------- `coef_` : array, shape = [n_classes-1, n_features] Coefficient of the features in the decision function. `intercept_` : array, shape = [n_classes-1] intercept (a.k.a. bias) added to the decision function. It is available only when parameter intercept is set to True See also -------- LinearSVC Notes ----- The underlying C implementation uses a random number generator to select features when fitting the model. It is thus not uncommon, to have slightly different results for the same input data. If that happens, try with a smaller tol parameter. References ---------- LIBLINEAR -- A Library for Large Linear Classification http://www.csie.ntu.edu.tw/~cjlin/liblinear/ """ def __init__(self, penalty='l2', dual=False, tol=1e-4, C=1.0, fit_intercept=True, intercept_scaling=1): super(LogisticRegression, self).__init__ (penalty=penalty, dual=dual, loss='lr', tol=tol, C=C, fit_intercept=fit_intercept, intercept_scaling=intercept_scaling) def predict_proba(self, X): """ Probability estimates. The returned estimates for all classes are ordered by the label of classes. """ X = sp.csr_matrix(X) X.data = np.asanyarray(X.data, dtype=np.float64, order='C') probas = csr_predict_prob(X.shape[1], X.data, X.indices, X.indptr, self.raw_coef_, self._get_solver_type(), self.tol, self.C, self.class_weight_label, self.class_weight, self.label_, self._get_bias()) return probas[:,np.argsort(self.label_)] def predict_log_proba(self, T): """ Log of Probability estimates. The returned estimates for all classes are ordered by the label of classes. """ return np.log(self.predict_proba(T))
bsd-3-clause
goodfeli/pylearn2
pylearn2/scripts/summarize_model.py
44
2999
#!/usr/bin/env python """ This script summarizes a model by showing some statistics about the parameters and checking whether the model completed training succesfully """ from __future__ import print_function __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" import argparse import numpy as np from pylearn2.compat import first_key from pylearn2.utils import serial def summarize(path): """ Summarize the model Parameters ---------- path : str The path to the pickled model to summarize """ model = serial.load(path) for param in model.get_params(): name = param.name if name is None: name = '<anon>' v = param.get_value() print(name + ': ' + str((v.min(), v.mean(), v.max())), end='') print(str(v.shape)) if np.sign(v.min()) != np.sign(v.max()): v = np.abs(v) print('abs(' + name + '): ' + str((v.min(), v.mean(), v.max()))) if v.ndim == 2: row_norms = np.sqrt(np.square(v).sum(axis=1)) print(name + " row norms:", end='') print((row_norms.min(), row_norms.mean(), row_norms.max())) col_norms = np.sqrt(np.square(v).sum(axis=0)) print(name + " col norms:", end='') print((col_norms.min(), col_norms.mean(), col_norms.max())) if hasattr(model, 'monitor'): print('trained on', model.monitor.get_examples_seen(), 'examples') print('which corresponds to ', end='') print(model.monitor.get_batches_seen(), 'batches') key = first_key(model.monitor.channels) hour = float(model.monitor.channels[key].time_record[-1]) / 3600. print('Trained for {0} hours'.format(hour)) try: print(model.monitor.get_epochs_seen(), 'epochs') except Exception: pass if hasattr(model.monitor, 'training_succeeded'): if model.monitor.training_succeeded: print('Training succeeded') else: print('Training was not yet completed ' + 'at the time of this save.') else: print('This pickle file is damaged, or was made before the ' + 'Monitor tracked whether training completed.') def make_argument_parser(): """ Creates an ArgumentParser to read the options for this script from sys.argv """ parser = argparse.ArgumentParser( description="Print some parameter statistics of a pickled model " "and check if it completed training succesfully." ) parser.add_argument('path', help='The pickled model to summarize') return parser if __name__ == "__main__": parser = make_argument_parser() args = parser.parse_args() summarize(args.path)
bsd-3-clause
eBusLabs/reboot2
src/profiles/views.py
58
2467
from __future__ import unicode_literals from django.views import generic from django.shortcuts import get_object_or_404, redirect from django.contrib import messages from braces.views import LoginRequiredMixin from . import forms from . import models class ShowProfile(LoginRequiredMixin, generic.TemplateView): template_name = "profiles/show_profile.html" http_method_names = ['get'] def get(self, request, *args, **kwargs): slug = self.kwargs.get('slug') if slug: profile = get_object_or_404(models.Profile, slug=slug) user = profile.user else: user = self.request.user if user == self.request.user: kwargs["editable"] = True kwargs["show_user"] = user return super(ShowProfile, self).get(request, *args, **kwargs) class EditProfile(LoginRequiredMixin, generic.TemplateView): template_name = "profiles/edit_profile.html" http_method_names = ['get', 'post'] def get(self, request, *args, **kwargs): user = self.request.user if "user_form" not in kwargs: kwargs["user_form"] = forms.UserForm(instance=user) if "profile_form" not in kwargs: kwargs["profile_form"] = forms.ProfileForm(instance=user.profile) return super(EditProfile, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): user = self.request.user user_form = forms.UserForm(request.POST, instance=user) profile_form = forms.ProfileForm(request.POST, request.FILES, instance=user.profile) if not (user_form.is_valid() and profile_form.is_valid()): messages.error(request, "There was a problem with the form. " "Please check the details.") user_form = forms.UserForm(instance=user) profile_form = forms.ProfileForm(instance=user.profile) return super(EditProfile, self).get(request, user_form=user_form, profile_form=profile_form) # Both forms are fine. Time to save! user_form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() messages.success(request, "Profile details saved!") return redirect("profiles:show_self")
mit
collects/VTK
Examples/VisualizationAlgorithms/Python/officeTubes.py
17
12565
#!/usr/bin/env python # This example demonstrates the use of streamlines generated from seeds, # combined with a tube filter to create several streamtubes. import vtk from vtk.util.misc import vtkGetDataRoot from vtk.util.colors import * VTK_DATA_ROOT = vtkGetDataRoot() # We read a data file the is a CFD analysis of airflow in an office # (with ventilation and a burning cigarette). We force an update so # that we can query the output for its length, i.e., the length of the # diagonal of the bounding box. This is useful for normalizing the # data. reader = vtk.vtkStructuredGridReader() reader.SetFileName(VTK_DATA_ROOT + "/Data/office.binary.vtk") reader.Update() length = reader.GetOutput().GetLength() maxVelocity =reader.GetOutput().GetPointData().GetVectors().GetMaxNorm() maxTime = 35.0*length/maxVelocity # Now we will generate multiple streamlines in the data. We create a # random cloud of points and then use those as integration seeds. We # select the integration order to use (RungeKutta order 4) and # associate it with the streamer. The start position is the position # in world space where we want to begin streamline integration; and we # integrate in both directions. The step length is the length of the # line segments that make up the streamline (i.e., related to # display). The IntegrationStepLength specifies the integration step # length as a fraction of the cell size that the streamline is in. # Create source for streamtubes seeds = vtk.vtkPointSource() seeds.SetRadius(0.15) seeds.SetCenter(0.1, 2.1, 0.5) seeds.SetNumberOfPoints(6) integ = vtk.vtkRungeKutta4() streamer = vtk.vtkStreamLine() streamer.SetInputConnection(reader.GetOutputPort()) streamer.SetSourceConnection(seeds.GetOutputPort()) streamer.SetMaximumPropagationTime(500) streamer.SetStepLength(0.5) streamer.SetIntegrationStepLength(0.05) streamer.SetIntegrationDirectionToIntegrateBothDirections() streamer.SetIntegrator(integ) # The tube is wrapped around the generated streamline. By varying the # radius by the inverse of vector magnitude, we are creating a tube # whose radius is proportional to mass flux (in incompressible flow). streamTube = vtk.vtkTubeFilter() streamTube.SetInputConnection(streamer.GetOutputPort()) streamTube.SetRadius(0.02) streamTube.SetNumberOfSides(12) streamTube.SetVaryRadiusToVaryRadiusByVector() mapStreamTube = vtk.vtkPolyDataMapper() mapStreamTube.SetInputConnection(streamTube.GetOutputPort()) mapStreamTube.SetScalarRange(reader.GetOutput().GetPointData().GetScalars().GetRange()) streamTubeActor = vtk.vtkActor() streamTubeActor.SetMapper(mapStreamTube) streamTubeActor.GetProperty().BackfaceCullingOn() # From here on we generate a whole bunch of planes which correspond to # the geometry in the analysis; tables, bookshelves and so on. table1 = vtk.vtkStructuredGridGeometryFilter() table1.SetInputConnection(reader.GetOutputPort()) table1.SetExtent(11, 15, 7, 9, 8, 8) mapTable1 = vtk.vtkPolyDataMapper() mapTable1.SetInputConnection(table1.GetOutputPort()) mapTable1.ScalarVisibilityOff() table1Actor = vtk.vtkActor() table1Actor.SetMapper(mapTable1) table1Actor.GetProperty().SetColor(.59, .427, .392) table2 = vtk.vtkStructuredGridGeometryFilter() table2.SetInputConnection(reader.GetOutputPort()) table2.SetExtent(11, 15, 10, 12, 8, 8) mapTable2 = vtk.vtkPolyDataMapper() mapTable2.SetInputConnection(table2.GetOutputPort()) mapTable2.ScalarVisibilityOff() table2Actor = vtk.vtkActor() table2Actor.SetMapper(mapTable2) table2Actor.GetProperty().SetColor(.59, .427, .392) FilingCabinet1 = vtk.vtkStructuredGridGeometryFilter() FilingCabinet1.SetInputConnection(reader.GetOutputPort()) FilingCabinet1.SetExtent(15, 15, 7, 9, 0, 8) mapFilingCabinet1 = vtk.vtkPolyDataMapper() mapFilingCabinet1.SetInputConnection(FilingCabinet1.GetOutputPort()) mapFilingCabinet1.ScalarVisibilityOff() FilingCabinet1Actor = vtk.vtkActor() FilingCabinet1Actor.SetMapper(mapFilingCabinet1) FilingCabinet1Actor.GetProperty().SetColor(.8, .8, .6) FilingCabinet2 = vtk.vtkStructuredGridGeometryFilter() FilingCabinet2.SetInputConnection(reader.GetOutputPort()) FilingCabinet2.SetExtent(15, 15, 10, 12, 0, 8) mapFilingCabinet2 = vtk.vtkPolyDataMapper() mapFilingCabinet2.SetInputConnection(FilingCabinet2.GetOutputPort()) mapFilingCabinet2.ScalarVisibilityOff() FilingCabinet2Actor = vtk.vtkActor() FilingCabinet2Actor.SetMapper(mapFilingCabinet2) FilingCabinet2Actor.GetProperty().SetColor(.8, .8, .6) bookshelf1Top = vtk.vtkStructuredGridGeometryFilter() bookshelf1Top.SetInputConnection(reader.GetOutputPort()) bookshelf1Top.SetExtent(13, 13, 0, 4, 0, 11) mapBookshelf1Top = vtk.vtkPolyDataMapper() mapBookshelf1Top.SetInputConnection(bookshelf1Top.GetOutputPort()) mapBookshelf1Top.ScalarVisibilityOff() bookshelf1TopActor = vtk.vtkActor() bookshelf1TopActor.SetMapper(mapBookshelf1Top) bookshelf1TopActor.GetProperty().SetColor(.8, .8, .6) bookshelf1Bottom = vtk.vtkStructuredGridGeometryFilter() bookshelf1Bottom.SetInputConnection(reader.GetOutputPort()) bookshelf1Bottom.SetExtent(20, 20, 0, 4, 0, 11) mapBookshelf1Bottom = vtk.vtkPolyDataMapper() mapBookshelf1Bottom.SetInputConnection(bookshelf1Bottom.GetOutputPort()) mapBookshelf1Bottom.ScalarVisibilityOff() bookshelf1BottomActor = vtk.vtkActor() bookshelf1BottomActor.SetMapper(mapBookshelf1Bottom) bookshelf1BottomActor.GetProperty().SetColor(.8, .8, .6) bookshelf1Front = vtk.vtkStructuredGridGeometryFilter() bookshelf1Front.SetInputConnection(reader.GetOutputPort()) bookshelf1Front.SetExtent(13, 20, 0, 0, 0, 11) mapBookshelf1Front = vtk.vtkPolyDataMapper() mapBookshelf1Front.SetInputConnection(bookshelf1Front.GetOutputPort()) mapBookshelf1Front.ScalarVisibilityOff() bookshelf1FrontActor = vtk.vtkActor() bookshelf1FrontActor.SetMapper(mapBookshelf1Front) bookshelf1FrontActor.GetProperty().SetColor(.8, .8, .6) bookshelf1Back = vtk.vtkStructuredGridGeometryFilter() bookshelf1Back.SetInputConnection(reader.GetOutputPort()) bookshelf1Back.SetExtent(13, 20, 4, 4, 0, 11) mapBookshelf1Back = vtk.vtkPolyDataMapper() mapBookshelf1Back.SetInputConnection(bookshelf1Back.GetOutputPort()) mapBookshelf1Back.ScalarVisibilityOff() bookshelf1BackActor = vtk.vtkActor() bookshelf1BackActor.SetMapper(mapBookshelf1Back) bookshelf1BackActor.GetProperty().SetColor(.8, .8, .6) bookshelf1LHS = vtk.vtkStructuredGridGeometryFilter() bookshelf1LHS.SetInputConnection(reader.GetOutputPort()) bookshelf1LHS.SetExtent(13, 20, 0, 4, 0, 0) mapBookshelf1LHS = vtk.vtkPolyDataMapper() mapBookshelf1LHS.SetInputConnection(bookshelf1LHS.GetOutputPort()) mapBookshelf1LHS.ScalarVisibilityOff() bookshelf1LHSActor = vtk.vtkActor() bookshelf1LHSActor.SetMapper(mapBookshelf1LHS) bookshelf1LHSActor.GetProperty().SetColor(.8, .8, .6) bookshelf1RHS = vtk.vtkStructuredGridGeometryFilter() bookshelf1RHS.SetInputConnection(reader.GetOutputPort()) bookshelf1RHS.SetExtent(13, 20, 0, 4, 11, 11) mapBookshelf1RHS = vtk.vtkPolyDataMapper() mapBookshelf1RHS.SetInputConnection(bookshelf1RHS.GetOutputPort()) mapBookshelf1RHS.ScalarVisibilityOff() bookshelf1RHSActor = vtk.vtkActor() bookshelf1RHSActor.SetMapper(mapBookshelf1RHS) bookshelf1RHSActor.GetProperty().SetColor(.8, .8, .6) bookshelf2Top = vtk.vtkStructuredGridGeometryFilter() bookshelf2Top.SetInputConnection(reader.GetOutputPort()) bookshelf2Top.SetExtent(13, 13, 15, 19, 0, 11) mapBookshelf2Top = vtk.vtkPolyDataMapper() mapBookshelf2Top.SetInputConnection(bookshelf2Top.GetOutputPort()) mapBookshelf2Top.ScalarVisibilityOff() bookshelf2TopActor = vtk.vtkActor() bookshelf2TopActor.SetMapper(mapBookshelf2Top) bookshelf2TopActor.GetProperty().SetColor(.8, .8, .6) bookshelf2Bottom = vtk.vtkStructuredGridGeometryFilter() bookshelf2Bottom.SetInputConnection(reader.GetOutputPort()) bookshelf2Bottom.SetExtent(20, 20, 15, 19, 0, 11) mapBookshelf2Bottom = vtk.vtkPolyDataMapper() mapBookshelf2Bottom.SetInputConnection(bookshelf2Bottom.GetOutputPort()) mapBookshelf2Bottom.ScalarVisibilityOff() bookshelf2BottomActor = vtk.vtkActor() bookshelf2BottomActor.SetMapper(mapBookshelf2Bottom) bookshelf2BottomActor.GetProperty().SetColor(.8, .8, .6) bookshelf2Front = vtk.vtkStructuredGridGeometryFilter() bookshelf2Front.SetInputConnection(reader.GetOutputPort()) bookshelf2Front.SetExtent(13, 20, 15, 15, 0, 11) mapBookshelf2Front = vtk.vtkPolyDataMapper() mapBookshelf2Front.SetInputConnection(bookshelf2Front.GetOutputPort()) mapBookshelf2Front.ScalarVisibilityOff() bookshelf2FrontActor = vtk.vtkActor() bookshelf2FrontActor.SetMapper(mapBookshelf2Front) bookshelf2FrontActor.GetProperty().SetColor(.8, .8, .6) bookshelf2Back = vtk.vtkStructuredGridGeometryFilter() bookshelf2Back.SetInputConnection(reader.GetOutputPort()) bookshelf2Back.SetExtent(13, 20, 19, 19, 0, 11) mapBookshelf2Back = vtk.vtkPolyDataMapper() mapBookshelf2Back.SetInputConnection(bookshelf2Back.GetOutputPort()) mapBookshelf2Back.ScalarVisibilityOff() bookshelf2BackActor = vtk.vtkActor() bookshelf2BackActor.SetMapper(mapBookshelf2Back) bookshelf2BackActor.GetProperty().SetColor(.8, .8, .6) bookshelf2LHS = vtk.vtkStructuredGridGeometryFilter() bookshelf2LHS.SetInputConnection(reader.GetOutputPort()) bookshelf2LHS.SetExtent(13, 20, 15, 19, 0, 0) mapBookshelf2LHS = vtk.vtkPolyDataMapper() mapBookshelf2LHS.SetInputConnection(bookshelf2LHS.GetOutputPort()) mapBookshelf2LHS.ScalarVisibilityOff() bookshelf2LHSActor = vtk.vtkActor() bookshelf2LHSActor.SetMapper(mapBookshelf2LHS) bookshelf2LHSActor.GetProperty().SetColor(.8, .8, .6) bookshelf2RHS = vtk.vtkStructuredGridGeometryFilter() bookshelf2RHS.SetInputConnection(reader.GetOutputPort()) bookshelf2RHS.SetExtent(13, 20, 15, 19, 11, 11) mapBookshelf2RHS = vtk.vtkPolyDataMapper() mapBookshelf2RHS.SetInputConnection(bookshelf2RHS.GetOutputPort()) mapBookshelf2RHS.ScalarVisibilityOff() bookshelf2RHSActor = vtk.vtkActor() bookshelf2RHSActor.SetMapper(mapBookshelf2RHS) bookshelf2RHSActor.GetProperty().SetColor(.8, .8, .6) window = vtk.vtkStructuredGridGeometryFilter() window.SetInputConnection(reader.GetOutputPort()) window.SetExtent(20, 20, 6, 13, 10, 13) mapWindow = vtk.vtkPolyDataMapper() mapWindow.SetInputConnection(window.GetOutputPort()) mapWindow.ScalarVisibilityOff() windowActor = vtk.vtkActor() windowActor.SetMapper(mapWindow) windowActor.GetProperty().SetColor(.3, .3, .5) outlet = vtk.vtkStructuredGridGeometryFilter() outlet.SetInputConnection(reader.GetOutputPort()) outlet.SetExtent(0, 0, 9, 10, 14, 16) mapOutlet = vtk.vtkPolyDataMapper() mapOutlet.SetInputConnection(outlet.GetOutputPort()) mapOutlet.ScalarVisibilityOff() outletActor = vtk.vtkActor() outletActor.SetMapper(mapOutlet) outletActor.GetProperty().SetColor(0, 0, 0) inlet = vtk.vtkStructuredGridGeometryFilter() inlet.SetInputConnection(reader.GetOutputPort()) inlet.SetExtent(0, 0, 9, 10, 0, 6) mapInlet = vtk.vtkPolyDataMapper() mapInlet.SetInputConnection(inlet.GetOutputPort()) mapInlet.ScalarVisibilityOff() inletActor = vtk.vtkActor() inletActor.SetMapper(mapInlet) inletActor.GetProperty().SetColor(0, 0, 0) outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputConnection(reader.GetOutputPort()) mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(mapOutline) outlineActor.GetProperty().SetColor(0, 0, 0) # Now create the usual graphics stuff. ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren.AddActor(table1Actor) ren.AddActor(table2Actor) ren.AddActor(FilingCabinet1Actor) ren.AddActor(FilingCabinet2Actor) ren.AddActor(bookshelf1TopActor) ren.AddActor(bookshelf1BottomActor) ren.AddActor(bookshelf1FrontActor) ren.AddActor(bookshelf1BackActor) ren.AddActor(bookshelf1LHSActor) ren.AddActor(bookshelf1RHSActor) ren.AddActor(bookshelf2TopActor) ren.AddActor(bookshelf2BottomActor) ren.AddActor(bookshelf2FrontActor) ren.AddActor(bookshelf2BackActor) ren.AddActor(bookshelf2LHSActor) ren.AddActor(bookshelf2RHSActor) ren.AddActor(windowActor) ren.AddActor(outletActor) ren.AddActor(inletActor) ren.AddActor(outlineActor) ren.AddActor(streamTubeActor) ren.SetBackground(slate_grey) # Here we specify a particular view. aCamera = vtk.vtkCamera() aCamera.SetClippingRange(0.726079, 36.3039) aCamera.SetFocalPoint(2.43584, 2.15046, 1.11104) aCamera.SetPosition(-4.76183, -10.4426, 3.17203) aCamera.SetViewUp(0.0511273, 0.132773, 0.989827) aCamera.SetViewAngle(18.604) aCamera.Zoom(1.2) ren.SetActiveCamera(aCamera) renWin.SetSize(500, 300) iren.Initialize() renWin.Render() iren.Start()
bsd-3-clause
silvau/Addons_Odoo
hr_bulk_period/__openerp__.py
1
1643
# -*- encoding: utf-8 -*- ############################################################################ # Module for OpenERP, Open Source Management Solution # # Copyright (c) 2013 Zenpar - http://www.zeval.com.mx/ # All Rights Reserved. ############################################################################ # Coded by: jsolorzano@zeval.com.mx # Manager: Orlando Zentella ozentella@zeval.com.mx ############################################################################ # # 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' : 'Bulk period on payslip', 'version' : '1.0', 'author' : 'silvau', 'website' : 'http://www.zeval.com.mx', 'category' : 'HR', 'depends' : ['hr_payroll'], 'data': [ 'wizard/hr_bulk_period.xml', 'hr_payroll_view.xml', ], 'demo': [], 'test': [], 'installable': True, 'auto_install': False, 'images': [], }
gpl-2.0
svn2github/vbox
src/VBox/ValidationKit/testmanager/batch/add_build.py
4
5758
#!/usr/bin/env python # -*- coding: utf-8 -*- # $Id$ # pylint: disable=C0301 """ Interface used by the tinderbox server side software to add a fresh build. """ __copyright__ = \ """ Copyright (C) 2012-2014 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation, in version 2 as it comes in the "COPYING" file of the VirtualBox OSE distribution. VirtualBox OSE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. The contents of this file may alternatively be used under the terms of the Common Development and Distribution License Version 1.0 (CDDL) only, as it comes in the "COPYING.CDDL" file of the VirtualBox OSE distribution, in which case the provisions of the CDDL are applicable instead of those of the GPL. You may elect to license modified versions of this file under the terms and conditions of either the GPL or the CDDL or both. """ __version__ = "$Revision$" # Standard python imports import sys; import os; from optparse import OptionParser; # Add Test Manager's modules path g_ksTestManagerDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))); sys.path.append(g_ksTestManagerDir); # Test Manager imports from testmanager.core.db import TMDatabaseConnection; from testmanager.core.build import BuildDataEx, BuildLogic, BuildCategoryData; class Build(object): # pylint: disable=R0903 """ Add build info into Test Manager database. """ def __init__(self): """ Parse command line. """ oParser = OptionParser(); oParser.add_option('-q', '--quiet', dest = 'fQuiet', action = 'store_true', help = 'Quiet execution'); oParser.add_option('-b', '--branch', dest = 'sBranch', metavar = '<branch>', help = 'branch name (default: trunk)', default = 'trunk'); oParser.add_option('-p', '--product', dest = 'sProductName', metavar = '<name>', help = 'The product name.'); oParser.add_option('-r', '--revision', dest = 'iRevision', metavar = '<rev>', help = 'revision number'); oParser.add_option('-R', '--repository', dest = 'sRepository', metavar = '<repository>', help = 'Version control repository name.'); oParser.add_option('-t', '--type', dest = 'sBuildType', metavar = '<type>', help = 'build type (debug, release etc.)'); oParser.add_option('-v', '--version', dest = 'sProductVersion', metavar = '<ver>', help = 'The product version number (suitable for RTStrVersionCompare)'); oParser.add_option('-o', '--os-arch', dest = 'asTargetOsArches', metavar = '<os.arch>', action = 'append', help = 'Target OS and architecture. This option can be repeated.'); oParser.add_option('-l', '--log', dest = 'sBuildLogPath', metavar = '<url>', help = 'URL to the build logs (optional).'); oParser.add_option('-f', '--file', dest = 'asFiles', metavar = '<file|url>', action = 'append', help = 'URLs or build share relative path to a build output file. This option can be repeated.'); (self.oConfig, _) = oParser.parse_args(); # Check command line asMissing = []; if self.oConfig.sBranch is None: asMissing.append('--branch'); if self.oConfig.iRevision is None: asMissing.append('--revision'); if self.oConfig.sProductVersion is None: asMissing.append('--version'); if self.oConfig.sProductName is None: asMissing.append('--product'); if self.oConfig.sBuildType is None: asMissing.append('--type'); if self.oConfig.asTargetOsArches is None: asMissing.append('--os-arch'); if self.oConfig.asFiles is None: asMissing.append('--file'); if len(asMissing) > 0: sys.stderr.write('syntax error: Missing: %s\n' % (asMissing,)); sys.exit(1); # Temporary default. if self.oConfig.sRepository is None: self.oConfig.sRepository = 'vbox'; def add(self): """ Add build data record into database. """ oDb = TMDatabaseConnection() # Assemble the build data. oBuildData = BuildDataEx() oBuildData.idBuildCategory = None; oBuildData.iRevision = self.oConfig.iRevision oBuildData.sVersion = self.oConfig.sProductVersion oBuildData.sLogUrl = self.oConfig.sBuildLogPath oBuildData.sBinaries = ','.join(self.oConfig.asFiles); oBuildData.oCat = BuildCategoryData().initFromValues(sProduct = self.oConfig.sProductName, sRepository = self.oConfig.sRepository, sBranch = self.oConfig.sBranch, sType = self.oConfig.sBuildType, asOsArches = self.oConfig.asTargetOsArches); # Add record to database try: BuildLogic(oDb).addEntry(oBuildData, fCommit = True); except: if self.oConfig.fQuiet: sys.exit(1); raise; oDb.close(); return 0; if __name__ == '__main__': sys.exit(Build().add());
gpl-2.0
pombredanne/MOG
nova/virt/baremetal/driver.py
7
21022
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # coding=utf-8 # # Copyright (c) 2012 NTT DOCOMO, INC # Copyright (c) 2011 University of Southern California / ISI # 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. """ A driver for Bare-metal platform. """ from oslo.config import cfg from nova.compute import power_state from nova import context as nova_context from nova import exception from nova.openstack.common import excutils from nova.openstack.common.gettextutils import _ from nova.openstack.common import importutils from nova.openstack.common import jsonutils from nova.openstack.common import log as logging from nova.virt.baremetal import baremetal_states from nova.virt.baremetal import db from nova.virt.baremetal import pxe from nova.virt import driver from nova.virt import firewall from nova.virt.libvirt import imagecache LOG = logging.getLogger(__name__) opts = [ cfg.StrOpt('vif_driver', default='nova.virt.baremetal.vif_driver.BareMetalVIFDriver', help='Baremetal VIF driver.'), cfg.StrOpt('volume_driver', default='nova.virt.baremetal.volume_driver.LibvirtVolumeDriver', help='Baremetal volume driver.'), cfg.ListOpt('instance_type_extra_specs', default=[], help='a list of additional capabilities corresponding to ' 'instance_type_extra_specs for this compute ' 'host to advertise. Valid entries are name=value, pairs ' 'For example, "key1:val1, key2:val2"'), cfg.StrOpt('driver', default='nova.virt.baremetal.pxe.PXE', help='Baremetal driver back-end (pxe or tilera)'), cfg.StrOpt('power_manager', default='nova.virt.baremetal.ipmi.IPMI', help='Baremetal power management method'), cfg.StrOpt('tftp_root', default='/tftpboot', help='Baremetal compute node\'s tftp root path'), ] baremetal_group = cfg.OptGroup(name='baremetal', title='Baremetal Options') CONF = cfg.CONF CONF.register_group(baremetal_group) CONF.register_opts(opts, baremetal_group) CONF.import_opt('host', 'nova.netconf') CONF.import_opt('my_ip', 'nova.netconf') DEFAULT_FIREWALL_DRIVER = "%s.%s" % ( firewall.__name__, firewall.NoopFirewallDriver.__name__) def _get_baremetal_node_by_instance_uuid(instance_uuid): ctx = nova_context.get_admin_context() node = db.bm_node_get_by_instance_uuid(ctx, instance_uuid) if node['service_host'] != CONF.host: LOG.error(_("Request for baremetal node %s " "sent to wrong service host") % instance_uuid) raise exception.InstanceNotFound(instance_id=instance_uuid) return node def _update_state(context, node, instance, state): """Update the node state in baremetal DB If instance is not supplied, reset the instance_uuid field for this node. """ values = {'task_state': state} if not instance: values['instance_uuid'] = None values['instance_name'] = None db.bm_node_update(context, node['id'], values) def get_power_manager(**kwargs): cls = importutils.import_class(CONF.baremetal.power_manager) return cls(**kwargs) class BareMetalDriver(driver.ComputeDriver): """BareMetal hypervisor driver.""" capabilities = { "has_imagecache": True, } def __init__(self, virtapi, read_only=False): super(BareMetalDriver, self).__init__(virtapi) self.driver = importutils.import_object( CONF.baremetal.driver, virtapi) self.vif_driver = importutils.import_object( CONF.baremetal.vif_driver) self.firewall_driver = firewall.load_driver( default=DEFAULT_FIREWALL_DRIVER) self.volume_driver = importutils.import_object( CONF.baremetal.volume_driver, virtapi) self.image_cache_manager = imagecache.ImageCacheManager() extra_specs = {} extra_specs["baremetal_driver"] = CONF.baremetal.driver for pair in CONF.baremetal.instance_type_extra_specs: keyval = pair.split(':', 1) keyval[0] = keyval[0].strip() keyval[1] = keyval[1].strip() extra_specs[keyval[0]] = keyval[1] if 'cpu_arch' not in extra_specs: LOG.warning( _('cpu_arch is not found in instance_type_extra_specs')) extra_specs['cpu_arch'] = '' self.extra_specs = extra_specs self.supported_instances = [ (extra_specs['cpu_arch'], 'baremetal', 'baremetal'), ] @classmethod def instance(cls): if not hasattr(cls, '_instance'): cls._instance = cls() return cls._instance def init_host(self, host): return def get_hypervisor_type(self): return 'baremetal' def get_hypervisor_version(self): # TODO(deva): define the version properly elsewhere return 1 def list_instances(self): l = [] context = nova_context.get_admin_context() for node in db.bm_node_get_associated(context, service_host=CONF.host): l.append(node['instance_name']) return l def _require_node(self, instance): """Get a node's uuid out of a manager instance dict. The compute manager is meant to know the node uuid, so missing uuid a significant issue - it may mean we've been passed someone elses data. """ node_uuid = instance.get('node') if not node_uuid: raise exception.NovaException(_( "Baremetal node id not supplied to driver for %r") % instance['uuid']) return node_uuid def _attach_block_devices(self, instance, block_device_info): block_device_mapping = driver.\ block_device_info_get_mapping(block_device_info) for vol in block_device_mapping: connection_info = vol['connection_info'] mountpoint = vol['mount_device'] self.attach_volume(None, connection_info, instance['name'], mountpoint) def _detach_block_devices(self, instance, block_device_info): block_device_mapping = driver.\ block_device_info_get_mapping(block_device_info) for vol in block_device_mapping: connection_info = vol['connection_info'] mountpoint = vol['mount_device'] self.detach_volume( connection_info, instance['name'], mountpoint) def _start_firewall(self, instance, network_info): self.firewall_driver.setup_basic_filtering( instance, network_info) self.firewall_driver.prepare_instance_filter( instance, network_info) self.firewall_driver.apply_instance_filter( instance, network_info) def _stop_firewall(self, instance, network_info): self.firewall_driver.unfilter_instance( instance, network_info) def macs_for_instance(self, instance): context = nova_context.get_admin_context() node_uuid = self._require_node(instance) node = db.bm_node_get_by_node_uuid(context, node_uuid) ifaces = db.bm_interface_get_all_by_bm_node_id(context, node['id']) return set(iface['address'] for iface in ifaces) def spawn(self, context, instance, image_meta, injected_files, admin_password, network_info=None, block_device_info=None): node_uuid = self._require_node(instance) # NOTE(deva): this db method will raise an exception if the node is # already in use. We call it here to ensure no one else # allocates this node before we begin provisioning it. node = db.bm_node_associate_and_update(context, node_uuid, {'instance_uuid': instance['uuid'], 'instance_name': instance['hostname'], 'task_state': baremetal_states.BUILDING}) try: self._plug_vifs(instance, network_info, context=context) self._attach_block_devices(instance, block_device_info) self._start_firewall(instance, network_info) self.driver.cache_images( context, node, instance, admin_password=admin_password, image_meta=image_meta, injected_files=injected_files, network_info=network_info, ) self.driver.activate_bootloader(context, node, instance, network_info=network_info) # NOTE(deva): ensure node is really off before we turn it on # fixes bug https://code.launchpad.net/bugs/1178919 self.power_off(instance, node) self.power_on(context, instance, network_info, block_device_info, node) self.driver.activate_node(context, node, instance) _update_state(context, node, instance, baremetal_states.ACTIVE) except Exception: with excutils.save_and_reraise_exception(): LOG.error(_("Error deploying instance %(instance)s " "on baremetal node %(node)s.") % {'instance': instance['uuid'], 'node': node['uuid']}) # Do not set instance=None yet. This prevents another # spawn() while we are cleaning up. _update_state(context, node, instance, baremetal_states.ERROR) self.driver.deactivate_node(context, node, instance) self.power_off(instance, node) self.driver.deactivate_bootloader(context, node, instance) self.driver.destroy_images(context, node, instance) self._detach_block_devices(instance, block_device_info) self._stop_firewall(instance, network_info) self._unplug_vifs(instance, network_info) _update_state(context, node, None, baremetal_states.DELETED) def reboot(self, context, instance, network_info, reboot_type, block_device_info=None, bad_volumes_callback=None): node = _get_baremetal_node_by_instance_uuid(instance['uuid']) ctx = nova_context.get_admin_context() pm = get_power_manager(node=node, instance=instance) state = pm.reboot_node() if pm.state != baremetal_states.ACTIVE: raise exception.InstanceRebootFailure(_( "Baremetal power manager failed to restart node " "for instance %r") % instance['uuid']) _update_state(ctx, node, instance, state) def destroy(self, instance, network_info, block_device_info=None, context=None): context = nova_context.get_admin_context() try: node = _get_baremetal_node_by_instance_uuid(instance['uuid']) except exception.InstanceNotFound: LOG.warning(_("Destroy called on non-existing instance %s") % instance['uuid']) return try: self.driver.deactivate_node(context, node, instance) self.power_off(instance, node) self.driver.deactivate_bootloader(context, node, instance) self.driver.destroy_images(context, node, instance) self._detach_block_devices(instance, block_device_info) self._stop_firewall(instance, network_info) self._unplug_vifs(instance, network_info) _update_state(context, node, None, baremetal_states.DELETED) except Exception as e: with excutils.save_and_reraise_exception(): try: LOG.error(_("Error from baremetal driver " "during destroy: %s") % e) _update_state(context, node, instance, baremetal_states.ERROR) except Exception: LOG.error(_("Error while recording destroy failure in " "baremetal database: %s") % e) def power_off(self, instance, node=None): """Power off the specified instance.""" if not node: node = _get_baremetal_node_by_instance_uuid(instance['uuid']) pm = get_power_manager(node=node, instance=instance) pm.deactivate_node() if pm.state != baremetal_states.DELETED: raise exception.InstancePowerOffFailure(_( "Baremetal power manager failed to stop node " "for instance %r") % instance['uuid']) pm.stop_console() def power_on(self, context, instance, network_info, block_device_info=None, node=None): """Power on the specified instance.""" if not node: node = _get_baremetal_node_by_instance_uuid(instance['uuid']) pm = get_power_manager(node=node, instance=instance) pm.activate_node() if pm.state != baremetal_states.ACTIVE: raise exception.InstancePowerOnFailure(_( "Baremetal power manager failed to start node " "for instance %r") % instance['uuid']) pm.start_console() def get_volume_connector(self, instance): return self.volume_driver.get_volume_connector(instance) def attach_volume(self, context, connection_info, instance, mountpoint, encryption=None): return self.volume_driver.attach_volume(connection_info, instance, mountpoint) def detach_volume(self, connection_info, instance_name, mountpoint, encryption=None): return self.volume_driver.detach_volume(connection_info, instance_name, mountpoint) def get_info(self, instance): inst_uuid = instance.get('uuid') node = _get_baremetal_node_by_instance_uuid(inst_uuid) pm = get_power_manager(node=node, instance=instance) # NOTE(deva): Power manager may not be able to determine power state # in which case it may return "None" here. ps = pm.is_power_on() if ps: pstate = power_state.RUNNING elif ps is False: pstate = power_state.SHUTDOWN else: pstate = power_state.NOSTATE return {'state': pstate, 'max_mem': node['memory_mb'], 'mem': node['memory_mb'], 'num_cpu': node['cpus'], 'cpu_time': 0} def refresh_security_group_rules(self, security_group_id): self.firewall_driver.refresh_security_group_rules(security_group_id) return True def refresh_security_group_members(self, security_group_id): self.firewall_driver.refresh_security_group_members(security_group_id) return True def refresh_provider_fw_rules(self): self.firewall_driver.refresh_provider_fw_rules() def _node_resource(self, node): vcpus_used = 0 memory_mb_used = 0 local_gb_used = 0 vcpus = node['cpus'] memory_mb = node['memory_mb'] local_gb = node['local_gb'] if node['instance_uuid']: vcpus_used = node['cpus'] memory_mb_used = node['memory_mb'] local_gb_used = node['local_gb'] dic = {'vcpus': vcpus, 'memory_mb': memory_mb, 'local_gb': local_gb, 'vcpus_used': vcpus_used, 'memory_mb_used': memory_mb_used, 'local_gb_used': local_gb_used, 'hypervisor_type': self.get_hypervisor_type(), 'hypervisor_version': self.get_hypervisor_version(), 'hypervisor_hostname': str(node['uuid']), 'cpu_info': 'baremetal cpu', 'supported_instances': jsonutils.dumps(self.supported_instances), 'stats': self.extra_specs } return dic def refresh_instance_security_rules(self, instance): self.firewall_driver.refresh_instance_security_rules(instance) def get_available_resource(self, nodename): context = nova_context.get_admin_context() resource = {} try: node = db.bm_node_get_by_node_uuid(context, nodename) resource = self._node_resource(node) except exception.NodeNotFoundByUUID: pass return resource def ensure_filtering_rules_for_instance(self, instance_ref, network_info): self.firewall_driver.setup_basic_filtering(instance_ref, network_info) self.firewall_driver.prepare_instance_filter(instance_ref, network_info) def unfilter_instance(self, instance_ref, network_info): self.firewall_driver.unfilter_instance(instance_ref, network_info=network_info) def get_host_stats(self, refresh=False): caps = [] context = nova_context.get_admin_context() nodes = db.bm_node_get_all(context, service_host=CONF.host) for node in nodes: res = self._node_resource(node) nodename = str(node['uuid']) data = {} data['vcpus'] = res['vcpus'] data['vcpus_used'] = res['vcpus_used'] data['cpu_info'] = res['cpu_info'] data['disk_total'] = res['local_gb'] data['disk_used'] = res['local_gb_used'] data['disk_available'] = res['local_gb'] - res['local_gb_used'] data['host_memory_total'] = res['memory_mb'] data['host_memory_free'] = res['memory_mb'] - res['memory_mb_used'] data['hypervisor_type'] = res['hypervisor_type'] data['hypervisor_version'] = res['hypervisor_version'] data['hypervisor_hostname'] = nodename data['supported_instances'] = self.supported_instances data.update(self.extra_specs) data['host'] = CONF.host data['node'] = nodename # TODO(NTTdocomo): put node's extra specs here caps.append(data) return caps def plug_vifs(self, instance, network_info): """Plugin VIFs into networks.""" self._plug_vifs(instance, network_info) def _plug_vifs(self, instance, network_info, context=None): if not context: context = nova_context.get_admin_context() node = _get_baremetal_node_by_instance_uuid(instance['uuid']) if node: pifs = db.bm_interface_get_all_by_bm_node_id(context, node['id']) for pif in pifs: if pif['vif_uuid']: db.bm_interface_set_vif_uuid(context, pif['id'], None) for vif in network_info: self.vif_driver.plug(instance, vif) def _unplug_vifs(self, instance, network_info): for vif in network_info: self.vif_driver.unplug(instance, vif) def manage_image_cache(self, context, all_instances): """Manage the local cache of images.""" self.image_cache_manager.verify_base_images(context, all_instances) def get_console_output(self, instance): node = _get_baremetal_node_by_instance_uuid(instance['uuid']) return self.driver.get_console_output(node, instance) def get_available_nodes(self, refresh=False): context = nova_context.get_admin_context() return [str(n['uuid']) for n in db.bm_node_get_all(context, service_host=CONF.host)] def dhcp_options_for_instance(self, instance): # NOTE(deva): This only works for PXE driver currently: # If not running the PXE driver, you should not enable # DHCP updates in nova.conf. bootfile_name = pxe.get_pxe_bootfile_name(instance) opts = [{'opt_name': 'bootfile-name', 'opt_value': bootfile_name}, {'opt_name': 'server-ip-address', 'opt_value': CONF.my_ip}, {'opt_name': 'tftp-server', 'opt_value': CONF.my_ip} ] return opts
apache-2.0
QGB/shadowsocks
shadowsocks/encrypt.py
990
5180
#!/usr/bin/env python # # Copyright 2012-2015 clowwindy # # 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 __future__ import absolute_import, division, print_function, \ with_statement import os import sys import hashlib import logging from shadowsocks import common from shadowsocks.crypto import rc4_md5, openssl, sodium, table method_supported = {} method_supported.update(rc4_md5.ciphers) method_supported.update(openssl.ciphers) method_supported.update(sodium.ciphers) method_supported.update(table.ciphers) def random_string(length): return os.urandom(length) cached_keys = {} def try_cipher(key, method=None): Encryptor(key, method) def EVP_BytesToKey(password, key_len, iv_len): # equivalent to OpenSSL's EVP_BytesToKey() with count 1 # so that we make the same key and iv as nodejs version cached_key = '%s-%d-%d' % (password, key_len, iv_len) r = cached_keys.get(cached_key, None) if r: return r m = [] i = 0 while len(b''.join(m)) < (key_len + iv_len): md5 = hashlib.md5() data = password if i > 0: data = m[i - 1] + password md5.update(data) m.append(md5.digest()) i += 1 ms = b''.join(m) key = ms[:key_len] iv = ms[key_len:key_len + iv_len] cached_keys[cached_key] = (key, iv) return key, iv class Encryptor(object): def __init__(self, key, method): self.key = key self.method = method self.iv = None self.iv_sent = False self.cipher_iv = b'' self.decipher = None method = method.lower() self._method_info = self.get_method_info(method) if self._method_info: self.cipher = self.get_cipher(key, method, 1, random_string(self._method_info[1])) else: logging.error('method %s not supported' % method) sys.exit(1) def get_method_info(self, method): method = method.lower() m = method_supported.get(method) return m def iv_len(self): return len(self.cipher_iv) def get_cipher(self, password, method, op, iv): password = common.to_bytes(password) m = self._method_info if m[0] > 0: key, iv_ = EVP_BytesToKey(password, m[0], m[1]) else: # key_length == 0 indicates we should use the key directly key, iv = password, b'' iv = iv[:m[1]] if op == 1: # this iv is for cipher not decipher self.cipher_iv = iv[:m[1]] return m[2](method, key, iv, op) def encrypt(self, buf): if len(buf) == 0: return buf if self.iv_sent: return self.cipher.update(buf) else: self.iv_sent = True return self.cipher_iv + self.cipher.update(buf) def decrypt(self, buf): if len(buf) == 0: return buf if self.decipher is None: decipher_iv_len = self._method_info[1] decipher_iv = buf[:decipher_iv_len] self.decipher = self.get_cipher(self.key, self.method, 0, iv=decipher_iv) buf = buf[decipher_iv_len:] if len(buf) == 0: return buf return self.decipher.update(buf) def encrypt_all(password, method, op, data): result = [] method = method.lower() (key_len, iv_len, m) = method_supported[method] if key_len > 0: key, _ = EVP_BytesToKey(password, key_len, iv_len) else: key = password if op: iv = random_string(iv_len) result.append(iv) else: iv = data[:iv_len] data = data[iv_len:] cipher = m(method, key, iv, op) result.append(cipher.update(data)) return b''.join(result) CIPHERS_TO_TEST = [ 'aes-128-cfb', 'aes-256-cfb', 'rc4-md5', 'salsa20', 'chacha20', 'table', ] def test_encryptor(): from os import urandom plain = urandom(10240) for method in CIPHERS_TO_TEST: logging.warn(method) encryptor = Encryptor(b'key', method) decryptor = Encryptor(b'key', method) cipher = encryptor.encrypt(plain) plain2 = decryptor.decrypt(cipher) assert plain == plain2 def test_encrypt_all(): from os import urandom plain = urandom(10240) for method in CIPHERS_TO_TEST: logging.warn(method) cipher = encrypt_all(b'key', method, 1, plain) plain2 = encrypt_all(b'key', method, 0, cipher) assert plain == plain2 if __name__ == '__main__': test_encrypt_all() test_encryptor()
apache-2.0
Silmathoron/nest-simulator
pynest/nest/tests/test_json.py
7
2151
# -*- coding: utf-8 -*- # # test_json.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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. # # NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. """ Test if json output work properly """ import unittest import nest @nest.ll_api.check_stack class StatusTestCase(unittest.TestCase): """Tests of data in JSON format""" def test_GetDefaults_JSON(self): """JSON data of GetDefaults""" # sli_neuron does not work under PyNEST models = (m for m in nest.Models() if m != 'sli_neuron') for m in models: d_json = nest.GetDefaults(m, output='json') self.assertIsInstance(d_json, str) d = nest.GetDefaults(m) d_json = nest.hl_api.to_json(d) self.assertIsInstance(d_json, str) def test_GetKernelStatus_JSON(self): """JSON data of KernelStatus""" d = nest.GetKernelStatus() d_json = nest.hl_api.to_json(d) self.assertIsInstance(d_json, str) def test_GetStatus_JSON(self): """JSON data of GetStatus""" # sli_neuron does not work under PyNEST models = (m for m in nest.Models('nodes') if m != 'sli_neuron') for m in models: nest.ResetKernel() n = nest.Create(m) d_json = nest.GetStatus(n, output='json') self.assertIsInstance(d_json, str) def suite(): suite = unittest.makeSuite(StatusTestCase, 'test') return suite def run(): runner = unittest.TextTestRunner(verbosity=2) runner.run(suite()) if __name__ == "__main__": run()
gpl-2.0
GaussDing/django
tests/template_tests/filter_tests/test_floatformat.py
345
4480
# -*- coding: utf-8 -*- from __future__ import unicode_literals from decimal import Decimal, localcontext from unittest import expectedFailure from django.template.defaultfilters import floatformat from django.test import SimpleTestCase from django.utils import six from django.utils.safestring import mark_safe from ..utils import setup class FloatformatTests(SimpleTestCase): @setup({'floatformat01': '{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}{% endautoescape %}'}) def test_floatformat01(self): output = self.engine.render_to_string('floatformat01', {"a": "1.42", "b": mark_safe("1.42")}) self.assertEqual(output, "1.4 1.4") @setup({'floatformat02': '{{ a|floatformat }} {{ b|floatformat }}'}) def test_floatformat02(self): output = self.engine.render_to_string('floatformat02', {"a": "1.42", "b": mark_safe("1.42")}) self.assertEqual(output, "1.4 1.4") class FunctionTests(SimpleTestCase): def test_inputs(self): self.assertEqual(floatformat(7.7), '7.7') self.assertEqual(floatformat(7.0), '7') self.assertEqual(floatformat(0.7), '0.7') self.assertEqual(floatformat(0.07), '0.1') self.assertEqual(floatformat(0.007), '0.0') self.assertEqual(floatformat(0.0), '0') self.assertEqual(floatformat(7.7, 3), '7.700') self.assertEqual(floatformat(6.000000, 3), '6.000') self.assertEqual(floatformat(6.200000, 3), '6.200') self.assertEqual(floatformat(6.200000, -3), '6.200') self.assertEqual(floatformat(13.1031, -3), '13.103') self.assertEqual(floatformat(11.1197, -2), '11.12') self.assertEqual(floatformat(11.0000, -2), '11') self.assertEqual(floatformat(11.000001, -2), '11.00') self.assertEqual(floatformat(8.2798, 3), '8.280') self.assertEqual(floatformat(5555.555, 2), '5555.56') self.assertEqual(floatformat(001.3000, 2), '1.30') self.assertEqual(floatformat(0.12345, 2), '0.12') self.assertEqual(floatformat(Decimal('555.555'), 2), '555.56') self.assertEqual(floatformat(Decimal('09.000')), '9') self.assertEqual(floatformat('foo'), '') self.assertEqual(floatformat(13.1031, 'bar'), '13.1031') self.assertEqual(floatformat(18.125, 2), '18.13') self.assertEqual(floatformat('foo', 'bar'), '') self.assertEqual(floatformat('¿Cómo esta usted?'), '') self.assertEqual(floatformat(None), '') def test_zero_values(self): """ Check that we're not converting to scientific notation. """ self.assertEqual(floatformat(0, 6), '0.000000') self.assertEqual(floatformat(0, 7), '0.0000000') self.assertEqual(floatformat(0, 10), '0.0000000000') self.assertEqual(floatformat(0.000000000000000000015, 20), '0.00000000000000000002') def test_infinity(self): pos_inf = float(1e30000) self.assertEqual(floatformat(pos_inf), six.text_type(pos_inf)) neg_inf = float(-1e30000) self.assertEqual(floatformat(neg_inf), six.text_type(neg_inf)) nan = pos_inf / pos_inf self.assertEqual(floatformat(nan), six.text_type(nan)) def test_float_dunder_method(self): class FloatWrapper(object): def __init__(self, value): self.value = value def __float__(self): return self.value self.assertEqual(floatformat(FloatWrapper(11.000001), -2), '11.00') def test_low_decimal_precision(self): """ #15789 """ with localcontext() as ctx: ctx.prec = 2 self.assertEqual(floatformat(1.2345, 2), '1.23') self.assertEqual(floatformat(15.2042, -3), '15.204') self.assertEqual(floatformat(1.2345, '2'), '1.23') self.assertEqual(floatformat(15.2042, '-3'), '15.204') self.assertEqual(floatformat(Decimal('1.2345'), 2), '1.23') self.assertEqual(floatformat(Decimal('15.2042'), -3), '15.204') def test_many_zeroes(self): self.assertEqual(floatformat(1.00000000000000015, 16), '1.0000000000000002') if six.PY2: # The above test fails because of Python 2's float handling. Floats # with many zeroes after the decimal point should be passed in as # another type such as unicode or Decimal. test_many_zeroes = expectedFailure(test_many_zeroes)
bsd-3-clause
isandlaTech/cohorte-demos
led/dump/led-demo-yun/cohorte/dist/cohorte-1.0.0-20141216.234517-57-python-distribution/repo/cohorte/forker/__init__.py
4
4326
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ COHORTE Forker package Contains all modules and packages specific to the forker :author: Thomas Calmant :license: Apache Software License 2.0 .. Copyright 2014 isandlaTech 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. """ # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ FORKER_NAME = 'cohorte.internals.forker' """ All forkers have the same name """ # ------------------------------------------------------------------------------ SERVICE_FORKER_LISTENER = 'cohorte.forker.listener' """ Specification of a forker event listener: - forker_ready(uid, node) - forker_gone(uid, node) """ SERVICE_STARTER = 'cohorte.forker.starter' """ Specification of an isolate starter """ PROP_STARTER_KINDS = 'forker.starter.kinds' """ Kinds of isolates handled by the starter """ SERVICE_WATCHER = 'cohorte.forker.watcher' """ Specification of an isolate watcher service """ SERVICE_WATCHER_LISTENER = 'cohorte.forker.watcher.listener' """ Specification of an isolate that listens to a watcher service """ # ------------------------------------------------------------------------------ __SIGNALS_FORKER_PREFIX = "/cohorte/forker" """ Prefix to all forker signals """ SIGNALS_FORKER_PATTERN = "{0}/*".format(__SIGNALS_FORKER_PREFIX) """ Pattern to catch all forker signals """ SIGNAL_PING_ISOLATE = "{0}/ping".format(__SIGNALS_FORKER_PREFIX) """ Ping isolate request: - sent by any isolate - contains the UID of the isolate to ping """ SIGNAL_START_ISOLATE = "{0}/start".format(__SIGNALS_FORKER_PREFIX) """ Start isolate request: - sent by the monitor - contains the whole configuration of the isolate to start (with a UID) """ SIGNAL_KILL_ISOLATE = "{0}/kill".format(__SIGNALS_FORKER_PREFIX) """ Request to the forker to stop or kill the given isolate - sent by the monitor, to the forker associated to the isolate - contains the UID of the isolate to stop. """ SIGNAL_STOP_FORKER = "{0}/stop".format(__SIGNALS_FORKER_PREFIX) """ A monitor tells a forker to stop itself - sent by the monitor, to one or more forkers - no content """ SIGNAL_FORKER_STOPPING = "{0}/stopping".format(__SIGNALS_FORKER_PREFIX) """ A forker indicates that it will stop soon - sent by the stopping forker, to all - contains the UID of the forker, its node and the list of its isolates (UIDs) """ SIGNAL_FORKER_LOST = "{0}/lost".format(__SIGNALS_FORKER_PREFIX) """ A monitor indicates that it lost contact with a forker - sent by the monitor, to all - contains the UID of the forker, its node and the list of its isolates (UIDs) """ # ------------------------------------------------------------------------------ REQUEST_NO_MATCHING_FORKER = -20 """ No forker for the node """ REQUEST_NO_PROCESS_REF = 2 """ No reference to the isolate process, unknown state """ REQUEST_NO_WATCHER = 3 """ No isolate watcher could be started (active isolate waiter) """ REQUEST_ERROR = -3 """ Error sending the request """ REQUEST_NO_RESULT = -2 """ Forker didn't returned any result """ REQUEST_TIMEOUT = -1 """ Forker timed out """ REQUEST_SUCCESS = 0 """ Successful operation """ REQUEST_ALREADY_RUNNING = 1 """ The isolate is already running """ REQUEST_RUNNER_EXCEPTION = 4 """ An error occurred calling the forker """ REQUEST_UNKNOWN_KIND = 5 """ Unknown kind of isolate """ REQUEST_SUCCESSES = (REQUEST_SUCCESS, REQUEST_ALREADY_RUNNING) """ A request is a success if the isolate is running """ # ------------------------------------------------------------------------------ PING_ALIVE = 0 """ Isolate is alive (response to ping) """ PING_DEAD = 1 """ Process is dead (not running) """ PING_STUCK = 2 """ Process is stuck (running, but not responding) """
apache-2.0
DataDog/wal-e
tests/blackbox.py
5
6326
import os import pytest import s3_integration_help import sys from wal_e import cmd _PREFIX_VARS = ['WALE_S3_PREFIX', 'WALE_WABS_PREFIX', 'WALE_SWIFT_PREFIX'] _AWS_CRED_ENV_VARS = ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN'] class AwsTestConfig(object): name = 'aws' def __init__(self, request): self.env_vars = {} self.monkeypatch = request.getfuncargvalue('monkeypatch') for name in _AWS_CRED_ENV_VARS: maybe_value = os.getenv(name) self.env_vars[name] = maybe_value def patch(self, test_name, default_test_bucket): # Scrub WAL-E prefixes left around in the user's environment to # prevent unexpected results. for name in _PREFIX_VARS: self.monkeypatch.delenv(name, raising=False) # Set other credentials. for name, value in self.env_vars.iteritems(): if value is None: self.monkeypatch.delenv(name, raising=False) else: self.monkeypatch.setenv(name, value) self.monkeypatch.setenv('WALE_S3_PREFIX', 's3://{0}/{1}' .format(default_test_bucket, test_name)) def main(self, *args): self.monkeypatch.setattr(sys, 'argv', ['wal-e'] + list(args)) return cmd.main() class AwsTestConfigSetImpl(AwsTestConfig): name = 'aws+impl' # The same as AwsTestConfig but with a WALE_S3_ENDPOINT override. def patch(self, test_name, default_test_bucket): self.monkeypatch.setenv( 'WALE_S3_ENDPOINT', 'http+path://s3-us-west-1.amazonaws.com:80') return AwsTestConfig.patch(self, test_name, default_test_bucket) class AwsInstanceProfileTestConfig(object): name = 'aws+instance-profile' def __init__(self, request): self.request = request self.monkeypatch = request.getfuncargvalue('monkeypatch') def patch(self, test_name, default_test_bucket): # Get STS-vended credentials to stand in for Instance Profile # credentials before scrubbing the environment of AWS # environment variables. c = s3_integration_help.sts_conn() policy = s3_integration_help.make_policy(default_test_bucket, test_name) fed = c.get_federation_token(default_test_bucket, policy=policy) # Scrub AWS environment-variable based cred to make sure the # instance profile path is used. for name in _AWS_CRED_ENV_VARS: self.monkeypatch.delenv(name, raising=False) self.monkeypatch.setenv('WALE_S3_PREFIX', 's3://{0}/{1}' .format(default_test_bucket, test_name)) # Patch boto.utils.get_instance_metadata to return a ginned up # credential. m = { "Code": "Success", "LastUpdated": "3014-01-11T02:13:53Z", "Type": "AWS-HMAC", "AccessKeyId": fed.credentials.access_key, "SecretAccessKey": fed.credentials.secret_key, "Token": fed.credentials.session_token, "Expiration": "3014-01-11T08:16:59Z" } from boto import provider self.monkeypatch.setattr(provider.Provider, '_credentials_need_refresh', lambda self: False) # Different versions of boto require slightly different return # formats. import test_aws_instance_profiles if test_aws_instance_profiles.boto_flat_metadata(): m = {'irrelevant': m} else: m = {'iam': {'security-credentials': {'irrelevant': m}}} from boto import utils self.monkeypatch.setattr(utils, 'get_instance_metadata', lambda *args, **kwargs: m) def main(self, *args): self.monkeypatch.setattr( sys, 'argv', ['wal-e', '--aws-instance-profile'] + list(args)) return cmd.main() def _make_fixture_param_and_ids(): ret = { 'params': [], 'ids': [], } def _add_config(c): ret['params'].append(c) ret['ids'].append(c.name) if not s3_integration_help.no_real_s3_credentials(): _add_config(AwsTestConfig) _add_config(AwsTestConfigSetImpl) _add_config(AwsInstanceProfileTestConfig) return ret @pytest.fixture(**_make_fixture_param_and_ids()) def config(request, monkeypatch, default_test_bucket): config = request.param(request) config.patch(request.node.name, default_test_bucket) return config class NoopPgBackupStatements(object): @classmethod def run_start_backup(cls): name = '0' * 8 * 3 offset = '0' * 8 return {'file_name': name, 'file_offset': offset, 'pg_xlogfile_name_offset': 'START-BACKUP-FAKE-XLOGPOS'} @classmethod def run_stop_backup(cls): name = '1' * 8 * 3 offset = '1' * 8 return {'file_name': name, 'file_offset': offset, 'pg_xlogfile_name_offset': 'STOP-BACKUP-FAKE-XLOGPOS'} @classmethod def pg_version(cls): return {'version': 'FAKE-PG-VERSION'} @pytest.fixture def noop_pg_backup_statements(monkeypatch): import wal_e.operator.backup monkeypatch.setattr(wal_e.operator.backup, 'PgBackupStatements', NoopPgBackupStatements) # psql binary test will fail if local pg env isn't set up monkeypatch.setattr(wal_e.cmd, 'external_program_check', lambda *args, **kwargs: None) @pytest.fixture def small_push_dir(tmpdir): """Create a small pg data directory-alike""" contents = 'abcdefghijlmnopqrstuvwxyz\n' * 10000 push_dir = tmpdir.join('push-from').ensure(dir=True) push_dir.join('arbitrary-file').write(contents) # Construct a symlink a non-existent path. This provoked a crash # at one time. push_dir.join('pg_xlog').mksymlinkto('/tmp/wal-e-test-must-not-exist') # Holy crap, the tar segmentation code relies on the directory # containing files without a common prefix...the first character # of two files must be distinct! push_dir.join('holy-smokes').ensure() return push_dir
bsd-3-clause
bkrukowski/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/steps/applywatchlist_unittest.py
124
2302
# Copyright (C) 2011 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. import unittest2 as unittest from webkitpy.common.system.outputcapture import OutputCapture from webkitpy.tool.mocktool import MockOptions, MockTool from webkitpy.tool.steps.applywatchlist import ApplyWatchList class ApplyWatchListTest(unittest.TestCase): def test_apply_watch_list_local(self): capture = OutputCapture() step = ApplyWatchList(MockTool(log_executive=True), MockOptions()) state = { 'bug_id': '50001', 'diff': 'The diff', } expected_logs = """MockWatchList: determine_cc_and_messages MOCK bug comment: bug_id=50001, cc=set(['levin@chromium.org']) --- Begin comment --- Message2. --- End comment --- """ capture.assert_outputs(self, step.run, [state], expected_logs=expected_logs)
bsd-3-clause
Jgarcia-IAS/SAT
openerp/addons-extra/odoo-pruebas/odoo-server/addons-extra/hr_payroll_co_planning/warning.py
6
3356
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2013 Interconsulting S.A. e Innovatecsa SAS. (http://interconsulting.com.co). # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ WARNING_TYPES = [('warning','Warning'),('info','Information'),('error','Error')] class warning(osv.osv): _name = 'warning' _description = 'warning' _columns = { 'type': fields.selection(WARNING_TYPES, string='Type', readonly=True), 'title': fields.char(string="Title", size=100, readonly=True), 'message': fields.text(string="Message", readonly=True), } _req_name = 'title' def _get_view_id(self, cr, uid): """Get the view id @return: view id, or False if no view found """ res = self.pool.get('ir.model.data').get_object_reference(cr, uid,'hr_payroll_co_planning','warning_form') return res and res[1] or False def message(self, cr, uid, id, context): message = self.browse(cr, uid, id) message_type = [t[1]for t in WARNING_TYPES if message.type == t[0]][0] print '%s: %s' % (_(message_type), _(message.title)) res = { 'name': '%s: %s' % (_(message_type), _(message.title)), 'view_type': 'form', 'view_mode': 'form', 'view_id': self._get_view_id(cr, uid), 'res_model': 'warning', 'domain': [], 'context': context, 'type': 'ir.actions.act_window', 'target': 'new', 'res_id': message.id } return res def warning(self, cr, uid, title, message, context=None): id = self.create(cr, uid, {'title': title, 'message': message, 'type': 'warning'}) res = self.message(cr, uid, id, context) return res def info(self, cr, uid, title, message, context=None): id = self.create(cr, uid, {'title': title, 'message': message, 'type': 'info'}) res = self.message(cr, uid, id, context) return res def error(self, cr, uid, title, message, context=None): id = self.create(cr, uid, {'title': title, 'message': message, 'type': 'error'}) res = self.message(cr, uid, id, context) return res
agpl-3.0
NMGRL/pychron
pychron/ml/tasks/actions.py
1
1114
# =============================================================================== # Copyright 2019 Jake Ross # # 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. # =============================================================================== # ============= enthought library imports ======================= from traits.api import List, Int, HasTraits, Str, Bool from traitsui.api import View, UItem, Item, HGroup, VGroup # ============= standard library imports ======================== # ============= local library imports ========================== # ============= EOF =============================================
apache-2.0
nathania/networkx
networkx/algorithms/__init__.py
21
3095
from networkx.algorithms.assortativity import * from networkx.algorithms.block import * from networkx.algorithms.boundary import * from networkx.algorithms.centrality import * from networkx.algorithms.cluster import * from networkx.algorithms.clique import * from networkx.algorithms.community import * from networkx.algorithms.components import * from networkx.algorithms.coloring import * from networkx.algorithms.core import * from networkx.algorithms.cycles import * from networkx.algorithms.dag import * from networkx.algorithms.distance_measures import * from networkx.algorithms.dominance import * from networkx.algorithms.dominating import * from networkx.algorithms.hierarchy import * from networkx.algorithms.hybrid import * from networkx.algorithms.matching import * from networkx.algorithms.minors import * from networkx.algorithms.mis import * from networkx.algorithms.link_analysis import * from networkx.algorithms.link_prediction import * from networkx.algorithms.operators import * from networkx.algorithms.shortest_paths import * from networkx.algorithms.smetric import * from networkx.algorithms.triads import * from networkx.algorithms.traversal import * from networkx.algorithms.isolate import * from networkx.algorithms.euler import * from networkx.algorithms.vitality import * from networkx.algorithms.chordal import * from networkx.algorithms.richclub import * from networkx.algorithms.distance_regular import * from networkx.algorithms.swap import * from networkx.algorithms.graphical import * from networkx.algorithms.simple_paths import * import networkx.algorithms.assortativity import networkx.algorithms.bipartite import networkx.algorithms.centrality import networkx.algorithms.cluster import networkx.algorithms.clique import networkx.algorithms.components import networkx.algorithms.connectivity import networkx.algorithms.coloring import networkx.algorithms.flow import networkx.algorithms.isomorphism import networkx.algorithms.link_analysis import networkx.algorithms.shortest_paths import networkx.algorithms.traversal import networkx.algorithms.chordal import networkx.algorithms.operators import networkx.algorithms.tree # bipartite from networkx.algorithms.bipartite import (projected_graph, project, is_bipartite, complete_bipartite_graph) # connectivity from networkx.algorithms.connectivity import (minimum_edge_cut, minimum_node_cut, average_node_connectivity, edge_connectivity, node_connectivity, stoer_wagner, all_pairs_node_connectivity, all_node_cuts, k_components) # isomorphism from networkx.algorithms.isomorphism import (is_isomorphic, could_be_isomorphic, fast_could_be_isomorphic, faster_could_be_isomorphic) # flow from networkx.algorithms.flow import (maximum_flow, maximum_flow_value, minimum_cut, minimum_cut_value, capacity_scaling, network_simplex, min_cost_flow_cost, max_flow_min_cost, min_cost_flow, cost_of_flow) from .tree.recognition import * from .tree.mst import * from .tree.branchings import ( maximum_branching, minimum_branching, maximum_spanning_arborescence, minimum_spanning_arborescence )
bsd-3-clause
Dandandan/wikiprogramming
jsrepl/extern/python/reloop-closured/lib/python2.7/encodings/palmos.py
647
2936
""" Python Character Mapping Codec for PalmOS 3.5. Written by Sjoerd Mullender (sjoerd@acm.org); based on iso8859_15.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_map)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='palmos', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) # The PalmOS character set is mostly iso-8859-1 with some differences. decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x0089: 0x2030, # PER MILLE SIGN 0x008a: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: 0x0152, # LATIN CAPITAL LIGATURE OE 0x008d: 0x2666, # BLACK DIAMOND SUIT 0x008e: 0x2663, # BLACK CLUB SUIT 0x008f: 0x2665, # BLACK HEART SUIT 0x0090: 0x2660, # BLACK SPADE SUIT 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x02dc, # SMALL TILDE 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x009c: 0x0153, # LATIN SMALL LIGATURE OE 0x009f: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
mit
rlutz/xorn
src/backend/gnet_bae.py
1
1626
# gaf.netlist - gEDA Netlist Extraction and Generation # Copyright (C) 1998-2010 Ales Hvezda # Copyright (C) 1998-2010 gEDA Contributors (see ChangeLog for details) # Copyright (C) 2013-2019 Roland Lutz # # 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. # Bartels Format # Layout board; # PARTS # part : footprint; # CONNECT # /net1/ uref.pin=uref.pin=uref.pin=...uref.pin; # /net2/ PRIORITY(1..100) MINDIST(mm) ROUTWIDTH(mm) uref.pin(width_mm)=...; # END. def run(f, netlist): f.write('LAYOUT board;\n') f.write('PARTS\n') for package in reversed(netlist.packages): f.write(' %s : %s;\n' % ( package.refdes, package.get_attribute('footprint', 'unknown'))) f.write('CONNECT\n') for net in reversed(netlist.nets): f.write(" /'%s'/ %s;\n" % ( net.name, '='.join('%s.%s' % (pin.package.refdes, pin.number) for pin in reversed(net.connections)))) f.write('END.\n')
gpl-2.0
marcoarruda/MissionPlanner
Lib/smtpd.py
50
19098
#! /usr/bin/env python """An RFC 2821 smtp proxy. Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]] Options: --nosetuid -n This program generally tries to setuid `nobody', unless this flag is set. The setuid call will fail if this program is not run as root (in which case, use this flag). --version -V Print the version number and exit. --class classname -c classname Use `classname' as the concrete SMTP proxy class. Uses `PureProxy' by default. --debug -d Turn on debugging prints. --help -h Print this message and exit. Version: %(__version__)s If localhost is not given then `localhost' is used, and if localport is not given then 8025 is used. If remotehost is not given then `localhost' is used, and if remoteport is not given, then 25 is used. """ # Overview: # # This file implements the minimal SMTP protocol as defined in RFC 821. It # has a hierarchy of classes which implement the backend functionality for the # smtpd. A number of classes are provided: # # SMTPServer - the base class for the backend. Raises NotImplementedError # if you try to use it. # # DebuggingServer - simply prints each message it receives on stdout. # # PureProxy - Proxies all messages to a real smtpd which does final # delivery. One known problem with this class is that it doesn't handle # SMTP errors from the backend server at all. This should be fixed # (contributions are welcome!). # # MailmanProxy - An experimental hack to work with GNU Mailman # <www.list.org>. Using this server as your real incoming smtpd, your # mailhost will automatically recognize and accept mail destined to Mailman # lists when those lists are created. Every message not destined for a list # gets forwarded to a real backend smtpd, as with PureProxy. Again, errors # are not handled correctly yet. # # Please note that this script requires Python 2.0 # # Author: Barry Warsaw <barry@python.org> # # TODO: # # - support mailbox delivery # - alias files # - ESMTP # - handle error codes from the backend smtpd import sys import os import errno import getopt import time import socket import asyncore import asynchat __all__ = ["SMTPServer","DebuggingServer","PureProxy","MailmanProxy"] program = sys.argv[0] __version__ = 'Python SMTP proxy version 0.2' class Devnull: def write(self, msg): pass def flush(self): pass DEBUGSTREAM = Devnull() NEWLINE = '\n' EMPTYSTRING = '' COMMASPACE = ', ' def usage(code, msg=''): print >> sys.stderr, __doc__ % globals() if msg: print >> sys.stderr, msg sys.exit(code) class SMTPChannel(asynchat.async_chat): COMMAND = 0 DATA = 1 def __init__(self, server, conn, addr): asynchat.async_chat.__init__(self, conn) self.__server = server self.__conn = conn self.__addr = addr self.__line = [] self.__state = self.COMMAND self.__greeting = 0 self.__mailfrom = None self.__rcpttos = [] self.__data = '' self.__fqdn = socket.getfqdn() try: self.__peer = conn.getpeername() except socket.error, err: # a race condition may occur if the other end is closing # before we can get the peername self.close() if err[0] != errno.ENOTCONN: raise return print >> DEBUGSTREAM, 'Peer:', repr(self.__peer) self.push('220 %s %s' % (self.__fqdn, __version__)) self.set_terminator('\r\n') # Overrides base class for convenience def push(self, msg): asynchat.async_chat.push(self, msg + '\r\n') # Implementation of base class abstract method def collect_incoming_data(self, data): self.__line.append(data) # Implementation of base class abstract method def found_terminator(self): line = EMPTYSTRING.join(self.__line) print >> DEBUGSTREAM, 'Data:', repr(line) self.__line = [] if self.__state == self.COMMAND: if not line: self.push('500 Error: bad syntax') return method = None i = line.find(' ') if i < 0: command = line.upper() arg = None else: command = line[:i].upper() arg = line[i+1:].strip() method = getattr(self, 'smtp_' + command, None) if not method: self.push('502 Error: command "%s" not implemented' % command) return method(arg) return else: if self.__state != self.DATA: self.push('451 Internal confusion') return # Remove extraneous carriage returns and de-transparency according # to RFC 821, Section 4.5.2. data = [] for text in line.split('\r\n'): if text and text[0] == '.': data.append(text[1:]) else: data.append(text) self.__data = NEWLINE.join(data) status = self.__server.process_message(self.__peer, self.__mailfrom, self.__rcpttos, self.__data) self.__rcpttos = [] self.__mailfrom = None self.__state = self.COMMAND self.set_terminator('\r\n') if not status: self.push('250 Ok') else: self.push(status) # SMTP and ESMTP commands def smtp_HELO(self, arg): if not arg: self.push('501 Syntax: HELO hostname') return if self.__greeting: self.push('503 Duplicate HELO/EHLO') else: self.__greeting = arg self.push('250 %s' % self.__fqdn) def smtp_NOOP(self, arg): if arg: self.push('501 Syntax: NOOP') else: self.push('250 Ok') def smtp_QUIT(self, arg): # args is ignored self.push('221 Bye') self.close_when_done() # factored def __getaddr(self, keyword, arg): address = None keylen = len(keyword) if arg[:keylen].upper() == keyword: address = arg[keylen:].strip() if not address: pass elif address[0] == '<' and address[-1] == '>' and address != '<>': # Addresses can be in the form <person@dom.com> but watch out # for null address, e.g. <> address = address[1:-1] return address def smtp_MAIL(self, arg): print >> DEBUGSTREAM, '===> MAIL', arg address = self.__getaddr('FROM:', arg) if arg else None if not address: self.push('501 Syntax: MAIL FROM:<address>') return if self.__mailfrom: self.push('503 Error: nested MAIL command') return self.__mailfrom = address print >> DEBUGSTREAM, 'sender:', self.__mailfrom self.push('250 Ok') def smtp_RCPT(self, arg): print >> DEBUGSTREAM, '===> RCPT', arg if not self.__mailfrom: self.push('503 Error: need MAIL command') return address = self.__getaddr('TO:', arg) if arg else None if not address: self.push('501 Syntax: RCPT TO: <address>') return self.__rcpttos.append(address) print >> DEBUGSTREAM, 'recips:', self.__rcpttos self.push('250 Ok') def smtp_RSET(self, arg): if arg: self.push('501 Syntax: RSET') return # Resets the sender, recipients, and data, but not the greeting self.__mailfrom = None self.__rcpttos = [] self.__data = '' self.__state = self.COMMAND self.push('250 Ok') def smtp_DATA(self, arg): if not self.__rcpttos: self.push('503 Error: need RCPT command') return if arg: self.push('501 Syntax: DATA') return self.__state = self.DATA self.set_terminator('\r\n.\r\n') self.push('354 End data with <CR><LF>.<CR><LF>') class SMTPServer(asyncore.dispatcher): def __init__(self, localaddr, remoteaddr): self._localaddr = localaddr self._remoteaddr = remoteaddr asyncore.dispatcher.__init__(self) try: self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # try to re-use a server port if possible self.set_reuse_addr() self.bind(localaddr) self.listen(5) except: # cleanup asyncore.socket_map before raising self.close() raise else: print >> DEBUGSTREAM, \ '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( self.__class__.__name__, time.ctime(time.time()), localaddr, remoteaddr) def handle_accept(self): pair = self.accept() if pair is not None: conn, addr = pair print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr) channel = SMTPChannel(self, conn, addr) # API for "doing something useful with the message" def process_message(self, peer, mailfrom, rcpttos, data): """Override this abstract method to handle messages from the client. peer is a tuple containing (ipaddr, port) of the client that made the socket connection to our smtp port. mailfrom is the raw address the client claims the message is coming from. rcpttos is a list of raw addresses the client wishes to deliver the message to. data is a string containing the entire full text of the message, headers (if supplied) and all. It has been `de-transparencied' according to RFC 821, Section 4.5.2. In other words, a line containing a `.' followed by other text has had the leading dot removed. This function should return None, for a normal `250 Ok' response; otherwise it returns the desired response string in RFC 821 format. """ raise NotImplementedError class DebuggingServer(SMTPServer): # Do something with the gathered message def process_message(self, peer, mailfrom, rcpttos, data): inheaders = 1 lines = data.split('\n') print '---------- MESSAGE FOLLOWS ----------' for line in lines: # headers first if inheaders and not line: print 'X-Peer:', peer[0] inheaders = 0 print line print '------------ END MESSAGE ------------' class PureProxy(SMTPServer): def process_message(self, peer, mailfrom, rcpttos, data): lines = data.split('\n') # Look for the last header i = 0 for line in lines: if not line: break i += 1 lines.insert(i, 'X-Peer: %s' % peer[0]) data = NEWLINE.join(lines) refused = self._deliver(mailfrom, rcpttos, data) # TBD: what to do with refused addresses? print >> DEBUGSTREAM, 'we got some refusals:', refused def _deliver(self, mailfrom, rcpttos, data): import smtplib refused = {} try: s = smtplib.SMTP() s.connect(self._remoteaddr[0], self._remoteaddr[1]) try: refused = s.sendmail(mailfrom, rcpttos, data) finally: s.quit() except smtplib.SMTPRecipientsRefused, e: print >> DEBUGSTREAM, 'got SMTPRecipientsRefused' refused = e.recipients except (socket.error, smtplib.SMTPException), e: print >> DEBUGSTREAM, 'got', e.__class__ # All recipients were refused. If the exception had an associated # error code, use it. Otherwise,fake it with a non-triggering # exception code. errcode = getattr(e, 'smtp_code', -1) errmsg = getattr(e, 'smtp_error', 'ignore') for r in rcpttos: refused[r] = (errcode, errmsg) return refused class MailmanProxy(PureProxy): def process_message(self, peer, mailfrom, rcpttos, data): from cStringIO import StringIO from Mailman import Utils from Mailman import Message from Mailman import MailList # If the message is to a Mailman mailing list, then we'll invoke the # Mailman script directly, without going through the real smtpd. # Otherwise we'll forward it to the local proxy for disposition. listnames = [] for rcpt in rcpttos: local = rcpt.lower().split('@')[0] # We allow the following variations on the theme # listname # listname-admin # listname-owner # listname-request # listname-join # listname-leave parts = local.split('-') if len(parts) > 2: continue listname = parts[0] if len(parts) == 2: command = parts[1] else: command = '' if not Utils.list_exists(listname) or command not in ( '', 'admin', 'owner', 'request', 'join', 'leave'): continue listnames.append((rcpt, listname, command)) # Remove all list recipients from rcpttos and forward what we're not # going to take care of ourselves. Linear removal should be fine # since we don't expect a large number of recipients. for rcpt, listname, command in listnames: rcpttos.remove(rcpt) # If there's any non-list destined recipients left, print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos) if rcpttos: refused = self._deliver(mailfrom, rcpttos, data) # TBD: what to do with refused addresses? print >> DEBUGSTREAM, 'we got refusals:', refused # Now deliver directly to the list commands mlists = {} s = StringIO(data) msg = Message.Message(s) # These headers are required for the proper execution of Mailman. All # MTAs in existence seem to add these if the original message doesn't # have them. if not msg.getheader('from'): msg['From'] = mailfrom if not msg.getheader('date'): msg['Date'] = time.ctime(time.time()) for rcpt, listname, command in listnames: print >> DEBUGSTREAM, 'sending message to', rcpt mlist = mlists.get(listname) if not mlist: mlist = MailList.MailList(listname, lock=0) mlists[listname] = mlist # dispatch on the type of command if command == '': # post msg.Enqueue(mlist, tolist=1) elif command == 'admin': msg.Enqueue(mlist, toadmin=1) elif command == 'owner': msg.Enqueue(mlist, toowner=1) elif command == 'request': msg.Enqueue(mlist, torequest=1) elif command in ('join', 'leave'): # TBD: this is a hack! if command == 'join': msg['Subject'] = 'subscribe' else: msg['Subject'] = 'unsubscribe' msg.Enqueue(mlist, torequest=1) class Options: setuid = 1 classname = 'PureProxy' def parseargs(): global DEBUGSTREAM try: opts, args = getopt.getopt( sys.argv[1:], 'nVhc:d', ['class=', 'nosetuid', 'version', 'help', 'debug']) except getopt.error, e: usage(1, e) options = Options() for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-V', '--version'): print >> sys.stderr, __version__ sys.exit(0) elif opt in ('-n', '--nosetuid'): options.setuid = 0 elif opt in ('-c', '--class'): options.classname = arg elif opt in ('-d', '--debug'): DEBUGSTREAM = sys.stderr # parse the rest of the arguments if len(args) < 1: localspec = 'localhost:8025' remotespec = 'localhost:25' elif len(args) < 2: localspec = args[0] remotespec = 'localhost:25' elif len(args) < 3: localspec = args[0] remotespec = args[1] else: usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args)) # split into host/port pairs i = localspec.find(':') if i < 0: usage(1, 'Bad local spec: %s' % localspec) options.localhost = localspec[:i] try: options.localport = int(localspec[i+1:]) except ValueError: usage(1, 'Bad local port: %s' % localspec) i = remotespec.find(':') if i < 0: usage(1, 'Bad remote spec: %s' % remotespec) options.remotehost = remotespec[:i] try: options.remoteport = int(remotespec[i+1:]) except ValueError: usage(1, 'Bad remote port: %s' % remotespec) return options if __name__ == '__main__': options = parseargs() # Become nobody if options.setuid: try: import pwd except ImportError: print >> sys.stderr, \ 'Cannot import module "pwd"; try running with -n option.' sys.exit(1) nobody = pwd.getpwnam('nobody')[2] try: os.setuid(nobody) except OSError, e: if e.errno != errno.EPERM: raise print >> sys.stderr, \ 'Cannot setuid "nobody"; try running with -n option.' sys.exit(1) classname = options.classname if "." in classname: lastdot = classname.rfind(".") mod = __import__(classname[:lastdot], globals(), locals(), [""]) classname = classname[lastdot+1:] else: import __main__ as mod class_ = getattr(mod, classname) proxy = class_((options.localhost, options.localport), (options.remotehost, options.remoteport)) try: asyncore.loop() except KeyboardInterrupt: pass
gpl-3.0
mne-tools/mne-python
examples/preprocessing/fnirs_artifact_removal.py
18
3643
""" .. _ex-fnirs-artifacts: ========================================== Visualise NIRS artifact correction methods ========================================== Here we artificially introduce several fNIRS artifacts and observe how artifact correction techniques attempt to correct the data. """ # Authors: Robert Luke <mail@robertluke.net> # # License: BSD (3-clause) import os import mne from mne.preprocessing.nirs import (optical_density, temporal_derivative_distribution_repair) ############################################################################### # Import data # ----------- # # Here we will work with the :ref:`fNIRS motor data <fnirs-motor-dataset>`. # We resample the data to make indexing exact times more convenient. # We then convert the data to optical density to perform corrections on # and plot these signals. fnirs_data_folder = mne.datasets.fnirs_motor.data_path() fnirs_cw_amplitude_dir = os.path.join(fnirs_data_folder, 'Participant-1') raw_intensity = mne.io.read_raw_nirx(fnirs_cw_amplitude_dir, verbose=True) raw_intensity.load_data().resample(3, npad="auto") raw_od = optical_density(raw_intensity) new_annotations = mne.Annotations([31, 187, 317], [8, 8, 8], ["Movement", "Movement", "Movement"]) raw_od.set_annotations(new_annotations) raw_od.plot(n_channels=15, duration=400, show_scrollbars=False) ############################################################################### # We can see some small artifacts in the above data from movement around 40, # 190 and 240 seconds. However, this data is relatively clean so we will # add some additional artifacts below. ############################################################################### # Add artificial artifacts to data # -------------------------------- # # Two common types of artifacts in NIRS data are spikes and baseline shifts. # Spikes often occur when a person moves and the optode moves relative to the # scalp and then returns to its original position. # Baseline shifts occur if the optode moves relative to the scalp and does not # return to its original position. # We add a spike type artifact at 100 seconds and a baseline shift at 200 # seconds to the data. corrupted_data = raw_od.get_data() corrupted_data[:, 298:302] = corrupted_data[:, 298:302] - 0.06 corrupted_data[:, 450:750] = corrupted_data[:, 450:750] + 0.03 corrupted_od = mne.io.RawArray(corrupted_data, raw_od.info, first_samp=raw_od.first_samp) new_annotations.append([95, 145, 245], [10, 10, 10], ["Spike", "Baseline", "Baseline"]) corrupted_od.set_annotations(new_annotations) corrupted_od.plot(n_channels=15, duration=400, show_scrollbars=False) ############################################################################### # Apply temporal derivative distribution repair # --------------------------------------------- # # This approach corrects baseline shift and spike artifacts without the need # for any user-supplied parameters :footcite:`FishburnEtAl2019`. corrected_tddr = temporal_derivative_distribution_repair(corrupted_od) corrected_tddr.plot(n_channels=15, duration=400, show_scrollbars=False) ############################################################################### # We can see in the data above that the introduced spikes and shifts are # largely removed, but some residual smaller artifact remains. # The same can be said for the artifacts in the original data. ############################################################################### # References # ---------- # # .. footbibliography::
bsd-3-clause
837278709/metro-openerp
metro_accounts/wizard/rpt_account_partner.py
2
25342
# -*- 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 lxml import etree from openerp.osv import fields, osv from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp class rpt_account_partner(osv.osv_memory): _name = "rpt.account.partner" _inherit = "rpt.base" _description = "China Account Report" _columns = { #report data lines 'rpt_lines': fields.one2many('rpt.account.partner.line', 'rpt_id', string='Report Line'), 'period_from': fields.many2one('account.period', 'Start Period'), 'period_to': fields.many2one('account.period', 'End Period'), 'target_move': fields.selection([('posted', 'All Posted Entries'), ('draft', 'All Unposted Entries'), ('all', 'All Entries'), ], 'Target Moves', required=True), 'reconcile': fields.selection([('all', 'All Entries'), ('full','Full Reconciled'), ('partial','Partial Reconciled'), ('no','UnReconciled'), ], 'Reconcile', required=True), 'partner_ids': fields.many2many('res.partner', string='Partners', required=False), 'account_ids': fields.many2many('account.account', string='Accounts', required=True), #report level 'level': fields.selection([('general', 'General'),('detail', 'Detail'),], "Report Level", required=True), #report level 'partner_type': fields.selection([('customer', 'Customer'),('supplier', 'Supplier'),], "Partner Type", required=True), #Show counterpart account flag for detail report level 'show_counter': fields.boolean("Show counterpart", required=False), 'no_zero_balance': fields.boolean("Hide data with zero balance", required=False, help="Check this to hide: \n1.The period without entries\n2.The partner with zero initial balance and all periods have no entries"), } _defaults = { 'type': 'account_partner', 'target_move': 'all', 'level': 'general', 'partner_type': 'supplier', 'reconcile':'all', 'no_zero_balance':True } def default_get(self, cr, uid, fields_list, context=None): resu = super(rpt_account_partner,self).default_get(cr, uid, fields_list, context) account_ids = [] company_id = self.pool.get('res.company')._company_default_get(cr, uid, 'account.rptcn', context=context) #handle the "default_partner_type" parameter, set the default account_ids default_partner_type = context and context.get('default_partner_type', False) or False if default_partner_type: account_types = [] if default_partner_type == 'customer': account_types = ['receivable'] if default_partner_type == 'supplier': account_types = ['payable'] if account_types: account_ids_inc = self.pool.get('account.account').search(cr, uid, [('type','in',account_types),('company_id','=',company_id)],context=context) if account_ids_inc: account_ids += account_ids_inc if account_ids: resu['account_ids'] = account_ids #set default periods period_from, period_ro = self.get_default_periods(cr, uid, self.pool.get('res.users').browse(cr,uid,uid,context=context).company_id.id,context) resu['period_from'] = period_from resu['period_to'] = period_ro return resu def fields_get(self, cr, uid, allfields=None, context=None, write_access=True): resu = super(rpt_account_partner,self).fields_get(cr, uid, allfields,context,write_access) #set the 'account_id'/'partner_id' domain dynamically by the default_project_type default_partner_type = context and context.get('default_partner_type', False) or False if default_partner_type: if default_partner_type == 'customer': resu['account_ids']['domain'] = [('type','=','receivable')] resu['partner_ids']['domain'] = [('customer','=',True)] if default_partner_type == 'supplier': resu['account_ids']['domain'] = [('type','=','payable')] resu['partner_ids']['domain'] = [('supplier','=',True)] return resu def _check_periods(self, cr, uid, ids, context=None): for wiz in self.browse(cr, uid, ids, context=context): if wiz.period_from and wiz.period_to and wiz.period_from.company_id.id != wiz.period_to.company_id.id: return False return True _constraints = [ (_check_periods, 'The chosen periods have to belong to the same company.', ['period_from','period_to']), ] def get_default_periods(self, cr, uid, company_id, context=None): start_period = end_period = False cr.execute(''' SELECT * FROM (SELECT p.id FROM account_period p WHERE p.company_id = %s AND p.special = false AND p.state = 'draft' ORDER BY p.date_start ASC, p.special ASC LIMIT 1) AS period_start UNION ALL SELECT * FROM (SELECT p.id FROM account_period p WHERE p.company_id = %s AND p.date_start < NOW() AND p.special = false AND p.state = 'draft' ORDER BY p.date_stop DESC LIMIT 1) AS period_stop''', (company_id, company_id)) periods = [i[0] for i in cr.fetchall()] if periods and len(periods) > 1: start_period = periods[0] end_period = periods[1] return end_period, end_period def _get_date_range(self, cr, uid, data, context=None): if not data.period_from or not data.period_to: raise osv.except_osv(_('Error!'),_('Select a starting and an ending period.')) return data.period_from.date_start, data.period_to.date_stop def _get_account_balance(self, partner_type, debit, credit): if debit == credit: bal_direct = 'balanced' if debit > credit: bal_direct = 'debit' if debit < credit: bal_direct = 'credit' balance = partner_type == 'supplier' and (credit-debit) or (debit-credit) return balance, bal_direct def onchange_company_id(self, cr, uid, ids, company_id, current_account_ids, rpt_name, context): val = {} resu = {'value':val} if not company_id: return resu account_ids = [] #filter currenet account ids using company_id current_account_ids = current_account_ids and current_account_ids[0][2] or None if current_account_ids: domain = [('id','in',current_account_ids),('company_id','=',company_id)] account_ids = self.pool.get('account.account').search(cr, uid, domain,context=context) #refresh the accounting list default_partner_type = context and context.get('default_partner_type', False) or False if not account_ids and default_partner_type: account_types = [] if default_partner_type == 'customer': account_types = ['receivable'] if default_partner_type == 'supplier': account_types = ['payable'] if account_types: account_ids = self.pool.get('account.account').search(cr, uid, [('type','in',account_types),('company_id','=',company_id)],context=context) val['account_ids'] = [[6, False, account_ids]] #refresh the periods period_from, period_to = self.get_default_periods(cr, uid, company_id, context=context) val.update({'period_from':period_from, 'period_to':period_to}) return resu def run_account_partner(self, cr, uid, ids, context=None): if context is None: context = {} rpt = self.browse(cr, uid, ids, context=context)[0] account_obj = self.pool.get('account.account') period_obj = self.pool.get('account.period') labels = {'init_bal':_('Initial balance'), 'period_sum':_('Period total'), 'year_sum':_('Year total'), 'bal_direct_debit':_('Debit'), 'bal_direct_credit':_('Credit'), 'bal_direct_balanced':_('Balanced')} company_id = rpt.company_id.id date_from,date_to = self._get_date_range(cr, uid, rpt, context) period_ids = period_obj.build_ctx_periods(cr, uid, rpt.period_from.id, rpt.period_to.id) move_state = ['draft','posted'] if rpt.target_move == 'posted': move_state = ['posted'] if rpt.target_move == 'draft': move_state = ['draft'] #move line common query where aml_common_query = 'aml.company_id=%s'%(company_id,) if rpt.reconcile == 'full': aml_common_query += '\n and aml.reconcile_id is not null ' if rpt.reconcile == 'partial': aml_common_query += '\n and aml.reconcile_partial_id is not null ' if rpt.reconcile == 'no': aml_common_query += '\n and (aml.reconcile_id is null and aml.reconcile_partial_id is null) ' seq = 1 rpt_lns = [] #the search account ids search_account_ids = [] for act in rpt.account_ids: search_account_ids += account_obj._get_children_and_consol(cr, uid, [act.id], context=context) search_account_ids = tuple(search_account_ids) #get partner_ids partner_ids = rpt.partner_ids if not partner_ids: partner_domain = [('parent_id','=',False),('company_id','=',company_id)] if rpt.partner_type == 'supplier': partner_domain += [('supplier','=',True)] if rpt.partner_type == 'customer': partner_domain += [('customer','=',True)] partner_ids = self.pool.get('res.partner').search(cr, uid, partner_domain, context=context) partner_ids = self.pool.get('res.partner').browse(cr, uid, partner_ids, context=context) for partner in partner_ids: rpt_lns_row = [] balance_sum = 0.0 #1.the initial balance line cr.execute('SELECT COALESCE(SUM(aml.debit),0) as debit, COALESCE(SUM(aml.credit), 0) as credit \ FROM account_move_line aml \ JOIN account_move am ON (am.id = aml.move_id) \ WHERE (aml.account_id IN %s) \ AND (aml.partner_id = %s) \ AND (am.state IN %s) \ AND (am.date < %s) \ AND '+ aml_common_query +' ' ,(search_account_ids, partner.id, tuple(move_state), date_from)) row = cr.fetchone() debit = row[0] credit = row[1] balance, direction = self._get_account_balance(rpt.partner_type, debit, credit) rpt_ln = {'seq':seq, # 'code':account.code, 'name':partner.name, 'period_id':rpt.period_from.id, 'notes':labels['init_bal'], 'debit':debit, 'credit':credit, 'bal_direct':labels['bal_direct_%s'%(direction,)], 'balance':balance, 'data_level':'init_bal'} seq += 1 rpt_lns_row.append(rpt_ln) balance_sum += balance #2.loop by periods year_sum = {} for period in period_obj.browse(cr, uid, period_ids,context=context): #the year sum data for credit/debit if not year_sum.get(period.fiscalyear_id.code,False): if period.fiscalyear_id.date_start < date_from: #Only when we start from the middle of a year, then need to sum year cr.execute('SELECT COALESCE(SUM(aml.debit),0) as debit, COALESCE(SUM(aml.credit), 0) as credit \ FROM account_move_line aml \ JOIN account_move am ON (am.id = aml.move_id) \ WHERE (aml.account_id IN %s) \ AND (aml.partner_id = %s) \ AND (am.state IN %s) \ AND (am.date >= %s) \ AND (am.date < %s) \ AND '+ aml_common_query +' ' ,(search_account_ids, partner.id, tuple(move_state), period.fiscalyear_id.date_start, date_from)) row = cr.fetchone() year_sum[period.fiscalyear_id.code] = {'debit':row[0],'credit':row[1]} else: year_sum[period.fiscalyear_id.code] = {'debit':0.0,'credit':0.0} #detail lines if rpt.level == 'detail': cr.execute('SELECT aml.account_id,aml.debit, aml.credit,aml.date_biz as move_date, am.name as move_name, aml.name as move_line_name, \ aml.id,aml.move_id \ FROM account_move_line aml \ JOIN account_move am ON (am.id = aml.move_id) \ WHERE (aml.account_id IN %s) \ AND (aml.partner_id = %s) \ AND (am.state IN %s) \ AND (am.period_id = %s) \ AND '+ aml_common_query +' \ ORDER by aml.date, aml.move_id' ,(search_account_ids, partner.id, tuple(move_state), period.id)) rows = cr.dictfetchall() balance_detail = balance_sum for row in rows: #move detail line debit = row['debit'] credit = row['credit'] balance, direction = self._get_account_balance(rpt.partner_type, debit, credit) balance_detail += balance rpt_ln = {'seq':seq, 'code':'', 'name':'', 'period_id':period.id, 'aml_id':row['id'], # for detail 'account_id':row['account_id'], # for detail 'date':row['move_date'], # for detail 'am_name':row['move_name'], # for detail 'notes':row['move_line_name'], 'debit':debit, 'credit':credit, 'bal_direct':labels['bal_direct_%s'%(direction,)], 'balance':balance_detail, 'data_level':'detail'} if rpt.show_counter: rpt_ln['counter_account'] = '' rpt_lns_row.append(rpt_ln) seq += 1 #the period credit/debit cr.execute('SELECT COALESCE(SUM(aml.debit),0) as debit, COALESCE(SUM(aml.credit), 0) as credit \ FROM account_move_line aml \ JOIN account_move am ON (am.id = aml.move_id) \ WHERE (aml.account_id IN %s) \ AND (aml.partner_id = %s) \ AND (am.state IN %s) \ AND (am.period_id = %s) \ AND '+ aml_common_query +' ' ,(search_account_ids, partner.id, tuple(move_state), period.id)) row = cr.fetchone() #period sum line debit = row[0] credit = row[1] balance, direction = self._get_account_balance(rpt.partner_type, debit, credit) #if "no zero balance period" is set, and no entries of this period, then do not show this period if rpt.no_zero_balance and debit == 0.0 and credit == 0: continue balance_sum += balance rpt_ln = {'seq':seq, 'code':'', 'name':'', 'period_id':period.id, 'notes':labels['period_sum'], 'debit':debit, 'credit':credit, 'bal_direct':labels['bal_direct_%s'%(direction,)], 'balance':balance_sum, 'data_level':'period_sum'} rpt_lns_row.append(rpt_ln) seq += 1 #year sum line debit_year = debit + year_sum[period.fiscalyear_id.code]['debit'] credit_year = credit + year_sum[period.fiscalyear_id.code]['credit'] balance_year, direction_year = self._get_account_balance(rpt.partner_type, debit_year, credit_year) balance_year = balance_sum rpt_ln = {'seq':seq, 'code':'', 'name':'', 'period_id':period.id, 'notes':labels['year_sum'], 'debit':debit_year, 'credit':credit_year, 'bal_direct':labels['bal_direct_%s'%(direction_year,)], 'balance':balance_year, 'data_level':'year_sum'} #increase the year sum value year_sum[period.fiscalyear_id.code]['debit'] = debit_year year_sum[period.fiscalyear_id.code]['credit'] = credit_year rpt_lns_row.append(rpt_ln) seq += 1 #if only have the initial balance row, and the initial balance is zero then skip this partner if rpt.no_zero_balance and len(rpt_lns_row) == 1 and rpt_lns_row[0]['balance'] == 0.0: continue rpt_lns += rpt_lns_row #update the reconcile and residual data if rpt.level == 'detail': mvln_ids = [ln['aml_id'] for ln in rpt_lns if ln.get('aml_id',False)] mvln_data = self.pool.get('account.move.line').read(cr, uid, mvln_ids, ['reconcile','amount_residual']) # {'amount_residual': 0.0, 'id': 58854, 'reconcile': 'A1167'} mvlns = {} for mvln in mvln_data: mvlns[mvln['id']] = {'amount_residual':mvln['amount_residual'],'reconcile':mvln['reconcile']} for ln in rpt_lns: aml_id = ln.get('aml_id',False) if aml_id: mvln = mvlns.get(aml_id,False) if mvln: ln.update(mvln) return self.pool.get('rpt.account.partner.line'), rpt_lns return True def _pdf_data(self, cr, uid, ids, form_data, context=None): rpt_name = 'rpt.account.partner.gl' if form_data['level'] == 'detail': rpt_name = 'rpt.account.partner.detail' return {'xmlrpt_name': rpt_name} rpt_account_partner() class rpt_account_partner_line(osv.osv_memory): _name = "rpt.account.partner.line" _inherit = "rpt.base.line" _description = "China Account Report Lines" _columns = { 'rpt_id': fields.many2one('rpt.account.partner', 'Report'), #for GL 'period_id': fields.many2one('account.period', 'Period',), #for detail 'aml_id': fields.many2one('account.move.line', 'Move Line', ), 'aml_source_id': fields.related('aml_id', 'source_id', string='Source',type='reference'), 'account_id': fields.many2one('account.account','Account'), 'date': fields.date('Move Date', ), 'am_name': fields.char('Move Name', size=64, ), 'counter_account': fields.char('Counter Account', size=64, ), 'reconcile': fields.char('Reconcile', size=64 ), # 'reconcile_partial': fields.char('Partial Reconcile', size=64 ), 'amount_residual': fields.float('Residual Amount', digits_compute=dp.get_precision('Account')), #for both Gl and detail, move line name or static:期初,本期合计,本年合计 'notes': fields.char('Notes', size=64, ), #for all 'debit': fields.float('Debit', digits_compute=dp.get_precision('Account')), 'credit': fields.float('Credit', digits_compute=dp.get_precision('Account')), #debit/credit direction:Debit(借)/Credit(贷) 'bal_direct': fields.char('Balance Direction', size=16, ), 'balance': fields.float('Balance', digits_compute=dp.get_precision('Account')), #report level 'level': fields.related('rpt_id','level',type='selection',selection=[('general', 'General'),('detail', 'Detail'),], string="Report Level"), #Show counterpart account flag for detail report level 'show_counter': fields.related('rpt_id','show_counter',type='boolean', string="Show counterpart", required=False), } def open_move(self, cr, uid, ids, context=None): res_id = None if isinstance(ids, list): res_id = ids[0] else: res_id = ids aml_id = self.browse(cr, uid, res_id, context=context).aml_id if not aml_id: return False move_id = aml_id.move_id.id #got to accountve move form form_view = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'account', 'view_move_form') form_view_id = form_view and form_view[1] or False return { 'name': _('Account Move'), 'view_type': 'form', 'view_mode': 'form', 'view_id': [form_view_id], 'res_model': 'account.move', 'type': 'ir.actions.act_window', 'res_id': move_id, } def open_source(self, cr, uid, ids, context=None): res_id = None if isinstance(ids, list): res_id = ids[0] else: res_id = ids aml_id = self.browse(cr, uid, res_id, context=context).aml_id if not aml_id or not aml_id.source_id: return False res_model = aml_id.source_id._model._name res_id = aml_id.source_id.id #got to source model's form return { 'name': _('Source Detail'), 'view_type': 'form', 'view_mode': 'form', 'res_model': res_model, 'type': 'ir.actions.act_window', 'res_id': res_id, } rpt_account_partner_line() from openerp.report import report_sxw report_sxw.report_sxw('report.rpt.account.partner.gl', 'rpt.account.partner', 'addons/metro_accounts/report/rpt_account_partner_gl.rml', parser=report_sxw.rml_parse, header='internal landscape') report_sxw.report_sxw('report.rpt.account.partner.detail', 'rpt.account.partner', 'addons/metro_accounts/report/rpt_account_partner_detail.rml', parser=report_sxw.rml_parse, header='internal landscape') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
EvilCult/Video-Downloader
Library/toolClass.py
1
3025
#!/usr/bin/env python # -*- coding: utf-8 -*- import pycurl import StringIO import random class Tools : def __init__ (self) : pass def getPage (self, url, requestHeader = []) : resultFormate = StringIO.StringIO() fakeIp = self.fakeIp() requestHeader.append('CLIENT-IP:' + fakeIp) requestHeader.append('X-FORWARDED-FOR:' + fakeIp) try: curl = pycurl.Curl() curl.setopt(pycurl.URL, url.strip()) curl.setopt(pycurl.ENCODING, 'gzip,deflate') curl.setopt(pycurl.HEADER, 1) curl.setopt(pycurl.TIMEOUT, 120) curl.setopt(pycurl.SSL_VERIFYPEER, 0) curl.setopt(pycurl.SSL_VERIFYHOST, 0) curl.setopt(pycurl.HTTPHEADER, requestHeader) curl.setopt(pycurl.WRITEFUNCTION, resultFormate.write) curl.perform() headerSize = curl.getinfo(pycurl.HEADER_SIZE) curl.close() header = resultFormate.getvalue()[0 : headerSize].split('\r\n') body = resultFormate.getvalue()[headerSize : ] except Exception, e: header = '' body = '' return header, body def fakeIp (self) : fakeIpList = [] for x in xrange(0, 4): fakeIpList.append(str(int(random.uniform(0, 255)))) fakeIp = '.'.join(fakeIpList) return fakeIp def xor (self, x, y, base = 32) : stat = True if x >= 0 : x = str(bin(int(str(x), 10)))[2:] for i in xrange(0, base - len(x)): x = '0' + x else : x = str(bin(int(str(x + 1), 10)))[3:] for i in xrange(0, base - len(x)): x = '0' + x t = '' for i in xrange(0,len(x)): if x[i] == '1' : t = t + '0' else : t = t + '1' x = t if y >= 0 : y = str(bin(int(str(y), 10)))[2:] for i in xrange(0, base - len(y)): y = '0' + y else : y = str(bin(int(str(y + 1), 10)))[3:] for i in xrange(0, base - len(y)): y = '0' + y t = '' for i in xrange(0,len(y)): if y[i] == '1' : t = t + '0' else : t = t + '1' y = t t = '' for i in xrange(0, base): if x[i] == y[i] : t = t + '0' else : t = t + '1' x = t if x[0] == '1' : stat = False t = '' for i in xrange(0,len(x)): if x[i] == '1' : t = t + '0' else : t = t + '1' x = t r = int(str(x), 2) if stat == False : r = 0 - r - 1 return r def rotate (self, x, y, w, base = 32) : stat = True if x >= 0 : x = str(bin(int(str(x), 10)))[2:] for i in xrange(0, base - len(x)): x = '0' + x else : x = str(bin(int(str(x + 1), 10)))[3:] for i in xrange(0, base - len(x)): x = '0' + x t = '' for i in xrange(0,len(x)): if x[i] == '1' : t = t + '0' else : t = t + '1' x = t if y >= base : y = y % base for i in xrange (0, y) : if w != 'r+' : x = x[0] + x + '0' else : x = '0' + x + '0' if w == 'r' or w == 'r+' : x = x[0 : base] else : x = x[(len(x) - base) : ] if x[0] == '1' : stat = False t = '' for i in xrange(0,len(x)): if x[i] == '1' : t = t + '0' else : t = t + '1' x = t r = int(str(x), 2) if stat == False : r = 0 - r - 1 return r
gpl-2.0
munyirik/python
cpython/Lib/distutils/cmd.py
97
19147
"""distutils.cmd Provides the Command class, the base class for the command classes in the distutils.command package. """ import sys, os, re from distutils.errors import DistutilsOptionError from distutils import util, dir_util, file_util, archive_util, dep_util from distutils import log class Command: """Abstract base class for defining command classes, the "worker bees" of the Distutils. A useful analogy for command classes is to think of them as subroutines with local variables called "options". The options are "declared" in 'initialize_options()' and "defined" (given their final values, aka "finalized") in 'finalize_options()', both of which must be defined by every command class. The distinction between the two is necessary because option values might come from the outside world (command line, config file, ...), and any options dependent on other options must be computed *after* these outside influences have been processed -- hence 'finalize_options()'. The "body" of the subroutine, where it does all its work based on the values of its options, is the 'run()' method, which must also be implemented by every command class. """ # 'sub_commands' formalizes the notion of a "family" of commands, # eg. "install" as the parent with sub-commands "install_lib", # "install_headers", etc. The parent of a family of commands # defines 'sub_commands' as a class attribute; it's a list of # (command_name : string, predicate : unbound_method | string | None) # tuples, where 'predicate' is a method of the parent command that # determines whether the corresponding command is applicable in the # current situation. (Eg. we "install_headers" is only applicable if # we have any C header files to install.) If 'predicate' is None, # that command is always applicable. # # 'sub_commands' is usually defined at the *end* of a class, because # predicates can be unbound methods, so they must already have been # defined. The canonical example is the "install" command. sub_commands = [] # -- Creation/initialization methods ------------------------------- def __init__(self, dist): """Create and initialize a new Command object. Most importantly, invokes the 'initialize_options()' method, which is the real initializer and depends on the actual command being instantiated. """ # late import because of mutual dependence between these classes from distutils.dist import Distribution if not isinstance(dist, Distribution): raise TypeError("dist must be a Distribution instance") if self.__class__ is Command: raise RuntimeError("Command is an abstract class") self.distribution = dist self.initialize_options() # Per-command versions of the global flags, so that the user can # customize Distutils' behaviour command-by-command and let some # commands fall back on the Distribution's behaviour. None means # "not defined, check self.distribution's copy", while 0 or 1 mean # false and true (duh). Note that this means figuring out the real # value of each flag is a touch complicated -- hence "self._dry_run" # will be handled by __getattr__, below. # XXX This needs to be fixed. self._dry_run = None # verbose is largely ignored, but needs to be set for # backwards compatibility (I think)? self.verbose = dist.verbose # Some commands define a 'self.force' option to ignore file # timestamps, but methods defined *here* assume that # 'self.force' exists for all commands. So define it here # just to be safe. self.force = None # The 'help' flag is just used for command-line parsing, so # none of that complicated bureaucracy is needed. self.help = 0 # 'finalized' records whether or not 'finalize_options()' has been # called. 'finalize_options()' itself should not pay attention to # this flag: it is the business of 'ensure_finalized()', which # always calls 'finalize_options()', to respect/update it. self.finalized = 0 # XXX A more explicit way to customize dry_run would be better. def __getattr__(self, attr): if attr == 'dry_run': myval = getattr(self, "_" + attr) if myval is None: return getattr(self.distribution, attr) else: return myval else: raise AttributeError(attr) def ensure_finalized(self): if not self.finalized: self.finalize_options() self.finalized = 1 # Subclasses must define: # initialize_options() # provide default values for all options; may be customized by # setup script, by options from config file(s), or by command-line # options # finalize_options() # decide on the final values for all options; this is called # after all possible intervention from the outside world # (command-line, option file, etc.) has been processed # run() # run the command: do whatever it is we're here to do, # controlled by the command's various option values def initialize_options(self): """Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, 'initialize_options()' implementations are just a bunch of "self.foo = None" assignments. This method must be implemented by all command classes. """ raise RuntimeError("abstract method -- subclass %s must override" % self.__class__) def finalize_options(self): """Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as long as 'foo' still has the same value it was assigned in 'initialize_options()'. This method must be implemented by all command classes. """ raise RuntimeError("abstract method -- subclass %s must override" % self.__class__) def dump_options(self, header=None, indent=""): from distutils.fancy_getopt import longopt_xlate if header is None: header = "command options for '%s':" % self.get_command_name() self.announce(indent + header, level=log.INFO) indent = indent + " " for (option, _, _) in self.user_options: option = option.translate(longopt_xlate) if option[-1] == "=": option = option[:-1] value = getattr(self, option) self.announce(indent + "%s = %s" % (option, value), level=log.INFO) def run(self): """A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All terminal output and filesystem interaction should be done by 'run()'. This method must be implemented by all command classes. """ raise RuntimeError("abstract method -- subclass %s must override" % self.__class__) def announce(self, msg, level=1): """If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout. """ log.log(level, msg) def debug_print(self, msg): """Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. """ from distutils.debug import DEBUG if DEBUG: print(msg) sys.stdout.flush() # -- Option validation methods ------------------------------------- # (these are very handy in writing the 'finalize_options()' method) # # NB. the general philosophy here is to ensure that a particular option # value meets certain type and value constraints. If not, we try to # force it into conformance (eg. if we expect a list but have a string, # split the string on comma and/or whitespace). If we can't force the # option into conformance, raise DistutilsOptionError. Thus, command # classes need do nothing more than (eg.) # self.ensure_string_list('foo') # and they can be guaranteed that thereafter, self.foo will be # a list of strings. def _ensure_stringlike(self, option, what, default=None): val = getattr(self, option) if val is None: setattr(self, option, default) return default elif not isinstance(val, str): raise DistutilsOptionError("'%s' must be a %s (got `%s`)" % (option, what, val)) return val def ensure_string(self, option, default=None): """Ensure that 'option' is a string; if not defined, set it to 'default'. """ self._ensure_stringlike(option, "string", default) def ensure_string_list(self, option): """Ensure that 'option' is a list of strings. If 'option' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"]. """ val = getattr(self, option) if val is None: return elif isinstance(val, str): setattr(self, option, re.split(r',\s*|\s+', val)) else: if isinstance(val, list): ok = all(isinstance(v, str) for v in val) else: ok = False if not ok: raise DistutilsOptionError( "'%s' must be a list of strings (got %r)" % (option, val)) def _ensure_tested_string(self, option, tester, what, error_fmt, default=None): val = self._ensure_stringlike(option, what, default) if val is not None and not tester(val): raise DistutilsOptionError(("error in '%s' option: " + error_fmt) % (option, val)) def ensure_filename(self, option): """Ensure that 'option' is the name of an existing file.""" self._ensure_tested_string(option, os.path.isfile, "filename", "'%s' does not exist or is not a file") def ensure_dirname(self, option): self._ensure_tested_string(option, os.path.isdir, "directory name", "'%s' does not exist or is not a directory") # -- Convenience methods for commands ------------------------------ def get_command_name(self): if hasattr(self, 'command_name'): return self.command_name else: return self.__class__.__name__ def set_undefined_options(self, src_cmd, *option_pairs): """Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'initialize_options()' and 'finalize_options()'. Usually called from 'finalize_options()' for options that depend on some other command rather than another option of the same command. 'src_cmd' is the other command from which option values will be taken (a command object will be created for it if necessary); the remaining arguments are '(src_option,dst_option)' tuples which mean "take the value of 'src_option' in the 'src_cmd' command object, and copy it to 'dst_option' in the current command object". """ # Option_pairs: list of (src_option, dst_option) tuples src_cmd_obj = self.distribution.get_command_obj(src_cmd) src_cmd_obj.ensure_finalized() for (src_option, dst_option) in option_pairs: if getattr(self, dst_option) is None: setattr(self, dst_option, getattr(src_cmd_obj, src_option)) def get_finalized_command(self, command, create=1): """Wrapper around Distribution's 'get_command_obj()' method: find (create if necessary and 'create' is true) the command object for 'command', call its 'ensure_finalized()' method, and return the finalized command object. """ cmd_obj = self.distribution.get_command_obj(command, create) cmd_obj.ensure_finalized() return cmd_obj # XXX rename to 'get_reinitialized_command()'? (should do the # same in dist.py, if so) def reinitialize_command(self, command, reinit_subcommands=0): return self.distribution.reinitialize_command(command, reinit_subcommands) def run_command(self, command): """Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method. """ self.distribution.run_command(command) def get_sub_commands(self): """Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the 'sub_commands' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be run for the current distribution. Return a list of command names. """ commands = [] for (cmd_name, method) in self.sub_commands: if method is None or method(self): commands.append(cmd_name) return commands # -- External world manipulation ----------------------------------- def warn(self, msg): log.warn("warning: %s: %s\n" % (self.get_command_name(), msg)) def execute(self, func, args, msg=None, level=1): util.execute(func, args, msg, dry_run=self.dry_run) def mkpath(self, name, mode=0o777): dir_util.mkpath(name, mode, dry_run=self.dry_run) def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1): """Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don't define it.)""" return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, not self.force, link, dry_run=self.dry_run) def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1): """Copy an entire directory tree respecting verbose, dry-run, and force flags. """ return dir_util.copy_tree(infile, outfile, preserve_mode, preserve_times, preserve_symlinks, not self.force, dry_run=self.dry_run) def move_file (self, src, dst, level=1): """Move a file respecting dry-run flag.""" return file_util.move_file(src, dst, dry_run=self.dry_run) def spawn(self, cmd, search_path=1, level=1): """Spawn an external command respecting dry-run flag.""" from distutils.spawn import spawn spawn(cmd, search_path, dry_run=self.dry_run) def make_archive(self, base_name, format, root_dir=None, base_dir=None, owner=None, group=None): return archive_util.make_archive(base_name, format, root_dir, base_dir, dry_run=self.dry_run, owner=owner, group=group) def make_file(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1): """Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the command defined 'self.force', and it is true, then the command is unconditionally run -- does no timestamp checks. """ if skip_msg is None: skip_msg = "skipping %s (inputs unchanged)" % outfile # Allow 'infiles' to be a single string if isinstance(infiles, str): infiles = (infiles,) elif not isinstance(infiles, (list, tuple)): raise TypeError( "'infiles' must be a string, or a list or tuple of strings") if exec_msg is None: exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles)) # If 'outfile' must be regenerated (either because it doesn't # exist, is out-of-date, or the 'force' flag is true) then # perform the action that presumably regenerates it if self.force or dep_util.newer_group(infiles, outfile): self.execute(func, args, exec_msg, level) # Otherwise, print the "skip" message else: log.debug(skip_msg) # XXX 'install_misc' class not currently used -- it was the base class for # both 'install_scripts' and 'install_data', but they outgrew it. It might # still be useful for 'install_headers', though, so I'm keeping it around # for the time being. class install_misc(Command): """Common base class for installing some files in a subdirectory. Currently used by install_data and install_scripts. """ user_options = [('install-dir=', 'd', "directory to install the files to")] def initialize_options (self): self.install_dir = None self.outfiles = [] def _install_dir_from(self, dirname): self.set_undefined_options('install', (dirname, 'install_dir')) def _copy_files(self, filelist): self.outfiles = [] if not filelist: return self.mkpath(self.install_dir) for f in filelist: self.copy_file(f, self.install_dir) self.outfiles.append(os.path.join(self.install_dir, f)) def get_outputs(self): return self.outfiles
bsd-3-clause
drawquest/drawquest-web
common/boto/gs/resumable_upload_handler.py
2
26230
# Copyright 2010 Google Inc. # # 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 cgi import errno import httplib import os import re import socket import time import urlparse import boto from boto import config from boto.connection import AWSAuthConnection from boto.exception import InvalidUriError from boto.exception import ResumableTransferDisposition from boto.exception import ResumableUploadException """ Handler for Google Storage resumable uploads. See http://code.google.com/apis/storage/docs/developer-guide.html#resumable for details. Resumable uploads will retry failed uploads, resuming at the byte count completed by the last upload attempt. If too many retries happen with no progress (per configurable num_retries param), the upload will be aborted in the current process. The caller can optionally specify a tracker_file_name param in the ResumableUploadHandler constructor. If you do this, that file will save the state needed to allow retrying later, in a separate process (e.g., in a later run of gsutil). """ class ResumableUploadHandler(object): BUFFER_SIZE = 8192 RETRYABLE_EXCEPTIONS = (httplib.HTTPException, IOError, socket.error, socket.gaierror) # (start, end) response indicating server has nothing (upload protocol uses # inclusive numbering). SERVER_HAS_NOTHING = (0, -1) def __init__(self, tracker_file_name=None, num_retries=None): """ Constructor. Instantiate once for each uploaded file. :type tracker_file_name: string :param tracker_file_name: optional file name to save tracker URI. If supplied and the current process fails the upload, it can be retried in a new process. If called with an existing file containing a valid tracker URI, we'll resume the upload from this URI; else we'll start a new resumable upload (and write the URI to this tracker file). :type num_retries: int :param num_retries: the number of times we'll re-try a resumable upload making no progress. (Count resets every time we get progress, so upload can span many more than this number of retries.) """ self.tracker_file_name = tracker_file_name self.num_retries = num_retries self.server_has_bytes = 0 # Byte count at last server check. self.tracker_uri = None if tracker_file_name: self._load_tracker_uri_from_file() # Save upload_start_point in instance state so caller can find how # much was transferred by this ResumableUploadHandler (across retries). self.upload_start_point = None def _load_tracker_uri_from_file(self): f = None try: f = open(self.tracker_file_name, 'r') uri = f.readline().strip() self._set_tracker_uri(uri) except IOError, e: # Ignore non-existent file (happens first time an upload # is attempted on a file), but warn user for other errors. if e.errno != errno.ENOENT: # Will restart because self.tracker_uri == None. print('Couldn\'t read URI tracker file (%s): %s. Restarting ' 'upload from scratch.' % (self.tracker_file_name, e.strerror)) except InvalidUriError, e: # Warn user, but proceed (will restart because # self.tracker_uri == None). print('Invalid tracker URI (%s) found in URI tracker file ' '(%s). Restarting upload from scratch.' % (uri, self.tracker_file_name)) finally: if f: f.close() def _save_tracker_uri_to_file(self): """ Saves URI to tracker file if one was passed to constructor. """ if not self.tracker_file_name: return f = None try: f = open(self.tracker_file_name, 'w') f.write(self.tracker_uri) except IOError, e: raise ResumableUploadException( 'Couldn\'t write URI tracker file (%s): %s.\nThis can happen' 'if you\'re using an incorrectly configured upload tool\n' '(e.g., gsutil configured to save tracker files to an ' 'unwritable directory)' % (self.tracker_file_name, e.strerror), ResumableTransferDisposition.ABORT) finally: if f: f.close() def _set_tracker_uri(self, uri): """ Called when we start a new resumable upload or get a new tracker URI for the upload. Saves URI and resets upload state. Raises InvalidUriError if URI is syntactically invalid. """ parse_result = urlparse.urlparse(uri) if (parse_result.scheme.lower() not in ['http', 'https'] or not parse_result.netloc or not parse_result.query): raise InvalidUriError('Invalid tracker URI (%s)' % uri) qdict = cgi.parse_qs(parse_result.query) if not qdict or not 'upload_id' in qdict: raise InvalidUriError('Invalid tracker URI (%s)' % uri) self.tracker_uri = uri self.tracker_uri_host = parse_result.netloc self.tracker_uri_path = '%s/?%s' % (parse_result.netloc, parse_result.query) self.server_has_bytes = 0 def get_tracker_uri(self): """ Returns upload tracker URI, or None if the upload has not yet started. """ return self.tracker_uri def _remove_tracker_file(self): if (self.tracker_file_name and os.path.exists(self.tracker_file_name)): os.unlink(self.tracker_file_name) def _build_content_range_header(self, range_spec='*', length_spec='*'): return 'bytes %s/%s' % (range_spec, length_spec) def _query_server_state(self, conn, file_length): """ Queries server to find out state of given upload. Note that this method really just makes special case use of the fact that the upload server always returns the current start/end state whenever a PUT doesn't complete. Returns HTTP response from sending request. Raises ResumableUploadException if problem querying server. """ # Send an empty PUT so that server replies with this resumable # transfer's state. put_headers = {} put_headers['Content-Range'] = ( self._build_content_range_header('*', file_length)) put_headers['Content-Length'] = '0' return AWSAuthConnection.make_request(conn, 'PUT', path=self.tracker_uri_path, auth_path=self.tracker_uri_path, headers=put_headers, host=self.tracker_uri_host) def _query_server_pos(self, conn, file_length): """ Queries server to find out what bytes it currently has. Returns (server_start, server_end), where the values are inclusive. For example, (0, 2) would mean that the server has bytes 0, 1, *and* 2. Raises ResumableUploadException if problem querying server. """ resp = self._query_server_state(conn, file_length) if resp.status == 200: return (0, file_length) # Completed upload. if resp.status != 308: # This means the server didn't have any state for the given # upload ID, which can happen (for example) if the caller saved # the tracker URI to a file and then tried to restart the transfer # after that upload ID has gone stale. In that case we need to # start a new transfer (and the caller will then save the new # tracker URI to the tracker file). raise ResumableUploadException( 'Got non-308 response (%s) from server state query' % resp.status, ResumableTransferDisposition.START_OVER) got_valid_response = False range_spec = resp.getheader('range') if range_spec: # Parse 'bytes=<from>-<to>' range_spec. m = re.search('bytes=(\d+)-(\d+)', range_spec) if m: server_start = long(m.group(1)) server_end = long(m.group(2)) got_valid_response = True else: # No Range header, which means the server does not yet have # any bytes. Note that the Range header uses inclusive 'from' # and 'to' values. Since Range 0-0 would mean that the server # has byte 0, omitting the Range header is used to indicate that # the server doesn't have any bytes. return self.SERVER_HAS_NOTHING if not got_valid_response: raise ResumableUploadException( 'Couldn\'t parse upload server state query response (%s)' % str(resp.getheaders()), ResumableTransferDisposition.START_OVER) if conn.debug >= 1: print 'Server has: Range: %d - %d.' % (server_start, server_end) return (server_start, server_end) def _start_new_resumable_upload(self, key, headers=None): """ Starts a new resumable upload. Raises ResumableUploadException if any errors occur. """ conn = key.bucket.connection if conn.debug >= 1: print 'Starting new resumable upload.' self.server_has_bytes = 0 # Start a new resumable upload by sending a POST request with an # empty body and the "X-Goog-Resumable: start" header. Include any # caller-provided headers (e.g., Content-Type) EXCEPT Content-Length # (and raise an exception if they tried to pass one, since it's # a semantic error to specify it at this point, and if we were to # include one now it would cause the server to expect that many # bytes; the POST doesn't include the actual file bytes We set # the Content-Length in the subsequent PUT, based on the uploaded # file size. post_headers = {} for k in headers: if k.lower() == 'content-length': raise ResumableUploadException( 'Attempt to specify Content-Length header (disallowed)', ResumableTransferDisposition.ABORT) post_headers[k] = headers[k] post_headers[conn.provider.resumable_upload_header] = 'start' resp = conn.make_request( 'POST', key.bucket.name, key.name, post_headers) # Get tracker URI from response 'Location' header. body = resp.read() # Check for various status conditions. if resp.status in [500, 503]: # Retry status 500 and 503 errors after a delay. raise ResumableUploadException( 'Got status %d from attempt to start resumable upload. ' 'Will wait/retry' % resp.status, ResumableTransferDisposition.WAIT_BEFORE_RETRY) elif resp.status != 200 and resp.status != 201: raise ResumableUploadException( 'Got status %d from attempt to start resumable upload. ' 'Aborting' % resp.status, ResumableTransferDisposition.ABORT) # Else we got 200 or 201 response code, indicating the resumable # upload was created. tracker_uri = resp.getheader('Location') if not tracker_uri: raise ResumableUploadException( 'No resumable tracker URI found in resumable initiation ' 'POST response (%s)' % body, ResumableTransferDisposition.WAIT_BEFORE_RETRY) self._set_tracker_uri(tracker_uri) self._save_tracker_uri_to_file() def _upload_file_bytes(self, conn, http_conn, fp, file_length, total_bytes_uploaded, cb, num_cb): """ Makes one attempt to upload file bytes, using an existing resumable upload connection. Returns etag from server upon success. Raises ResumableUploadException if any problems occur. """ buf = fp.read(self.BUFFER_SIZE) if cb: if num_cb > 2: cb_count = file_length / self.BUFFER_SIZE / (num_cb-2) elif num_cb < 0: cb_count = -1 else: cb_count = 0 i = 0 cb(total_bytes_uploaded, file_length) # Build resumable upload headers for the transfer. Don't send a # Content-Range header if the file is 0 bytes long, because the # resumable upload protocol uses an *inclusive* end-range (so, sending # 'bytes 0-0/1' would actually mean you're sending a 1-byte file). put_headers = {} if file_length: range_header = self._build_content_range_header( '%d-%d' % (total_bytes_uploaded, file_length - 1), file_length) put_headers['Content-Range'] = range_header # Set Content-Length to the total bytes we'll send with this PUT. put_headers['Content-Length'] = str(file_length - total_bytes_uploaded) http_request = AWSAuthConnection.build_base_http_request( conn, 'PUT', path=self.tracker_uri_path, auth_path=None, headers=put_headers, host=self.tracker_uri_host) http_conn.putrequest('PUT', http_request.path) for k in put_headers: http_conn.putheader(k, put_headers[k]) http_conn.endheaders() # Turn off debug on http connection so upload content isn't included # in debug stream. http_conn.set_debuglevel(0) while buf: http_conn.send(buf) total_bytes_uploaded += len(buf) if cb: i += 1 if i == cb_count or cb_count == -1: cb(total_bytes_uploaded, file_length) i = 0 buf = fp.read(self.BUFFER_SIZE) if cb: cb(total_bytes_uploaded, file_length) if total_bytes_uploaded != file_length: # Abort (and delete the tracker file) so if the user retries # they'll start a new resumable upload rather than potentially # attempting to pick back up later where we left off. raise ResumableUploadException( 'File changed during upload: EOF at %d bytes of %d byte file.' % (total_bytes_uploaded, file_length), ResumableTransferDisposition.ABORT) resp = http_conn.getresponse() body = resp.read() # Restore http connection debug level. http_conn.set_debuglevel(conn.debug) if resp.status == 200: return resp.getheader('etag') # Success # Retry timeout (408) and status 500 and 503 errors after a delay. elif resp.status in [408, 500, 503]: disposition = ResumableTransferDisposition.WAIT_BEFORE_RETRY else: # Catch all for any other error codes. disposition = ResumableTransferDisposition.ABORT raise ResumableUploadException('Got response code %d while attempting ' 'upload (%s)' % (resp.status, resp.reason), disposition) def _attempt_resumable_upload(self, key, fp, file_length, headers, cb, num_cb): """ Attempts a resumable upload. Returns etag from server upon success. Raises ResumableUploadException if any problems occur. """ (server_start, server_end) = self.SERVER_HAS_NOTHING conn = key.bucket.connection if self.tracker_uri: # Try to resume existing resumable upload. try: (server_start, server_end) = ( self._query_server_pos(conn, file_length)) self.server_has_bytes = server_start key=key if conn.debug >= 1: print 'Resuming transfer.' except ResumableUploadException, e: if conn.debug >= 1: print 'Unable to resume transfer (%s).' % e.message self._start_new_resumable_upload(key, headers) else: self._start_new_resumable_upload(key, headers) # upload_start_point allows the code that instantiated the # ResumableUploadHandler to find out the point from which it started # uploading (e.g., so it can correctly compute throughput). if self.upload_start_point is None: self.upload_start_point = server_end if server_end == file_length: # Boundary condition: complete file was already uploaded (e.g., # user interrupted a previous upload attempt after the upload # completed but before the gsutil tracker file was deleted). Set # total_bytes_uploaded to server_end so we'll attempt to upload # no more bytes but will still make final HTTP request and get # back the response (which contains the etag we need to compare # at the end). total_bytes_uploaded = server_end else: total_bytes_uploaded = server_end + 1 fp.seek(total_bytes_uploaded) conn = key.bucket.connection # Get a new HTTP connection (vs conn.get_http_connection(), which reuses # pool connections) because httplib requires a new HTTP connection per # transaction. (Without this, calling http_conn.getresponse() would get # "ResponseNotReady".) http_conn = conn.new_http_connection(self.tracker_uri_host, conn.is_secure) http_conn.set_debuglevel(conn.debug) # Make sure to close http_conn at end so if a local file read # failure occurs partway through server will terminate current upload # and can report that progress on next attempt. try: return self._upload_file_bytes(conn, http_conn, fp, file_length, total_bytes_uploaded, cb, num_cb) except (ResumableUploadException, socket.error): resp = self._query_server_state(conn, file_length) if resp.status == 400: raise ResumableUploadException('Got 400 response from server ' 'state query after failed resumable upload attempt. This ' 'can happen if the file size changed between upload ' 'attempts', ResumableTransferDisposition.ABORT) else: raise finally: http_conn.close() def _check_final_md5(self, key, etag): """ Checks that etag from server agrees with md5 computed before upload. This is important, since the upload could have spanned a number of hours and multiple processes (e.g., gsutil runs), and the user could change some of the file and not realize they have inconsistent data. """ if key.bucket.connection.debug >= 1: print 'Checking md5 against etag.' if key.md5 != etag.strip('"\''): # Call key.open_read() before attempting to delete the # (incorrect-content) key, so we perform that request on a # different HTTP connection. This is neededb because httplib # will return a "Response not ready" error if you try to perform # a second transaction on the connection. key.open_read() key.close() key.delete() raise ResumableUploadException( 'File changed during upload: md5 signature doesn\'t match etag ' '(incorrect uploaded object deleted)', ResumableTransferDisposition.ABORT) def send_file(self, key, fp, headers, cb=None, num_cb=10): """ Upload a file to a key into a bucket on GS, using GS resumable upload protocol. :type key: :class:`boto.s3.key.Key` or subclass :param key: The Key object to which data is to be uploaded :type fp: file-like object :param fp: The file pointer to upload :type headers: dict :param headers: The headers to pass along with the PUT request :type cb: function :param cb: a callback function that will be called to report progress on the upload. The callback should accept two integer parameters, the first representing the number of bytes that have been successfully transmitted to GS, and the second representing the total number of bytes that need to be transmitted. :type num_cb: int :param num_cb: (optional) If a callback is specified with the cb parameter, this parameter determines the granularity of the callback by defining the maximum number of times the callback will be called during the file transfer. Providing a negative integer will cause your callback to be called with each buffer read. Raises ResumableUploadException if a problem occurs during the transfer. """ if not headers: headers = {} fp.seek(0, os.SEEK_END) file_length = fp.tell() fp.seek(0) debug = key.bucket.connection.debug # Use num-retries from constructor if one was provided; else check # for a value specified in the boto config file; else default to 5. if self.num_retries is None: self.num_retries = config.getint('Boto', 'num_retries', 5) progress_less_iterations = 0 while True: # Retry as long as we're making progress. server_had_bytes_before_attempt = self.server_has_bytes try: etag = self._attempt_resumable_upload(key, fp, file_length, headers, cb, num_cb) # Upload succceded, so remove the tracker file (if have one). self._remove_tracker_file() self._check_final_md5(key, etag) if debug >= 1: print 'Resumable upload complete.' return except self.RETRYABLE_EXCEPTIONS, e: if debug >= 1: print('Caught exception (%s)' % e.__repr__()) if isinstance(e, IOError) and e.errno == errno.EPIPE: # Broken pipe error causes httplib to immediately # close the socket (http://bugs.python.org/issue5542), # so we need to close the connection before we resume # the upload (which will cause a new connection to be # opened the next time an HTTP request is sent). key.bucket.connection.connection.close() except ResumableUploadException, e: if (e.disposition == ResumableTransferDisposition.ABORT_CUR_PROCESS): if debug >= 1: print('Caught non-retryable ResumableUploadException ' '(%s); aborting but retaining tracker file' % e.message) raise elif (e.disposition == ResumableTransferDisposition.ABORT): if debug >= 1: print('Caught non-retryable ResumableUploadException ' '(%s); aborting and removing tracker file' % e.message) self._remove_tracker_file() raise else: if debug >= 1: print('Caught ResumableUploadException (%s) - will ' 'retry' % e.message) # At this point we had a re-tryable failure; see if made progress. if self.server_has_bytes > server_had_bytes_before_attempt: progress_less_iterations = 0 else: progress_less_iterations += 1 if progress_less_iterations > self.num_retries: # Don't retry any longer in the current process. raise ResumableUploadException( 'Too many resumable upload attempts failed without ' 'progress. You might try this upload again later', ResumableTransferDisposition.ABORT_CUR_PROCESS) sleep_time_secs = 2**progress_less_iterations if debug >= 1: print ('Got retryable failure (%d progress-less in a row).\n' 'Sleeping %d seconds before re-trying' % (progress_less_iterations, sleep_time_secs)) time.sleep(sleep_time_secs)
bsd-3-clause
bpetering/python-pattern-recognition
pattern_recognition.py
1
2300
def constant(diffs): val = diffs.pop() for d in diffs: if d != val: return False return val def pat1(seq): # consider two elements at a time diffs = [] for i in xrange(1, len(seq)): diffs.append( seq[i] - seq[i-1] ) # implicit directionality - factor out return constant(diffs) # representation of the pattern for pat1 was easy. how can we represent # more complex patterns? class Pattern(object): (PAT_INT_ADD, PAT_INT_MULT, PAT_INT_POW) = range(3) # TODO how does panda3d get constants? def __init__(self, pat_type, pat_vals, prev_data, over=2, *args, **kwargs): self.pat_type = pat_type self.over = over self.prev_data = prev_data self.pat_vals = pat_vals def next(self): if self.pat_type == Pattern.PAT_INT_ADD: tmp = self.prev_data[-1] + self.pat_vals[0] # TODO how much prev_data to keep? self.prev_data.append(tmp) return tmp class PatternSeq(object): def __init__(self, *args, **kwargs): self.pattern = None def have_pattern(self): return self.pattern is not None def infer(self, seq): v = pat1(seq) if v is not False: self.pattern = Pattern(pat_type=Pattern.PAT_INT_ADD, pat_vals=[v], prev_data=seq) # TODO generalize else: raise Exception("NYI") def extend(self, n): if self.have_pattern(): x = [] for i in xrange(n): x.append(self.pattern.next()) return x else: raise Exception("ALSDKJLASKJD") # def pat2(seq): # consider three elements at a time # diffs = [] # for i in xrange(1, len(seq)): # diffs.append( seq[i] - seq[i-1] ) # implicit directionality - factor out # val = constant(diffs) # if val is False: # print 'no pattern' # else: # print val # TODO look at sympy interface, requests interface # TODO detect pattern with certain number of anomalous values: # e.g. 2,4,6,8,11 ps = PatternSeq() ps.infer([2,4,6,8,10]) print "have pattern:", ps.have_pattern() print "next 10 vals:", ps.extend(10)
mit
SteveHNH/ansible
lib/ansible/modules/notification/typetalk.py
78
3392
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: typetalk version_added: "1.6" short_description: Send a message to typetalk description: - Send a message to typetalk using typetalk API ( http://developers.typetalk.in/ ) options: client_id: description: - OAuth2 client ID required: true client_secret: description: - OAuth2 client secret required: true topic: description: - topic id to post message required: true msg: description: - message body required: true requirements: [ json ] author: "Takashi Someda (@tksmd)" ''' EXAMPLES = ''' - typetalk: client_id: 12345 client_secret: 12345 topic: 1 msg: install completed ''' import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils.urls import fetch_url, ConnectionError def do_request(module, url, params, headers=None): data = urlencode(params) if headers is None: headers = dict() headers = dict(headers, **{ 'User-Agent': 'Ansible/typetalk module', }) r, info = fetch_url(module, url, data=data, headers=headers) if info['status'] != 200: exc = ConnectionError(info['msg']) exc.code = info['status'] raise exc return r def get_access_token(module, client_id, client_secret): params = { 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'client_credentials', 'scope': 'topic.post' } res = do_request(module, 'https://typetalk.in/oauth2/access_token', params) return json.load(res)['access_token'] def send_message(module, client_id, client_secret, topic, msg): """ send message to typetalk """ try: access_token = get_access_token(module, client_id, client_secret) url = 'https://typetalk.in/api/v1/topics/%d' % topic headers = { 'Authorization': 'Bearer %s' % access_token, } do_request(module, url, {'message': msg}, headers) return True, {'access_token': access_token} except ConnectionError as e: return False, e def main(): module = AnsibleModule( argument_spec=dict( client_id=dict(required=True), client_secret=dict(required=True, no_log=True), topic=dict(required=True, type='int'), msg=dict(required=True), ), supports_check_mode=False ) if not json: module.fail_json(msg="json module is required") client_id = module.params["client_id"] client_secret = module.params["client_secret"] topic = module.params["topic"] msg = module.params["msg"] res, error = send_message(module, client_id, client_secret, topic, msg) if not res: module.fail_json(msg='fail to send message with response code %s' % error.code) module.exit_json(changed=True, topic=topic, msg=msg) if __name__ == '__main__': main()
gpl-3.0
realsobek/freeipa
ipatests/test_integration/test_kerberos_flags.py
3
7164
# Authors: # Ana Krivokapic <akrivoka@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # 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/>. from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_plugins.integration import tasks class TestKerberosFlags(IntegrationTest): """ Test Kerberos Flags http://www.freeipa.org/page/V3/Kerberos_Flags#Test_Plan """ topology = 'line' num_clients = 1 def test_set_flag_with_host_add(self): host = 'host.example.com' host_service = 'host/%s' % host host_keytab = '/tmp/host.keytab' for trusted in (True, False, None): self.add_object('host', host, trusted=trusted, force=True) self.check_flag_cli('host', host, trusted=trusted) self.rekinit() self.getkeytab(host_service, host_keytab) self.kvno(host_service) self.check_flag_klist(host_service, trusted=trusted) self.del_object('host', host) def test_set_and_clear_flag_with_host_mod(self): client_hostname = self.clients[0].hostname host_service = 'host/%s' % client_hostname self.kvno(host_service) self.check_flag_cli('host', client_hostname, trusted=False) self.check_flag_klist(host_service, trusted=False) for trusted in (True, False): self.mod_object_cli('host', client_hostname, trusted=trusted) self.check_flag_cli('host', client_hostname, trusted=trusted) self.rekinit() self.kvno(host_service) self.check_flag_klist(host_service, trusted=trusted) for trusted in (True, False): self.mod_service_kadmin_local(host_service, trusted=trusted) self.check_flag_cli('host', client_hostname, trusted=trusted) self.rekinit() self.kvno(host_service) self.check_flag_klist(host_service, trusted=trusted) def test_set_flag_with_service_add(self): ftp_service = 'ftp/%s' % self.master.hostname ftp_keytab = '/tmp/ftp.keytab' for trusted in (True, False, None): self.add_object('service', ftp_service, trusted=trusted) self.check_flag_cli('service', ftp_service, trusted=trusted) self.rekinit() self.getkeytab(ftp_service, ftp_keytab) self.kvno(ftp_service) self.check_flag_klist(ftp_service, trusted=trusted) self.del_object('service', ftp_service) def test_set_and_clear_flag_with_service_mod(self): http_service = 'HTTP/%s' % self.master.hostname self.kvno(http_service) self.check_flag_cli('service', http_service, trusted=False) self.check_flag_klist(http_service, trusted=False) for trusted in (True, False): self.mod_object_cli('service', http_service, trusted=trusted) self.check_flag_cli('service', http_service, trusted=trusted) self.rekinit() self.kvno(http_service) self.check_flag_klist(http_service, trusted=trusted) for trusted in (True, False): self.mod_service_kadmin_local(http_service, trusted=trusted) self.check_flag_cli('service', http_service, trusted=trusted) self.rekinit() self.kvno(http_service) self.check_flag_klist(http_service, trusted=trusted) def test_try_to_set_flag_using_unexpected_values(self): http_service = 'HTTP/%s' % self.master.hostname invalid_values = ['blah', 'yes', 'y', '2', '1.0', '$'] for v in invalid_values: self.mod_object_cli('service', http_service, trusted=v, expect_fail=True) def add_object(self, object_type, object_id, trusted=None, force=False): args = ['ipa', '%s-add' % object_type, object_id] if trusted is True: args.extend(['--ok-as-delegate', '1']) elif trusted is False: args.extend(['--ok-as-delegate', '0']) if force: args.append('--force') self.master.run_command(args) def del_object(self, object_type, object_id): self.master.run_command(['ipa', '%s-del' % object_type, object_id]) def mod_object_cli(self, object_type, object_id, trusted, expect_fail=False): args = ['ipa', '%s-mod' % object_type, object_id] if trusted is True: args.extend(['--ok-as-delegate', '1']) elif trusted is False: args.extend(['--ok-as-delegate', '0']) else: args.extend(['--ok-as-delegate', trusted]) result = self.master.run_command(args, raiseonerr=not expect_fail) if expect_fail: stderr_text = "invalid 'ipakrbokasdelegate': must be True or False" assert result.returncode == 1 assert stderr_text in result.stderr_text def mod_service_kadmin_local(self, service, trusted): sign = '+' if trusted else '-' stdin_text = '\n'.join([ 'modify_principal %sok_as_delegate %s' % (sign, service), 'q', '' ]) self.master.run_command('kadmin.local', stdin_text=stdin_text) def check_flag_cli(self, object_type, object_id, trusted): result = self.master.run_command( ['ipa', '%s-show' % object_type, object_id, '--all'] ) if trusted: assert 'Trusted for delegation: True' in result.stdout_text else: assert 'Trusted for delegation: False' in result.stdout_text def check_flag_klist(self, service, trusted): result = self.master.run_command(['klist', '-f']) output_lines = result.stdout_text.split('\n') flags = '' for line, next_line in zip(output_lines, output_lines[1:]): if service in line: flags = next_line.replace('Flags:', '').strip() if trusted: assert 'O' in flags else: assert 'O' not in flags def rekinit(self): self.master.run_command(['kdestroy']) tasks.kinit_admin(self.master) def getkeytab(self, service, keytab): result = self.master.run_command([ 'ipa-getkeytab', '-s', self.master.hostname, '-p', service, '-k', keytab ]) assert 'Keytab successfully retrieved' in result.stderr_text def kvno(self, service): self.master.run_command(['kvno', service])
gpl-3.0
cogstat/cogstat
cogstat/test/test_stat.py
1
22429
# -*- coding: utf-8 -*- import unittest import os import sys sys.path.insert(0, os.path.abspath('../..')) print(sys.path) from pathlib import Path import numpy as np import pandas as pd from cogstat import cogstat as cs print(cs.__file__) print(cs.__version__) print(os.path.abspath(cs.__file__)) """ - All statistical value should be tested at least once. - All leafs of the decision tree should be tested once. - Tests shouldn't give p<0.001 results, because exact values cannot be tested. - No need to test the details of the statistical methods imported from other modules, because that is the job of that specific module. - All variables should be used with 3 digits decimal precision, to ensure that copying the data for validation no additional rounding happens. """ #cs.output_type = 'do not format' np.random.seed(555) # https://docs.scipy.org/doc/numpy/reference/routines.random.html # Make sure to use round function to have the same precision of the data when copied to other software data_np = np.vstack(( np.round(np.random.normal(loc=3, scale=3, size=30), 3), np.round(np.random.lognormal(mean=3, sigma=3, size=30), 3), np.random.randint(3, size=30), np.random.randint(3, size=30), np.round(np.random.normal(loc=3, scale=3, size=30), 3), np.round(np.random.lognormal(mean=1.4, sigma=0.6, size=30), 3), np.round(np.random.normal(loc=6, scale=3, size=30), 3), np.round(np.random.normal(loc=7, scale=6, size=30), 3), np.random.randint(2, size=30), np.random.randint(2, size=30), np.random.randint(2, size=30), np.concatenate((np.round(np.random.normal(loc=3, scale=3, size=15), 3), np.round(np.random.normal(loc=4, scale=3, size=15), 3))), np.array([1]*15+[2]*15), np.array([1]+[2]*29), np.concatenate((np.round(np.random.normal(loc=3, scale=3, size=15), 3), np.round(np.random.lognormal(mean=1.5, sigma=2.0, size=15), 3))), np.concatenate((np.round(np.random.normal(loc=3, scale=3, size=15), 3), np.round(np.random.normal(loc=3, scale=7, size=15), 3))), np.array([1]*10+[2]*8+[3]*12), np.concatenate((np.round(np.random.normal(loc=3, scale=3, size=10), 3), np.round(np.random.normal(loc=3, scale=3, size=8), 3), np.round(np.random.normal(loc=6, scale=3, size=12), 3))) )) data_pd = pd.DataFrame(data_np.T, columns= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r']) data = cs.CogStatData(data=data_pd, measurement_levels=['int', 'int', 'nom', 'nom', 'int', 'int', 'int', 'int', 'nom', 'nom', 'nom', 'int', 'nom', 'nom', 'int', 'int', 'int', 'int']) #pd.set_option('display.expand_frame_repr', False) #print (data_pd) class CogStatTestCase(unittest.TestCase): """Unit tests for CogStat.""" def test_explore_variables(self): """Test explore variables""" # Int variable result = data.explore_variable('a', 1, 2.0) #for i, res in enumerate(result): print(i, res) self.assertTrue('N of valid cases: 30' in result[2]) self.assertTrue('N of missing cases: 0' in result[2]) self.assertTrue('<td>Mean</td> <td>3.1438</td>' in result[4]) self.assertTrue('<td>Standard deviation</td> <td>3.2152</td>' in result[4]) self.assertTrue('<td>Skewness</td> <td>0.3586</td>' in result[4]) self.assertTrue('<td>Kurtosis</td> <td>0.0446</td>' in result[4]) self.assertTrue('<td>Range</td> <td>12.7840</td>' in result[4]) self.assertTrue('<td>Maximum</td> <td>9.9810</td>' in result[4]) self.assertTrue('<td>Upper quartile</td> <td>4.3875</td>' in result[4]) self.assertTrue('<td>Median</td> <td>2.8545</td>' in result[4]) self.assertTrue('<td>Lower quartile</td> <td>1.4190</td>' in result[4]) self.assertTrue('<td>Minimum</td> <td>-2.8030</td>' in result[4]) # Shapiro–Wilk normality self.assertTrue('<i>W</i> = 0.96' in result[6]) # <i>W</i> = 0.959 self.assertTrue('<i>p</i> = .287' in result[6]) # Population estimation and one sample t-test self.assertTrue('<td>Mean</td> <td>3.1438</td> <td>1.9227</td> <td>4.3649</td>' in result[9]) self.assertTrue('<td>Standard deviation</td> <td>3.2702</td> <td>2.6044</td> <td>4.3961</td>' in result[9]) # Sensitivity power analysis # G*Power 3.1.9.6: 0.6811825 # jamovi v1.2.19.0, jpower 0.1.2: 0.681 self.assertTrue('(effect size is in d): 0.68' in result[11]) self.assertTrue('t</i>(29) = 1.92' in result[11]) self.assertTrue('p</i> = .065' in result[11]) # Wilcoxon signed-rank test for non-normal interval variable result = data.explore_variable('b', 0, 20.0) self.assertTrue('T</i> = 203' in result[11]) self.assertTrue('p</i> = .551' in result[11]) # Ord variable data.data_measlevs['a'] = 'ord' result = data.explore_variable('a', 1, 2.0) self.assertTrue('N of valid cases: 30' in result[2]) self.assertTrue('N of missing cases: 0' in result[2]) self.assertTrue('<td>Maximum</td> <td>9.9810</td>' in result[4]) self.assertTrue('<td>Upper quartile</td> <td>4.3875</td>' in result[4]) self.assertTrue('<td>Median</td> <td>2.8545</td>' in result[4]) self.assertTrue('<td>Lower quartile</td> <td>1.4190</td>' in result[4]) self.assertTrue('<td>Minimum</td> <td>-2.8030</td>' in result[4]) # TODO median CI # Wilcoxon signed-rank test self.assertTrue('T</i> = 145' in result[9]) self.assertTrue('p</i> = .074' in result[9]) data.data_measlevs['a'] = 'int' # Nominal variable #result = data.explore_variable('c') # TODO variation ratio # TODO multinomial proportion CI def test_explore_variable_pairs(self): """Test explore variable pairs""" # Int variables result = data.explore_variable_pair('a', 'b') self.assertTrue('N of valid pairs: 30' in result[1]) self.assertTrue('N of missing pairs: 0' in result[1]) self.assertTrue('-0.141' in result[4]) self.assertTrue('[-0.477, 0.231]' in result[6]) self.assertTrue("Pearson's correlation: <i>r</i>(28) = -0.14, <i>p</i> = .456" in result[7]) # <i>r</i>(28) = -0.141 self.assertTrue('y = -21.811x + 300.505' in result[3]) self.assertTrue('-0.363' in result[4]) self.assertTrue('[-0.640, -0.003]' in result[6]) self.assertTrue("Spearman's rank-order correlation: <i>r<sub>s</sub></i>(28) = -0.36, <i>p</i> = .048" in result[7]) # <i>r<sub>s</sub></i>(28) = -0.363 # Ord variables data.data_measlevs['a'] = 'ord' data.data_measlevs['b'] = 'ord' result = data.explore_variable_pair('a', 'b') self.assertTrue('-0.363' in result[4]) self.assertTrue('[-0.640, -0.003]' in result[5]) self.assertTrue("Spearman's rank-order correlation: <i>r<sub>s</sub></i>(28) = -0.36, <i>p</i> = .048" in result[6]) # <i>r<sub>s</sub></i>(28) = -0.363 data.data_measlevs['a'] = 'int' data.data_measlevs['b'] = 'int' # Nom variables result = data.explore_variable_pair('c', 'd') self.assertTrue('N of valid pairs: 30' in result[1]) self.assertTrue('N of missing pairs: 0' in result[1]) # Cramer's V self.assertTrue('<sub>c</sub></i> = 0.372' in result[4]) # Sensitivity power analysis # G*Power 3.1.9.6, Goodness of fit test, df=4: Contingency tables: 0.7868005 # TODO GPower gives 0.8707028 with df of 8; Seems like statsmodels GofChisquarePower calculates power # with df=8; should we use 4 or 8 df? https://github.com/cogstat/cogstat/issues/134 self.assertTrue('(effect size is in w): 0.87' in result[6]) # Chi-squared # jamovi v1.2.19.0: X2, df, p, N: 8.31, 4, 0.081, 30 self.assertTrue('(4, <i>N</i> = 30) = 8.31' in result[6]) # (4, <i>N</i> = 30) = 8.312 self.assertTrue('<i>p</i> = .081' in result[6]) def test_diffusion(self): """Test diffusion analysis""" data_diffusion = cs.CogStatData(data=str(Path('data/diffusion.csv'))) result = data_diffusion.diffusion(error_name=['Error'], RT_name=['RT_sec'], participant_name=['Name'], condition_names=['Num1', 'Num2']) # Drift rate self.assertTrue('<td>zsiraf</td> <td>0.190</td> <td>0.276</td> <td>0.197</td> <td>0.235</td> <td>0.213</td>' in result[1]) # Threshold self.assertTrue('<td>zsiraf</td> <td>0.178</td> <td>0.096</td> <td>0.171</td> <td>0.112</td> <td>0.088</td>' in result[1]) # Nondecision time self.assertTrue('<td>zsiraf</td> <td>0.481</td> <td>0.590</td> <td>0.483</td> <td>0.561</td> <td>0.522</td>' in result[1]) def test_compare_variables(self): """Test compare variables""" # 2 Int variables result = data.compare_variables(['a', 'e']) self.assertTrue('N of valid cases: 30' in result[1]) self.assertTrue('N of missing cases: 0' in result[1]) # Cohen's d # CS formula: https://pingouin-stats.org/generated/pingouin.compute_effsize.html # Based on the formula, calculated in LO Calc 6.4: 0.030004573510063 # jamovi v1.2.19.0: 0.0202; formula: https://github.com/jamovi/jmv/blob/master/R/ttestps.b.R#L54-L66 self.assertTrue("<td>Cohen's d</td> <td>0.030</td>" in result[3]) # eta-squared # CS formula: https://pingouin-stats.org/generated/pingouin.convert_effsize.html # Based on the formula, calculated in LO Calc 6.4: 0.0002250179634 # jamovi v1.2.19.0: 0.000 self.assertTrue('<td>Eta-squared</td> <td>0.000</td>' in result[3]) # Sample means self.assertTrue('<td>3.1438</td> <td>3.0502</td>' in result[3]) # Hedges'g (with CI) # CS formula: https://pingouin-stats.org/generated/pingouin.compute_effsize.html # https://pingouin-stats.org/generated/pingouin.compute_esci.html # Note that the latter (CI) method has changed in v0.3.5 https://pingouin-stats.org/changelog.html # Based on the formula, calculated in LO Calc 7.0: 0.029614903724218, -0.34445335392457, 0.403683161373007 # Note that the last value is 0.404 in LO, not .403 as in pingouin self.assertTrue("<td>Hedges' g</td> <td>0.030</td> <td>-0.344</td> <td>0.403</td>" in result[5]) self.assertTrue('<i>W</i> = 0.95, <i>p</i> = .215' in result[7]) # <i>W</i> = 0.954 # Sensitivity power analysis # G*Power 3.1.9.6: 0.6811825 # jamovi v1.2.19.0, jpower 0.1.2: 0.681 self.assertTrue('(effect size is in d): 0.68' in result[7]) # Paired samples t-test # jamovi v1.2.19.0: t, df, p: 0.110, 29.0, 0.913 self.assertTrue('<i>t</i>(29) = 0.11, <i>p</i> = .913' in result[7]) # 2 Int variables - non-normal result = data.compare_variables(['e', 'f']) self.assertTrue('<i>W</i> = 0.91, <i>p</i> = .019' in result[7]) # <i>W</i> = 0.915 self.assertTrue('<i>T</i> = 110.00, <i>p</i> = .012' in result[7]) # 3 Int variables result = data.compare_variables(['a', 'e', 'g']) self.assertTrue('<td>3.1438</td> <td>3.0502</td> <td>5.7295</td>' in result[3]) self.assertTrue('a: <i>W</i> = 0.96, <i>p</i> = .287' in result[7]) # <i>W</i> = 0.959 self.assertTrue('e: <i>W</i> = 0.97, <i>p</i> = .435' in result[7]) # <i>W</i> = 0.966 self.assertTrue('g: <i>W</i> = 0.95, <i>p</i> = .133' in result[7]) #x <i>W</i> = 0.946 self.assertTrue('sphericity: <i>W</i> = 0.98, <i>p</i> = .703' in result[7]) # <i>W</i> = 0.975 self.assertTrue('<i>F</i>(2, 58) = 6.17, <i>p</i> = .004' in result[7]) self.assertTrue('0.11, <i>p</i> = .913' in result[7]) # TODO keep the order of the variables, and have a fixed sign self.assertTrue('3.17, <i>p</i> = .011' in result[7]) self.assertTrue('2.88, <i>p</i> = .015' in result[7]) # 3 Int variables, sphericity violated result = data.compare_variables(['a', 'e', 'h']) self.assertTrue('<td>3.1438</td> <td>3.0502</td> <td>6.5786</td>' in result[3]) self.assertTrue('a: <i>W</i> = 0.96, <i>p</i> = .287' in result[7]) # <i>W</i> = 0.959 self.assertTrue('e: <i>W</i> = 0.97, <i>p</i> = .435' in result[7]) # <i>W</i> = 0.966 self.assertTrue('h: <i>W</i> = 0.98, <i>p</i> = .824' in result[7]) self.assertTrue('sphericity: <i>W</i> = 0.79, <i>p</i> = .039' in result[7]) # <i>W</i> = 0.793 self.assertTrue('<i>F</i>(1.66, 48) = 6.16, <i>p</i> = .007' in result[7]) self.assertTrue('0.11, <i>p</i> = .913' in result[7]) # TODO keep the order of the variables, and have a fixed sign self.assertTrue('2.68, <i>p</i> = .024' in result[7]) self.assertTrue('2.81, <i>p</i> = .026' in result[7]) # 3 Int variables, non-normal result = data.compare_variables(['a', 'e', 'f']) self.assertTrue('<td>3.1438</td> <td>3.0502</td> <td>5.3681</td>' in result[3]) self.assertTrue('a: <i>W</i> = 0.96, <i>p</i> = .287' in result[7]) # <i>W</i> = 0.959 self.assertTrue('e: <i>W</i> = 0.97, <i>p</i> = .435' in result[7]) # <i>W</i> = 0.966 self.assertTrue('f: <i>W</i> = 0.82, <i>p</i> &lt; .001' in result[7]) # <i>W</i> = 0.818 self.assertTrue('&chi;<sup>2</sup>(2, <i>N</i> = 30) = 6.47, <i>p</i> = .039' in result[7]) # 2 × 2 Int variables result = data.compare_variables(['a', 'b', 'e', 'f'], factors=[['first', 2], ['second', 2]]) self.assertTrue('Main effect of first: <i>F</i>(1, 29) = 6.06, <i>p</i> = .020' in result[7]) self.assertTrue('Main effect of second: <i>F</i>(1, 29) = 6.29, <i>p</i> = .018' in result[7]) self.assertTrue('Interaction of factors first, second: <i>F</i>(1, 29) = 6.04, <i>p</i> = .020' in result[7]) # 2 Ord variables data.data_measlevs['a'] = 'ord' data.data_measlevs['e'] = 'ord' data.data_measlevs['f'] = 'ord' result = data.compare_variables(['e', 'f']) self.assertTrue('<td>2.3895</td> <td>4.2275</td>' in result[3]) self.assertTrue('<i>T</i> = 110.00, <i>p</i> = .012' in result[6]) # 3 Ord variables result = data.compare_variables(['a', 'e', 'f']) self.assertTrue('<td>2.8545</td> <td>2.3895</td> <td>4.2275</td>' in result[3]) self.assertTrue('&chi;<sup>2</sup>(2, <i>N</i> = 30) = 6.47, <i>p</i> = .039' in result[6]) data.data_measlevs['a'] = 'int' data.data_measlevs['e'] = 'int' data.data_measlevs['f'] = 'int' # 2 Nom variables result = data.compare_variables(['i', 'j']) # TODO on Linux the row labels are 0.0 and 1.0 instead of 0 and 1 self.assertTrue('<td>0.0</td> <td>4</td> <td>9</td> <td>13</td> </tr> <tr> <td>1.0</td> <td>9</td>' in result[3]) self.assertTrue('&chi;<sup>2</sup>(1, <i>N</i> = 30) = 0.06, <i>p</i> = .814' in result[5]) # &chi;<sup>2</sup>(1, <i>N</i> = 30) = 0.0556 # 3 Nom variables result = data.compare_variables(['i', 'j', 'k']) self.assertTrue('<i>Q</i>(2, <i>N</i> = 30) = 0.78, <i>p</i> = .676' in result[7]) # <i>Q</i>(2, <i>N</i> = 30) = 0.783 def test_compare_groups(self): """Test compare groups""" # 2 Int groups result = data.compare_groups('l', ['m']) self.assertTrue('<td>2.5316</td> <td>4.5759</td>' in result[3]) # Cohen's d # CS formula: https://pingouin-stats.org/generated/pingouin.compute_effsize.html # Based on the formula, calculated in LO Calc 6.4: -0.704171924382848 # jamovi v1.2.19.0: 0.0704 self.assertTrue("<td>Cohen's d</td> <td>-0.704</td>" in result[3]) # eta-squared # CS formula: https://pingouin-stats.org/generated/pingouin.convert_effsize.html # Based on the formula, calculated in LO Calc 6.4: 0.110292204104377 # jamovi v1.2.19.0: 0.117 # TODO why the difference? self.assertTrue('<td>Eta-squared</td> <td>0.110</td>' in result[3]) # Hedges'g (with CI) # CS formula: https://pingouin-stats.org/generated/pingouin.compute_effsize.html # https://pingouin-stats.org/generated/pingouin.compute_esci.html # Note that the latter (CI) method has changed in v0.3.5 https://pingouin-stats.org/changelog.html # Based on the formula, calculated in LO Calc 7.0: -0.685140250750879, -1.45474443187683, 0.084463930375068 self.assertTrue('<td>Difference between the two groups:</td> <td>-2.0443</td> <td>-4.2157</td> <td>0.1272</td>' in result[5]) self.assertTrue("<td>Hedges' g</td> <td>-0.685</td> <td>-1.455</td> <td>0.084</td>" in result[6]) self.assertTrue('(m: 1.0): <i>W</i> = 0.96, <i>p</i> = .683' in result[8]) # <i>W</i> = 0.959 self.assertTrue('(m: 2.0): <i>W</i> = 0.98, <i>p</i> = .991' in result[8]) # <i>W</i> = 0.984 self.assertTrue('<i>W</i> = 0.30, <i>p</i> = .585' in result[8]) # <i>W</i> = 0.305 # Sensitivity power analysis # G*Power 3.1.9.6: 1.3641059 # jamovi v1.2.19.0, jpower 0.1.2: 1.36 self.assertTrue('(effect size is in d): 1.36' in result[8]) # independent samples t-test # jamovi v1.2.19.0: t, df, p: -1.93, 28.0, 0.064 self.assertTrue('<i>t</i>(28) = -1.93, <i>p</i> = .064' in result[8]) # Non-normal group result = data.compare_groups('o', ['m']) self.assertTrue('(m: 2.0): <i>W</i> = 0.81, <i>p</i> = .005' in result[8]) # <i>W</i> = 0.808 self.assertTrue('<i>U</i> = 51.00, <i>p</i> = .011' in result[8]) # Heteroscedastic groups result = data.compare_groups('p', ['m']) self.assertTrue('<i>t</i>(25.3) = 0.12, <i>p</i> = .907' in result[8]) # <i>t</i>(25.3) = 0.119 # TODO single case vs. group # 3 Int groups result = data.compare_groups('r', ['q']) self.assertTrue('<td>3.2869</td> <td>5.0400</td> <td>7.2412</td>' in result[3]) self.assertTrue('<i>W</i> = 0.68, <i>p</i> = .517' in result[8]) # TODO this might be incorrect # <i>W</i> = 0.675 # Sensitivity power analysis # G*Power 3.1.9.6: 0.7597473 self.assertTrue('(effect size is in f): 0.76' in result[8]) self.assertTrue('<i>F</i>(2, 27) = 4.00, <i>p</i> = .030' in result[8]) self.assertTrue('&omega;<sup>2</sup> = 0.167' in result[6]) # TODO post-hoc # 3 Int groups with assumption violation result = data.compare_groups('o', ['q']) self.assertTrue('&chi;<sup>2</sup>(2, <i>N</i> = 30) = 8.37, <i>p</i> = .015' in result[8]) # 2 Ord groups data.data_measlevs['o'] = 'ord' result = data.compare_groups('o', ['m']) self.assertTrue('<i>U</i> = 51.00, <i>p</i> = .011' in result[6]) # 3 Ord groups data.data_measlevs['o'] = 'ord' result = data.compare_groups('o', ['q']) self.assertTrue('&chi;<sup>2</sup>(2, <i>N</i> = 30) = 8.37, <i>p</i> = .015' in result[6]) data.data_measlevs['o'] = 'int' # 2 Nom groups result = data.compare_groups('i', ['j']) self.assertTrue('&phi;<i><sub>c</sub></i> = 0.154' in result[3]) # TODO validate self.assertTrue('&chi;<sup>2</sup></i>(1, <i>N</i> = 30) = 0.71, <i>p</i> = .399' in result[5]) # TODO validate # &chi;<sup>2</sup></i>(1, <i>N</i> = 30) = 0.710 # 3 Nom groups result = data.compare_groups('i', ['c']) self.assertTrue('&phi;<i><sub>c</sub></i> = 0.009' in result[3]) # TODO validate self.assertTrue('&chi;<sup>2</sup></i>(2, <i>N</i> = 30) = 0.00, <i>p</i> = .999' in result[5]) # TODO validate # &chi;<sup>2</sup></i>(2, <i>N</i> = 30) = 0.002 # 3 × 3 Int groups result = data.compare_groups('a', ['c', 'd']) self.assertTrue('<td>Mean</td> <td>1.0695</td> <td>1.8439</td> <td>2.3693</td>' in result[3]) self.assertTrue('<td>Standard deviation</td> <td>2.7005</td> <td>2.0891</td> <td>4.2610</td>' in result[3]) self.assertTrue('<td>Maximum</td> <td>4.4130</td> <td>4.7890</td> <td>9.1600</td>' in result[3]) self.assertTrue('<td>Upper quartile</td> <td>3.0000</td> <td>3.0213</td> <td>4.4028</td>' in result[3]) self.assertTrue('<td>Median</td> <td>1.3340</td> <td>2.4590</td> <td>0.9015</td>' in result[3]) self.assertTrue('<td>Lower quartile</td> <td>-0.5965</td> <td>0.8870</td> <td>-1.1320</td>' in result[3]) self.assertTrue('<td>Minimum</td> <td>-2.8030</td> <td>-2.2890</td> <td>-1.4860</td>' in result[3]) # TODO the two main effects differ from the SPSS result, see issue #91 self.assertTrue('<i>F</i>(2, 21) = 2.35, <i>p</i> = .120' in result[7]) self.assertTrue('<i>F</i>(2, 21) = 0.19, <i>p</i> = .832' in result[7]) # <i>F</i>(2, 21) = 0.185 self.assertTrue('<i>F</i>(4, 21) = 1.15, <i>p</i> = .363' in result[7]) def test_single_case(self): # Test for the slope stat data = cs.CogStatData(data='''group slope slope_SE Patient 0.247 0.069 Control 0.492 0.106 Control 0.559 0.108 Control 0.63 0.116 Control 0.627 0.065 Control 0.674 0.105 Control 0.538 0.107''') result = data.compare_groups('slope', ['group'], 'slope_SE', 25) self.assertTrue('Test d.2: <i>t</i>(42.1) = -4.21, <i>p</i> &lt; .001' in result[8]) result = data.compare_groups('slope', ['group']) self.assertTrue('<i>t</i>(5) = -5.05, <i>p</i> = .004' in result[8]) if __name__ == '__main__': unittest.main()
gpl-3.0
kochbeck/icsisumm
icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/draw/plot.py
9
28788
# Natural Language Toolkit: Simple Plotting # # Copyright (C) 2001-2008 University of Pennsylvania # Author: Edward Loper <edloper@gradient.cis.upenn.edu> # URL: <http://nltk.sf.net> # For license information, see LICENSE.TXT # # $Id: plot.py 5609 2007-12-31 03:02:41Z stevenbird $ """ A simple tool for plotting functions. Each new C{Plot} object opens a new window, containing the plot for a sinlge function. See the documentation for L{Plot} for information about creating new plots. Example plots ============= Plot sin(x) from -10 to 10, with a step of 0.1: >>> Plot(math.sin) Plot cos(x) from 0 to 2*pi, with a step of 0.01: >>> Plot(math.cos, slice(0, 2*math.pi, 0.01)) Plot a list of points (connected by lines). >>> points = ([1,1], [3,8], [5,3], [6,12], [1,24]) >>> Plot(points) Plot a list of y-values (connected by lines). Each value[i] is plotted at x=i. >>> values = [x**2 for x in range(200)] >>> Plot(values) Plot a function with logarithmic axes. >>> def f(x): return 5*x**2+2*x+8 >>> Plot(f, slice(1,10,.1), scale='log') Plot the same function with semi-logarithmic axes. >>> Plot(f, slice(1,10,.1), scale='log-linear') # logarithmic x; linear y >>> Plot(f, slice(1,10,.1), scale='linear-log') # linear x; logarithmic y BLT === If U{BLT<http://incrtcl.sourceforge.net/blt/>} and U{PMW<http://pmw.sourceforge.net/>} are both installed, then BLT is used to plot graphs. Otherwise, a simple Tkinter-based implementation is used. The Tkinter-based implementation does I{not} display axis values. @group Plot Frame Implementations: PlotFrameI, CanvasPlotFrame, BLTPlotFrame """ # This is used by "from nltk.draw.plot import *". to decide what to # import. It also declares to nltk that only the Plot class is public. __all__ = ['Plot'] # Implementation note: # For variable names, I use x,y for pixel coordinates; and i,j for # plot coordinates. # Delegate to BLT? # # from types import * from math import log, log10, ceil, floor import Tkinter, sys, time from nltk.draw import ShowText, in_idle class PlotFrameI(object): """ A frame for plotting graphs. If BLT is present, then we use BLTPlotFrame, since it's nicer. But we fall back on CanvasPlotFrame if BLTPlotFrame is unavaibale. """ def postscript(self, filename): 'Print the contents of the plot to the given file' raise AssertionError, 'PlotFrameI is an interface' def config_axes(self, xlog, ylog): 'Set the scale for the axes (linear/logarithmic)' raise AssertionError, 'PlotFrameI is an interface' def invtransform(self, x, y): 'Transform pixel coordinates to plot coordinates' raise AssertionError, 'PlotFrameI is an interface' def zoom(self, i1, j1, i2, j2): 'Zoom to the given range' raise AssertionError, 'PlotFrameI is an interface' def visible_area(self): 'Return the visible area rect (in plot coordinates)' raise AssertionError, 'PlotFrameI is an interface' def create_zoom_marker(self): 'mark the zoom region, for drag-zooming' raise AssertionError, 'PlotFrameI is an interface' def adjust_zoom_marker(self, x0, y0, x1, y1): 'adjust the zoom region marker, for drag-zooming' raise AssertionError, 'PlotFrameI is an interface' def delete_zoom_marker(self): 'delete the zoom region marker (for drag-zooming)' raise AssertionError, 'PlotFrameI is an interface' def bind(self, *args): 'bind an event to a function' raise AssertionError, 'PlotFrameI is an interface' def unbind(self, *args): 'unbind an event' raise AssertionError, 'PlotFrameI is an interface' class CanvasPlotFrame(PlotFrameI): def __init__(self, root, vals, rng): self._root = root self._original_rng = rng self._original_vals = vals self._frame = Tkinter.Frame(root) self._frame.pack(expand=1, fill='both') # Set up the canvas self._canvas = Tkinter.Canvas(self._frame, background='white') self._canvas['scrollregion'] = (0,0,200,200) # Give the canvas scrollbars. sb1 = Tkinter.Scrollbar(self._frame, orient='vertical') sb1.pack(side='right', fill='y') sb2 = Tkinter.Scrollbar(self._frame, orient='horizontal') sb2.pack(side='bottom', fill='x') self._canvas.pack(side='left', fill='both', expand=1) # Connect the scrollbars to the canvas. sb1.config(command=self._canvas.yview) sb2['command']=self._canvas.xview self._canvas['yscrollcommand'] = sb1.set self._canvas['xscrollcommand'] = sb2.set self._width = self._height = -1 self._canvas.bind('<Configure>', self._configure) # Start out with linear coordinates. self.config_axes(0, 0) def _configure(self, event): if self._width != event.width or self._height != event.height: self._width = event.width self._height = event.height (i1, j1, i2, j2) = self.visible_area() self.zoom(i1, j1, i2, j2) def postscript(self, filename): (x0, y0, w, h) = self._canvas['scrollregion'].split() self._canvas.postscript(file=filename, x=float(x0), y=float(y0), width=float(w)+2, height=float(h)+2) def _plot(self, *args): self._canvas.delete('all') (i1, j1, i2, j2) = self.visible_area() # Draw the Axes xzero = -self._imin*self._dx yzero = self._ymax+self._jmin*self._dy neginf = min(self._imin, self._jmin, -1000)*1000 posinf = max(self._imax, self._jmax, 1000)*1000 self._canvas.create_line(neginf,yzero,posinf,yzero, fill='gray', width=2) self._canvas.create_line(xzero,neginf,xzero,posinf, fill='gray', width=2) # Draw the X grid. if self._xlog: (i1, i2) = (10**(i1), 10**(i2)) (imin, imax) = (10**(self._imin), 10**(self._imax)) # Grid step size. di = (i2-i1)/1000.0 # round to a power of 10 di = 10.0**(int(log10(di))) # grid start location i = ceil(imin/di)*di while i <= imax: if i > 10*di: di *= 10 x = log10(i)*self._dx - log10(imin)*self._dx self._canvas.create_line(x, neginf, x, posinf, fill='gray') i += di else: # Grid step size. di = max((i2-i1)/10.0, (self._imax-self._imin)/100) # round to a power of 2 di = 2.0**(int(log(di)/log(2))) # grid start location i = int(self._imin/di)*di # Draw the grid. while i <= self._imax: x = (i-self._imin)*self._dx self._canvas.create_line(x, neginf, x, posinf, fill='gray') i += di # Draw the Y grid if self._ylog: (j1, j2) = (10**(j1), 10**(j2)) (jmin, jmax) = (10**(self._jmin), 10**(self._jmax)) # Grid step size. dj = (j2-j1)/1000.0 # round to a power of 10 dj = 10.0**(int(log10(dj))) # grid start locatjon j = ceil(jmin/dj)*dj while j <= jmax: if j > 10*dj: dj *= 10 y = log10(jmax)*self._dy - log10(j)*self._dy self._canvas.create_line(neginf, y, posinf, y, fill='gray') j += dj else: # Grid step size. dj = max((j2-j1)/10.0, (self._jmax-self._jmin)/100) # round to a power of 2 dj = 2.0**(int(log(dj)/log(2))) # grid start location j = int(self._jmin/dj)*dj # Draw the grid while j <= self._jmax: y = (j-self._jmin)*self._dy self._canvas.create_line(neginf, y, posinf, y, fill='gray') j += dj # The plot line = [] for (i,j) in zip(self._rng, self._vals): x = (i-self._imin) * self._dx y = self._ymax-((j-self._jmin) * self._dy) line.append( (x,y) ) if len(line) == 1: line.append(line[0]) self._canvas.create_line(line, fill='black') def config_axes(self, xlog, ylog): if hasattr(self, '_rng'): (i1, j1, i2, j2) = self.visible_area() zoomed=1 else: zoomed=0 self._xlog = xlog self._ylog = ylog if xlog: self._rng = [log10(x) for x in self._original_rng] else: self._rng = self._original_rng if ylog: self._vals = [log10(x) for x in self._original_vals] else: self._vals = self._original_vals self._imin = min(self._rng) self._imax = max(self._rng) if self._imax == self._imin: self._imin -= 1 self._imax += 1 self._jmin = min(self._vals) self._jmax = max(self._vals) if self._jmax == self._jmin: self._jmin -= 1 self._jmax += 1 if zoomed: self.zoom(i1, j1, i2, j2) else: self.zoom(self._imin, self._jmin, self._imax, self._jmax) def invtransform(self, x, y): x = self._canvas.canvasx(x) y = self._canvas.canvasy(y) return (self._imin+x/self._dx, self._jmin+(self._ymax-y)/self._dy) def zoom(self, i1, j1, i2, j2): w = self._width h = self._height self._xmax = (self._imax-self._imin)/(i2-i1) * w self._ymax = (self._jmax-self._jmin)/(j2-j1) * h self._canvas['scrollregion'] = (0, 0, self._xmax, self._ymax) self._dx = self._xmax/(self._imax-self._imin) self._dy = self._ymax/(self._jmax-self._jmin) self._plot() # Pan to the correct place self._canvas.xview('moveto', (i1-self._imin)/(self._imax-self._imin)) self._canvas.yview('moveto', (self._jmax-j2)/(self._jmax-self._jmin)) def visible_area(self): xview = self._canvas.xview() yview = self._canvas.yview() i1 = self._imin + xview[0] * (self._imax-self._imin) i2 = self._imin + xview[1] * (self._imax-self._imin) j1 = self._jmax - yview[1] * (self._jmax-self._jmin) j2 = self._jmax - yview[0] * (self._jmax-self._jmin) return (i1, j1, i2, j2) def create_zoom_marker(self): self._canvas.create_rectangle(0,0,0,0, tag='zoom') def adjust_zoom_marker(self, x0, y0, x1, y1): x0 = self._canvas.canvasx(x0) y0 = self._canvas.canvasy(y0) x1 = self._canvas.canvasx(x1) y1 = self._canvas.canvasy(y1) self._canvas.coords('zoom', x0, y0, x1, y1) def delete_zoom_marker(self): self._canvas.delete('zoom') def bind(self, *args): self._canvas.bind(*args) def unbind(self, *args): self._canvas.unbind(*args) class BLTPlotFrame(PlotFrameI): def __init__(self, root, vals, rng): #raise ImportError # for debugging CanvasPlotFrame # Find ranges self._imin = min(rng) self._imax = max(rng) if self._imax == self._imin: self._imin -= 1 self._imax += 1 self._jmin = min(vals) self._jmax = max(vals) if self._jmax == self._jmin: self._jmin -= 1 self._jmax += 1 # Create top-level frame. self._root = root self._frame = Tkinter.Frame(root) self._frame.pack(expand=1, fill='both') # Create the graph. try: import Pmw # This reload is needed to prevent an error if we create # more than 1 graph in the same interactive session: reload(Pmw.Blt) Pmw.initialise() self._graph = Pmw.Blt.Graph(self._frame) except: raise ImportError('Pmw not installed!') # Add scrollbars. sb1 = Tkinter.Scrollbar(self._frame, orient='vertical') sb1.pack(side='right', fill='y') sb2 = Tkinter.Scrollbar(self._frame, orient='horizontal') sb2.pack(side='bottom', fill='x') self._graph.pack(side='left', fill='both', expand='yes') self._yscroll = sb1 self._xscroll = sb2 # Connect the scrollbars to the canvas. sb1['command'] = self._yview sb2['command'] = self._xview # Create the plot. self._graph.line_create('plot', xdata=tuple(rng), ydata=tuple(vals), symbol='') self._graph.legend_configure(hide=1) self._graph.grid_configure(hide=0) self._set_scrollbars() def _set_scrollbars(self): (i1, j1, i2, j2) = self.visible_area() (imin, imax) = (self._imin, self._imax) (jmin, jmax) = (self._jmin, self._jmax) self._xscroll.set((i1-imin)/(imax-imin), (i2-imin)/(imax-imin)) self._yscroll.set(1-(j2-jmin)/(jmax-jmin), 1-(j1-jmin)/(jmax-jmin)) def _xview(self, *command): (i1, j1, i2, j2) = self.visible_area() (imin, imax) = (self._imin, self._imax) (jmin, jmax) = (self._jmin, self._jmax) if command[0] == 'moveto': f = float(command[1]) elif command[0] == 'scroll': dir = int(command[1]) if command[2] == 'pages': f = (i1-imin)/(imax-imin) + dir*(i2-i1)/(imax-imin) elif command[2] == 'units': f = (i1-imin)/(imax-imin) + dir*(i2-i1)/(10*(imax-imin)) else: return else: return f = max(f, 0) f = min(f, 1-(i2-i1)/(imax-imin)) self.zoom(imin + f*(imax-imin), j1, imin + f*(imax-imin)+(i2-i1), j2) self._set_scrollbars() def _yview(self, *command): (i1, j1, i2, j2) = self.visible_area() (imin, imax) = (self._imin, self._imax) (jmin, jmax) = (self._jmin, self._jmax) if command[0] == 'moveto': f = 1.0-float(command[1]) - (j2-j1)/(jmax-jmin) elif command[0] == 'scroll': dir = -int(command[1]) if command[2] == 'pages': f = (j1-jmin)/(jmax-jmin) + dir*(j2-j1)/(jmax-jmin) elif command[2] == 'units': f = (j1-jmin)/(jmax-jmin) + dir*(j2-j1)/(10*(jmax-jmin)) else: return else: return f = max(f, 0) f = min(f, 1-(j2-j1)/(jmax-jmin)) self.zoom(i1, jmin + f*(jmax-jmin), i2, jmin + f*(jmax-jmin)+(j2-j1)) self._set_scrollbars() def config_axes(self, xlog, ylog): self._graph.xaxis_configure(logscale=xlog) self._graph.yaxis_configure(logscale=ylog) def invtransform(self, x, y): return self._graph.invtransform(x, y) def zoom(self, i1, j1, i2, j2): self._graph.xaxis_configure(min=i1, max=i2) self._graph.yaxis_configure(min=j1, max=j2) self._set_scrollbars() def visible_area(self): (i1, i2) = self._graph.xaxis_limits() (j1, j2) = self._graph.yaxis_limits() return (i1, j1, i2, j2) def create_zoom_marker(self): self._graph.marker_create("line", name="zoom", dashes=(2, 2)) def adjust_zoom_marker(self, press_x, press_y, release_x, release_y): (i1, j1) = self._graph.invtransform(press_x, press_y) (i2, j2) = self._graph.invtransform(release_x, release_y) coords = (i1, j1, i2, j1, i2, j2, i1, j2, i1, j1) self._graph.marker_configure("zoom", coords=coords) def delete_zoom_marker(self): self._graph.marker_delete("zoom") def bind(self, *args): self._graph.bind(*args) def unbind(self, *args): self._graph.unbind(*args) def postscript(self, filename): self._graph.postscript_output(filename) class Plot(object): """ A simple graphical tool for plotting functions. Each new C{Plot} object opens a new window, containing the plot for a sinlge function. Multiple plots in the same window are not (yet) supported. The C{Plot} constructor supports several mechanisms for defining the set of points to plot. Example plots ============= Plot the math.sin function over the range [-10:10:.1]: >>> import math >>> Plot(math.sin) Plot the math.sin function over the range [0:1:.001]: >>> Plot(math.sin, slice(0, 1, .001)) Plot a list of points: >>> points = ([1,1], [3,8], [5,3], [6,12], [1,24]) >>> Plot(points) Plot a list of values, at x=0, x=1, x=2, ..., x=n: >>> Plot(x**2 for x in range(20)) """ def __init__(self, vals, rng=None, **kwargs): """ Create a new C{Plot}. @param vals: The set of values to plot. C{vals} can be a list of y-values; a list of points; or a function. @param rng: The range over which to plot. C{rng} can be a list of x-values, or a slice object. If no range is specified, a default range will be used. Note that C{rng} may I{not} be specified if C{vals} is a list of points. @keyword scale: The scales that should be used for the axes. Possible values are: - C{'linear'}: both axes are linear. - C{'log-linear'}: The x axis is logarithmic; and the y axis is linear. - C{'linear-log'}: The x axis is linear; and the y axis is logarithmic. - C{'log'}: Both axes are logarithmic. By default, C{scale} is C{'linear'}. """ # If range is a slice, then expand it to a list. if type(rng) is SliceType: (start, stop, step) = (rng.start, rng.stop, rng.step) if step>0 and stop>start: rng = [start] i = 0 while rng[-1] < stop: rng.append(start+i*step) i += 1 elif step<0 and stop<start: rng = [start] i = 0 while rng[-1] > stop: rng.append(start+i*step) i += 1 else: rng = [] # If vals is a function, evaluate it over range. if type(vals) in (FunctionType, BuiltinFunctionType, MethodType): if rng is None: rng = [x*0.1 for x in range(-100, 100)] try: vals = [vals(i) for i in rng] except TypeError: raise TypeError, 'Bad range type: %s' % type(rng) # If vals isn't a function, make sure it's a sequence: elif type(vals) not in (ListType, TupleType): raise ValueError, 'Bad values type: %s' % type(vals) # If vals is a list of points, unzip it. elif len(vals) > 0 and type(vals[0]) in (ListType, TupleType): if rng is not None: estr = "Can't specify a range when vals is a list of points." raise ValueError, estr (rng, vals) = zip(*vals) # If vals & rng are both lists, make sure their lengths match. elif type(rng) in (ListType, TupleType): if len(rng) != len(vals): estr = 'Range list and value list have different lengths.' raise ValueError, estr # If rng is unspecified, take it to be integers starting at zero elif rng is None: rng = range(len(vals)) # If it's an unknown range type, then fail. else: raise TypeError, 'Bad range type: %s' % type(rng) # Check that we have something to plot if len(vals) == 0: raise ValueError, 'Nothing to plot!' # Set _rng/_vals self._rng = rng self._vals = vals # Find max/min's. self._imin = min(rng) self._imax = max(rng) if self._imax == self._imin: self._imin -= 1 self._imax += 1 self._jmin = min(vals) self._jmax = max(vals) if self._jmax == self._jmin: self._jmin -= 1 self._jmax += 1 # Do some basic error checking. if len(self._rng) != len(self._vals): raise ValueError("Rng and vals have different lengths") if len(self._rng) == 0: raise ValueError("Nothing to plot") # Set up the tk window self._root = Tkinter.Tk() self._init_bindings(self._root) # Create the actual plot frame try: self._plot = BLTPlotFrame(self._root, vals, rng) except ImportError: self._plot = CanvasPlotFrame(self._root, vals, rng) # Set up the axes self._ilog = Tkinter.IntVar(self._root); self._ilog.set(0) self._jlog = Tkinter.IntVar(self._root); self._jlog.set(0) scale = kwargs.get('scale', 'linear') if scale in ('log-linear', 'log_linear', 'log'): self._ilog.set(1) if scale in ('linear-log', 'linear_log', 'log'): self._jlog.set(1) self._plot.config_axes(self._ilog.get(), self._jlog.get()) ## Set up zooming self._plot.bind("<ButtonPress-1>", self._zoom_in_buttonpress) self._plot.bind("<ButtonRelease-1>", self._zoom_in_buttonrelease) self._plot.bind("<ButtonPress-2>", self._zoom_out) self._plot.bind("<ButtonPress-3>", self._zoom_out) self._init_menubar(self._root) def _init_bindings(self, parent): self._root.bind('<Control-q>', self.destroy) self._root.bind('<Control-x>', self.destroy) self._root.bind('<Control-p>', self.postscript) self._root.bind('<Control-a>', self._zoom_all) self._root.bind('<F1>', self.help) def _init_menubar(self, parent): menubar = Tkinter.Menu(parent) filemenu = Tkinter.Menu(menubar, tearoff=0) filemenu.add_command(label='Print to Postscript', underline=0, command=self.postscript, accelerator='Ctrl-p') filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x') menubar.add_cascade(label='File', underline=0, menu=filemenu) zoommenu = Tkinter.Menu(menubar, tearoff=0) zoommenu.add_command(label='Zoom in', underline=5, command=self._zoom_in, accelerator='left click') zoommenu.add_command(label='Zoom out', underline=5, command=self._zoom_out, accelerator='right click') zoommenu.add_command(label='View 100%', command=self._zoom_all, accelerator='Ctrl-a') menubar.add_cascade(label='Zoom', underline=0, menu=zoommenu) axismenu = Tkinter.Menu(menubar, tearoff=0) if self._imin > 0: xstate = 'normal' else: xstate = 'disabled' if self._jmin > 0: ystate = 'normal' else: ystate = 'disabled' axismenu.add_checkbutton(label='Log X axis', underline=4, variable=self._ilog, state=xstate, command=self._log) axismenu.add_checkbutton(label='Log Y axis', underline=4, variable=self._jlog, state=ystate, command=self._log) menubar.add_cascade(label='Axes', underline=0, menu=axismenu) helpmenu = Tkinter.Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) helpmenu.add_command(label='Instructions', underline=0, command=self.help, accelerator='F1') menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) def _log(self, *e): self._plot.config_axes(self._ilog.get(), self._jlog.get()) def about(self, *e): """ Dispaly an 'about' dialog window for the NLTK plot tool. """ ABOUT = ("NLTK Plot Tool\n" "<http://nltk.sourceforge.net>") TITLE = 'About: Plot Tool' if isinstance(self._plot, BLTPlotFrame): ABOUT += '\n\nBased on the BLT Widget' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._root, TITLE, ABOUT) def help(self, *e): """ Display a help window. """ doc = __doc__.split('\n@', 1)[0].strip() import re doc = re.sub(r'[A-Z]{([^}<]*)(<[^>}]*>)?}', r'\1', doc) self._autostep = 0 # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._root, 'Help: Plot Tool', doc, width=75, font='fixed') except: ShowText(self._root, 'Help: Plot Tool', doc, width=75) def postscript(self, *e): """ Print the (currently visible) contents of the plot window to a postscript file. """ from tkFileDialog import asksaveasfilename ftypes = [('Postscript files', '.ps'), ('All files', '*')] filename = asksaveasfilename(filetypes=ftypes, defaultextension='.ps') if not filename: return self._plot.postscript(filename) def destroy(self, *args): """ Cloase the plot window. """ if self._root is None: return self._root.destroy() self._root = None def mainloop(self, *varargs, **kwargs): """ Enter the mainloop for the window. This method must be called if a Plot is constructed from a non-interactive Python program (e.g., from a script); otherwise, the plot window will close as soon se the script completes. """ if in_idle(): return self._root.mainloop(*varargs, **kwargs) def _zoom(self, i1, j1, i2, j2): # Make sure they're ordered correctly. if i1 > i2: (i1,i2) = (i2,i1) if j1 > j2: (j1,j2) = (j2,j1) # Bounds checking: x if i1 < self._imin: i2 = min(self._imax, i2 + (self._imin - i1)) i1 = self._imin if i2 > self._imax: i1 = max(self._imin, i1 - (i2 - self._imax)) i2 = self._imax # Bounds checking: y if j1 < self._jmin: j2 = min(self._jmax, j2 + self._jmin - j1) j1 = self._jmin if j2 > self._jmax: j1 = max(self._jmin, j1 - (j2 - self._jmax)) j2 = self._jmax # Range size checking: if i1 == i2: i2 += 1 if j1 == j2: j2 += 1 if self._ilog.get(): i1 = max(1e-100, i1) if self._jlog.get(): j1 = max(1e-100, j1) # Do the actual zooming. self._plot.zoom(i1, j1, i2, j2) def _zoom_in_buttonpress(self, event): self._press_x = event.x self._press_y = event.y self._press_time = time.time() self._plot.create_zoom_marker() self._bind_id = self._plot.bind("<Motion>", self._zoom_in_drag) def _zoom_in_drag(self, event): self._plot.adjust_zoom_marker(self._press_x, self._press_y, event.x, event.y) def _zoom_in_buttonrelease(self, event): self._plot.delete_zoom_marker() self._plot.unbind("<Motion>", self._bind_id) if ((time.time() - self._press_time > 0.1) and abs(self._press_x-event.x) + abs(self._press_y-event.y) > 5): (i1, j1) = self._plot.invtransform(self._press_x, self._press_y) (i2, j2) = self._plot.invtransform(event.x, event.y) self._zoom(i1, j1, i2, j2) else: self._zoom_in() def _zoom_in(self, *e): (i1, j1, i2, j2) = self._plot.visible_area() di = (i2-i1)*0.1 dj = (j2-j1)*0.1 self._zoom(i1+di, j1+dj, i2-di, j2-dj) def _zoom_out(self, *e): (i1, j1, i2, j2) = self._plot.visible_area() di = -(i2-i1)*0.1 dj = -(j2-j1)*0.1 self._zoom(i1+di, j1+dj, i2-di, j2-dj) def _zoom_all(self, *e): self._zoom(self._imin, self._jmin, self._imax, self._jmax) if __name__ == '__main__': from math import sin #Plot(lambda v: sin(v)**2+0.01) Plot(lambda x:abs(x**2-sin(20*x**3))+.1, [0.01*x for x in range(1,100)], scale='log').mainloop()
gpl-3.0
jansel/loxodo
src/frontends/wx/mergeframe.py
4
2907
# # Loxodo -- Password Safe V3 compatible Password Vault # Copyright (C) 2008 Christoph Sommer <mail@christoph-sommer.de> # # 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 wx from .wxlocale import _ class MergeFrame(wx.Dialog): """ Displays a list of Vault Records for interactive merge of Vaults. """ def __init__(self, parent, oldrecord_newrecord_reason_pairs): wx.Dialog.__init__(self, parent, -1, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) self.panel = wx.Panel(self, -1) _sz_main = wx.BoxSizer(wx.VERTICAL) _lb_text = wx.StaticText(self.panel, -1, _("Select the Records to merge into this Vault") + ":") _sz_main.Add(_lb_text) self._cl_records = wx.CheckListBox(self.panel, -1) self._cl_records.AppendItems(['"' + newrecord.title + '" (' + reason + ')' for (oldrecord, newrecord, reason) in oldrecord_newrecord_reason_pairs]) for i in range(len(oldrecord_newrecord_reason_pairs)): self._cl_records.Check(i) _sz_main.Add(self._cl_records, 1, wx.EXPAND | wx.GROW) _ln_line = wx.StaticLine(self.panel, -1, size=(20, -1), style=wx.LI_HORIZONTAL) _sz_main.Add(_ln_line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, 5) btnsizer = wx.StdDialogButtonSizer() btn = wx.Button(self.panel, wx.ID_CANCEL) btnsizer.AddButton(btn) btn = wx.Button(self.panel, wx.ID_OK) btn.SetDefault() btnsizer.AddButton(btn) btnsizer.Realize() _sz_main.Add(btnsizer, 0, wx.ALIGN_RIGHT | wx.TOP | wx.BOTTOM, 5) self.panel.SetSizer(_sz_main) _sz_frame = wx.BoxSizer() _sz_frame.Add(self.panel, 1, wx.EXPAND | wx.ALL, 5) self.SetSizer(_sz_frame) self.SetTitle("Loxodo - " + _("Merge Vault Records")) self.Layout() self.Fit() self.SetMinSize(self.GetSize()) self._vault_record = None self.refresh_subscriber = None self.oldrecord_newrecord_reason_pairs = oldrecord_newrecord_reason_pairs def get_checked_items(self): return [self.oldrecord_newrecord_reason_pairs[i] for i in range(len(self.oldrecord_newrecord_reason_pairs)) if self._cl_records.IsChecked(i)]
gpl-2.0
rodrigc/buildbot
worker/buildbot_worker/pbutil.py
6
4551
# This file is part of Buildbot. Buildbot 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, version 2. # # 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. # # Copyright Buildbot Team Members """Base classes handy for use with PB clients. """ from __future__ import absolute_import from __future__ import print_function from future.utils import iteritems from twisted.cred import error from twisted.internet import reactor from twisted.python import log from twisted.spread import pb from twisted.spread.pb import PBClientFactory from buildbot_worker.compat import bytes2unicode class AutoLoginPBFactory(PBClientFactory): """Factory for PB brokers that are managed through a ClientService. Upon reconnect issued by ClientService this factory will re-login. Instead of using f.getRootObject (which gives a Deferred that can only be fired once), override the gotRootObject method. GR -> yes in case a user would use that to be notified of root object appearances, it wouldn't work. But getRootObject() can itself be used as much as one wants. Instead of using the f.login (which is also one-shot), call f.startLogin() with the credentials and client, and override the gotPerspective method. gotRootObject and gotPerspective will be called each time the object is received (once per successful connection attempt). If an authorization error occurs, failedToGetPerspective() will be invoked. """ def clientConnectionMade(self, broker): PBClientFactory.clientConnectionMade(self, broker) self.doLogin(self._root, broker) self.gotRootObject(self._root) def login(self, *args): raise RuntimeError("login is one-shot: use startLogin instead") def startLogin(self, credentials, client=None): self._credentials = credentials self._client = client def doLogin(self, root, broker): d = self._cbSendUsername(root, self._credentials.username, self._credentials.password, self._client) d.addCallbacks(self.gotPerspective, self.failedToGetPerspective, errbackArgs=(broker,)) return d # methods to override def gotPerspective(self, perspective): """The remote avatar or perspective (obtained each time this factory connects) is now available.""" def gotRootObject(self, root): """The remote root object (obtained each time this factory connects) is now available. This method will be called each time the connection is established and the object reference is retrieved.""" def failedToGetPerspective(self, why, broker): """The login process failed, most likely because of an authorization failure (bad password), but it is also possible that we lost the new connection before we managed to send our credentials. """ log.msg("ReconnectingPBClientFactory.failedToGetPerspective") # put something useful in the logs if why.check(pb.PBConnectionLost): log.msg("we lost the brand-new connection") # fall through elif why.check(error.UnauthorizedLogin): log.msg("unauthorized login; check worker name and password") # fall through else: log.err(why, 'While trying to connect:') reactor.stop() return # lose the current connection, which will trigger a retry broker.transport.loseConnection() def decode(data, encoding='utf-8', errors='strict'): """We need to convert a dictionary where keys and values are bytes, to unicode strings. This happens when a Python 2 master sends a dictionary back to a Python 3 worker. """ data_type = type(data) if data_type == bytes: return bytes2unicode(data, encoding, errors) if data_type in (dict, list, tuple): if data_type == dict: data = iteritems(data) return data_type(map(decode, data)) return data
gpl-2.0
maxoflow/MaXoFloW-Repo
plugin.video.MaXoFloWCinEsteno/youtubedl.py
255
1840
# -*- coding: utf-8 -*- import xbmc,xbmcgui try: from YDStreamExtractor import getVideoInfo from YDStreamExtractor import handleDownload except Exception: print 'importing Error. You need youtubedl module which is in official xbmc.org' xbmc.executebuiltin("XBMC.Notification(LiveStreamsPro,Please [COLOR yellow]install Youtube-dl[/COLOR] module ,10000,"")") def single_YD(url,download=False,dl_info=False,audio=False): if dl_info: handleDownload(dl_info,bg=True) return else: info = getVideoInfo(url,quality=3,resolve_redirects=True) if info is None: print 'Fail to extract' return None elif info and download : if audio: try: for s in info.streams(): print 'len(s[',len(s['ytdl_format']['formats']) for i in range(len(s['ytdl_format']['formats'])): if s['ytdl_format']['formats'][i]['format_id'] == '140': print 'm4a found' audio_url = s['ytdl_format']['formats'][i]['url'].encode('utf-8','ignore') title = s['title'].encode('utf-8','ignore') info = {'url':audio_url,'title':title,'media_type':'audio'} break except Exception: print 'audio download failed' return handleDownload(info,bg=True) else: for s in info.streams(): try: stream_url = s['xbmc_url'].encode('utf-8','ignore') print stream_url return stream_url except Exception: return None
gpl-2.0
mancoast/CPythonPyc_test
cpython/200_test_b2.py
6
10123
# Python test set -- part 4b, built-in functions n-z from test_support import * print 'oct' if oct(100) != '0144': raise TestFailed, 'oct(100)' if oct(100L) != '0144L': raise TestFailed, 'oct(100L)' if oct(-100) not in ('037777777634', '01777777777777777777634'): raise TestFailed, 'oct(-100)' if oct(-100L) != '-0144L': raise TestFailed, 'oct(-100L)' print 'open' # NB the first 4 lines are also used to test input and raw_input, below fp = open(TESTFN, 'w') try: fp.write('1+1\n') fp.write('1+1\n') fp.write('The quick brown fox jumps over the lazy dog') fp.write('.\n') fp.write('Dear John\n') fp.write('XXX'*100) fp.write('YYY'*100) finally: fp.close() # fp = open(TESTFN, 'r') try: if fp.readline(4) <> '1+1\n': raise TestFailed, 'readline(4) # exact' if fp.readline(4) <> '1+1\n': raise TestFailed, 'readline(4) # exact' if fp.readline() <> 'The quick brown fox jumps over the lazy dog.\n': raise TestFailed, 'readline() # default' if fp.readline(4) <> 'Dear': raise TestFailed, 'readline(4) # short' if fp.readline(100) <> ' John\n': raise TestFailed, 'readline(100)' if fp.read(300) <> 'XXX'*100: raise TestFailed, 'read(300)' if fp.read(1000) <> 'YYY'*100: raise TestFailed, 'read(1000) # truncate' finally: fp.close() print 'ord' if ord(' ') <> 32: raise TestFailed, 'ord(\' \')' if ord('A') <> 65: raise TestFailed, 'ord(\'A\')' if ord('a') <> 97: raise TestFailed, 'ord(\'a\')' print 'pow' if pow(0,0) <> 1: raise TestFailed, 'pow(0,0)' if pow(0,1) <> 0: raise TestFailed, 'pow(0,1)' if pow(1,0) <> 1: raise TestFailed, 'pow(1,0)' if pow(1,1) <> 1: raise TestFailed, 'pow(1,1)' # if pow(2,0) <> 1: raise TestFailed, 'pow(2,0)' if pow(2,10) <> 1024: raise TestFailed, 'pow(2,10)' if pow(2,20) <> 1024*1024: raise TestFailed, 'pow(2,20)' if pow(2,30) <> 1024*1024*1024: raise TestFailed, 'pow(2,30)' # if pow(-2,0) <> 1: raise TestFailed, 'pow(-2,0)' if pow(-2,1) <> -2: raise TestFailed, 'pow(-2,1)' if pow(-2,2) <> 4: raise TestFailed, 'pow(-2,2)' if pow(-2,3) <> -8: raise TestFailed, 'pow(-2,3)' # if pow(0L,0) <> 1: raise TestFailed, 'pow(0L,0)' if pow(0L,1) <> 0: raise TestFailed, 'pow(0L,1)' if pow(1L,0) <> 1: raise TestFailed, 'pow(1L,0)' if pow(1L,1) <> 1: raise TestFailed, 'pow(1L,1)' # if pow(2L,0) <> 1: raise TestFailed, 'pow(2L,0)' if pow(2L,10) <> 1024: raise TestFailed, 'pow(2L,10)' if pow(2L,20) <> 1024*1024: raise TestFailed, 'pow(2L,20)' if pow(2L,30) <> 1024*1024*1024: raise TestFailed, 'pow(2L,30)' # if pow(-2L,0) <> 1: raise TestFailed, 'pow(-2L,0)' if pow(-2L,1) <> -2: raise TestFailed, 'pow(-2L,1)' if pow(-2L,2) <> 4: raise TestFailed, 'pow(-2L,2)' if pow(-2L,3) <> -8: raise TestFailed, 'pow(-2L,3)' # if fcmp(pow(0.,0), 1.): raise TestFailed, 'pow(0.,0)' if fcmp(pow(0.,1), 0.): raise TestFailed, 'pow(0.,1)' if fcmp(pow(1.,0), 1.): raise TestFailed, 'pow(1.,0)' if fcmp(pow(1.,1), 1.): raise TestFailed, 'pow(1.,1)' # if fcmp(pow(2.,0), 1.): raise TestFailed, 'pow(2.,0)' if fcmp(pow(2.,10), 1024.): raise TestFailed, 'pow(2.,10)' if fcmp(pow(2.,20), 1024.*1024.): raise TestFailed, 'pow(2.,20)' if fcmp(pow(2.,30), 1024.*1024.*1024.): raise TestFailed, 'pow(2.,30)' # # XXX These don't work -- negative float to the float power... #if fcmp(pow(-2.,0), 1.): raise TestFailed, 'pow(-2.,0)' #if fcmp(pow(-2.,1), -2.): raise TestFailed, 'pow(-2.,1)' #if fcmp(pow(-2.,2), 4.): raise TestFailed, 'pow(-2.,2)' #if fcmp(pow(-2.,3), -8.): raise TestFailed, 'pow(-2.,3)' # for x in 2, 2L, 2.0: for y in 10, 10L, 10.0: for z in 1000, 1000L, 1000.0: if fcmp(pow(x, y, z), 24.0): raise TestFailed, 'pow(%s, %s, %s)' % (x, y, z) print 'range' if range(3) <> [0, 1, 2]: raise TestFailed, 'range(3)' if range(1, 5) <> [1, 2, 3, 4]: raise TestFailed, 'range(1, 5)' if range(0) <> []: raise TestFailed, 'range(0)' if range(-3) <> []: raise TestFailed, 'range(-3)' if range(1, 10, 3) <> [1, 4, 7]: raise TestFailed, 'range(1, 10, 3)' if range(5, -5, -3) <> [5, 2, -1, -4]: raise TestFailed, 'range(5, -5, -3)' print 'input and raw_input' import sys fp = open(TESTFN, 'r') savestdin = sys.stdin try: sys.stdin = fp if input() <> 2: raise TestFailed, 'input()' if input('testing\n') <> 2: raise TestFailed, 'input()' if raw_input() <> 'The quick brown fox jumps over the lazy dog.': raise TestFailed, 'raw_input()' if raw_input('testing\n') <> 'Dear John': raise TestFailed, 'raw_input(\'testing\\n\')' finally: sys.stdin = savestdin fp.close() print 'reduce' if reduce(lambda x, y: x+y, ['a', 'b', 'c'], '') <> 'abc': raise TestFailed, 'reduce(): implode a string' if reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []) <> ['a','c','d','w']: raise TestFailed, 'reduce(): append' if reduce(lambda x, y: x*y, range(2,8), 1) <> 5040: raise TestFailed, 'reduce(): compute 7!' if reduce(lambda x, y: x*y, range(2,21), 1L) <> 2432902008176640000L: raise TestFailed, 'reduce(): compute 20!, use long' class Squares: def __init__(self, max): self.max = max self.sofar = [] def __len__(self): return len(self.sofar) def __getitem__(self, i): if not 0 <= i < self.max: raise IndexError n = len(self.sofar) while n <= i: self.sofar.append(n*n) n = n+1 return self.sofar[i] if reduce(lambda x, y: x+y, Squares(10)) != 285: raise TestFailed, 'reduce(<+>, Squares(10))' if reduce(lambda x, y: x+y, Squares(10), 0) != 285: raise TestFailed, 'reduce(<+>, Squares(10), 0)' if reduce(lambda x, y: x+y, Squares(0), 0) != 0: raise TestFailed, 'reduce(<+>, Squares(0), 0)' print 'reload' import marshal reload(marshal) import string reload(string) ## import sys ## try: reload(sys) ## except ImportError: pass ## else: raise TestFailed, 'reload(sys) should fail' print 'repr' if repr('') <> '\'\'': raise TestFailed, 'repr(\'\')' if repr(0) <> '0': raise TestFailed, 'repr(0)' if repr(0L) <> '0L': raise TestFailed, 'repr(0L)' if repr(()) <> '()': raise TestFailed, 'repr(())' if repr([]) <> '[]': raise TestFailed, 'repr([])' if repr({}) <> '{}': raise TestFailed, 'repr({})' print 'round' if round(0.0) <> 0.0: raise TestFailed, 'round(0.0)' if round(1.0) <> 1.0: raise TestFailed, 'round(1.0)' if round(10.0) <> 10.0: raise TestFailed, 'round(10.0)' if round(1000000000.0) <> 1000000000.0: raise TestFailed, 'round(1000000000.0)' if round(1e20) <> 1e20: raise TestFailed, 'round(1e20)' if round(-1.0) <> -1.0: raise TestFailed, 'round(-1.0)' if round(-10.0) <> -10.0: raise TestFailed, 'round(-10.0)' if round(-1000000000.0) <> -1000000000.0: raise TestFailed, 'round(-1000000000.0)' if round(-1e20) <> -1e20: raise TestFailed, 'round(-1e20)' if round(0.1) <> 0.0: raise TestFailed, 'round(0.0)' if round(1.1) <> 1.0: raise TestFailed, 'round(1.0)' if round(10.1) <> 10.0: raise TestFailed, 'round(10.0)' if round(1000000000.1) <> 1000000000.0: raise TestFailed, 'round(1000000000.0)' if round(-1.1) <> -1.0: raise TestFailed, 'round(-1.0)' if round(-10.1) <> -10.0: raise TestFailed, 'round(-10.0)' if round(-1000000000.1) <> -1000000000.0: raise TestFailed, 'round(-1000000000.0)' if round(0.9) <> 1.0: raise TestFailed, 'round(0.9)' if round(9.9) <> 10.0: raise TestFailed, 'round(9.9)' if round(999999999.9) <> 1000000000.0: raise TestFailed, 'round(999999999.9)' if round(-0.9) <> -1.0: raise TestFailed, 'round(-0.9)' if round(-9.9) <> -10.0: raise TestFailed, 'round(-9.9)' if round(-999999999.9) <> -1000000000.0: raise TestFailed, 'round(-999999999.9)' print 'setattr' import sys setattr(sys, 'spam', 1) if sys.spam != 1: raise TestFailed, 'setattr(sys, \'spam\', 1)' print 'str' if str('') <> '': raise TestFailed, 'str(\'\')' if str(0) <> '0': raise TestFailed, 'str(0)' if str(0L) <> '0': raise TestFailed, 'str(0L)' if str(()) <> '()': raise TestFailed, 'str(())' if str([]) <> '[]': raise TestFailed, 'str([])' if str({}) <> '{}': raise TestFailed, 'str({})' print 'tuple' if tuple(()) <> (): raise TestFailed, 'tuple(())' if tuple((0, 1, 2, 3)) <> (0, 1, 2, 3): raise TestFailed, 'tuple((0, 1, 2, 3))' if tuple([]) <> (): raise TestFailed, 'tuple([])' if tuple([0, 1, 2, 3]) <> (0, 1, 2, 3): raise TestFailed, 'tuple([0, 1, 2, 3])' if tuple('') <> (): raise TestFailed, 'tuple('')' if tuple('spam') <> ('s', 'p', 'a', 'm'): raise TestFailed, "tuple('spam')" print 'type' if type('') <> type('123') or type('') == type(()): raise TestFailed, 'type()' print 'vars' a = b = None a = vars().keys() b = dir() a.sort() b.sort() if a <> b: raise TestFailed, 'vars()' import sys a = vars(sys).keys() b = dir(sys) a.sort() b.sort() if a <> b: raise TestFailed, 'vars(sys)' def f0(): if vars() != {}: raise TestFailed, 'vars() in f0()' f0() def f2(): f0() a = 1 b = 2 if vars() != {'a': a, 'b': b}: raise TestFailed, 'vars() in f2()' f2() print 'xrange' if tuple(xrange(10)) <> tuple(range(10)): raise TestFailed, 'xrange(10)' if tuple(xrange(5,10)) <> tuple(range(5,10)): raise TestFailed, 'xrange(5,10)' if tuple(xrange(0,10,2)) <> tuple(range(0,10,2)): raise TestFailed, 'xrange(0,10,2)' print 'zip' a = (1, 2, 3) b = (4, 5, 6) t = [(1, 4), (2, 5), (3, 6)] if zip(a, b) <> t: raise TestFailed, 'zip(a, b) - same size, both tuples' b = [4, 5, 6] if zip(a, b) <> t: raise TestFailed, 'zip(a, b) - same size, tuple/list' b = (4, 5, 6, 7) if zip(a, b) <> t: raise TestFailed, 'zip(a, b) - b is longer' class I: def __getitem__(self, i): if i < 0 or i > 2: raise IndexError return i + 4 if zip(a, I()) <> t: raise TestFailed, 'zip(a, b) - b is instance' exc = 0 try: zip() except TypeError: exc = 1 except: e = sys.exc_info()[0] raise TestFailed, 'zip() - no args, expected TypeError, got %s' % e if not exc: raise TestFailed, 'zip() - no args, missing expected TypeError' exc = 0 try: zip(None) except TypeError: exc = 1 except: e = sys.exc_info()[0] raise TestFailed, 'zip(None) - expected TypeError, got %s' % e if not exc: raise TestFailed, 'zip(None) - missing expected TypeError' class G: pass exc = 0 try: zip(a, G()) except AttributeError: exc = 1 except: e = sys.exc_info()[0] raise TestFailed, 'zip(a, b) - b instance w/o __getitem__' if not exc: raise TestFailed, 'zip(a, b) - missing expected AttributeError' # Epilogue -- unlink the temp file unlink(TESTFN)
gpl-3.0
netsamir/dotfiles
files/vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/status_codes.py
202
3280
# -*- coding: utf-8 -*- from .structures import LookupDict _codes = { # Informational. 100: ('continue',), 101: ('switching_protocols',), 102: ('processing',), 103: ('checkpoint',), 122: ('uri_too_long', 'request_uri_too_long'), 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'), 201: ('created',), 202: ('accepted',), 203: ('non_authoritative_info', 'non_authoritative_information'), 204: ('no_content',), 205: ('reset_content', 'reset'), 206: ('partial_content', 'partial'), 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'), 208: ('already_reported',), 226: ('im_used',), # Redirection. 300: ('multiple_choices',), 301: ('moved_permanently', 'moved', '\\o-'), 302: ('found',), 303: ('see_other', 'other'), 304: ('not_modified',), 305: ('use_proxy',), 306: ('switch_proxy',), 307: ('temporary_redirect', 'temporary_moved', 'temporary'), 308: ('permanent_redirect', 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 # Client Error. 400: ('bad_request', 'bad'), 401: ('unauthorized',), 402: ('payment_required', 'payment'), 403: ('forbidden',), 404: ('not_found', '-o-'), 405: ('method_not_allowed', 'not_allowed'), 406: ('not_acceptable',), 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'), 408: ('request_timeout', 'timeout'), 409: ('conflict',), 410: ('gone',), 411: ('length_required',), 412: ('precondition_failed', 'precondition'), 413: ('request_entity_too_large',), 414: ('request_uri_too_large',), 415: ('unsupported_media_type', 'unsupported_media', 'media_type'), 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'), 417: ('expectation_failed',), 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'), 422: ('unprocessable_entity', 'unprocessable'), 423: ('locked',), 424: ('failed_dependency', 'dependency'), 425: ('unordered_collection', 'unordered'), 426: ('upgrade_required', 'upgrade'), 428: ('precondition_required', 'precondition'), 429: ('too_many_requests', 'too_many'), 431: ('header_fields_too_large', 'fields_too_large'), 444: ('no_response', 'none'), 449: ('retry_with', 'retry'), 450: ('blocked_by_windows_parental_controls', 'parental_controls'), 451: ('unavailable_for_legal_reasons', 'legal_reasons'), 499: ('client_closed_request',), # Server Error. 500: ('internal_server_error', 'server_error', '/o\\', '✗'), 501: ('not_implemented',), 502: ('bad_gateway',), 503: ('service_unavailable', 'unavailable'), 504: ('gateway_timeout',), 505: ('http_version_not_supported', 'http_version'), 506: ('variant_also_negotiates',), 507: ('insufficient_storage',), 509: ('bandwidth_limit_exceeded', 'bandwidth'), 510: ('not_extended',), 511: ('network_authentication_required', 'network_auth', 'network_authentication'), } codes = LookupDict(name='status_codes') for code, titles in _codes.items(): for title in titles: setattr(codes, title, code) if not title.startswith('\\'): setattr(codes, title.upper(), code)
unlicense
xyuanmu/XX-Net
python3.8.2/Lib/site-packages/pip/_internal/pyproject.py
13
6464
from __future__ import absolute_import import io import os import sys from pip._vendor import pytoml, six from pip._internal.exceptions import InstallationError from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any, Tuple, Optional, List def _is_list_of_str(obj): # type: (Any) -> bool return ( isinstance(obj, list) and all(isinstance(item, six.string_types) for item in obj) ) def make_pyproject_path(setup_py_dir): # type: (str) -> str path = os.path.join(setup_py_dir, 'pyproject.toml') # Python2 __file__ should not be unicode if six.PY2 and isinstance(path, six.text_type): path = path.encode(sys.getfilesystemencoding()) return path def load_pyproject_toml( use_pep517, # type: Optional[bool] pyproject_toml, # type: str setup_py, # type: str req_name # type: str ): # type: (...) -> Optional[Tuple[List[str], str, List[str]]] """Load the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file req_name - The name of the requirement we're processing (for error reporting) Returns: None if we should use the legacy code path, otherwise a tuple ( requirements from pyproject.toml, name of PEP 517 backend, requirements we should check are installed after setting up the build environment ) """ has_pyproject = os.path.isfile(pyproject_toml) has_setup = os.path.isfile(setup_py) if has_pyproject: with io.open(pyproject_toml, encoding="utf-8") as f: pp_toml = pytoml.load(f) build_system = pp_toml.get("build-system") else: build_system = None # The following cases must use PEP 517 # We check for use_pep517 being non-None and falsey because that means # the user explicitly requested --no-use-pep517. The value 0 as # opposed to False can occur when the value is provided via an # environment variable or config file option (due to the quirk of # strtobool() returning an integer in pip's configuration code). if has_pyproject and not has_setup: if use_pep517 is not None and not use_pep517: raise InstallationError( "Disabling PEP 517 processing is invalid: " "project does not have a setup.py" ) use_pep517 = True elif build_system and "build-backend" in build_system: if use_pep517 is not None and not use_pep517: raise InstallationError( "Disabling PEP 517 processing is invalid: " "project specifies a build backend of {} " "in pyproject.toml".format( build_system["build-backend"] ) ) use_pep517 = True # If we haven't worked out whether to use PEP 517 yet, # and the user hasn't explicitly stated a preference, # we do so if the project has a pyproject.toml file. elif use_pep517 is None: use_pep517 = has_pyproject # At this point, we know whether we're going to use PEP 517. assert use_pep517 is not None # If we're using the legacy code path, there is nothing further # for us to do here. if not use_pep517: return None if build_system is None: # Either the user has a pyproject.toml with no build-system # section, or the user has no pyproject.toml, but has opted in # explicitly via --use-pep517. # In the absence of any explicit backend specification, we # assume the setuptools backend that most closely emulates the # traditional direct setup.py execution, and require wheel and # a version of setuptools that supports that backend. build_system = { "requires": ["setuptools>=40.8.0", "wheel"], "build-backend": "setuptools.build_meta:__legacy__", } # If we're using PEP 517, we have build system information (either # from pyproject.toml, or defaulted by the code above). # Note that at this point, we do not know if the user has actually # specified a backend, though. assert build_system is not None # Ensure that the build-system section in pyproject.toml conforms # to PEP 518. error_template = ( "{package} has a pyproject.toml file that does not comply " "with PEP 518: {reason}" ) # Specifying the build-system table but not the requires key is invalid if "requires" not in build_system: raise InstallationError( error_template.format(package=req_name, reason=( "it has a 'build-system' table but not " "'build-system.requires' which is mandatory in the table" )) ) # Error out if requires is not a list of strings requires = build_system["requires"] if not _is_list_of_str(requires): raise InstallationError(error_template.format( package=req_name, reason="'build-system.requires' is not a list of strings.", )) backend = build_system.get("build-backend") check = [] # type: List[str] if backend is None: # If the user didn't specify a backend, we assume they want to use # the setuptools backend. But we can't be sure they have included # a version of setuptools which supplies the backend, or wheel # (which is needed by the backend) in their requirements. So we # make a note to check that those requirements are present once # we have set up the environment. # This is quite a lot of work to check for a very specific case. But # the problem is, that case is potentially quite common - projects that # adopted PEP 518 early for the ability to specify requirements to # execute setup.py, but never considered needing to mention the build # tools themselves. The original PEP 518 code had a similar check (but # implemented in a different way). backend = "setuptools.build_meta:__legacy__" check = ["setuptools>=40.8.0", "wheel"] return (requires, backend, check)
bsd-2-clause
mikebrevard/UnixAdministration
vagrant/etc/data/genData/venv/lib/python3.4/site-packages/pip/_vendor/requests/packages/chardet/hebrewprober.py
2929
13359
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Shy Shalom # Portions created by the Initial Developer are Copyright (C) 2005 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .charsetprober import CharSetProber from .constants import eNotMe, eDetecting from .compat import wrap_ord # This prober doesn't actually recognize a language or a charset. # It is a helper prober for the use of the Hebrew model probers ### General ideas of the Hebrew charset recognition ### # # Four main charsets exist in Hebrew: # "ISO-8859-8" - Visual Hebrew # "windows-1255" - Logical Hebrew # "ISO-8859-8-I" - Logical Hebrew # "x-mac-hebrew" - ?? Logical Hebrew ?? # # Both "ISO" charsets use a completely identical set of code points, whereas # "windows-1255" and "x-mac-hebrew" are two different proper supersets of # these code points. windows-1255 defines additional characters in the range # 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific # diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6. # x-mac-hebrew defines similar additional code points but with a different # mapping. # # As far as an average Hebrew text with no diacritics is concerned, all four # charsets are identical with respect to code points. Meaning that for the # main Hebrew alphabet, all four map the same values to all 27 Hebrew letters # (including final letters). # # The dominant difference between these charsets is their directionality. # "Visual" directionality means that the text is ordered as if the renderer is # not aware of a BIDI rendering algorithm. The renderer sees the text and # draws it from left to right. The text itself when ordered naturally is read # backwards. A buffer of Visual Hebrew generally looks like so: # "[last word of first line spelled backwards] [whole line ordered backwards # and spelled backwards] [first word of first line spelled backwards] # [end of line] [last word of second line] ... etc' " # adding punctuation marks, numbers and English text to visual text is # naturally also "visual" and from left to right. # # "Logical" directionality means the text is ordered "naturally" according to # the order it is read. It is the responsibility of the renderer to display # the text from right to left. A BIDI algorithm is used to place general # punctuation marks, numbers and English text in the text. # # Texts in x-mac-hebrew are almost impossible to find on the Internet. From # what little evidence I could find, it seems that its general directionality # is Logical. # # To sum up all of the above, the Hebrew probing mechanism knows about two # charsets: # Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are # backwards while line order is natural. For charset recognition purposes # the line order is unimportant (In fact, for this implementation, even # word order is unimportant). # Logical Hebrew - "windows-1255" - normal, naturally ordered text. # # "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be # specifically identified. # "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew # that contain special punctuation marks or diacritics is displayed with # some unconverted characters showing as question marks. This problem might # be corrected using another model prober for x-mac-hebrew. Due to the fact # that x-mac-hebrew texts are so rare, writing another model prober isn't # worth the effort and performance hit. # #### The Prober #### # # The prober is divided between two SBCharSetProbers and a HebrewProber, # all of which are managed, created, fed data, inquired and deleted by the # SBCSGroupProber. The two SBCharSetProbers identify that the text is in # fact some kind of Hebrew, Logical or Visual. The final decision about which # one is it is made by the HebrewProber by combining final-letter scores # with the scores of the two SBCharSetProbers to produce a final answer. # # The SBCSGroupProber is responsible for stripping the original text of HTML # tags, English characters, numbers, low-ASCII punctuation characters, spaces # and new lines. It reduces any sequence of such characters to a single space. # The buffer fed to each prober in the SBCS group prober is pure text in # high-ASCII. # The two SBCharSetProbers (model probers) share the same language model: # Win1255Model. # The first SBCharSetProber uses the model normally as any other # SBCharSetProber does, to recognize windows-1255, upon which this model was # built. The second SBCharSetProber is told to make the pair-of-letter # lookup in the language model backwards. This in practice exactly simulates # a visual Hebrew model using the windows-1255 logical Hebrew model. # # The HebrewProber is not using any language model. All it does is look for # final-letter evidence suggesting the text is either logical Hebrew or visual # Hebrew. Disjointed from the model probers, the results of the HebrewProber # alone are meaningless. HebrewProber always returns 0.00 as confidence # since it never identifies a charset by itself. Instead, the pointer to the # HebrewProber is passed to the model probers as a helper "Name Prober". # When the Group prober receives a positive identification from any prober, # it asks for the name of the charset identified. If the prober queried is a # Hebrew model prober, the model prober forwards the call to the # HebrewProber to make the final decision. In the HebrewProber, the # decision is made according to the final-letters scores maintained and Both # model probers scores. The answer is returned in the form of the name of the # charset identified, either "windows-1255" or "ISO-8859-8". # windows-1255 / ISO-8859-8 code points of interest FINAL_KAF = 0xea NORMAL_KAF = 0xeb FINAL_MEM = 0xed NORMAL_MEM = 0xee FINAL_NUN = 0xef NORMAL_NUN = 0xf0 FINAL_PE = 0xf3 NORMAL_PE = 0xf4 FINAL_TSADI = 0xf5 NORMAL_TSADI = 0xf6 # Minimum Visual vs Logical final letter score difference. # If the difference is below this, don't rely solely on the final letter score # distance. MIN_FINAL_CHAR_DISTANCE = 5 # Minimum Visual vs Logical model score difference. # If the difference is below this, don't rely at all on the model score # distance. MIN_MODEL_DISTANCE = 0.01 VISUAL_HEBREW_NAME = "ISO-8859-8" LOGICAL_HEBREW_NAME = "windows-1255" class HebrewProber(CharSetProber): def __init__(self): CharSetProber.__init__(self) self._mLogicalProber = None self._mVisualProber = None self.reset() def reset(self): self._mFinalCharLogicalScore = 0 self._mFinalCharVisualScore = 0 # The two last characters seen in the previous buffer, # mPrev and mBeforePrev are initialized to space in order to simulate # a word delimiter at the beginning of the data self._mPrev = ' ' self._mBeforePrev = ' ' # These probers are owned by the group prober. def set_model_probers(self, logicalProber, visualProber): self._mLogicalProber = logicalProber self._mVisualProber = visualProber def is_final(self, c): return wrap_ord(c) in [FINAL_KAF, FINAL_MEM, FINAL_NUN, FINAL_PE, FINAL_TSADI] def is_non_final(self, c): # The normal Tsadi is not a good Non-Final letter due to words like # 'lechotet' (to chat) containing an apostrophe after the tsadi. This # apostrophe is converted to a space in FilterWithoutEnglishLetters # causing the Non-Final tsadi to appear at an end of a word even # though this is not the case in the original text. # The letters Pe and Kaf rarely display a related behavior of not being # a good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak' # for example legally end with a Non-Final Pe or Kaf. However, the # benefit of these letters as Non-Final letters outweighs the damage # since these words are quite rare. return wrap_ord(c) in [NORMAL_KAF, NORMAL_MEM, NORMAL_NUN, NORMAL_PE] def feed(self, aBuf): # Final letter analysis for logical-visual decision. # Look for evidence that the received buffer is either logical Hebrew # or visual Hebrew. # The following cases are checked: # 1) A word longer than 1 letter, ending with a final letter. This is # an indication that the text is laid out "naturally" since the # final letter really appears at the end. +1 for logical score. # 2) A word longer than 1 letter, ending with a Non-Final letter. In # normal Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi, # should not end with the Non-Final form of that letter. Exceptions # to this rule are mentioned above in isNonFinal(). This is an # indication that the text is laid out backwards. +1 for visual # score # 3) A word longer than 1 letter, starting with a final letter. Final # letters should not appear at the beginning of a word. This is an # indication that the text is laid out backwards. +1 for visual # score. # # The visual score and logical score are accumulated throughout the # text and are finally checked against each other in GetCharSetName(). # No checking for final letters in the middle of words is done since # that case is not an indication for either Logical or Visual text. # # We automatically filter out all 7-bit characters (replace them with # spaces) so the word boundary detection works properly. [MAP] if self.get_state() == eNotMe: # Both model probers say it's not them. No reason to continue. return eNotMe aBuf = self.filter_high_bit_only(aBuf) for cur in aBuf: if cur == ' ': # We stand on a space - a word just ended if self._mBeforePrev != ' ': # next-to-last char was not a space so self._mPrev is not a # 1 letter word if self.is_final(self._mPrev): # case (1) [-2:not space][-1:final letter][cur:space] self._mFinalCharLogicalScore += 1 elif self.is_non_final(self._mPrev): # case (2) [-2:not space][-1:Non-Final letter][ # cur:space] self._mFinalCharVisualScore += 1 else: # Not standing on a space if ((self._mBeforePrev == ' ') and (self.is_final(self._mPrev)) and (cur != ' ')): # case (3) [-2:space][-1:final letter][cur:not space] self._mFinalCharVisualScore += 1 self._mBeforePrev = self._mPrev self._mPrev = cur # Forever detecting, till the end or until both model probers return # eNotMe (handled above) return eDetecting def get_charset_name(self): # Make the decision: is it Logical or Visual? # If the final letter score distance is dominant enough, rely on it. finalsub = self._mFinalCharLogicalScore - self._mFinalCharVisualScore if finalsub >= MIN_FINAL_CHAR_DISTANCE: return LOGICAL_HEBREW_NAME if finalsub <= -MIN_FINAL_CHAR_DISTANCE: return VISUAL_HEBREW_NAME # It's not dominant enough, try to rely on the model scores instead. modelsub = (self._mLogicalProber.get_confidence() - self._mVisualProber.get_confidence()) if modelsub > MIN_MODEL_DISTANCE: return LOGICAL_HEBREW_NAME if modelsub < -MIN_MODEL_DISTANCE: return VISUAL_HEBREW_NAME # Still no good, back to final letter distance, maybe it'll save the # day. if finalsub < 0.0: return VISUAL_HEBREW_NAME # (finalsub > 0 - Logical) or (don't know what to do) default to # Logical. return LOGICAL_HEBREW_NAME def get_state(self): # Remain active as long as any of the model probers are active. if (self._mLogicalProber.get_state() == eNotMe) and \ (self._mVisualProber.get_state() == eNotMe): return eNotMe return eDetecting
mit
jymannob/CouchPotatoServer
libs/requests/packages/charade/sbcharsetprober.py
2927
4793
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import sys from . import constants from .charsetprober import CharSetProber from .compat import wrap_ord SAMPLE_SIZE = 64 SB_ENOUGH_REL_THRESHOLD = 1024 POSITIVE_SHORTCUT_THRESHOLD = 0.95 NEGATIVE_SHORTCUT_THRESHOLD = 0.05 SYMBOL_CAT_ORDER = 250 NUMBER_OF_SEQ_CAT = 4 POSITIVE_CAT = NUMBER_OF_SEQ_CAT - 1 #NEGATIVE_CAT = 0 class SingleByteCharSetProber(CharSetProber): def __init__(self, model, reversed=False, nameProber=None): CharSetProber.__init__(self) self._mModel = model # TRUE if we need to reverse every pair in the model lookup self._mReversed = reversed # Optional auxiliary prober for name decision self._mNameProber = nameProber self.reset() def reset(self): CharSetProber.reset(self) # char order of last character self._mLastOrder = 255 self._mSeqCounters = [0] * NUMBER_OF_SEQ_CAT self._mTotalSeqs = 0 self._mTotalChar = 0 # characters that fall in our sampling range self._mFreqChar = 0 def get_charset_name(self): if self._mNameProber: return self._mNameProber.get_charset_name() else: return self._mModel['charsetName'] def feed(self, aBuf): if not self._mModel['keepEnglishLetter']: aBuf = self.filter_without_english_letters(aBuf) aLen = len(aBuf) if not aLen: return self.get_state() for c in aBuf: order = self._mModel['charToOrderMap'][wrap_ord(c)] if order < SYMBOL_CAT_ORDER: self._mTotalChar += 1 if order < SAMPLE_SIZE: self._mFreqChar += 1 if self._mLastOrder < SAMPLE_SIZE: self._mTotalSeqs += 1 if not self._mReversed: i = (self._mLastOrder * SAMPLE_SIZE) + order model = self._mModel['precedenceMatrix'][i] else: # reverse the order of the letters in the lookup i = (order * SAMPLE_SIZE) + self._mLastOrder model = self._mModel['precedenceMatrix'][i] self._mSeqCounters[model] += 1 self._mLastOrder = order if self.get_state() == constants.eDetecting: if self._mTotalSeqs > SB_ENOUGH_REL_THRESHOLD: cf = self.get_confidence() if cf > POSITIVE_SHORTCUT_THRESHOLD: if constants._debug: sys.stderr.write('%s confidence = %s, we have a' 'winner\n' % (self._mModel['charsetName'], cf)) self._mState = constants.eFoundIt elif cf < NEGATIVE_SHORTCUT_THRESHOLD: if constants._debug: sys.stderr.write('%s confidence = %s, below negative' 'shortcut threshhold %s\n' % (self._mModel['charsetName'], cf, NEGATIVE_SHORTCUT_THRESHOLD)) self._mState = constants.eNotMe return self.get_state() def get_confidence(self): r = 0.01 if self._mTotalSeqs > 0: r = ((1.0 * self._mSeqCounters[POSITIVE_CAT]) / self._mTotalSeqs / self._mModel['mTypicalPositiveRatio']) r = r * self._mFreqChar / self._mTotalChar if r >= 1.0: r = 0.99 return r
gpl-3.0
inspirehep/invenio
modules/bibcatalog/lib/bibcatalog_unit_tests.py
16
3943
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ BibCatalog unit tests """ from invenio.testutils import make_test_suite, run_test_suite, InvenioTestCase from invenio.bibcatalog_utils import \ load_tag_code_from_name, \ split_tag_code, \ record_get_value_with_provenence, \ record_id_from_record, \ record_in_collection, \ BibCatalogTagNotFound from invenio.bibformat_dblayer import get_all_name_tag_mappings class TestUtilityFunctions(InvenioTestCase): """Test non-data-specific utility functions for BibCatalog.""" def setUp(self): self.record = {'001': [([], ' ', ' ', '1', 1)], '650': [([('2', 'SzGeCERN'), ('a', 'Experiments and Tracks')], '1', '7', '', 2), ([('9', 'arXiv'), ('a', 'hep-ph')], '1', '7', '', 3), ([('9', 'arXiv'), ('a', 'hep-th')], '1', '7', '', 4)], '980': [([('a', 'PICTURE')], ' ', ' ', '', 3)]} def test_load_tag_code_from_name(self): """Tests function bibcatalog_utils.load_tag_code_from_name""" if 'record ID' in get_all_name_tag_mappings(): self.assertEqual(load_tag_code_from_name("record ID"), "001") # Name "foo" should not exist and raise an exception self.assertRaises(BibCatalogTagNotFound, load_tag_code_from_name, "foo") def test_split_tag_code(self): """Tests function bibcatalog_utils.split_tag_code""" self.assertEqual(split_tag_code('035__a'), {"tag": "035", "ind1": "_", "ind2": "_", "code": "a"}) self.assertEqual(split_tag_code('035'), {"tag": "035", "ind1": "%", "ind2": "%", "code": "%"}) def test_record_in_collection(self): """Tests function bibcatalog_utils.record_in_collection""" self.assertFalse(record_in_collection(self.record, "THESIS")) self.assertTrue(record_in_collection(self.record, "picture")) def test_record_id_from_record(self): """Tests function bibcatalog_utils.record_id_from_record""" self.assertEqual("1", record_id_from_record(self.record)) def test_record_get_value_with_provenence(self): """Tests function bibcatalog_utils.record_get_value_with_provenence""" self.assertEqual(["hep-ph", "hep-th"], record_get_value_with_provenence(record=self.record, provenence_value="arXiv", provenence_code="9", tag="650", ind1="1", ind2="7", code="a")) TEST_SUITE = make_test_suite(TestUtilityFunctions) if __name__ == "__main__": run_test_suite(TEST_SUITE)
gpl-2.0
JazzeYoung/VeryDeepAutoEncoder
pylearn2/models/tests/test_vae.py
44
20236
from nose.tools import raises import os import numpy import theano import theano.tensor as T from pylearn2.compat import OrderedDict from pylearn2.config import yaml_parse from pylearn2.models.mlp import ( MLP, Linear, CompositeLayer, ConvRectifiedLinear, SpaceConverter ) from pylearn2.models.vae import VAE from pylearn2.models.vae.kl import DiagonalGaussianPriorPosteriorKL from pylearn2.models.vae.prior import Prior, DiagonalGaussianPrior from pylearn2.models.vae.conditional import ( Conditional, BernoulliVector, DiagonalGaussian ) from pylearn2.space import CompositeSpace, VectorSpace, Conv2DSpace from pylearn2.utils.rng import make_np_rng from pylearn2.utils import as_floatX from pylearn2.utils import testing class DummyVAE(object): rng = make_np_rng(default_seed=11223) batch_size = 100 class DummyPrior(Prior): def initialize_parameters(self, *args, **kwargs): self._params = [] class DummyConditional(Conditional): def _get_default_output_layer(self): return CompositeLayer(layer_name='composite', layers=[Linear(layer_name='1', dim=self.ndim, irange=0.01), Linear(layer_name='2', dim=self.ndim, irange=0.01)]) def _get_required_mlp_output_space(self): return CompositeSpace([VectorSpace(dim=self.ndim), VectorSpace(dim=self.ndim)]) ############################################################################### # models/vae/prior.py tests ############################################################################### # -------------------------------- Prior -------------------------------------- def test_prior_set_vae(): """ Prior.set_vae adds a reference to the vae and adopts the vae's rng and batch_size attributes """ prior = DummyPrior() vae = DummyVAE() prior.set_vae(vae) testing.assert_same_object(prior.vae, vae) testing.assert_same_object(prior.rng, vae.rng) testing.assert_equal(prior.batch_size, vae.batch_size) @raises(RuntimeError) def test_prior_raises_exception_if_called_twice(): """ Prior.set_vae raises an exception if it has already been called """ prior = DummyPrior() vae = DummyVAE() prior.set_vae(vae) prior.set_vae(vae) def test_prior_get_vae(): """ Prior.get_vae returns its VAE """ prior = DummyPrior() vae = DummyVAE() prior.set_vae(vae) testing.assert_same_object(prior.get_vae(), vae) # ------------------------- DiagonalGaussianPrior ----------------------------- def test_diagonal_gaussian_prior_initialize_parameters(): """ DiagonalGaussianPrior.initialize_parameters works without crashing """ prior = DiagonalGaussianPrior() vae = DummyVAE() prior.set_vae(vae) prior.initialize_parameters(nhid=5) def test_diagonal_gaussian_prior_sample_from_p_z(): """ DiagonalGaussianPrior.sample_from_p_z works without crashing """ prior = DiagonalGaussianPrior() vae = DummyVAE() prior.set_vae(vae) prior.initialize_parameters(nhid=5) prior.sample_from_p_z(10) def test_diagonal_gaussian_prior_log_p_z(): """ DiagonalGaussianPrior.log_p_z works without crashing """ prior = DiagonalGaussianPrior() vae = DummyVAE() prior.set_vae(vae) prior.initialize_parameters(nhid=5) z = T.tensor3('z') prior.log_p_z(z) ############################################################################### # models/vae/conditional.py tests ############################################################################### # ----------------------------- Conditional ----------------------------------- @raises(ValueError) def test_conditional_requires_nested_mlp(): """ Conditional rejects non-nested MLPs """ mlp = MLP(nvis=10, layers=[Linear(layer_name='h', dim=10, irange=0.01)]) Conditional(mlp=mlp, name='conditional') @raises(ValueError) def test_conditional_rejects_invalid_output_layer(): """ Conditional rejects invalid user-defined output layer """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01), Linear(layer_name='mu', dim=5, irange=0.01)]) conditional = DummyConditional(mlp=mlp, name='conditional', output_layer_required=False) vae = DummyVAE() conditional.set_vae(vae) conditional.initialize_parameters(input_space=VectorSpace(dim=5), ndim=5) def test_conditional_returns_mlp_weights(): """ Conditional.get_weights calls its MLP's get_weights method """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01)]) conditional = DummyConditional(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) conditional.initialize_parameters(input_space=VectorSpace(dim=5), ndim=5) numpy.testing.assert_equal(conditional.get_weights(), mlp.get_weights()) def test_conditional_returns_lr_scalers(): """ Conditional.get_lr_scalers calls its MLP's get_lr_scalers method """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, W_lr_scale=0.01)]) conditional = DummyConditional(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) conditional.initialize_parameters(input_space=VectorSpace(dim=5), ndim=5) testing.assert_equal(conditional.get_lr_scalers(), mlp.get_lr_scalers()) def test_conditional_modify_updates(): """ Conditional.modify_updates calls its MLP's modify_updates method """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = DummyConditional(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) conditional.initialize_parameters(input_space=VectorSpace(dim=5), ndim=5) updates = OrderedDict(zip(mlp.get_params(), mlp.get_params())) testing.assert_equal(conditional.modify_updates(updates), mlp.modify_updates(updates)) def test_conditional_set_vae(): """ Conditional.set_vae adds a reference to the vae and adopts the vae's rng and batch_size attributes """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01)]) conditional = DummyConditional(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) testing.assert_same_object(conditional.vae, vae) testing.assert_same_object(conditional.rng, vae.rng) testing.assert_equal(conditional.batch_size, vae.batch_size) @raises(RuntimeError) def test_conditional_raises_exception_if_called_twice(): """ Conditional.set_vae raises an exception if it has already been called """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01)]) conditional = DummyConditional(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) conditional.set_vae(vae) def test_conditional_get_vae(): """ Conditional.get_vae returns its VAE """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01)]) conditional = DummyConditional(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) testing.assert_same_object(conditional.get_vae(), vae) def test_conditional_initialize_parameters(): """ Conditional.initialize_parameters does the following: * Set its input_space and ndim attributes * Calls its MLP's set_mlp method * Sets its MLP's input_space * Validates its MLP * Sets its params and param names """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = DummyConditional(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) testing.assert_same_object(input_space, conditional.input_space) testing.assert_equal(conditional.ndim, 5) testing.assert_same_object(mlp.get_mlp(), conditional) testing.assert_same_object(mlp.input_space, input_space) mlp_params = mlp.get_params() conditional_params = conditional.get_params() assert all([mp in conditional_params for mp in mlp_params]) assert all([cp in mlp_params for cp in conditional_params]) def test_conditional_encode_conditional_parameters(): """ Conditional.encode_conditional_parameters calls its MLP's fprop method """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = DummyConditional(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) X = T.matrix('X') mlp_Y1, mlp_Y2 = mlp.fprop(X) cond_Y1, cond_Y2 = conditional.encode_conditional_params(X) f = theano.function([X], [mlp_Y1, mlp_Y2, cond_Y1, cond_Y2]) rval = f(as_floatX(numpy.random.uniform(size=(10, 5)))) numpy.testing.assert_allclose(rval[0], rval[2]) numpy.testing.assert_allclose(rval[1], rval[3]) # ----------------------------- BernoulliVector ------------------------------- def test_bernoulli_vector_default_output_layer(): """ BernoulliVector's default output layer is compatible with its required output space """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = BernoulliVector(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) def test_bernoulli_vector_sample_from_conditional(): """ BernoulliVector.sample_from_conditional works when num_samples is provided """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = BernoulliVector(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) mu = T.matrix('mu') conditional.sample_from_conditional([mu], num_samples=2) @raises(ValueError) def test_bernoulli_vector_reparametrization_trick(): """ BernoulliVector.sample_from_conditional raises an error when asked to sample using the reparametrization trick """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = BernoulliVector(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) mu = T.matrix('mu') epsilon = T.tensor3('epsilon') conditional.sample_from_conditional([mu], epsilon=epsilon) def test_bernoulli_vector_conditional_expectation(): """ BernoulliVector.conditional_expectation doesn't crash """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = BernoulliVector(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) mu = T.matrix('mu') conditional.conditional_expectation([mu]) def test_bernoulli_vector_log_conditional(): """ BernoulliVector.log_conditional doesn't crash """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = BernoulliVector(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) mu = T.matrix('mu') samples = T.tensor3('samples') conditional.log_conditional(samples, [mu]) # ---------------------------- DiagonalGaussian ------------------------------- def test_diagonal_gaussian_default_output_layer(): """ DiagonalGaussian's default output layer is compatible with its required output space """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = DiagonalGaussian(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) def test_diagonal_gaussian_sample_from_conditional(): """ DiagonalGaussian.sample_from_conditional works when num_samples is provided """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = DiagonalGaussian(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) mu = T.matrix('mu') log_sigma = T.matrix('log_sigma') conditional.sample_from_conditional([mu, log_sigma], num_samples=2) def test_diagonal_gaussian_reparametrization_trick(): """ DiagonalGaussian.sample_from_conditional works when asked to sample using the reparametrization trick """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = DiagonalGaussian(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) mu = T.matrix('mu') log_sigma = T.matrix('log_sigma') epsilon = T.tensor3('epsilon') conditional.sample_from_conditional([mu, log_sigma], epsilon=epsilon) def test_diagonal_gaussian_conditional_expectation(): """ DiagonalGaussian.conditional_expectation doesn't crash """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = DiagonalGaussian(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) mu = T.matrix('mu') log_sigma = T.matrix('log_sigma') conditional.conditional_expectation([mu, log_sigma]) def test_diagonal_gaussian_log_conditional(): """ DiagonalGaussian.log_conditional doesn't crash """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = DiagonalGaussian(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) mu = T.matrix('mu') log_sigma = T.matrix('log_sigma') samples = T.tensor3('samples') conditional.log_conditional(samples, [mu, log_sigma]) def test_diagonal_gaussian_sample_from_epsilon(): """ DiagonalGaussian.sample_from_epsilon doesn't crash """ mlp = MLP(layers=[Linear(layer_name='h', dim=5, irange=0.01, max_col_norm=0.01)]) conditional = DiagonalGaussian(mlp=mlp, name='conditional') vae = DummyVAE() conditional.set_vae(vae) input_space = VectorSpace(dim=5) conditional.initialize_parameters(input_space=input_space, ndim=5) conditional.sample_from_epsilon((2, 10, 5)) ############################################################################### # models/vae/__init__.py tests ############################################################################### def test_one_sample_allowed(): """ VAE allows one sample per data point """ encoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)]) decoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)]) prior = DiagonalGaussianPrior() conditional = BernoulliVector(mlp=decoding_model, name='conditional') posterior = DiagonalGaussian(mlp=encoding_model, name='posterior') vae = VAE(nvis=10, prior=prior, conditional=conditional, posterior=posterior, nhid=5) X = T.matrix('X') lower_bound = vae.log_likelihood_lower_bound(X, num_samples=1) f = theano.function(inputs=[X], outputs=lower_bound) rng = make_np_rng(default_seed=11223) f(as_floatX(rng.uniform(size=(10, 10)))) def test_multiple_samples_allowed(): """ VAE allows multiple samples per data point """ encoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)]) decoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)]) prior = DiagonalGaussianPrior() conditional = BernoulliVector(mlp=decoding_model, name='conditional') posterior = DiagonalGaussian(mlp=encoding_model, name='posterior') vae = VAE(nvis=10, prior=prior, conditional=conditional, posterior=posterior, nhid=5) X = T.matrix('X') lower_bound = vae.log_likelihood_lower_bound(X, num_samples=10) f = theano.function(inputs=[X], outputs=lower_bound) rng = make_np_rng(default_seed=11223) f(as_floatX(rng.uniform(size=(10, 10)))) def test_convolutional_compatible(): """ VAE allows convolutional encoding networks """ encoding_model = MLP( layers=[ SpaceConverter( layer_name='conv2d_converter', output_space=Conv2DSpace(shape=[4, 4], num_channels=1) ), ConvRectifiedLinear( layer_name='h', output_channels=2, kernel_shape=[2, 2], kernel_stride=[1, 1], pool_shape=[1, 1], pool_stride=[1, 1], pool_type='max', irange=0.01) ] ) decoding_model = MLP(layers=[Linear(layer_name='h', dim=16, irange=0.01)]) prior = DiagonalGaussianPrior() conditional = BernoulliVector(mlp=decoding_model, name='conditional') posterior = DiagonalGaussian(mlp=encoding_model, name='posterior') vae = VAE(nvis=16, prior=prior, conditional=conditional, posterior=posterior, nhid=16) X = T.matrix('X') lower_bound = vae.log_likelihood_lower_bound(X, num_samples=10) f = theano.function(inputs=[X], outputs=lower_bound) rng = make_np_rng(default_seed=11223) f(as_floatX(rng.uniform(size=(10, 16)))) def test_vae_automatically_finds_kl_integrator(): """ VAE automatically finds the right KLIntegrator """ encoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)]) decoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)]) prior = DiagonalGaussianPrior() conditional = BernoulliVector(mlp=decoding_model, name='conditional') posterior = DiagonalGaussian(mlp=encoding_model, name='posterior') vae = VAE(nvis=10, prior=prior, conditional=conditional, posterior=posterior, nhid=5) assert (vae.kl_integrator is not None and isinstance(vae.kl_integrator, DiagonalGaussianPriorPosteriorKL)) ############################################################################### # costs/vae.py tests ############################################################################### def test_VAE_cost(): """ VAE trains properly with the VAE cost """ yaml_src_path = os.path.join(os.path.dirname(__file__), 'test_vae_cost_vae_criterion.yaml') train_object = yaml_parse.load_path(yaml_src_path) train_object.main_loop() def test_IS_cost(): """ VAE trains properly with the importance sampling cost """ yaml_src_path = os.path.join(os.path.dirname(__file__), 'test_vae_cost_is_criterion.yaml') train_object = yaml_parse.load_path(yaml_src_path) train_object.main_loop()
bsd-3-clause
ShinyROM/android_external_chromium_org
tools/perf/record_android_profile.py
42
1209
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys import tempfile sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, 'telemetry')) from telemetry.core import browser_finder from telemetry.core import browser_options def _RunPrebuilt(options): browser_to_create = browser_finder.FindBrowser(options) with browser_to_create.Create() as browser: browser.Start() output_file = os.path.join(tempfile.mkdtemp(), options.profiler) raw_input('Press enter to start profiling...') print '>> Starting profiler', options.profiler browser.StartProfiling(options.profiler, output_file) print 'Press enter or CTRL+C to stop' try: raw_input() except KeyboardInterrupt: pass finally: browser.StopProfiling() print '<< Stopped profiler ', options.profiler if __name__ == '__main__': browser_finder_options = browser_options.BrowserFinderOptions() parser = browser_finder_options.CreateParser('') profiler_options, _ = parser.parse_args() sys.exit(_RunPrebuilt(profiler_options))
bsd-3-clause
hnakamur/saklient.python
saklient/cloud/models/model_iface.py
1
3605
# -*- coding:utf-8 -*- from ..client import Client from .model import Model from ..resources.resource import Resource from ..resources.iface import Iface from ...util import Util import saklient # module saklient.cloud.models.model_iface class Model_Iface(Model): ## インタフェースを検索・作成するための機能を備えたクラス。 ## @private # @return {str} def _api_path(self): return "/interface" ## @private # @return {str} def _root_key(self): return "Interface" ## @private # @return {str} def _root_key_m(self): return "Interfaces" ## @private # @return {str} def _class_name(self): return "Iface" ## @private # @param {any} obj # @param {bool} wrapped=False # @return {saklient.cloud.resources.resource.Resource} def _create_resource_impl(self, obj, wrapped=False): Util.validate_type(wrapped, "bool") return Iface(self._client, obj, wrapped) ## 次に取得するリストの開始オフセットを指定します。 # # @param {int} offset オフセット # @return {saklient.cloud.models.model_iface.Model_Iface} this def offset(self, offset): Util.validate_type(offset, "int") return self._offset(offset) ## 次に取得するリストの上限レコード数を指定します。 # # @param {int} count 上限レコード数 # @return {saklient.cloud.models.model_iface.Model_Iface} this def limit(self, count): Util.validate_type(count, "int") return self._limit(count) ## Web APIのフィルタリング設定を直接指定します。 # # @param {str} key キー # @param {any} value 値 # @param {bool} multiple=False valueに配列を与え、OR条件で完全一致検索する場合にtrueを指定します。通常、valueはスカラ値であいまい検索されます。 # @return {saklient.cloud.models.model_iface.Model_Iface} def filter_by(self, key, value, multiple=False): Util.validate_type(key, "str") Util.validate_type(multiple, "bool") return self._filter_by(key, value, multiple) ## 次のリクエストのために設定されているステートをすべて破棄します。 # # @return {saklient.cloud.models.model_iface.Model_Iface} this def reset(self): return self._reset() ## 新規リソース作成用のオブジェクトを用意します。 # # 返り値のオブジェクトにパラメータを設定し、save() を呼ぶことで実際のリソースが作成されます。 # # @return {saklient.cloud.resources.iface.Iface} リソースオブジェクト def create(self): return self._create() ## 指定したIDを持つ唯一のリソースを取得します。 # # @param {str} id # @return {saklient.cloud.resources.iface.Iface} リソースオブジェクト def get_by_id(self, id): Util.validate_type(id, "str") return self._get_by_id(id) ## リソースの検索リクエストを実行し、結果をリストで取得します。 # # @return {saklient.cloud.resources.iface.Iface[]} リソースオブジェクトの配列 def find(self): return self._find() ## @ignore # @param {saklient.cloud.client.Client} client def __init__(self, client): super(Model_Iface, self).__init__(client) Util.validate_type(client, "saklient.cloud.client.Client")
mit
krytarowski/coreclr
src/ToolBox/SOS/tests/t_cmd_histroot.py
43
1757
import lldb import re import testutils as test def runScenario(assembly, debugger, target): process = target.GetProcess() res = lldb.SBCommandReturnObject() ci = debugger.GetCommandInterpreter() # Run debugger, wait until libcoreclr is loaded, # set breakpoint at Test.Main and stop there test.stop_in_main(debugger, assembly) ci.HandleCommand("dso", res) print(res.GetOutput()) print(res.GetError()) # Interpreter must have this command and able to run it test.assertTrue(res.Succeeded()) output = res.GetOutput() # Output is not empty test.assertTrue(len(output) > 0) # Get all objects objects = [] for line in output.split('\n'): match = re.match('([0-9a-fA-F]+)\s+([0-9a-fA-F]+)\s', line) # Not all lines list objects if match: groups = match.groups() # Match has exactly two subgroups test.assertEqual(len(groups), 2) obj_addr = groups[1] # Address must be a hex number test.assertTrue(test.is_hexnum(obj_addr)) objects.append(obj_addr) # There must be at least one object test.assertTrue(len(objects) > 0) for obj in objects: ci.HandleCommand("histroot " + obj, res) print(res.GetOutput()) print(res.GetError()) # Interpreter must have this command and able to run it test.assertTrue(res.Succeeded()) output = res.GetOutput() # Output is not empty test.assertTrue(len(output) > 0) match = re.search('GCCount', output) test.assertTrue(match) # TODO: test other use cases # Continue current process and checks its exit code test.exit_lldb(debugger, assembly)
mit
okuraoy/mywork
mtlearn/datasets.py
1
2037
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import pandas as pd from sklearn.datasets.base import Bunch from os.path import join PATH = "d:\\data" # class Bunch(dict): # """Container object for datasets # Dictionary-like object that exposes its keys as attributes. # # See: sklearn.datasets.base.py Bunch # """ # # def __init__(self, **kwargs): # super(Bunch, self).__init__(kwargs) # # def __setattr__(self, key, value): # self[key] = value # # def __dir__(self): # return self.keys() # # def __getattr__(self, key): # try: # return self[key] # except KeyError: # raise AttributeError(key) # # def __setstate__(self, state): # # Bunch pickles generated with scikit-learn 0.16.* have an non # # empty __dict__. This causes a surprising behaviour when # # loading these pickles scikit-learn 0.17: reading bunch.key # # uses __dict__ but assigning to bunch.key use __setattr__ and # # only changes bunch['key']. More details can be found at: # # https://github.com/scikit-learn/scikit-learn/issues/6196. # # Overriding __setstate__ to be a noop has the effect of # # ignoring the pickled __dict__ # pass def parse_date(x): return pd.datetime.strptime(x, '%Y-%m-%d') def load_pcs_data(): # column: date,pcs,f1,f2,... # sep='\001', df = pd.read_csv(join(PATH, 'spu_pcs_20170721.csv'), sep='\001', parse_dates=['date'], date_parser=parse_date) df.sort_values(by='date') columns = np.array(df.columns.values) feature_name = columns[2:] tmp_data = np.array(df) inx_data = tmp_data[:, 0] target = tmp_data[:, 1] data = tmp_data[:, 2:] # print shape print data.shape print feature_name return Bunch(data=data, target=target, feature_names=feature_name, inx=inx_data) if __name__ == '__main__': load_pcs_data()
apache-2.0
adrienbrault/home-assistant
tests/components/gios/test_init.py
6
1617
"""Test init of GIOS integration.""" from unittest.mock import patch from homeassistant.components.gios.const import DOMAIN from homeassistant.config_entries import ( ENTRY_STATE_LOADED, ENTRY_STATE_NOT_LOADED, ENTRY_STATE_SETUP_RETRY, ) from homeassistant.const import STATE_UNAVAILABLE from tests.common import MockConfigEntry from tests.components.gios import init_integration async def test_async_setup_entry(hass): """Test a successful setup entry.""" await init_integration(hass) state = hass.states.get("air_quality.home") assert state is not None assert state.state != STATE_UNAVAILABLE assert state.state == "4" async def test_config_not_ready(hass): """Test for setup failure if connection to GIOS is missing.""" entry = MockConfigEntry( domain=DOMAIN, title="Home", unique_id=123, data={"station_id": 123, "name": "Home"}, ) with patch( "homeassistant.components.gios.Gios._get_stations", side_effect=ConnectionError(), ): entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) assert entry.state == ENTRY_STATE_SETUP_RETRY async def test_unload_entry(hass): """Test successful unload of entry.""" entry = await init_integration(hass) assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert entry.state == ENTRY_STATE_LOADED assert await hass.config_entries.async_unload(entry.entry_id) await hass.async_block_till_done() assert entry.state == ENTRY_STATE_NOT_LOADED assert not hass.data.get(DOMAIN)
mit
relic7/prodimages
python/jbmodules/cacheclear_tools/add_colorstyle_cache_clear_queue.py
2
1825
#!/usr/bin/env python # -*- coding: utf-8 -*- def post_or_put_style_to_api(colorstyle, api_url=None, AuthToken=None): import requests, json import http.client, urllib.parse if not api_url: api_url = 'http://prodimages.ny.bluefly.com/image-update/' update_styles = list(set(sorted(update_styles))) for colorstyle in update_styles: data = {'colorstyle': colorstyle} #params = urllib.parse.urlencode(data) params = json.dumps(data) auth = {'Authorization': 'Token ' + AuthToken} content_type = {'content-type': 'application/json'} headers = json.dumps(auth,content_type) # conn = http.client.HTTPConnection(api_url, 80) # conn.request("PUT", "/", BODY) #response = conn.getresponse() try: response = requests.post(api_url, headers=headers, params=params) print response.status, response.method, data #print(resp.status, response.reason) except: try: response = requests.put(api_url, headers=headers, params=params) print response.status, response.method, data except: curlauth = 'Authorization: Token ' + AuthToken curldata = 'colorstyle=' + colorstyle # try: # subprocess.call([ 'curl', '-u', 'james:hoetker', '-d', curldata, '-H', curlauth, '-X', 'PUT', api_url]) # except: # subprocess.call([ 'curl', '-u', 'james:hoetker' '-d', curldata, '-H', curlauth, api_url]) if __name__ == '__main__': import os,sys try: colorstyle = sys.argv[1] post_or_put_style_to_api(colorstyle, api_url=None, AuthToken=None) except IndexError: print 'Enter a style numbert to add to clear queue'
mit
hopshadoop/hops-hadoop-chef
files/default/hadoop_logs_mgm.py
5
9009
# This file is part of Hopsworks # Copyright (C) 2018, Logical Clocks AB. All rights reserved # Hopsworks 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. # Hopsworks 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 <https://www.gnu.org/licenses/>. ''' Dependencies: Pydoop: 1.2.0 kagent_utils: 0.1+ ''' __license__ = "AGPL v3" __version__ = "0.1" import os import re import time import argparse import ConfigParser import logging.handlers import pydoop.hdfs as hdfs from kagent_utils import IntervalParser BACKUP_OP = "backup" DELETE_OP = "delete" BACKUP_PERMISSIONS = 0700 ROLLED_LOG_REGEX = re.compile(".*\.log\.[1-9]+") class LogFile: def __init__(self, dirpath, filename): self.filepath = os.path.join(dirpath, filename) self.filename = filename self.mtime = os.path.getmtime(self.filepath) def __str__(self): return "{0}: {1}".format(self.filepath, self.mtime) def list_local_files(local_log_dir): log_files = [] for dirpath, dirnames, filenames in os.walk(local_log_dir): for filename in filenames: if ROLLED_LOG_REGEX.match(filename): log_files.append(LogFile(dirpath, filename)) return log_files def load_checkpoint(checkpoint_file): LOGGER = logging.getLogger(__name__) if not os.path.isfile(checkpoint_file): LOGGER.debug("Checkpoint file does not exist") return -1 with open(checkpoint_file, 'r') as fd: checkpoint = float(fd.readline()) LOGGER.debug("Last checkpoint at {0}".format(time.ctime(checkpoint))) return checkpoint def write_checkpoint(checkpoint_file): with open(checkpoint_file, 'w') as fd: fd.write(str(time.time())) def get_remote_dir(log_file, remote_basedir): LOGGER = logging.getLogger(__name__) time_struct = time.gmtime(log_file.mtime) remote_dir = os.path.join(remote_basedir, str(time_struct.tm_year), str(time_struct.tm_mon)) LOGGER.debug("Remote dir for {0} is {1}".format(log_file, remote_dir)) return remote_dir def remote_dir_exists(remote_dir): return hdfs.path.isdir(remote_dir) def create_remote_dir(remote_dir): hdfs.mkdir(remote_dir) logging.getLogger(__name__).debug("Creating remote directory {0}".format(remote_dir)) def copy_file_2_remote_dir(remote_dir, log_file): LOGGER = logging.getLogger(__name__) suffix = time.strftime('%d-%m-%y_%H-%M-%S', time.gmtime(log_file.mtime)) dest_filename = os.path.join(remote_dir, "{0}-{1}".format(log_file.filename, suffix)) LOGGER.debug("Copying {0} to {1}".format(log_file.filepath, dest_filename)) hdfs.put(log_file.filepath, dest_filename) LOGGER.debug("Copied {0} to HDFS".format(log_file.filepath)) hdfs.chmod(dest_filename, BACKUP_PERMISSIONS) LOGGER.debug("Changed permissions for {0}".format(dest_filename)) def backup(config): LOGGER = logging.getLogger(__name__) remote_basedir = config.get('backup', 'remote-basedir') local_log_dir = config.get('backup', 'local-log-dir') checkpoint_file = config.get('backup', 'checkpoint') if not remote_dir_exists(remote_basedir): LOGGER.debug("Remote directory {0} does not exist, creating it".format(remote_basedir)) create_remote_dir(remote_basedir) hdfs.chmod(remote_basedir, BACKUP_PERMISSIONS) log_files = list_local_files(local_log_dir) now = time.time() checkpoint = load_checkpoint(checkpoint_file) copied_log_files = {} for log_file in log_files: if log_file.mtime > checkpoint: remote_dir = get_remote_dir(log_file, remote_basedir) if not remote_dir_exists(remote_dir): create_remote_dir(remote_dir) LOGGER.debug("Created remote directory {0}".format(remote_dir)) try: copy_file_2_remote_dir(remote_dir, log_file) copied_log_files[log_file] = remote_dir except Exception as ex: LOGGER.warn("Error while copying {0} - {1}".format(log_file, ex)) LOGGER.debug("Finished copying, updating checkpoint") write_checkpoint(checkpoint_file) if not copied_log_files: LOGGER.debug("Did not copy any log file") else: for lf, rd in copied_log_files.iteritems(): LOGGER.info("Copied file {0} to {1}".format(lf, rd)) LOGGER.info("Finished copying files") def walk_remotely(remote_path): LOGGER.debug("Walking {0}".format(remote_path)) inodes = hdfs.lsl(remote_path, recursive=True) return inodes def delete_files(remote_basedir, retention): inodes = walk_remotely(remote_basedir) now = time.time() deleted_files = [] for inode in inodes: if now - inode['last_mod'] > retention and inode['kind'] == 'file': LOGGER.debug("Deleting file {0}".format(inode['path'])) hdfs.rmr(inode['path']) deleted_files.append(inode['path']) return deleted_files def clean_empty_dirs(remote_basedir): LOGGER = logging.getLogger(__name__) deleted_dirs = [] ## Directory structure is {remote_basedir}/{year}/{month} year_dirs = hdfs.ls(remote_basedir) # Do an ls to find all month dirs for year_dir in year_dirs: month_dirs = hdfs.ls(hdfs.path.join(remote_basedir, year_dir)) # Check to see if month dirs are empty month_dirs_deleted = 0 for month_dir in month_dirs: files = hdfs.ls(hdfs.path.join(remote_basedir, year_dir, month_dir)) if not files: LOGGER.debug("Directory {0} is empty, deleting it".format(month_dir)) hdfs.rmr(month_dir) deleted_dirs.append(month_dir) month_dirs_deleted += 1 if month_dirs_deleted == len(month_dirs): # Deleted all month sub-directories, so delete year directory too LOGGER.debug("Directory {0} is empty, deleting it".format(year_dir)) hdfs.rmr(year_dir) deleted_dirs.append(year_dir) return deleted_dirs def delete(config): LOGGER = logging.getLogger(__name__) remote_basedir = config.get('backup', 'remote-basedir') retention = config.get('delete', 'retention') interval_parser = IntervalParser() retention_sec = interval_parser.get_interval_in_s(retention) deleted_files = delete_files(remote_basedir, retention_sec) deleted_dirs = clean_empty_dirs(remote_basedir) if not deleted_files: LOGGER.debug("No log files deleted") else: [LOGGER.info("Deleted log file: {0}".format(f)) for f in deleted_files] if not deleted_dirs: LOGGER.debug("No empty dirs deleted") else: [LOGGER.info("Deleted empty dir {0}".format(f)) for f in deleted_dirs] LOGGER.info("Done deleting files") def setup_logging(log_file, logging_level): logger = logging.getLogger(__name__) logger_formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') logger_file_handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=50000000, backupCount=5) logger_stream_handler = logging.StreamHandler() logger_file_handler.setFormatter(logger_formatter) logger_stream_handler.setFormatter(logger_formatter) logger.addHandler(logger_file_handler) logger.addHandler(logger_stream_handler) logger.setLevel(logging_level) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Hops logs backup") parser.add_argument('-c', '--config', help='Configuration file') subparser = parser.add_subparsers(dest='operation', help='Operations') subparser.add_parser(BACKUP_OP, help='Move Hops log files to HDFS') subparser.add_parser(DELETE_OP, help='Delete old log files from HDFS') args = parser.parse_args() config = ConfigParser.ConfigParser() config.read(args.config) log_file = config.get('general', 'log-file') logging_level_str = config.get('general', 'logging-level') logging_level = getattr(logging, logging_level_str.upper(), None) if not isinstance(logging_level, int): raise ValueError("Invalid log level {0}".format(logging_level_str)) setup_logging(log_file, logging_level) LOGGER = logging.getLogger(__name__) if args.operation == BACKUP_OP: LOGGER.debug("Performing BACKUP") backup(config) elif args.operation == DELETE_OP: LOGGER.debug("Performing DELETE") delete(config) else: LOGGER.error("Unknown operation {0}".format(args.operation))
agpl-3.0
chelsea1620/google-belay
station/openid/extensions/draft/pape2.py
156
9330
"""An implementation of the OpenID Provider Authentication Policy Extension 1.0 @see: http://openid.net/developers/specs/ @since: 2.1.0 """ __all__ = [ 'Request', 'Response', 'ns_uri', 'AUTH_PHISHING_RESISTANT', 'AUTH_MULTI_FACTOR', 'AUTH_MULTI_FACTOR_PHYSICAL', ] from openid.extension import Extension import re ns_uri = "http://specs.openid.net/extensions/pape/1.0" AUTH_MULTI_FACTOR_PHYSICAL = \ 'http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical' AUTH_MULTI_FACTOR = \ 'http://schemas.openid.net/pape/policies/2007/06/multi-factor' AUTH_PHISHING_RESISTANT = \ 'http://schemas.openid.net/pape/policies/2007/06/phishing-resistant' TIME_VALIDATOR = re.compile('^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ$') class Request(Extension): """A Provider Authentication Policy request, sent from a relying party to a provider @ivar preferred_auth_policies: The authentication policies that the relying party prefers @type preferred_auth_policies: [str] @ivar max_auth_age: The maximum time, in seconds, that the relying party wants to allow to have elapsed before the user must re-authenticate @type max_auth_age: int or NoneType """ ns_alias = 'pape' def __init__(self, preferred_auth_policies=None, max_auth_age=None): super(Request, self).__init__() if not preferred_auth_policies: preferred_auth_policies = [] self.preferred_auth_policies = preferred_auth_policies self.max_auth_age = max_auth_age def __nonzero__(self): return bool(self.preferred_auth_policies or self.max_auth_age is not None) def addPolicyURI(self, policy_uri): """Add an acceptable authentication policy URI to this request This method is intended to be used by the relying party to add acceptable authentication types to the request. @param policy_uri: The identifier for the preferred type of authentication. @see: http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#auth_policies """ if policy_uri not in self.preferred_auth_policies: self.preferred_auth_policies.append(policy_uri) def getExtensionArgs(self): """@see: C{L{Extension.getExtensionArgs}} """ ns_args = { 'preferred_auth_policies':' '.join(self.preferred_auth_policies) } if self.max_auth_age is not None: ns_args['max_auth_age'] = str(self.max_auth_age) return ns_args def fromOpenIDRequest(cls, request): """Instantiate a Request object from the arguments in a C{checkid_*} OpenID message """ self = cls() args = request.message.getArgs(self.ns_uri) if args == {}: return None self.parseExtensionArgs(args) return self fromOpenIDRequest = classmethod(fromOpenIDRequest) def parseExtensionArgs(self, args): """Set the state of this request to be that expressed in these PAPE arguments @param args: The PAPE arguments without a namespace @rtype: None @raises ValueError: When the max_auth_age is not parseable as an integer """ # preferred_auth_policies is a space-separated list of policy URIs self.preferred_auth_policies = [] policies_str = args.get('preferred_auth_policies') if policies_str: for uri in policies_str.split(' '): if uri not in self.preferred_auth_policies: self.preferred_auth_policies.append(uri) # max_auth_age is base-10 integer number of seconds max_auth_age_str = args.get('max_auth_age') self.max_auth_age = None if max_auth_age_str: try: self.max_auth_age = int(max_auth_age_str) except ValueError: pass def preferredTypes(self, supported_types): """Given a list of authentication policy URIs that a provider supports, this method returns the subsequence of those types that are preferred by the relying party. @param supported_types: A sequence of authentication policy type URIs that are supported by a provider @returns: The sub-sequence of the supported types that are preferred by the relying party. This list will be ordered in the order that the types appear in the supported_types sequence, and may be empty if the provider does not prefer any of the supported authentication types. @returntype: [str] """ return filter(self.preferred_auth_policies.__contains__, supported_types) Request.ns_uri = ns_uri class Response(Extension): """A Provider Authentication Policy response, sent from a provider to a relying party """ ns_alias = 'pape' def __init__(self, auth_policies=None, auth_time=None, nist_auth_level=None): super(Response, self).__init__() if auth_policies: self.auth_policies = auth_policies else: self.auth_policies = [] self.auth_time = auth_time self.nist_auth_level = nist_auth_level def addPolicyURI(self, policy_uri): """Add a authentication policy to this response This method is intended to be used by the provider to add a policy that the provider conformed to when authenticating the user. @param policy_uri: The identifier for the preferred type of authentication. @see: http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#auth_policies """ if policy_uri not in self.auth_policies: self.auth_policies.append(policy_uri) def fromSuccessResponse(cls, success_response): """Create a C{L{Response}} object from a successful OpenID library response (C{L{openid.consumer.consumer.SuccessResponse}}) response message @param success_response: A SuccessResponse from consumer.complete() @type success_response: C{L{openid.consumer.consumer.SuccessResponse}} @rtype: Response or None @returns: A provider authentication policy response from the data that was supplied with the C{id_res} response or None if the provider sent no signed PAPE response arguments. """ self = cls() # PAPE requires that the args be signed. args = success_response.getSignedNS(self.ns_uri) # Only try to construct a PAPE response if the arguments were # signed in the OpenID response. If not, return None. if args is not None: self.parseExtensionArgs(args) return self else: return None def parseExtensionArgs(self, args, strict=False): """Parse the provider authentication policy arguments into the internal state of this object @param args: unqualified provider authentication policy arguments @param strict: Whether to raise an exception when bad data is encountered @returns: None. The data is parsed into the internal fields of this object. """ policies_str = args.get('auth_policies') if policies_str and policies_str != 'none': self.auth_policies = policies_str.split(' ') nist_level_str = args.get('nist_auth_level') if nist_level_str: try: nist_level = int(nist_level_str) except ValueError: if strict: raise ValueError('nist_auth_level must be an integer between ' 'zero and four, inclusive') else: self.nist_auth_level = None else: if 0 <= nist_level < 5: self.nist_auth_level = nist_level auth_time = args.get('auth_time') if auth_time: if TIME_VALIDATOR.match(auth_time): self.auth_time = auth_time elif strict: raise ValueError("auth_time must be in RFC3339 format") fromSuccessResponse = classmethod(fromSuccessResponse) def getExtensionArgs(self): """@see: C{L{Extension.getExtensionArgs}} """ if len(self.auth_policies) == 0: ns_args = { 'auth_policies':'none', } else: ns_args = { 'auth_policies':' '.join(self.auth_policies), } if self.nist_auth_level is not None: if self.nist_auth_level not in range(0, 5): raise ValueError('nist_auth_level must be an integer between ' 'zero and four, inclusive') ns_args['nist_auth_level'] = str(self.nist_auth_level) if self.auth_time is not None: if not TIME_VALIDATOR.match(self.auth_time): raise ValueError('auth_time must be in RFC3339 format') ns_args['auth_time'] = self.auth_time return ns_args Response.ns_uri = ns_uri
apache-2.0
ahlfors/omaha
site_scons/site_tools/wix.py
63
5679
"""SCons.Tool.wix Tool-specific initialization for wix, the Windows Installer XML Tool. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation # # 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, # 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: # # 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 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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 IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/wix.py 3897 2009/01/13 06:45:54 scons" import SCons.Builder import SCons.Action import os import string def generate(env): """Add Builders and construction variables for WiX to an Environment.""" if not exists(env): return env['WIXCANDLEFLAGS'] = ['-nologo'] env['WIXCANDLEINCLUDE'] = [] env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}' env['WIXLIGHTFLAGS'].append( '-nologo' ) env['WIXLIGHTCOM'] = "$WIXLIGHT $WIXLIGHTFLAGS -out ${TARGET} ${SOURCES}" #BEGIN_OMAHA_ADDITION # Necessary to build multiple MSIs from a single .wxs without explicitly # building the .wixobj. # Follows the convention of obj file prefixes in other tools, such as # OBJPREFIX in msvc.py. env['WIXOBJPREFIX'] = '' #END_OMAHA_ADDITION object_builder = SCons.Builder.Builder( action = '$WIXCANDLECOM', #BEGIN_OMAHA_ADDITION prefix = '$WIXOBJPREFIX', #END_OMAHA_ADDITION #BEGIN_OMAHA_CHANGE # The correct/default suffix is .wixobj, not .wxiobj. # suffix = '.wxiobj', suffix = '.wixobj', #END_OMAHA_CHANGE src_suffix = '.wxs') linker_builder = SCons.Builder.Builder( action = '$WIXLIGHTCOM', #BEGIN_OMAHA_CHANGE # The correct/default suffix is .wixobj, not .wxiobj. # src_suffix = '.wxiobj', src_suffix = '.wixobj', #END_OMAHA_CHANGE src_builder = object_builder) env['BUILDERS']['WiX'] = linker_builder def exists(env): env['WIXCANDLE'] = 'candle.exe' env['WIXLIGHT'] = 'light.exe' #BEGIN_OMAHA_CHANGE # # try to find the candle.exe and light.exe tools and # try to find the candle.exe and light.exe tools and #END_OMAHA_CHANGE # add the install directory to light libpath. #BEGIN_OMAHA_CHANGE # For backwards compatibility, search PATH environment variable for tools. # #for path in os.environ['PATH'].split(os.pathsep): # for path in string.split(os.environ['PATH'], os.pathsep): for path in os.environ['PATH'].split(os.pathsep): #END_OMAHA_CHANGE if not path: continue # workaround for some weird python win32 bug. if path[0] == '"' and path[-1:]=='"': path = path[1:-1] # normalize the path path = os.path.normpath(path) # search for the tools in the PATH environment variable try: #BEGIN_OMAHA_CHANGE # if env['WIXCANDLE'] in os.listdir(path) and\ # env['WIXLIGHT'] in os.listdir(path): files = os.listdir(path) if (env['WIXCANDLE'] in files and env['WIXLIGHT'] in files): # env.PrependENVPath('PATH', path) env.PrependENVPath('PATH', path) # env['WIXLIGHTFLAGS'] = [ os.path.join( path, 'wixui.wixlib' ), # '-loc', # os.path.join( path, 'WixUI_en-us.wxl' ) ] # return 1 break #END_OMAHA_CHANGE except OSError: pass # ignore this, could be a stale PATH entry. #BEGIN_OMAHA_ADDITION # Search for the tools in the SCons paths. for path in env['ENV'].get('PATH', '').split(os.pathsep): try: files = os.listdir(path) if (env['WIXCANDLE'] in files and env['WIXLIGHT'] in files): # The following is for compatibility with versions prior to 3. # Version 3 no longer has these files. extra_files = [os.path.join(i) for i in ['wixui.wixlib', 'WixUI_en-us.wxl']] if (os.path.exists(extra_files[0]) and os.path.exists(extra_files[1])): env.Append(WIXLIGHTFLAGS=[ extra_files[0], '-loc', extra_files[1]]) else: # Create empty variable so the append in generate() works. env.Append(WIXLIGHTFLAGS=[]) # WiX was found. return 1 except OSError: pass # ignore this, could be a stale PATH entry. #END_OMAHA_ADDITION return None
apache-2.0
emilio/servo
tests/wpt/web-platform-tests/tools/third_party/html5lib/parse.py
26
9201
#!/usr/bin/env python """usage: %prog [options] filename Parse a document to a tree, with optional profiling """ import sys import traceback from optparse import OptionParser from html5lib import html5parser from html5lib import treebuilders, serializer, treewalkers from html5lib import constants from html5lib import _utils def parse(): optParser = getOptParser() opts, args = optParser.parse_args() encoding = "utf8" try: f = args[-1] # Try opening from the internet if f.startswith('http://'): try: import urllib.request import urllib.parse import urllib.error import cgi f = urllib.request.urlopen(f) contentType = f.headers.get('content-type') if contentType: (mediaType, params) = cgi.parse_header(contentType) encoding = params.get('charset') except: pass elif f == '-': f = sys.stdin if sys.version_info[0] >= 3: encoding = None else: try: # Try opening from file system f = open(f, "rb") except IOError as e: sys.stderr.write("Unable to open file: %s\n" % e) sys.exit(1) except IndexError: sys.stderr.write("No filename provided. Use -h for help\n") sys.exit(1) treebuilder = treebuilders.getTreeBuilder(opts.treebuilder) p = html5parser.HTMLParser(tree=treebuilder, debug=opts.log) if opts.fragment: parseMethod = p.parseFragment else: parseMethod = p.parse if opts.profile: import cProfile import pstats cProfile.runctx("run(parseMethod, f, encoding, scripting)", None, {"run": run, "parseMethod": parseMethod, "f": f, "encoding": encoding, "scripting": opts.scripting}, "stats.prof") # XXX - We should use a temp file here stats = pstats.Stats('stats.prof') stats.strip_dirs() stats.sort_stats('time') stats.print_stats() elif opts.time: import time t0 = time.time() document = run(parseMethod, f, encoding, opts.scripting) t1 = time.time() if document: printOutput(p, document, opts) t2 = time.time() sys.stderr.write("\n\nRun took: %fs (plus %fs to print the output)" % (t1 - t0, t2 - t1)) else: sys.stderr.write("\n\nRun took: %fs" % (t1 - t0)) else: document = run(parseMethod, f, encoding, opts.scripting) if document: printOutput(p, document, opts) def run(parseMethod, f, encoding, scripting): try: document = parseMethod(f, override_encoding=encoding, scripting=scripting) except: document = None traceback.print_exc() return document def printOutput(parser, document, opts): if opts.encoding: print("Encoding:", parser.tokenizer.stream.charEncoding) for item in parser.log: print(item) if document is not None: if opts.xml: tb = opts.treebuilder.lower() if tb == "dom": document.writexml(sys.stdout, encoding="utf-8") elif tb == "lxml": import lxml.etree sys.stdout.write(lxml.etree.tostring(document, encoding="unicode")) elif tb == "etree": sys.stdout.write(_utils.default_etree.tostring(document, encoding="unicode")) elif opts.tree: if not hasattr(document, '__getitem__'): document = [document] for fragment in document: print(parser.tree.testSerializer(fragment)) elif opts.html: kwargs = {} for opt in serializer.HTMLSerializer.options: try: kwargs[opt] = getattr(opts, opt) except: pass if not kwargs['quote_char']: del kwargs['quote_char'] if opts.sanitize: kwargs["sanitize"] = True tokens = treewalkers.getTreeWalker(opts.treebuilder)(document) if sys.version_info[0] >= 3: encoding = None else: encoding = "utf-8" for text in serializer.HTMLSerializer(**kwargs).serialize(tokens, encoding=encoding): sys.stdout.write(text) if not text.endswith('\n'): sys.stdout.write('\n') if opts.error: errList = [] for pos, errorcode, datavars in parser.errors: errList.append("Line %i Col %i" % pos + " " + constants.E.get(errorcode, 'Unknown error "%s"' % errorcode) % datavars) sys.stdout.write("\nParse errors:\n" + "\n".join(errList) + "\n") def getOptParser(): parser = OptionParser(usage=__doc__) parser.add_option("-p", "--profile", action="store_true", default=False, dest="profile", help="Use the hotshot profiler to " "produce a detailed log of the run") parser.add_option("-t", "--time", action="store_true", default=False, dest="time", help="Time the run using time.time (may not be accurate on all platforms, especially for short runs)") parser.add_option("-b", "--treebuilder", action="store", type="string", dest="treebuilder", default="etree") parser.add_option("-e", "--error", action="store_true", default=False, dest="error", help="Print a list of parse errors") parser.add_option("-f", "--fragment", action="store_true", default=False, dest="fragment", help="Parse as a fragment") parser.add_option("-s", "--scripting", action="store_true", default=False, dest="scripting", help="Handle noscript tags as if scripting was enabled") parser.add_option("", "--tree", action="store_true", default=False, dest="tree", help="Output as debug tree") parser.add_option("-x", "--xml", action="store_true", default=False, dest="xml", help="Output as xml") parser.add_option("", "--no-html", action="store_false", default=True, dest="html", help="Don't output html") parser.add_option("-c", "--encoding", action="store_true", default=False, dest="encoding", help="Print character encoding used") parser.add_option("", "--inject-meta-charset", action="store_true", default=False, dest="inject_meta_charset", help="inject <meta charset>") parser.add_option("", "--strip-whitespace", action="store_true", default=False, dest="strip_whitespace", help="strip whitespace") parser.add_option("", "--omit-optional-tags", action="store_true", default=False, dest="omit_optional_tags", help="omit optional tags") parser.add_option("", "--quote-attr-values", action="store_true", default=False, dest="quote_attr_values", help="quote attribute values") parser.add_option("", "--use-best-quote-char", action="store_true", default=False, dest="use_best_quote_char", help="use best quote character") parser.add_option("", "--quote-char", action="store", default=None, dest="quote_char", help="quote character") parser.add_option("", "--no-minimize-boolean-attributes", action="store_false", default=True, dest="minimize_boolean_attributes", help="minimize boolean attributes") parser.add_option("", "--use-trailing-solidus", action="store_true", default=False, dest="use_trailing_solidus", help="use trailing solidus") parser.add_option("", "--space-before-trailing-solidus", action="store_true", default=False, dest="space_before_trailing_solidus", help="add space before trailing solidus") parser.add_option("", "--escape-lt-in-attrs", action="store_true", default=False, dest="escape_lt_in_attrs", help="escape less than signs in attribute values") parser.add_option("", "--escape-rcdata", action="store_true", default=False, dest="escape_rcdata", help="escape rcdata element values") parser.add_option("", "--sanitize", action="store_true", default=False, dest="sanitize", help="sanitize") parser.add_option("-l", "--log", action="store_true", default=False, dest="log", help="log state transitions") return parser if __name__ == "__main__": parse()
mpl-2.0
FelixZYY/gyp
test/rules-rebuild/gyptest-all.py
351
1662
#!/usr/bin/env python # Copyright (c) 2009 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. """ Verifies that a rule that generates multiple outputs rebuilds correctly when the inputs change. """ import TestGyp test = TestGyp.TestGyp(workdir='workarea_all') test.run_gyp('same_target.gyp', chdir='src') test.relocate('src', 'relocate/src') test.build('same_target.gyp', test.ALL, chdir='relocate/src') expect = """\ Hello from main.c Hello from prog1.in! Hello from prog2.in! """ test.run_built_executable('program', chdir='relocate/src', stdout=expect) test.up_to_date('same_target.gyp', 'program', chdir='relocate/src') test.sleep() contents = test.read(['relocate', 'src', 'prog1.in']) contents = contents.replace('!', ' AGAIN!') test.write(['relocate', 'src', 'prog1.in'], contents) test.build('same_target.gyp', test.ALL, chdir='relocate/src') expect = """\ Hello from main.c Hello from prog1.in AGAIN! Hello from prog2.in! """ test.run_built_executable('program', chdir='relocate/src', stdout=expect) test.up_to_date('same_target.gyp', 'program', chdir='relocate/src') test.sleep() contents = test.read(['relocate', 'src', 'prog2.in']) contents = contents.replace('!', ' AGAIN!') test.write(['relocate', 'src', 'prog2.in'], contents) test.build('same_target.gyp', test.ALL, chdir='relocate/src') expect = """\ Hello from main.c Hello from prog1.in AGAIN! Hello from prog2.in AGAIN! """ test.run_built_executable('program', chdir='relocate/src', stdout=expect) test.up_to_date('same_target.gyp', 'program', chdir='relocate/src') test.pass_test()
bsd-3-clause
jemmyw/ansible
v1/ansible/runner/action_plugins/patch.py
93
2501
# (c) 2015, Brian Coca <briancoca+dev@gmail.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 import os from ansible import utils from ansible.runner.return_data import ReturnData class ActionModule(object): def __init__(self, runner): self.runner = runner def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs): options = {} if complex_args: options.update(complex_args) options.update(utils.parse_kv(module_args)) src = options.get('src', None) dest = options.get('dest', None) remote_src = utils.boolean(options.get('remote_src', 'no')) if src is None: result = dict(failed=True, msg="src is required") return ReturnData(conn=conn, comm_ok=False, result=result) if remote_src: return self.runner._execute_module(conn, tmp, 'patch', module_args, inject=inject, complex_args=complex_args) # Source is local if '_original_file' in inject: src = utils.path_dwim_relative(inject['_original_file'], 'files', src, self.runner.basedir) else: src = utils.path_dwim(self.runner.basedir, src) if tmp is None or "-tmp-" not in tmp: tmp = self.runner._make_tmp_path(conn) tmp_src = conn.shell.join_path(tmp, os.path.basename(src)) conn.put_file(src, tmp_src) if self.runner.become and self.runner.become_user != 'root': if not self.runner.noop_on_check(inject): self.runner._remote_chmod(conn, 'a+r', tmp_src, tmp) new_module_args = dict( src=tmp_src, ) if self.runner.noop_on_check(inject): new_module_args['CHECKMODE'] = True module_args = utils.merge_module_args(module_args, new_module_args) return self.runner._execute_module(conn, tmp, 'patch', module_args, inject=inject, complex_args=complex_args)
gpl-3.0
michaelkirk/QGIS
python/plugins/MetaSearch/dialogs/manageconnectionsdialog.py
13
6638
# -*- coding: utf-8 -*- ############################################################################### # # CSW Client # --------------------------------------------------------- # QGIS Catalogue Service client. # # Copyright (C) 2010 NextGIS (http://nextgis.org), # Alexander Bruy (alexander.bruy@gmail.com), # Maxim Dubinin (sim@gis-lab.info) # # Copyright (C) 2014 Tom Kralidis (tomkralidis@gmail.com) # # This source 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 code 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 xml.etree.ElementTree as etree from PyQt4.QtCore import QSettings from PyQt4.QtGui import (QDialog, QDialogButtonBox, QFileDialog, QListWidgetItem, QMessageBox) from MetaSearch.util import (get_connections_from_file, get_ui_class, prettify_xml) BASE_CLASS = get_ui_class('manageconnectionsdialog.ui') class ManageConnectionsDialog(QDialog, BASE_CLASS): """manage connections""" def __init__(self, mode): """init dialog""" QDialog.__init__(self) self.setupUi(self) self.settings = QSettings() self.filename = None self.mode = mode # 0 - save, 1 - load self.btnBrowse.clicked.connect(self.select_file) self.manage_gui() def manage_gui(self): """manage interface""" if self.mode == 1: self.label.setText(self.tr('Load from file')) self.buttonBox.button(QDialogButtonBox.Ok).setText(self.tr('Load')) else: self.label.setText(self.tr('Save to file')) self.buttonBox.button(QDialogButtonBox.Ok).setText(self.tr('Save')) self.populate() self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) def select_file(self): """select file ops""" label = self.tr('eXtensible Markup Language (*.xml *.XML)') if self.mode == 0: slabel = self.tr('Save connections') self.filename = QFileDialog.getSaveFileName(self, slabel, '.', label) else: slabel = self.tr('Load connections') self.filename = QFileDialog.getOpenFileName(self, slabel, '.', label) if not self.filename: return # ensure the user never omitted the extension from the file name if not self.filename.lower().endswith('.xml'): self.filename = '%s.xml' % self.filename self.leFileName.setText(self.filename) if self.mode == 1: self.populate() self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True) def populate(self): """populate connections list from settings""" if self.mode == 0: self.settings.beginGroup('/MetaSearch/') keys = self.settings.childGroups() for key in keys: item = QListWidgetItem(self.listConnections) item.setText(key) self.settings.endGroup() else: # populate connections list from file doc = get_connections_from_file(self, self.filename) if doc is None: self.filename = None self.leFileName.clear() self.listConnections.clear() return for csw in doc.findall('csw'): item = QListWidgetItem(self.listConnections) item.setText(csw.attrib.get('name')) def save(self, connections): """save connections ops""" doc = etree.Element('qgsCSWConnections') doc.attrib['version'] = '1.0' for conn in connections: url = self.settings.value('/MetaSearch/%s/url' % conn) if url is not None: connection = etree.SubElement(doc, 'csw') connection.attrib['name'] = conn connection.attrib['url'] = url # write to disk with open(self.filename, 'w') as fileobj: fileobj.write(prettify_xml(etree.tostring(doc))) QMessageBox.information(self, self.tr('Save Connections'), self.tr('Saved to %s') % self.filename) self.reject() def load(self, items): """load connections""" self.settings.beginGroup('/MetaSearch/') keys = self.settings.childGroups() self.settings.endGroup() exml = etree.parse(self.filename).getroot() for csw in exml.findall('csw'): conn_name = csw.attrib.get('name') # process only selected connections if conn_name not in items: continue # check for duplicates if conn_name in keys: label = self.tr('File %s exists. Overwrite?') % conn_name res = QMessageBox.warning(self, self.tr('Loading Connections'), label, QMessageBox.Yes | QMessageBox.No) if res != QMessageBox.Yes: continue # no dups detected or overwrite is allowed url = '/MetaSearch/%s/url' % conn_name self.settings.setValue(url, csw.attrib.get('url')) def accept(self): """accept connections""" selection = self.listConnections.selectedItems() if len(selection) == 0: return items = [] for sel in selection: items.append(sel.text()) if self.mode == 0: # save self.save(items) else: # load self.load(items) self.filename = None self.leFileName.clear() self.listConnections.clear() self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) def reject(self): """back out of manage connections dialogue""" QDialog.reject(self)
gpl-2.0