repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
dushu1203/chromium.src
refs/heads/nw12
native_client_sdk/src/doc/_sphinxext/chromesite_builder.py
93
# Copyright 2014 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. # # This is a Sphinx extension. # from __future__ import print_function import codecs from collections import namedtuple, OrderedDict import os import string from docutils import nodes from docutils.parsers.rst import Directive, directives from sphinx.util.osutil import ensuredir from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.writers.html import HTMLWriter from sphinx.writers.html import SmartyPantsHTMLTranslator as HTMLTranslator from sphinx.util.console import bold # PEPPER_VERSION = "31" # TODO(eliben): it may be interesting to use an actual Sphinx template here at # some point. PAGE_TEMPLATE = string.Template(r''' {{+bindTo:partials.${doc_template}}} ${doc_body} {{/partials.${doc_template}}} '''.lstrip()) # Path to the top-level YAML table-of-contents file for the chromesite BOOK_TOC_TEMPLATE = '_book_template.yaml' class ChromesiteHTMLTranslator(HTMLTranslator): """ Custom HTML translator for chromesite output. Hooked into the HTML builder by setting the html_translator_class option in conf.py HTMLTranslator is provided by Sphinx. We're actually using SmartyPantsHTMLTranslator to use its quote and dash-formatting capabilities. It's a subclass of the HTMLTranslator provided by docutils, with Sphinx-specific features added. Here we provide chromesite-specific behavior by overriding some of the visiting methods. """ def __init__(self, builder, *args, **kwds): # HTMLTranslator is an old-style Python class, so 'super' doesn't work: use # direct parent invocation. HTMLTranslator.__init__(self, builder, *args, **kwds) self.within_toc = False def visit_bullet_list(self, node): # Use our own class attribute for <ul>. Don't care about compacted lists. self.body.append(self.starttag(node, 'ul', **{'class': 'small-gap'})) def depart_bullet_list(self, node): # Override to not pop anything from context self.body.append('</ul>\n') def visit_literal(self, node): # Don't insert "smart" quotes here self.no_smarty += 1 # Sphinx emits <tt></tt> for literals (``like this``), with <span> per word # to protect against wrapping, etc. We're required to emit plain <code> # tags for them. # Emit a simple <code> tag without enabling "protect_literal_text" mode, # so Sphinx's visit_Text doesn't mess with the contents. self.body.append(self.starttag(node, 'code', suffix='')) def depart_literal(self, node): self.no_smarty -= 1 self.body.append('</code>') def visit_literal_block(self, node): # Don't insert "smart" quotes here self.no_smarty += 1 # We don't use Sphinx's buildin pygments integration for code highlighting, # because the chromesite requires special <pre> tags for that and handles # the highlighting on its own. attrs = {'class': 'prettyprint'} if node.get('prettyprint', 1) else {} self.body.append(self.starttag(node, 'pre', **attrs)) def depart_literal_block(self, node): self.no_smarty -= 1 self.body.append('\n</pre>\n') def visit_title(self, node): if isinstance(node.parent, nodes.section): # Steal the id from the parent. This is used in chromesite to handle the # auto-generated navbar and permalinks. if node.parent.hasattr('ids'): node['ids'] = node.parent['ids'][:] HTMLTranslator.visit_title(self, node) def visit_section(self, node): # chromesite needs <section> instead of <div class='section'> self.section_level += 1 if self.section_level == 1: self.body.append(self.starttag(node, 'section')) def depart_section(self, node): if self.section_level == 1: self.body.append('</section>') self.section_level -= 1 def visit_image(self, node): # Paths to images in .rst sources should be absolute. This visitor does the # required transformation for the path to be correct in the final HTML. # if self.builder.chromesite_production_mode: node['uri'] = self.builder.get_production_url(node['uri']) HTMLTranslator.visit_image(self, node) def visit_reference(self, node): # In "kill_internal_links" mode, we don't emit the actual links for internal # nodes. if self.builder.chromesite_kill_internal_links and node.get('internal'): pass else: HTMLTranslator.visit_reference(self, node) def depart_reference(self, node): if self.builder.chromesite_kill_internal_links and node.get('internal'): pass else: HTMLTranslator.depart_reference(self, node) def visit_topic(self, node): if 'contents' in node['classes']: # TODO(binji): # Detect a TOC: we want to hide these from chromesite, but still keep # them in devsite. An easy hack is to add display: none to the element # here. # When we remove devsite support, we can remove this hack. self.within_toc = True attrs = {'style': 'display: none'} self.body.append(self.starttag(node, 'div', **attrs)) else: HTMLTranslator.visit_topic(self, node) def depart_topic(self, node): if self.within_toc: self.body.append('\n</div>') else: HTMLTranslator.visit_topic(self, node) def write_colspecs(self): # Override this method from docutils to do nothing. We don't need those # pesky <col width=NN /> tags in our markup. pass def visit_admonition(self, node, name=''): self.body.append(self.starttag(node, 'aside', CLASS=node.get('class', ''))) def depart_admonition(self, node=''): self.body.append('\n</aside>\n') def unknown_visit(self, node): raise NotImplementedError('Unknown node: ' + node.__class__.__name__) class ChromesiteBuilder(StandaloneHTMLBuilder): """ Builder for the NaCl chromesite HTML output. Loosely based on the code of Sphinx's standard SerializingHTMLBuilder. """ name = 'chromesite' out_suffix = '.html' link_suffix = '.html' # Disable the addition of "pi"-permalinks to each section header add_permalinks = False def init(self): self.config.html_translator_class = \ 'chromesite_builder.ChromesiteHTMLTranslator' self.chromesite_kill_internal_links = \ int(self.config.chromesite_kill_internal_links) == 1 self.info("----> Chromesite builder") self.config_hash = '' self.tags_hash = '' self.theme = None # no theme necessary self.templates = None # no template bridge necessary self.init_translator_class() self.init_highlighter() def finish(self): super(ChromesiteBuilder, self).finish() # if self.chromesite_production_mode: # # We decided to keep the manual _book.yaml for now; # # The code for auto-generating YAML TOCs from index.rst was removed in # # https://codereview.chromium.org/57923006/ # self.info(bold('generating YAML table-of-contents... ')) # subs = { 'version': PEPPER_VERSION } # with open(os.path.join(self.env.srcdir, '_book.yaml')) as in_f: # with open(os.path.join(self.outdir, '_book.yaml'), 'w') as out_f: # out_f.write(string.Template(in_f.read()).substitute(subs)) self.info() def dump_inventory(self): # We don't want an inventory file when building for chromesite # if not self.chromesite_production_mode: # super(ChromesiteBuilder, self).dump_inventory() pass def get_production_url(self, url): # if not self.chromesite_production_mode: # return url return '/native-client/%s' % url def get_target_uri(self, docname, typ=None): # if self.chromesite_production_mode: return self.get_production_url(docname) + self.link_suffix # else: # return docname + self.link_suffix def handle_page(self, pagename, ctx, templatename='page.html', outfilename=None, event_arg=None): ctx['current_page_name'] = pagename if not outfilename: outfilename = os.path.join(self.outdir, pagename + self.out_suffix) # Emit an event to Sphinx self.app.emit('html-page-context', pagename, templatename, ctx, event_arg) ensuredir(os.path.dirname(outfilename)) self._dump_context(ctx, outfilename) def _dump_context(self, context, filename): """ Do the actual dumping of the page to the file. context is a dict. Some important fields: body - document contents title current_page_name Some special pages (genindex, etc.) may not have some of the fields, so fetch them conservatively. """ if not 'body' in context: return template = context.get('meta', {}).get('template', 'standard_nacl_article') title = context.get('title', '') body = context.get('body', '') # codecs.open is the fast Python 2.x way of emulating the encoding= argument # in Python 3's builtin open. with codecs.open(filename, 'w', encoding='utf-8') as f: f.write(PAGE_TEMPLATE.substitute( doc_template=template, doc_title=title, doc_body=body)) def _conditional_chromesite(self, s): # return s if self.chromesite_production_mode else '' return s def _conditional_nonprod(self, s): # return s if not self.chromesite_production_mode else '' return '' class NaclCodeDirective(Directive): """ Custom "naclcode" directive for code snippets. To keep it under our control. """ has_content = True required_arguments = 0 optional_arguments = 1 option_spec = { 'prettyprint': int, } def run(self): code = u'\n'.join(self.content) literal = nodes.literal_block(code, code) literal['prettyprint'] = self.options.get('prettyprint', 1) return [literal] def setup(app): """ Extension registration hook. """ # linkcheck issues HEAD requests to save time, but some Google properties # reject them and we get spurious 405 responses. Monkey-patch sphinx to # just use normal GET requests. # See: https://bitbucket.org/birkenfeld/sphinx/issue/1292/ from sphinx.builders import linkcheck import urllib2 linkcheck.HeadRequest = urllib2.Request app.add_directive('naclcode', NaclCodeDirective) app.add_builder(ChromesiteBuilder) # "Production mode" for local testing vs. on-server documentation. app.add_config_value('chromesite_kill_internal_links', default='0', rebuild='html')
Passtechsoft/TPEAlpGen
refs/heads/master
blender/release/scripts/addons/presets/operator/mesh.primitive_xyz_function_surface/moebius.py
3
import bpy op = bpy.context.active_operator op.x_eq = 'cos(v)+u*cos(v/2)*cos(v)' op.y_eq = 'u*sin(v/2)' op.z_eq = 'sin(v)+u*cos(v/2)*sin(v)' op.range_u_min = -0.4000000059604645 op.range_u_max = 0.4000000059604645 op.range_u_step = 32 op.wrap_u = False op.range_v_min = 0.0 op.range_v_max = 6.2831854820251465 op.range_v_step = 32 op.wrap_v = False op.close_v = False op.n_eq = 1 op.a_eq = '0' op.b_eq = '0' op.c_eq = '0' op.f_eq = '0' op.g_eq = '0' op.h_eq = '0'
dhhjx880713/GPy
refs/heads/devel
GPy/old_tests/psi_stat_gradient_tests.py
19
''' Created on 22 Apr 2013 @author: maxz ''' import unittest import numpy import GPy import itertools from GPy.core import Model from GPy.core.parameterization.param import Param from GPy.core.parameterization.transformations import Logexp from GPy.core.parameterization.variational import NormalPosterior class PsiStatModel(Model): def __init__(self, which, X, X_variance, Z, num_inducing, kernel): super(PsiStatModel, self).__init__(name='psi stat test') self.which = which self.X = Param("X", X) self.X_variance = Param('X_variance', X_variance, Logexp()) self.q = NormalPosterior(self.X, self.X_variance) self.Z = Param("Z", Z) self.N, self.input_dim = X.shape self.num_inducing, input_dim = Z.shape assert self.input_dim == input_dim, "shape missmatch: Z:{!s} X:{!s}".format(Z.shape, X.shape) self.kern = kernel self.psi_ = self.kern.__getattribute__(self.which)(self.Z, self.q) self.add_parameters(self.q, self.Z, self.kern) def log_likelihood(self): return self.kern.__getattribute__(self.which)(self.Z, self.X, self.X_variance).sum() def parameters_changed(self): psimu, psiS = self.kern.__getattribute__("d" + self.which + "_dmuS")(numpy.ones_like(self.psi_), self.Z, self.q) self.X.gradient = psimu self.X_variance.gradient = psiS #psimu, psiS = numpy.ones(self.N * self.input_dim), numpy.ones(self.N * self.input_dim) try: psiZ = self.kern.__getattribute__("d" + self.which + "_dZ")(numpy.ones_like(self.psi_), self.Z, self.q) except AttributeError: psiZ = numpy.zeros_like(self.Z) self.Z.gradient = psiZ #psiZ = numpy.ones(self.num_inducing * self.input_dim) N,M = self.X.shape[0], self.Z.shape[0] dL_dpsi0, dL_dpsi1, dL_dpsi2 = numpy.zeros([N]), numpy.zeros([N,M]), numpy.zeros([N,M,M]) if self.which == 'psi0': dL_dpsi0 += 1 if self.which == 'psi1': dL_dpsi1 += 1 if self.which == 'psi2': dL_dpsi2 += 1 self.kern.update_gradients_variational(numpy.zeros([1,1]), dL_dpsi0, dL_dpsi1, dL_dpsi2, self.X, self.X_variance, self.Z) class DPsiStatTest(unittest.TestCase): input_dim = 5 N = 50 num_inducing = 10 input_dim = 20 X = numpy.random.randn(N, input_dim) X_var = .5 * numpy.ones_like(X) + .4 * numpy.clip(numpy.random.randn(*X.shape), 0, 1) Z = numpy.random.permutation(X)[:num_inducing] Y = X.dot(numpy.random.randn(input_dim, input_dim)) # kernels = [GPy.kern.Linear(input_dim, ARD=True, variances=numpy.random.rand(input_dim)), GPy.kern.RBF(input_dim, ARD=True), GPy.kern.Bias(input_dim)] kernels = [ GPy.kern.Linear(input_dim), GPy.kern.RBF(input_dim), #GPy.kern.Bias(input_dim), #GPy.kern.Linear(input_dim) + GPy.kern.Bias(input_dim), #GPy.kern.RBF(input_dim) + GPy.kern.Bias(input_dim) ] def testPsi0(self): for k in self.kernels: m = PsiStatModel('psi0', X=self.X, X_variance=self.X_var, Z=self.Z,\ num_inducing=self.num_inducing, kernel=k) m.randomize() assert m.checkgrad(), "{} x psi0".format("+".join(map(lambda x: x.name, k._parameters_))) def testPsi1(self): for k in self.kernels: m = PsiStatModel('psi1', X=self.X, X_variance=self.X_var, Z=self.Z, num_inducing=self.num_inducing, kernel=k) m.randomize() assert m.checkgrad(), "{} x psi1".format("+".join(map(lambda x: x.name, k._parameters_))) def testPsi2_lin(self): k = self.kernels[0] m = PsiStatModel('psi2', X=self.X, X_variance=self.X_var, Z=self.Z, num_inducing=self.num_inducing, kernel=k) m.randomize() assert m.checkgrad(), "{} x psi2".format("+".join(map(lambda x: x.name, k._parameters_))) def testPsi2_lin_bia(self): k = self.kernels[3] m = PsiStatModel('psi2', X=self.X, X_variance=self.X_var, Z=self.Z, num_inducing=self.num_inducing, kernel=k) m.randomize() assert m.checkgrad(), "{} x psi2".format("+".join(map(lambda x: x.name, k._parameters_))) def testPsi2_rbf(self): k = self.kernels[1] m = PsiStatModel('psi2', X=self.X, X_variance=self.X_var, Z=self.Z, num_inducing=self.num_inducing, kernel=k) m.randomize() assert m.checkgrad(), "{} x psi2".format("+".join(map(lambda x: x.name, k._parameters_))) def testPsi2_rbf_bia(self): k = self.kernels[-1] m = PsiStatModel('psi2', X=self.X, X_variance=self.X_var, Z=self.Z, num_inducing=self.num_inducing, kernel=k) m.randomize() assert m.checkgrad(), "{} x psi2".format("+".join(map(lambda x: x.name, k._parameters_))) def testPsi2_bia(self): k = self.kernels[2] m = PsiStatModel('psi2', X=self.X, X_variance=self.X_var, Z=self.Z, num_inducing=self.num_inducing, kernel=k) m.randomize() assert m.checkgrad(), "{} x psi2".format("+".join(map(lambda x: x.name, k._parameters_))) if __name__ == "__main__": import sys interactive = 'i' in sys.argv if interactive: # N, num_inducing, input_dim, input_dim = 30, 5, 4, 30 # X = numpy.random.rand(N, input_dim) # k = GPy.kern.Linear(input_dim) + GPy.kern.Bias(input_dim) + GPy.kern.White(input_dim, 0.00001) # K = k.K(X) # Y = numpy.random.multivariate_normal(numpy.zeros(N), K, input_dim).T # Y -= Y.mean(axis=0) # k = GPy.kern.Linear(input_dim) + GPy.kern.Bias(input_dim) + GPy.kern.White(input_dim, 0.00001) # m = GPy.models.Bayesian_GPLVM(Y, input_dim, kernel=k, num_inducing=num_inducing) # m.randomize() # # self.assertTrue(m.checkgrad()) numpy.random.seed(0) input_dim = 3 N = 3 num_inducing = 2 D = 15 X = numpy.random.randn(N, input_dim) X_var = .5 * numpy.ones_like(X) + .1 * numpy.clip(numpy.random.randn(*X.shape), 0, 1) Z = numpy.random.permutation(X)[:num_inducing] Y = X.dot(numpy.random.randn(input_dim, D)) # kernel = GPy.kern.Bias(input_dim) # # kernels = [GPy.kern.Linear(input_dim), GPy.kern.RBF(input_dim), GPy.kern.Bias(input_dim), # GPy.kern.Linear(input_dim) + GPy.kern.Bias(input_dim), # GPy.kern.RBF(input_dim) + GPy.kern.Bias(input_dim)] # for k in kernels: # m = PsiStatModel('psi1', X=X, X_variance=X_var, Z=Z, # num_inducing=num_inducing, kernel=k) # assert m.checkgrad(), "{} x psi1".format("+".join(map(lambda x: x.name, k.parts))) # m0 = PsiStatModel('psi0', X=X, X_variance=X_var, Z=Z, num_inducing=num_inducing, kernel=GPy.kern.RBF(input_dim)+GPy.kern.Bias(input_dim)) # m1 = PsiStatModel('psi1', X=X, X_variance=X_var, Z=Z, # num_inducing=num_inducing, kernel=kernel) # m1 = PsiStatModel('psi1', X=X, X_variance=X_var, Z=Z, # num_inducing=num_inducing, kernel=kernel) # m2 = PsiStatModel('psi2', X=X, X_variance=X_var, Z=Z, # num_inducing=num_inducing, kernel=GPy.kern.RBF(input_dim)) # m3 = PsiStatModel('psi2', X=X, X_variance=X_var, Z=Z, # num_inducing=num_inducing, kernel=GPy.kern.Linear(input_dim, ARD=True, variances=numpy.random.rand(input_dim))) # + GPy.kern.Bias(input_dim)) # m = PsiStatModel('psi2', X=X, X_variance=X_var, Z=Z, # num_inducing=num_inducing, # kernel=( # GPy.kern.RBF(input_dim, ARD=1) # +GPy.kern.Linear(input_dim, ARD=1) # +GPy.kern.Bias(input_dim)) # ) # m.ensure_default_constraints() m2 = PsiStatModel('psi2', X=X, X_variance=X_var, Z=Z, num_inducing=num_inducing, kernel=( GPy.kern.RBF(input_dim, numpy.random.rand(), numpy.random.rand(input_dim), ARD=1) #+GPy.kern.Linear(input_dim, numpy.random.rand(input_dim), ARD=1) #+GPy.kern.RBF(input_dim, numpy.random.rand(), numpy.random.rand(input_dim), ARD=1) #+GPy.kern.RBF(input_dim, numpy.random.rand(), numpy.random.rand(), ARD=0) +GPy.kern.Bias(input_dim) +GPy.kern.White(input_dim) ) ) #m2.ensure_default_constraints() else: unittest.main()
timvandermeij/servo
refs/heads/master
tests/wpt/web-platform-tests/XMLHttpRequest/resources/conditional.py
205
def main(request, response): tag = request.GET.first("tag", None) match = request.headers.get("If-None-Match", None) date = request.GET.first("date", "") modified = request.headers.get("If-Modified-Since", None) if tag: response.headers.set("ETag", '"%s"' % tag) elif date: response.headers.set("Last-Modified", date) if ((match is not None and match == tag) or (modified is not None and modified == date)): response.status = (304, "SUPERCOOL") return "" else: response.headers.set("Content-Type", "text/plain") return "MAYBE NOT"
AleksNeStu/ggrc-core
refs/heads/release/0.10-Raspberry
src/ggrc_workflows/models/mixins.py
7
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc.models.mixins import Timeboxed from ggrc import db class RelativeTimeboxed(Timeboxed): # Frequencies and offset: # annual: # month is the 0-indexed month (0 is January) # day is the 0-indexed offset day # quarterly: # month is in [0,1,2], as the offset within the quarter # day is same as annual # weekly: # month is ignored # day is in [1,2,3,4,5] where 0 is Monday relative_start_month = db.Column(db.Integer, nullable=True) relative_start_day = db.Column(db.Integer, nullable=True) relative_end_month = db.Column(db.Integer, nullable=True) relative_end_day = db.Column(db.Integer, nullable=True)
chispita/epiwork
refs/heads/master
apps/partnersites/migrations/0003_auto__add_field_sitesettings_footer.py
4
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'SiteSettings.footer' db.add_column('partnersites_sitesettings', 'footer', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'SiteSettings.footer' db.delete_column('partnersites_sitesettings', 'footer') models = { 'partnersites.sitesettings': { 'Meta': {'object_name': 'SiteSettings'}, 'footer': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'light_color': ('django.db.models.fields.CharField', [], {'default': "'ce2626'", 'max_length': '6'}), 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'site': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['sites.Site']", 'unique': 'True'}) }, 'sites.site': { 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['partnersites']
siosio/intellij-community
refs/heads/master
python/testData/refactoring/pullup/abstractMethodHasMeta/SuperClass.after.py
80
from abc import ABCMeta, abstractmethod class Parent(object): __metaclass__ = ABCMeta @abstractmethod def my_method2(self): pass @abstractmethod def my_method(self, foo): pass
jmesteve/medical
refs/heads/master
openerp/modules/migration.py
76
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2011 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """ Modules migration handling. """ import os, sys, imp from os.path import join as opj import itertools import zipimport import openerp import openerp.osv as osv import openerp.tools as tools import openerp.tools.osutil as osutil from openerp.tools.safe_eval import safe_eval as eval import openerp.pooler as pooler from openerp.tools.translate import _ import openerp.netsvc as netsvc import zipfile import openerp.release as release import re import base64 from zipfile import PyZipFile, ZIP_DEFLATED from cStringIO import StringIO import logging import openerp.modules.db import openerp.modules.graph _logger = logging.getLogger(__name__) class MigrationManager(object): """ This class manage the migration of modules Migrations files must be python files containing a "migrate(cr, installed_version)" function. Theses files must respect a directory tree structure: A 'migrations' folder which containt a folder by version. Version can be 'module' version or 'server.module' version (in this case, the files will only be processed by this version of the server). Python file names must start by 'pre' or 'post' and will be executed, respectively, before and after the module initialisation Example: <moduledir> `-- migrations |-- 1.0 | |-- pre-update_table_x.py | |-- pre-update_table_y.py | |-- post-clean-data.py | `-- README.txt # not processed |-- 5.0.1.1 # files in this folder will be executed only on a 5.0 server | |-- pre-delete_table_z.py | `-- post-clean-data.py `-- foo.py # not processed This similar structure is generated by the maintenance module with the migrations files get by the maintenance contract """ def __init__(self, cr, graph): self.cr = cr self.graph = graph self.migrations = {} self._get_files() def _get_files(self): """ import addons.base.maintenance.utils as maintenance_utils maintenance_utils.update_migrations_files(self.cr) #""" for pkg in self.graph: self.migrations[pkg.name] = {} if not (hasattr(pkg, 'update') or pkg.state == 'to upgrade'): continue get_module_filetree = openerp.modules.module.get_module_filetree self.migrations[pkg.name]['module'] = get_module_filetree(pkg.name, 'migrations') or {} self.migrations[pkg.name]['maintenance'] = get_module_filetree('base', 'maintenance/migrations/' + pkg.name) or {} def migrate_module(self, pkg, stage): assert stage in ('pre', 'post') stageformat = {'pre': '[>%s]', 'post': '[%s>]', } if not (hasattr(pkg, 'update') or pkg.state == 'to upgrade'): return def convert_version(version): if version.startswith(release.major_version) and version != release.major_version: return version # the version number already containt the server version return "%s.%s" % (release.major_version, version) def _get_migration_versions(pkg): def __get_dir(tree): return [d for d in tree if tree[d] is not None] versions = list(set( __get_dir(self.migrations[pkg.name]['module']) + __get_dir(self.migrations[pkg.name]['maintenance']) )) versions.sort(key=lambda k: parse_version(convert_version(k))) return versions def _get_migration_files(pkg, version, stage): """ return a list of tuple (module, file) """ m = self.migrations[pkg.name] lst = [] mapping = {'module': opj(pkg.name, 'migrations'), 'maintenance': opj('base', 'maintenance', 'migrations', pkg.name), } for x in mapping.keys(): if version in m[x]: for f in m[x][version]: if m[x][version][f] is not None: continue if not f.startswith(stage + '-'): continue lst.append(opj(mapping[x], version, f)) lst.sort() return lst def mergedict(a, b): a = a.copy() a.update(b) return a from openerp.tools.parse_version import parse_version parsed_installed_version = parse_version(pkg.installed_version or '') current_version = parse_version(convert_version(pkg.data['version'])) versions = _get_migration_versions(pkg) for version in versions: if parsed_installed_version < parse_version(convert_version(version)) <= current_version: strfmt = {'addon': pkg.name, 'stage': stage, 'version': stageformat[stage] % version, } for pyfile in _get_migration_files(pkg, version, stage): name, ext = os.path.splitext(os.path.basename(pyfile)) if ext.lower() != '.py': continue mod = fp = fp2 = None try: fp = tools.file_open(pyfile) # imp.load_source need a real file object, so we create # one from the file-like object we get from file_open fp2 = os.tmpfile() fp2.write(fp.read()) fp2.seek(0) try: mod = imp.load_source(name, pyfile, fp2) _logger.info('module %(addon)s: Running migration %(version)s %(name)s' % mergedict({'name': mod.__name__}, strfmt)) mod.migrate(self.cr, pkg.installed_version) except ImportError: _logger.error('module %(addon)s: Unable to load %(stage)s-migration file %(file)s' % mergedict({'file': pyfile}, strfmt)) raise except AttributeError: _logger.error('module %(addon)s: Each %(stage)s-migration file must have a "migrate(cr, installed_version)" function' % strfmt) except: raise finally: if fp: fp.close() if fp2: fp2.close() if mod: del mod # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
marcoserafini/h-store
refs/heads/master
third_party/python/boto/mashups/iobject.py
21
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import os def int_val_fn(v): try: int(v) return True except: return False class IObject(object): def choose_from_list(self, item_list, search_str='', prompt='Enter Selection'): if not item_list: print 'No Choices Available' return choice = None while not choice: n = 1 choices = [] for item in item_list: if isinstance(item, str): print '[%d] %s' % (n, item) choices.append(item) n += 1 else: obj, id, desc = item if desc: if desc.find(search_str) >= 0: print '[%d] %s - %s' % (n, id, desc) choices.append(obj) n += 1 else: if id.find(search_str) >= 0: print '[%d] %s' % (n, id) choices.append(obj) n += 1 if choices: val = raw_input('%s[1-%d]: ' % (prompt, len(choices))) if val.startswith('/'): search_str = val[1:] else: try: int_val = int(val) if int_val == 0: return None choice = choices[int_val-1] except ValueError: print '%s is not a valid choice' % val except IndexError: print '%s is not within the range[1-%d]' % (val, len(choices)) else: print "No objects matched your pattern" search_str = '' return choice def get_string(self, prompt, validation_fn=None): okay = False while not okay: val = raw_input('%s: ' % prompt) if validation_fn: okay = validation_fn(val) if not okay: print 'Invalid value: %s' % val else: okay = True return val def get_filename(self, prompt): okay = False val = '' while not okay: val = raw_input('%s: %s' % (prompt, val)) val = os.path.expanduser(val) if os.path.isfile(val): okay = True elif os.path.isdir(val): path = val val = self.choose_from_list(os.listdir(path)) if val: val = os.path.join(path, val) okay = True else: val = '' else: print 'Invalid value: %s' % val val = '' return val def get_int(self, prompt): s = self.get_string(prompt, int_val_fn) return int(s)
Lemma1/MAC-POSTS
refs/heads/master
doc_builder/sphinx-contrib/examplecode/sphinxcontrib/__init__.py
308
# -*- coding: utf-8 -*- """ sphinxcontrib ~~~~~~~~~~~~~ This package is a namespace package that contains all extensions distributed in the ``sphinx-contrib`` distribution. :copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ __import__('pkg_resources').declare_namespace(__name__)
DynoGraph/stinger-dynograph
refs/heads/master
lib/dynograph_util/googletest/test/gtest_catch_exceptions_test.py
2139
#!/usr/bin/env python # # Copyright 2010 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. """Tests Google Test's exception catching behavior. This script invokes gtest_catch_exceptions_test_ and gtest_catch_exceptions_ex_test_ (programs written with Google Test) and verifies their output. """ __author__ = 'vladl@google.com (Vlad Losev)' import os import gtest_test_utils # Constants. FLAG_PREFIX = '--gtest_' LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0' FILTER_FLAG = FLAG_PREFIX + 'filter' # Path to the gtest_catch_exceptions_ex_test_ binary, compiled with # exceptions enabled. EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath( 'gtest_catch_exceptions_ex_test_') # Path to the gtest_catch_exceptions_test_ binary, compiled with # exceptions disabled. EXE_PATH = gtest_test_utils.GetTestExecutablePath( 'gtest_catch_exceptions_no_ex_test_') environ = gtest_test_utils.environ SetEnvVar = gtest_test_utils.SetEnvVar # Tests in this file run a Google-Test-based test program and expect it # to terminate prematurely. Therefore they are incompatible with # the premature-exit-file protocol by design. Unset the # premature-exit filepath to prevent Google Test from creating # the file. SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None) TEST_LIST = gtest_test_utils.Subprocess( [EXE_PATH, LIST_TESTS_FLAG], env=environ).output SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST if SUPPORTS_SEH_EXCEPTIONS: BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output EX_BINARY_OUTPUT = gtest_test_utils.Subprocess( [EX_EXE_PATH], env=environ).output # The tests. if SUPPORTS_SEH_EXCEPTIONS: # pylint:disable-msg=C6302 class CatchSehExceptionsTest(gtest_test_utils.TestCase): """Tests exception-catching behavior.""" def TestSehExceptions(self, test_output): self.assert_('SEH exception with code 0x2a thrown ' 'in the test fixture\'s constructor' in test_output) self.assert_('SEH exception with code 0x2a thrown ' 'in the test fixture\'s destructor' in test_output) self.assert_('SEH exception with code 0x2a thrown in SetUpTestCase()' in test_output) self.assert_('SEH exception with code 0x2a thrown in TearDownTestCase()' in test_output) self.assert_('SEH exception with code 0x2a thrown in SetUp()' in test_output) self.assert_('SEH exception with code 0x2a thrown in TearDown()' in test_output) self.assert_('SEH exception with code 0x2a thrown in the test body' in test_output) def testCatchesSehExceptionsWithCxxExceptionsEnabled(self): self.TestSehExceptions(EX_BINARY_OUTPUT) def testCatchesSehExceptionsWithCxxExceptionsDisabled(self): self.TestSehExceptions(BINARY_OUTPUT) class CatchCxxExceptionsTest(gtest_test_utils.TestCase): """Tests C++ exception-catching behavior. Tests in this test case verify that: * C++ exceptions are caught and logged as C++ (not SEH) exceptions * Exception thrown affect the remainder of the test work flow in the expected manner. """ def testCatchesCxxExceptionsInFixtureConstructor(self): self.assert_('C++ exception with description ' '"Standard C++ exception" thrown ' 'in the test fixture\'s constructor' in EX_BINARY_OUTPUT) self.assert_('unexpected' not in EX_BINARY_OUTPUT, 'This failure belongs in this test only if ' '"CxxExceptionInConstructorTest" (no quotes) ' 'appears on the same line as words "called unexpectedly"') if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in EX_BINARY_OUTPUT): def testCatchesCxxExceptionsInFixtureDestructor(self): self.assert_('C++ exception with description ' '"Standard C++ exception" thrown ' 'in the test fixture\'s destructor' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInDestructorTest::TearDownTestCase() ' 'called as expected.' in EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInSetUpTestCase(self): self.assert_('C++ exception with description "Standard C++ exception"' ' thrown in SetUpTestCase()' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInConstructorTest::TearDownTestCase() ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInSetUpTestCaseTest constructor ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInSetUpTestCaseTest destructor ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInSetUpTestCaseTest::SetUp() ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInSetUpTestCaseTest::TearDown() ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInSetUpTestCaseTest test body ' 'called as expected.' in EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInTearDownTestCase(self): self.assert_('C++ exception with description "Standard C++ exception"' ' thrown in TearDownTestCase()' in EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInSetUp(self): self.assert_('C++ exception with description "Standard C++ exception"' ' thrown in SetUp()' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInSetUpTest::TearDownTestCase() ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInSetUpTest destructor ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInSetUpTest::TearDown() ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('unexpected' not in EX_BINARY_OUTPUT, 'This failure belongs in this test only if ' '"CxxExceptionInSetUpTest" (no quotes) ' 'appears on the same line as words "called unexpectedly"') def testCatchesCxxExceptionsInTearDown(self): self.assert_('C++ exception with description "Standard C++ exception"' ' thrown in TearDown()' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInTearDownTest::TearDownTestCase() ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInTearDownTest destructor ' 'called as expected.' in EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInTestBody(self): self.assert_('C++ exception with description "Standard C++ exception"' ' thrown in the test body' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInTestBodyTest::TearDownTestCase() ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInTestBodyTest destructor ' 'called as expected.' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInTestBodyTest::TearDown() ' 'called as expected.' in EX_BINARY_OUTPUT) def testCatchesNonStdCxxExceptions(self): self.assert_('Unknown C++ exception thrown in the test body' in EX_BINARY_OUTPUT) def testUnhandledCxxExceptionsAbortTheProgram(self): # Filters out SEH exception tests on Windows. Unhandled SEH exceptions # cause tests to show pop-up windows there. FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*' # By default, Google Test doesn't catch the exceptions. uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess( [EX_EXE_PATH, NO_CATCH_EXCEPTIONS_FLAG, FITLER_OUT_SEH_TESTS_FLAG], env=environ).output self.assert_('Unhandled C++ exception terminating the program' in uncaught_exceptions_ex_binary_output) self.assert_('unexpected' not in uncaught_exceptions_ex_binary_output) if __name__ == '__main__': gtest_test_utils.Main()
EricMountain-1A/openshift-ansible
refs/heads/master
roles/lib_openshift/src/class/oc_user.py
46
# pylint: skip-file # flake8: noqa # pylint: disable=too-many-instance-attributes class OCUser(OpenShiftCLI): ''' Class to wrap the oc command line tools ''' kind = 'users' def __init__(self, config, groups=None, verbose=False): ''' Constructor for OCUser ''' # namespace has no meaning for user operations, hardcode to 'default' super(OCUser, self).__init__('default', config.kubeconfig) self.config = config self.groups = groups self._user = None @property def user(self): ''' property function user''' if not self._user: self.get() return self._user @user.setter def user(self, data): ''' setter function for user ''' self._user = data def exists(self): ''' return whether a user exists ''' if self.user: return True return False def get(self): ''' return user information ''' result = self._get(self.kind, self.config.username) if result['returncode'] == 0: self.user = User(content=result['results'][0]) elif 'users \"%s\" not found' % self.config.username in result['stderr']: result['returncode'] = 0 result['results'] = [{}] return result def delete(self): ''' delete the object ''' return self._delete(self.kind, self.config.username) def create_group_entries(self): ''' make entries for user to the provided group list ''' if self.groups != None: for group in self.groups: cmd = ['groups', 'add-users', group, self.config.username] rval = self.openshift_cmd(cmd, oadm=True) if rval['returncode'] != 0: return rval return rval return {'returncode': 0} def create(self): ''' create the object ''' rval = self.create_group_entries() if rval['returncode'] != 0: return rval return self._create_from_content(self.config.username, self.config.data) def group_update(self): ''' update group membership ''' rval = {'returncode': 0} cmd = ['get', 'groups', '-o', 'json'] all_groups = self.openshift_cmd(cmd, output=True) # pylint misindentifying all_groups['results']['items'] type # pylint: disable=invalid-sequence-index for group in all_groups['results']['items']: # If we're supposed to be in this group if group['metadata']['name'] in self.groups \ and (group['users'] is None or self.config.username not in group['users']): cmd = ['groups', 'add-users', group['metadata']['name'], self.config.username] rval = self.openshift_cmd(cmd, oadm=True) if rval['returncode'] != 0: return rval # else if we're in the group, but aren't supposed to be elif group['users'] != None and self.config.username in group['users'] \ and group['metadata']['name'] not in self.groups: cmd = ['groups', 'remove-users', group['metadata']['name'], self.config.username] rval = self.openshift_cmd(cmd, oadm=True) if rval['returncode'] != 0: return rval return rval def update(self): ''' update the object ''' rval = self.group_update() if rval['returncode'] != 0: return rval # need to update the user's info return self._replace_content(self.kind, self.config.username, self.config.data, force=True) def needs_group_update(self): ''' check if there are group membership changes ''' cmd = ['get', 'groups', '-o', 'json'] all_groups = self.openshift_cmd(cmd, output=True) # pylint misindentifying all_groups['results']['items'] type # pylint: disable=invalid-sequence-index for group in all_groups['results']['items']: # If we're supposed to be in this group if group['metadata']['name'] in self.groups \ and (group['users'] is None or self.config.username not in group['users']): return True # else if we're in the group, but aren't supposed to be elif group['users'] != None and self.config.username in group['users'] \ and group['metadata']['name'] not in self.groups: return True return False def needs_update(self): ''' verify an update is needed ''' skip = [] if self.needs_group_update(): return True return not Utils.check_def_equal(self.config.data, self.user.yaml_dict, skip_keys=skip, debug=True) # pylint: disable=too-many-return-statements @staticmethod def run_ansible(params, check_mode=False): ''' run the idempotent ansible code params comes from the ansible portion of this module check_mode: does the module support check mode. (module.check_mode) ''' uconfig = UserConfig(params['kubeconfig'], params['username'], params['full_name'], ) oc_user = OCUser(uconfig, params['groups'], verbose=params['debug']) state = params['state'] api_rval = oc_user.get() ##### # Get ##### if state == 'list': return {'changed': False, 'results': api_rval['results'], 'state': "list"} ######## # Delete ######## if state == 'absent': if oc_user.exists(): if check_mode: return {'changed': False, 'msg': 'Would have performed a delete.'} api_rval = oc_user.delete() return {'changed': True, 'results': api_rval, 'state': "absent"} return {'changed': False, 'state': "absent"} if state == 'present': ######## # Create ######## if not oc_user.exists(): if check_mode: return {'changed': False, 'msg': 'Would have performed a create.'} # Create it here api_rval = oc_user.create() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} # return the created object api_rval = oc_user.get() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} return {'changed': True, 'results': api_rval, 'state': "present"} ######## # Update ######## if oc_user.needs_update(): api_rval = oc_user.update() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} orig_cmd = api_rval['cmd'] # return the created object api_rval = oc_user.get() # overwrite the get/list cmd api_rval['cmd'] = orig_cmd if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} return {'changed': True, 'results': api_rval, 'state': "present"} return {'changed': False, 'results': api_rval, 'state': "present"} return {'failed': True, 'changed': False, 'results': 'Unknown state passed. %s' % state, 'state': "unknown"}
gaddman/ansible
refs/heads/devel
lib/ansible/plugins/terminal/nxos.py
21
# # (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/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re import json from ansible.plugins.terminal import TerminalBase from ansible.errors import AnsibleConnectionFailure from ansible.module_utils._text import to_bytes, to_text class TerminalModule(TerminalBase): terminal_stdout_re = [ re.compile(br'[\r\n](?!\s*<)?(\x1b\S+)*[a-zA-Z_0-9]{1}[a-zA-Z0-9-_.]*[>|#](?:\s*)(\x1b\S+)*$'), re.compile(br'[\r\n]?[a-zA-Z0-9]{1}[a-zA-Z0-9-_.]*\(.+\)#(?:\s*)$') ] terminal_stderr_re = [ re.compile(br"% ?Error"), re.compile(br"^error:(.*)", re.I), re.compile(br"^% \w+", re.M), re.compile(br"% ?Bad secret"), re.compile(br"invalid input", re.I), re.compile(br"(?:incomplete|ambiguous) command", re.I), re.compile(br"connection timed out", re.I), re.compile(br"[^\r\n]+ not found", re.I), re.compile(br"'[^']' +returned error code: ?\d+"), re.compile(br"syntax error"), re.compile(br"unknown command"), re.compile(br"user not present"), re.compile(br"invalid (.+?)at '\^' marker", re.I), re.compile(br"[B|b]aud rate of console should be.* (\d*) to increase [a-z]* level", re.I), ] def on_become(self, passwd=None): if self._get_prompt().endswith(b'enable#'): return out = self._exec_cli_command('show privilege') out = to_text(out, errors='surrogate_then_replace').strip() if 'Disabled' in out: raise AnsibleConnectionFailure('Feature privilege is not enabled') # if already at privilege level 15 return if '15' in out: return cmd = {u'command': u'enable'} if passwd: cmd[u'prompt'] = to_text(r"(?i)[\r\n]?Password: $", errors='surrogate_or_strict') cmd[u'answer'] = passwd cmd[u'prompt_retry_check'] = True try: self._exec_cli_command(to_bytes(json.dumps(cmd), errors='surrogate_or_strict')) prompt = self._get_prompt() if prompt is None or not prompt.strip().endswith(b'enable#'): raise AnsibleConnectionFailure('failed to elevate privilege to enable mode still at prompt [%s]' % prompt) except AnsibleConnectionFailure as e: prompt = self._get_prompt() raise AnsibleConnectionFailure('unable to elevate privilege to enable mode, at prompt [%s] with error: %s' % (prompt, e.message)) def on_unbecome(self): prompt = self._get_prompt() if prompt is None: # if prompt is None most likely the terminal is hung up at a prompt return if b'(config' in prompt: self._exec_cli_command('end') self._exec_cli_command('exit') elif prompt.endswith(b'enable#'): self._exec_cli_command('exit') def on_open_shell(self): try: for cmd in ('terminal length 0', 'terminal width 511'): self._exec_cli_command(cmd) except AnsibleConnectionFailure: raise AnsibleConnectionFailure('unable to set terminal parameters')
tripleoxygen/kernel_zeebo
refs/heads/master
tools/perf/scripts/python/failed-syscalls-by-pid.py
944
# failed system call counts, by pid # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide failed system call totals, broken down by pid. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * usage = "perf trace -s syscall-counts-by-pid.py [comm]\n"; for_comm = None if len(sys.argv) > 2: sys.exit(usage) if len(sys.argv) > 1: for_comm = sys.argv[1] syscalls = autodict() def trace_begin(): pass def trace_end(): print_error_totals() def raw_syscalls__sys_exit(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, ret): if for_comm is not None: if common_comm != for_comm: return if ret < 0: try: syscalls[common_comm][common_pid][id][ret] += 1 except TypeError: syscalls[common_comm][common_pid][id][ret] = 1 def print_error_totals(): if for_comm is not None: print "\nsyscall errors for %s:\n\n" % (for_comm), else: print "\nsyscall errors:\n\n", print "%-30s %10s\n" % ("comm [pid]", "count"), print "%-30s %10s\n" % ("------------------------------", \ "----------"), comm_keys = syscalls.keys() for comm in comm_keys: pid_keys = syscalls[comm].keys() for pid in pid_keys: print "\n%s [%d]\n" % (comm, pid), id_keys = syscalls[comm][pid].keys() for id in id_keys: print " syscall: %-16d\n" % (id), ret_keys = syscalls[comm][pid][id].keys() for ret, val in sorted(syscalls[comm][pid][id].iteritems(), key = lambda(k, v): (v, k), reverse = True): print " err = %-20d %10d\n" % (ret, val),
sxjscience/tvm
refs/heads/master
tests/python/unittest/test_runtime_packed_func.py
2
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import te import tvm.testing import numpy as np def test_get_global(): targs = (10, 10.0, "hello") # register into global function table @tvm.register_func def my_packed_func(*args): assert tuple(args) == targs return 10 # get it out from global function table f = tvm.get_global_func("my_packed_func") assert isinstance(f, tvm.runtime.PackedFunc) y = f(*targs) assert y == 10 def test_get_callback_with_node(): x = tvm.runtime.convert(10) def test(y): assert y.handle != x.handle return y f2 = tvm.runtime.convert(test) # register into global function table @tvm.register_func def my_callback_with_node(y, f): assert y == x return f(y) # get it out from global function table f = tvm.get_global_func("my_callback_with_node") assert isinstance(f, tvm.runtime.PackedFunc) y = f(x, f2) assert y.value == 10 def test_return_func(): def addy(y): def add(x): return tvm.runtime.convert(x + y) return add myf = tvm.runtime.convert(addy) f = myf(10) assert f(11).value == 21 def test_convert(): # convert a function to tvm function targs = (10, 10.0, "hello", 10) def myfunc(*args): assert tuple(args) == targs f = tvm.runtime.convert(myfunc) assert isinstance(f, tvm.runtime.PackedFunc) def test_byte_array(): s = "hello" a = bytearray(s, encoding="ascii") def myfunc(ss): assert ss == a f = tvm.runtime.convert(myfunc) f(a) def test_empty_array(): def myfunc(ss): assert tuple(ss) == () x = tvm.runtime.convert(()) tvm.runtime.convert(myfunc)(x) def test_ctx(): def test_ctx_func(ctx): assert tvm.gpu(7) == ctx return tvm.cpu(0) x = test_ctx_func(tvm.gpu(7)) assert x == tvm.cpu(0) x = tvm.opencl(10) x = tvm.testing.context_test(x, x.device_type, x.device_id) assert x == tvm.opencl(10) def test_rvalue_ref(): def callback(x, expected_count): assert expected_count == tvm.testing.object_use_count(x) return x f = tvm.runtime.convert(callback) def check0(): x = tvm.tir.Var("x", "int32") assert tvm.testing.object_use_count(x) == 1 f(x, 2) y = f(x._move(), 1) assert x.handle.value == None def check1(): x = tvm.tir.Var("x", "int32") assert tvm.testing.object_use_count(x) == 1 y = f(x, 2) z = f(x._move(), 2) assert x.handle.value == None assert y.handle.value is not None check0() check1() def test_trace_default_action(): n = 2 x = te.placeholder((n, n, n), name="X", dtype="float32") y = te.compute(x.shape, lambda i, j, k: tvm.tir.trace([i, j, k, x[i][j][k]])) s = te.create_schedule(y.op) f = tvm.build(s, [x, y], target="llvm") xnd = tvm.nd.array(np.ones((n, n, n), dtype=x.dtype)) ynd = tvm.nd.array(np.zeros((n, n, n), dtype=y.dtype)) f(xnd, ynd) def test_trace_expr_assign(): @tvm.register_func("tvm.tir.trace_callback2") def trace_buffer(x): return def check_assign(dtype): n = 4 x = te.placeholder((n, n, n), name="X", dtype=dtype) y = te.compute( x.shape, lambda i, j, k: tvm.tir.trace([x[i][j][k]], "tvm.tir.trace_callback2") ) z = te.compute( x.shape, lambda i, j, k: tvm.tir.trace([y[i][j][k]], "tvm.tir.trace_callback2") ) s = te.create_schedule(z.op) f = tvm.build(s, [x, y, z], "llvm") xnd = tvm.nd.array(np.ones((n, n, n), dtype=x.dtype)) ynd = tvm.nd.array(np.zeros((n, n, n), dtype=y.dtype)) znd = tvm.nd.array(np.zeros((n, n, n), dtype=z.dtype)) f(xnd, ynd, znd) assert np.array_equal(xnd.asnumpy(), np.ones((n, n, n))) assert np.array_equal(ynd.asnumpy(), np.ones((n, n, n))) assert np.array_equal(znd.asnumpy(), np.ones((n, n, n))) for t in ["float64", "float32", "int64", "int32"]: check_assign(t) def test_trace_expr_sum_generated(): @tvm.register_func("tvm.tir.trace_callback3") def trace_buffer(x): return def check_expr_sum(dtype): n = 4 a = te.placeholder((n, n, n), name="a", dtype=dtype) b = te.placeholder((n, n, n), name="b", dtype=dtype) c = te.compute( a.shape, lambda i, j, k: tvm.tir.trace([a[i][j][k]], "tvm.tir.trace_callback3") + tvm.tir.trace([b[i][j][k]], "tvm.tir.trace_callback3"), ) s = te.create_schedule(c.op) f = tvm.build(s, [a, b, c]) xnd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=a.dtype))) ynd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=b.dtype))) znd = tvm.nd.array(np.zeros((n, n, n), dtype=c.dtype)) f(xnd, ynd, znd) assert np.array_equal(znd.asnumpy(), xnd.asnumpy() + ynd.asnumpy()) for t in ["float64", "float32", "int64", "int32"]: check_expr_sum(t) def test_trace_expr_sum_args(): @tvm.register_func("tvm.tir.trace_silent") def silent(*args): return def check_expr_sum(dtype): n = 4 a = te.placeholder((n, n, n), name="a", dtype=dtype) b = te.placeholder((n, n, n), name="b", dtype=dtype) e = te.placeholder((n, n, n), name="e", dtype=dtype) d = te.placeholder((n, n, n), name="d", dtype=dtype) c = te.compute( a.shape, lambda i, j, k: tvm.tir.trace([i, j, k, a[i][j][k]], "tvm.tir.trace_silent") + tvm.tir.trace([i, j, k, b[i][j][k]], "tvm.tir.trace_silent") + tvm.tir.trace([i, j, k, d[i][j][k]], "tvm.tir.trace_silent") + tvm.tir.trace([i, j, k, e[i][j][k]], "tvm.tir.trace_silent"), ) s = te.create_schedule(c.op) f = tvm.build(s, [a, b, d, e, c]) a_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=a.dtype))) b_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=b.dtype))) d_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=d.dtype))) e_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=e.dtype))) c_nd = tvm.nd.array(np.zeros((n, n, n), dtype=c.dtype)) f(a_nd, b_nd, d_nd, e_nd, c_nd) assert np.array_equal( c_nd.asnumpy(), a_nd.asnumpy() + b_nd.asnumpy() + d_nd.asnumpy() + e_nd.asnumpy() ) for t in ["float64", "float32", "int64", "int32"]: check_expr_sum(t) def test_trace_expr_sum_custom(): @tvm.register_func("tvm.tir.trace_callback4") def trace_buffer(x): return def check_expr_sum_custom(dtype): n = 4 a = te.placeholder((n, n), name="a", dtype=dtype) b = te.placeholder((n, n), name="b", dtype=dtype) c = te.compute( a.shape, lambda i, j: tvm.tir.trace([a[i][j]], "tvm.tir.trace_callback4") + tvm.tir.trace([b[i][j]], "tvm.tir.trace_callback4"), ) s = te.create_schedule(c.op) f = tvm.build(s, [a, b, c]) npa = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=a.dtype) npb = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=a.dtype) xnd = tvm.nd.array(npa) ynd = tvm.nd.array(npb) znd = tvm.nd.array(np.zeros((n, n), dtype=c.dtype)) f(xnd, ynd, znd) assert np.array_equal(znd.asnumpy(), npa + npb) for t in ["float64", "float32", "int64", "int32"]: check_expr_sum_custom(t) def test_trace_can_change_traced_value_int(): @tvm.register_func("tvm.tir.trace_change_int_first") def trace_buffer(x): return 13 @tvm.register_func("tvm.tir.trace_change_int_second") def trace_buffer(x): return 14 def check_assign(dtype): n = 4 x = te.placeholder((n,), name="X", dtype=dtype) y = te.compute(x.shape, lambda i: tvm.tir.trace([x[i]], "tvm.tir.trace_change_int_first")) z = te.compute(x.shape, lambda i: tvm.tir.trace([y[i]], "tvm.tir.trace_change_int_second")) s = te.create_schedule(z.op) f = tvm.build(s, [x, y, z], "llvm") xnd = tvm.nd.array(np.ones((n,), dtype=x.dtype)) ynd = tvm.nd.array(np.zeros((n,), dtype=y.dtype)) znd = tvm.nd.array(np.zeros((n,), dtype=z.dtype)) f(xnd, ynd, znd) check_array_first = np.array([13, 13, 13, 13]) check_array_second = np.array([14, 14, 14, 14]) assert np.array_equal(ynd.asnumpy(), check_array_first) assert np.array_equal(znd.asnumpy(), check_array_second) for t in ["int64", "int32"]: check_assign(t) def test_trace_can_change_traced_value_float(): @tvm.register_func("tvm.tir.trace_change_float_first") def trace_buffer(x): return 13.0 @tvm.register_func("tvm.tir.trace_change_float_second") def trace_buffer(x): return 14.0 def check_assign(dtype): n = 4 x = te.placeholder((n,), name="X", dtype=dtype) y = te.compute(x.shape, lambda i: tvm.tir.trace([x[i]], "tvm.tir.trace_change_float_first")) z = te.compute( x.shape, lambda i: tvm.tir.trace([y[i]], "tvm.tir.trace_change_float_second") ) s = te.create_schedule(z.op) f = tvm.build(s, [x, y, z], "llvm") xnd = tvm.nd.array(np.ones((n,), dtype=x.dtype)) ynd = tvm.nd.array(np.zeros((n,), dtype=y.dtype)) znd = tvm.nd.array(np.zeros((n,), dtype=z.dtype)) f(xnd, ynd, znd) check_array_first = np.array([13.0, 13.0, 13.0, 13.0]) check_array_second = np.array([14.0, 14.0, 14.0, 14.0]) assert np.array_equal(ynd.asnumpy(), check_array_first) assert np.array_equal(znd.asnumpy(), check_array_second) for t in ["float64", "float32"]: check_assign(t) def test_numpy_scalar(): maxint = (1 << 63) - 1 assert tvm.testing.echo(np.int64(maxint)) == maxint if __name__ == "__main__": test_numpy_scalar() test_rvalue_ref() test_empty_array() test_get_global() test_get_callback_with_node() test_convert() test_return_func() test_byte_array() test_ctx() test_trace_expr_assign() test_trace_expr_sum_generated() test_trace_expr_sum_custom() test_trace_expr_sum_args() test_trace_default_action() test_trace_can_change_traced_value_int() test_trace_can_change_traced_value_float()
fabiocorneti/django-multilingual
refs/heads/master
multilingual/models.py
5
""" Multilingual model support. This code is put in multilingual.models to make Django execute it during application initialization. TO DO: remove it. Right now multilingual must be imported directly into any file that defines translatable models, so it will be installed anyway. This module is here only to make it easier to upgrade from versions that did not require TranslatableModel.Translation classes to subclass multilingual.Translation to versions that do. """ from translation import install_translation_library install_translation_library() from validation import install_multilingual_admin_validation install_multilingual_admin_validation()
carlos-lopez-garces/mapnik-trunk
refs/heads/master
scons/scons-local-1.2.0/SCons/Tool/sgicc.py
12
"""SCons.Tool.sgicc Tool-specific initialization for MIPSPro cc on SGI. 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 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/sgicc.py 3842 2008/12/20 22:59:52 scons" import cc def generate(env): """Add Builders and construction variables for gcc to an Environment.""" cc.generate(env) env['CXX'] = 'CC' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 def exists(env): return env.Detect('cc')
GhostThrone/django
refs/heads/master
django/utils/archive.py
562
""" Based on "python-archive" -- http://pypi.python.org/pypi/python-archive/ Copyright (c) 2010 Gary Wilson Jr. <gary.wilson@gmail.com> and contributors. 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 os import shutil import tarfile import zipfile from django.utils import six class ArchiveException(Exception): """ Base exception class for all archive errors. """ class UnrecognizedArchiveFormat(ArchiveException): """ Error raised when passed file is not a recognized archive format. """ def extract(path, to_path=''): """ Unpack the tar or zip file at the specified path to the directory specified by to_path. """ with Archive(path) as archive: archive.extract(to_path) class Archive(object): """ The external API class that encapsulates an archive implementation. """ def __init__(self, file): self._archive = self._archive_cls(file)(file) @staticmethod def _archive_cls(file): cls = None if isinstance(file, six.string_types): filename = file else: try: filename = file.name except AttributeError: raise UnrecognizedArchiveFormat( "File object not a recognized archive format.") base, tail_ext = os.path.splitext(filename.lower()) cls = extension_map.get(tail_ext) if not cls: base, ext = os.path.splitext(base) cls = extension_map.get(ext) if not cls: raise UnrecognizedArchiveFormat( "Path not a recognized archive format: %s" % filename) return cls def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def extract(self, to_path=''): self._archive.extract(to_path) def list(self): self._archive.list() def close(self): self._archive.close() class BaseArchive(object): """ Base Archive class. Implementations should inherit this class. """ def split_leading_dir(self, path): path = str(path) path = path.lstrip('/').lstrip('\\') if '/' in path and (('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path): return path.split('/', 1) elif '\\' in path: return path.split('\\', 1) else: return path, '' def has_leading_dir(self, paths): """ Returns true if all the paths have the same leading path name (i.e., everything is in one subdirectory in an archive) """ common_prefix = None for path in paths: prefix, rest = self.split_leading_dir(path) if not prefix: return False elif common_prefix is None: common_prefix = prefix elif prefix != common_prefix: return False return True def extract(self): raise NotImplementedError('subclasses of BaseArchive must provide an extract() method') def list(self): raise NotImplementedError('subclasses of BaseArchive must provide a list() method') class TarArchive(BaseArchive): def __init__(self, file): self._archive = tarfile.open(file) def list(self, *args, **kwargs): self._archive.list(*args, **kwargs) def extract(self, to_path): # note: python<=2.5 doesn't seem to know about pax headers, filter them members = [member for member in self._archive.getmembers() if member.name != 'pax_global_header'] leading = self.has_leading_dir(x.name for x in members) for member in members: name = member.name if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) if member.isdir(): if filename and not os.path.exists(filename): os.makedirs(filename) else: try: extracted = self._archive.extractfile(member) except (KeyError, AttributeError) as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) print("In the tar file %s the member %s is invalid: %s" % (name, member.name, exc)) else: dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname) with open(filename, 'wb') as outfile: shutil.copyfileobj(extracted, outfile) finally: if extracted: extracted.close() def close(self): self._archive.close() class ZipArchive(BaseArchive): def __init__(self, file): self._archive = zipfile.ZipFile(file) def list(self, *args, **kwargs): self._archive.printdir(*args, **kwargs) def extract(self, to_path): namelist = self._archive.namelist() leading = self.has_leading_dir(namelist) for name in namelist: data = self._archive.read(name) if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname) if filename.endswith(('/', '\\')): # A directory if not os.path.exists(filename): os.makedirs(filename) else: with open(filename, 'wb') as outfile: outfile.write(data) def close(self): self._archive.close() extension_map = { '.tar': TarArchive, '.tar.bz2': TarArchive, '.tar.gz': TarArchive, '.tgz': TarArchive, '.tz2': TarArchive, '.zip': ZipArchive, }
q1ang/scikit-learn
refs/heads/master
benchmarks/bench_20newsgroups.py
377
from __future__ import print_function, division from time import time import argparse import numpy as np from sklearn.dummy import DummyClassifier from sklearn.datasets import fetch_20newsgroups_vectorized from sklearn.metrics import accuracy_score from sklearn.utils.validation import check_array from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB ESTIMATORS = { "dummy": DummyClassifier(), "random_forest": RandomForestClassifier(n_estimators=100, max_features="sqrt", min_samples_split=10), "extra_trees": ExtraTreesClassifier(n_estimators=100, max_features="sqrt", min_samples_split=10), "logistic_regression": LogisticRegression(), "naive_bayes": MultinomialNB(), "adaboost": AdaBoostClassifier(n_estimators=10), } ############################################################################### # Data if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-e', '--estimators', nargs="+", required=True, choices=ESTIMATORS) args = vars(parser.parse_args()) data_train = fetch_20newsgroups_vectorized(subset="train") data_test = fetch_20newsgroups_vectorized(subset="test") X_train = check_array(data_train.data, dtype=np.float32, accept_sparse="csc") X_test = check_array(data_test.data, dtype=np.float32, accept_sparse="csr") y_train = data_train.target y_test = data_test.target print("20 newsgroups") print("=============") print("X_train.shape = {0}".format(X_train.shape)) print("X_train.format = {0}".format(X_train.format)) print("X_train.dtype = {0}".format(X_train.dtype)) print("X_train density = {0}" "".format(X_train.nnz / np.product(X_train.shape))) print("y_train {0}".format(y_train.shape)) print("X_test {0}".format(X_test.shape)) print("X_test.format = {0}".format(X_test.format)) print("X_test.dtype = {0}".format(X_test.dtype)) print("y_test {0}".format(y_test.shape)) print() print("Classifier Training") print("===================") accuracy, train_time, test_time = {}, {}, {} for name in sorted(args["estimators"]): clf = ESTIMATORS[name] try: clf.set_params(random_state=0) except (TypeError, ValueError): pass print("Training %s ... " % name, end="") t0 = time() clf.fit(X_train, y_train) train_time[name] = time() - t0 t0 = time() y_pred = clf.predict(X_test) test_time[name] = time() - t0 accuracy[name] = accuracy_score(y_test, y_pred) print("done") print() print("Classification performance:") print("===========================") print() print("%s %s %s %s" % ("Classifier ", "train-time", "test-time", "Accuracy")) print("-" * 44) for name in sorted(accuracy, key=accuracy.get): print("%s %s %s %s" % (name.ljust(16), ("%.4fs" % train_time[name]).center(10), ("%.4fs" % test_time[name]).center(10), ("%.4f" % accuracy[name]).center(10))) print()
tumf/xen-3.3.1
refs/heads/master
tools/python/xen/xend/XendNode.py
4
#============================================================================ # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #============================================================================ # Copyright (C) 2004, 2005 Mike Wray <mike.wray@hp.com> # Copyright (c) 2006, 2007 Xensource Inc. #============================================================================ import os import socket import xen.lowlevel.xc from xen.util import Brctl from xen.util import pci as PciUtil from xen.xend import XendAPIStore from xen.xend import osdep import uuid, arch from XendPBD import XendPBD from XendError import * from XendOptions import instance as xendoptions from XendQCoWStorageRepo import XendQCoWStorageRepo from XendLocalStorageRepo import XendLocalStorageRepo from XendLogging import log from XendPIF import * from XendPIFMetrics import XendPIFMetrics from XendNetwork import * from XendStateStore import XendStateStore from XendMonitor import XendMonitor from XendPPCI import XendPPCI class XendNode: """XendNode - Represents a Domain 0 Host.""" def __init__(self): """Initalises the state of all host specific objects such as * host * host_CPU * host_metrics * PIF * PIF_metrics * network * Storage Repository * PPCI """ self.xc = xen.lowlevel.xc.xc() self.state_store = XendStateStore(xendoptions().get_xend_state_path()) self.monitor = XendMonitor() self.monitor.start() # load host state from XML file saved_host = self.state_store.load_state('host') if saved_host and len(saved_host.keys()) == 1: self.uuid = saved_host.keys()[0] host = saved_host[self.uuid] self.name = host.get('name_label', socket.gethostname()) self.desc = host.get('name_description', '') self.host_metrics_uuid = host.get('metrics_uuid', uuid.createString()) try: self.other_config = eval(host['other_config']) except: self.other_config = {} self.cpus = {} else: self.uuid = uuid.createString() self.name = socket.gethostname() self.desc = '' self.other_config = {} self.cpus = {} self.host_metrics_uuid = uuid.createString() # put some arbitrary params in other_config as this # is directly exposed via XenAPI self.other_config["xen_pagesize"] = self.xeninfo_dict()["xen_pagesize"] self.other_config["platform_params"] = self.xeninfo_dict()["platform_params"] # load CPU UUIDs saved_cpus = self.state_store.load_state('cpu') for cpu_uuid, cpu in saved_cpus.items(): self.cpus[cpu_uuid] = cpu cpuinfo = osdep.get_cpuinfo() physinfo = self.physinfo_dict() cpu_count = physinfo['nr_cpus'] cpu_features = physinfo['hw_caps'] virt_caps = physinfo['virt_caps'] # If the number of CPUs don't match, we should just reinitialise # the CPU UUIDs. if cpu_count != len(self.cpus): self.cpus = {} for i in range(cpu_count): u = uuid.createString() self.cpus[u] = {'uuid': u, 'number': i } for u in self.cpus.keys(): number = self.cpus[u]['number'] # We can run off the end of the cpuinfo list if domain0 does not # have #vcpus == #pcpus. In that case we just replicate one that's # in the hash table. if not cpuinfo.has_key(number): number = cpuinfo.keys()[0] if arch.type == "x86": self.cpus[u].update( { 'host' : self.uuid, 'features' : cpu_features, 'virt_caps': virt_caps, 'speed' : int(float(cpuinfo[number]['cpu MHz'])), 'vendor' : cpuinfo[number]['vendor_id'], 'modelname': cpuinfo[number]['model name'], 'stepping' : cpuinfo[number]['stepping'], 'flags' : cpuinfo[number]['flags'], }) elif arch.type == "ia64": self.cpus[u].update( { 'host' : self.uuid, 'features' : cpu_features, 'speed' : int(float(cpuinfo[number]['cpu MHz'])), 'vendor' : cpuinfo[number]['vendor'], 'modelname': cpuinfo[number]['family'], 'stepping' : cpuinfo[number]['model'], 'flags' : cpuinfo[number]['features'], }) else: self.cpus[u].update( { 'host' : self.uuid, 'features' : cpu_features, }) self.srs = {} # Initialise networks # First configure ones off disk saved_networks = self.state_store.load_state('network') if saved_networks: for net_uuid, network in saved_networks.items(): try: XendNetwork.recreate(network, net_uuid) except CreateUnspecifiedAttributeError: log.warn("Error recreating network %s", net_uuid) # Next discover any existing bridges and check # they are not already configured bridges = Brctl.get_state().keys() configured_bridges = [XendAPIStore.get( network_uuid, "network") .get_name_label() for network_uuid in XendNetwork.get_all()] unconfigured_bridges = [bridge for bridge in bridges if bridge not in configured_bridges] for unconfigured_bridge in unconfigured_bridges: XendNetwork.create_phy(unconfigured_bridge) # Initialise PIFs # First configure ones off disk saved_pifs = self.state_store.load_state('pif') if saved_pifs: for pif_uuid, pif in saved_pifs.items(): try: XendPIF.recreate(pif, pif_uuid) except CreateUnspecifiedAttributeError: log.warn("Error recreating PIF %s", pif_uuid) # Next discover any existing PIFs and check # they are not already configured configured_pifs = [XendAPIStore.get( pif_uuid, "PIF") .get_interface_name() for pif_uuid in XendPIF.get_all()] unconfigured_pifs = [(name, mtu, mac) for name, mtu, mac in linux_get_phy_ifaces() if name not in configured_pifs] # Get a mapping from interface to bridge if_to_br = dict([(i,b) for (b,ifs) in Brctl.get_state().items() for i in ifs]) for name, mtu, mac in unconfigured_pifs: # Check PIF is on bridge # if not, ignore bridge_name = if_to_br.get(name, None) if bridge_name is not None: # Translate bridge name to network uuid for network_uuid in XendNetwork.get_all(): network = XendAPIStore.get( network_uuid, 'network') if network.get_name_label() == bridge_name: XendPIF.create_phy(network_uuid, name, mac, mtu) break else: log.debug("Cannot find network for bridge %s " "when configuring PIF %s", (bridge_name, name)) # initialise storage saved_srs = self.state_store.load_state('sr') if saved_srs: for sr_uuid, sr_cfg in saved_srs.items(): if sr_cfg['type'] == 'qcow_file': self.srs[sr_uuid] = XendQCoWStorageRepo(sr_uuid) elif sr_cfg['type'] == 'local': self.srs[sr_uuid] = XendLocalStorageRepo(sr_uuid) # Create missing SRs if they don't exist if not self.get_sr_by_type('local'): image_sr_uuid = uuid.createString() self.srs[image_sr_uuid] = XendLocalStorageRepo(image_sr_uuid) if not self.get_sr_by_type('qcow_file'): qcow_sr_uuid = uuid.createString() self.srs[qcow_sr_uuid] = XendQCoWStorageRepo(qcow_sr_uuid) saved_pbds = self.state_store.load_state('pbd') if saved_pbds: for pbd_uuid, pbd_cfg in saved_pbds.items(): try: XendPBD.recreate(pbd_uuid, pbd_cfg) except CreateUnspecifiedAttributeError: log.warn("Error recreating PBD %s", pbd_uuid) # Initialise PPCIs saved_ppcis = self.state_store.load_state('ppci') saved_ppci_table = {} if saved_ppcis: for ppci_uuid, ppci_record in saved_ppcis.items(): try: saved_ppci_table[ppci_record['name']] = ppci_uuid except KeyError: pass for pci_dev in PciUtil.get_all_pci_devices(): ppci_record = { 'domain': pci_dev.domain, 'bus': pci_dev.bus, 'slot': pci_dev.slot, 'func': pci_dev.func, 'vendor_id': pci_dev.vendor, 'vendor_name': pci_dev.vendorname, 'device_id': pci_dev.device, 'device_name': pci_dev.devicename, 'revision_id': pci_dev.revision, 'class_code': pci_dev.classcode, 'class_name': pci_dev.classname, 'subsystem_vendor_id': pci_dev.subvendor, 'subsystem_vendor_name': pci_dev.subvendorname, 'subsystem_id': pci_dev.subdevice, 'subsystem_name': pci_dev.subdevicename, 'driver': pci_dev.driver } # If saved uuid exists, use it. Otherwise create one. ppci_uuid = saved_ppci_table.get(pci_dev.name, uuid.createString()) XendPPCI(ppci_uuid, ppci_record) ## def network_destroy(self, net_uuid): ## del self.networks[net_uuid] ## self.save_networks() def get_PIF_refs(self): log.debug(XendPIF.get_all()) return XendPIF.get_all() ## def _PIF_create(self, name, mtu, vlan, mac, network, persist = True, ## pif_uuid = None, metrics_uuid = None): ## for pif in self.pifs.values(): ## if pif.network == network: ## raise NetworkAlreadyConnected(pif.uuid) ## if pif_uuid is None: ## pif_uuid = uuid.createString() ## if metrics_uuid is None: ## metrics_uuid = uuid.createString() ## metrics = XendPIFMetrics(metrics_uuid) ## pif = XendPIF(pif_uuid, metrics, name, mtu, vlan, mac, network, self) ## metrics.set_PIF(pif) ## self.pif_metrics[metrics_uuid] = metrics ## self.pifs[pif_uuid] = pif ## if persist: ## self.save_PIFs() ## self.refreshBridges() ## return pif_uuid ## def PIF_destroy(self, pif_uuid): ## pif = self.pifs[pif_uuid] ## if pif.vlan == -1: ## raise PIFIsPhysical() ## del self.pifs[pif_uuid] ## self.save_PIFs() def get_PPCI_refs(self): return XendPPCI.get_all() def get_ppci_by_uuid(self, ppci_uuid): if ppci_uuid in self.get_PPCI_refs(): return ppci_uuid return None def save(self): # save state host_record = {self.uuid: {'name_label':self.name, 'name_description':self.desc, 'metrics_uuid': self.host_metrics_uuid, 'other_config': self.other_config}} self.state_store.save_state('host',host_record) self.state_store.save_state('cpu', self.cpus) self.save_PIFs() self.save_networks() self.save_PBDs() self.save_SRs() self.save_PPCIs() def save_PIFs(self): pif_records = dict([(pif_uuid, XendAPIStore.get( pif_uuid, "PIF").get_record()) for pif_uuid in XendPIF.get_all()]) self.state_store.save_state('pif', pif_records) def save_networks(self): net_records = dict([(network_uuid, XendAPIStore.get( network_uuid, "network").get_record()) for network_uuid in XendNetwork.get_all()]) self.state_store.save_state('network', net_records) def save_PBDs(self): pbd_records = dict([(pbd_uuid, XendAPIStore.get( pbd_uuid, "PBD").get_record()) for pbd_uuid in XendPBD.get_all()]) self.state_store.save_state('pbd', pbd_records) def save_SRs(self): sr_records = dict([(k, v.get_record(transient = False)) for k, v in self.srs.items()]) self.state_store.save_state('sr', sr_records) def save_PPCIs(self): ppci_records = dict([(ppci_uuid, XendAPIStore.get( ppci_uuid, "PPCI").get_record()) for ppci_uuid in XendPPCI.get_all()]) self.state_store.save_state('ppci', ppci_records) def shutdown(self): return 0 def reboot(self): return 0 def notify(self, _): return 0 # # Ref validation # def is_valid_host(self, host_ref): return (host_ref == self.uuid) def is_valid_cpu(self, cpu_ref): return (cpu_ref in self.cpus) def is_valid_sr(self, sr_ref): return (sr_ref in self.srs) def is_valid_vdi(self, vdi_ref): for sr in self.srs.values(): if sr.is_valid_vdi(vdi_ref): return True return False # # Storage Repositories # def get_sr(self, sr_uuid): return self.srs.get(sr_uuid) def get_sr_by_type(self, sr_type): return [sr.uuid for sr in self.srs.values() if sr.type == sr_type] def get_sr_by_name(self, name): return [sr.uuid for sr in self.srs.values() if sr.name_label == name] def get_all_sr_uuid(self): return self.srs.keys() def get_vdi_by_uuid(self, vdi_uuid): for sr in self.srs.values(): if sr.is_valid_vdi(vdi_uuid): return sr.get_vdi_by_uuid(vdi_uuid) return None def get_vdi_by_name_label(self, name): for sr in self.srs.values(): vdi = sr.get_vdi_by_name_label(name) if vdi: return vdi return None def get_sr_containing_vdi(self, vdi_uuid): for sr in self.srs.values(): if sr.is_valid_vdi(vdi_uuid): return sr return None # # Host Functions # def xen_version(self): info = self.xc.xeninfo() info = {'Xen': '%(xen_major)d.%(xen_minor)d' % info} # Add xend_config_format info.update(self.xendinfo_dict()) # Add version info about machine info.update(self.nodeinfo_dict()) # Add specific xen version info xeninfo_dict = self.xeninfo_dict() info.update({ "xen_major": xeninfo_dict["xen_major"], "xen_minor": xeninfo_dict["xen_minor"], "xen_extra": xeninfo_dict["xen_extra"], "cc_compiler": xeninfo_dict["cc_compiler"], "cc_compile_by": xeninfo_dict["cc_compile_by"], "cc_compile_domain": xeninfo_dict["cc_compile_domain"], "cc_compile_date": xeninfo_dict["cc_compile_date"], "xen_changeset": xeninfo_dict["xen_changeset"] }) return info def get_name(self): return self.name def set_name(self, new_name): self.name = new_name def get_description(self): return self.desc def set_description(self, new_desc): self.desc = new_desc def get_uuid(self): return self.uuid def get_capabilities(self): return self.xc.xeninfo()['xen_caps'].split(" ") # # Host CPU Functions # def get_host_cpu_by_uuid(self, host_cpu_uuid): if host_cpu_uuid in self.cpus: return host_cpu_uuid raise XendError('Invalid CPU UUID') def get_host_cpu_refs(self): return self.cpus.keys() def get_host_cpu_uuid(self, host_cpu_ref): if host_cpu_ref in self.cpus: return host_cpu_ref else: raise XendError('Invalid CPU Reference') def get_host_cpu_field(self, ref, field): try: return self.cpus[ref][field] except KeyError: raise XendError('Invalid CPU Reference') def get_host_cpu_load(self, host_cpu_ref): host_cpu = self.cpus.get(host_cpu_ref) if not host_cpu: return 0.0 vcpu = int(host_cpu['number']) cpu_loads = self.monitor.get_domain_vcpus_util() if 0 in cpu_loads and vcpu in cpu_loads[0]: return cpu_loads[0][vcpu] return 0.0 def get_vcpus_policy(self): sched_id = self.xc.sched_id_get() if sched_id == xen.lowlevel.xc.XEN_SCHEDULER_SEDF: return 'sedf' elif sched_id == xen.lowlevel.xc.XEN_SCHEDULER_CREDIT: return 'credit' else: return 'unknown' def get_cpu_configuration(self): phys_info = self.physinfo_dict() cpu_info = { "nr_nodes": phys_info["nr_nodes"], "nr_cpus": phys_info["nr_cpus"], "cores_per_socket": phys_info["cores_per_socket"], "threads_per_core": phys_info["threads_per_core"] } return cpu_info # # Network Functions # def bridge_to_network(self, bridge): """ Determine which network a particular bridge is attached to. @param bridge The name of the bridge. If empty, the default bridge will be used instead (the first one in the list returned by brctl show); this is the behaviour of the vif-bridge script. @return The XendNetwork instance to which this bridge is attached. @raise Exception if the interface is not connected to a network. """ if not bridge: rc, bridge = commands.getstatusoutput( 'brctl show | cut -d "\n" -f 2 | cut -f 1') if rc != 0 or not bridge: raise Exception( 'Could not find default bridge, and none was specified') for network_uuid in XendNetwork.get_all(): network = XendAPIStore.get(network_uuid, "network") if network.get_name_label() == bridge: return network else: raise Exception('Cannot find network for bridge %s' % bridge) # # Debug keys. # def send_debug_keys(self, keys): return self.xc.send_debug_keys(keys) # # Getting host information. # def info(self): return (self.nodeinfo() + self.physinfo() + self.xeninfo() + self.xendinfo()) def nodeinfo(self): (sys, host, rel, ver, mch) = os.uname() return [['system', sys], ['host', host], ['release', rel], ['version', ver], ['machine', mch]] def list_to_rangepairs(self,cmap): cmap.sort() pairs = [] x = y = 0 for i in range(0,len(cmap)): try: if ((cmap[y+1] - cmap[i]) > 1): pairs.append((cmap[x],cmap[y])) x = y = i+1 else: y = y + 1 # if we go off the end, then just add x to y except IndexError: pairs.append((cmap[x],cmap[y])) return pairs def format_pairs(self,pairs): if not pairs: return "no cpus" out = "" for f,s in pairs: if (f==s): out += '%d'%f else: out += '%d-%d'%(f,s) out += ',' # trim trailing ',' return out[:-1] def list_to_strrange(self,list): return self.format_pairs(self.list_to_rangepairs(list)) def format_node_to_cpu(self, pinfo): str='' whitespace='' try: node_to_cpu=pinfo['node_to_cpu'] for i in range(0, pinfo['nr_nodes']): str+='%snode%d:%s\n' % (whitespace, i, self.list_to_strrange(node_to_cpu[i])) whitespace='%25s' % '' except: str='none\n' return str[:-1]; def format_node_to_memory(self, pinfo): str='' whitespace='' try: node_to_memory=pinfo['node_to_memory'] for i in range(0, pinfo['nr_nodes']): str+='%snode%d:%d\n' % (whitespace, i, node_to_memory[i] / 1024) whitespace='%25s' % '' except: str='none\n' return str[:-1]; def physinfo(self): info = self.xc.physinfo() info['cpu_mhz'] = info['cpu_khz'] / 1000 # physinfo is in KiB, need it in MiB info['total_memory'] = info['total_memory'] / 1024 info['free_memory'] = info['free_memory'] / 1024 info['node_to_cpu'] = self.format_node_to_cpu(info) info['node_to_memory'] = self.format_node_to_memory(info) ITEM_ORDER = ['nr_cpus', 'nr_nodes', 'cores_per_socket', 'threads_per_core', 'cpu_mhz', 'hw_caps', 'virt_caps', 'total_memory', 'free_memory', 'node_to_cpu', 'node_to_memory' ] return [[k, info[k]] for k in ITEM_ORDER] def xenschedinfo(self): sched_id = self.xc.sched_id_get() if sched_id == xen.lowlevel.xc.XEN_SCHEDULER_SEDF: return 'sedf' elif sched_id == xen.lowlevel.xc.XEN_SCHEDULER_CREDIT: return 'credit' else: return 'unknown' def xeninfo(self): info = self.xc.xeninfo() info['xen_scheduler'] = self.xenschedinfo() ITEM_ORDER = ['xen_major', 'xen_minor', 'xen_extra', 'xen_caps', 'xen_scheduler', 'xen_pagesize', 'platform_params', 'xen_changeset', 'cc_compiler', 'cc_compile_by', 'cc_compile_domain', 'cc_compile_date', ] return [[k, info[k]] for k in ITEM_ORDER] def xendinfo(self): return [['xend_config_format', 4]] # # utilisation tracking # def get_vcpu_util(self, domid, vcpuid): cpu_loads = self.monitor.get_domain_vcpus_util() if domid in cpu_loads: return cpu_loads[domid].get(vcpuid, 0.0) return 0.0 def get_vif_util(self, domid, vifid): vif_loads = self.monitor.get_domain_vifs_util() if domid in vif_loads: return vif_loads[domid].get(vifid, (0.0, 0.0)) return (0.0, 0.0) def get_vif_stat(self, domid, vifid): vif_loads = self.monitor.get_domain_vifs_stat() if domid in vif_loads: return vif_loads[domid].get(vifid, (0.0, 0.0)) return (0.0, 0.0) def get_vbd_util(self, domid, vbdid): vbd_loads = self.monitor.get_domain_vbds_util() if domid in vbd_loads: return vbd_loads[domid].get(vbdid, (0.0, 0.0)) return (0.0, 0.0) # dictionary version of *info() functions to get rid of # SXPisms. def nodeinfo_dict(self): return dict(self.nodeinfo()) def xendinfo_dict(self): return dict(self.xendinfo()) def xeninfo_dict(self): return dict(self.xeninfo()) def physinfo_dict(self): return dict(self.physinfo()) def info_dict(self): return dict(self.info()) def instance(): global inst try: inst except: inst = XendNode() inst.save() return inst
duqiao/django
refs/heads/master
django/contrib/flatpages/__init__.py
808
default_app_config = 'django.contrib.flatpages.apps.FlatPagesConfig'
gyh1621/GetSubtitles
refs/heads/master
tests/unit/getsubtitles/test_process_archive.py
1
# coding: utf-8 import os from os import path import copy import shutil import unittest from unittest import mock import rarfile from tests import create_test_directory from tests.unit import assets_path from tests.unit.getsubtitles import get_function as get_f from getsub.models import Video def get_function(**kwargs): return get_f("process_archive", **kwargs) class TestProcessArchive(unittest.TestCase): test_dir = "testPA" test_video = Video(path.join(test_dir, "video.mkv"), test_dir) test_dir_structure = {} def tearDown(self): if path.exists(TestProcessArchive.test_dir): shutil.rmtree(TestProcessArchive.test_dir) def test_unsupported_archive(self): process_archive = get_function() err, subnames = process_archive(TestProcessArchive.test_video, b"", ".tar") self.assertEqual((err, subnames), ("unsupported file type .tar", [])) def test_invalid_archive(self): process_archive = get_function() self.assertRaises( rarfile.BadRarFile, process_archive, TestProcessArchive.test_video, b"", ".7z", ) def test_empty_archive(self): with open(path.join(assets_path, "empty.zip"), "rb") as f: data = f.read() process_archive = get_function() err, subnames = process_archive(TestProcessArchive.test_video, data, ".zip") self.assertEqual((err, subnames), ("no subtitle in this archive", [])) def test_fail_guess(self): with open(path.join(assets_path, "archive.zip"), "rb") as f: data = f.read() process_archive = get_function() err, subnames = process_archive(TestProcessArchive.test_video, data, ".zip") self.assertEqual((err, subnames), ("no guess result in auto mode", [])) @mock.patch("builtins.input", side_effect=["1"]) def test_choose_subtitle(self, mock_input): create_test_directory( TestProcessArchive.test_dir_structure, parent_dir=TestProcessArchive.test_dir, ) with open(path.join(assets_path, "archive.zip"), "rb") as f: data = f.read() test_video = Video(path.join(TestProcessArchive.test_dir, "sub1.mkv")) process_archive = get_function(single=True) err, subnames = process_archive(test_video, data, ".zip") self.assertEqual((err, subnames), ("", [["dir1/sub1.ass", ".ass"]])) def test_save_both_subtitles_success(self): create_test_directory( TestProcessArchive.test_dir_structure, parent_dir=TestProcessArchive.test_dir, ) with open(path.join(assets_path, "archive.zip"), "rb") as f: data = f.read() test_video = Video(path.join(TestProcessArchive.test_dir, "sub.mkv")) process_archive = get_function(both=True) err, subnames = process_archive(test_video, data, ".zip") self.assertTrue( "sub.ass" in os.listdir(TestProcessArchive.test_dir) and "sub.srt" in os.listdir(TestProcessArchive.test_dir) ) def test_save_both_subtitles_fail(self): create_test_directory( TestProcessArchive.test_dir_structure, parent_dir=TestProcessArchive.test_dir, ) with open(path.join(assets_path, "archive.zip"), "rb") as f: data = f.read() process_archive = get_function(both=True) test_video = Video(path.join(TestProcessArchive.test_dir, "sub1.mkv")) err, subnames = process_archive(test_video, data, ".zip") self.assertTrue( "sub1.ass" in os.listdir(TestProcessArchive.test_dir) and "sub1.srt" not in os.listdir(TestProcessArchive.test_dir) ) def test_delete_existed_subtitles(self): dir_structure = copy.copy(TestProcessArchive.test_dir_structure) dir_structure["sub1.ass"] = None dir_structure["sub1.srt"] = None create_test_directory( dir_structure, parent_dir=TestProcessArchive.test_dir, ) with open(path.join(assets_path, "archive.zip"), "rb") as f: data = f.read() process_archive = get_function(both=True) test_video = Video(path.join(TestProcessArchive.test_dir, "sub1.mkv")) err, subnames = process_archive(test_video, data, ".zip") self.assertTrue( "sub1.ass" in os.listdir(TestProcessArchive.test_dir) and "sub1.srt" not in os.listdir(TestProcessArchive.test_dir) ) def test_identifier(self): dir_structure = copy.copy(TestProcessArchive.test_dir_structure) dir_structure["sub1.ass"] = None dir_structure["sub1.zh.srt"] = None create_test_directory( dir_structure, parent_dir=TestProcessArchive.test_dir, ) with open(path.join(assets_path, "archive.zip"), "rb") as f: data = f.read() process_archive = get_function() test_video = Video( path.join(TestProcessArchive.test_dir, "sub1.mkv"), identifier=".zh" ) err, subnames = process_archive(test_video, data, ".zip") self.assertTrue( "sub1.ass" in os.listdir(TestProcessArchive.test_dir) and "sub1.zh.ass" in os.listdir(TestProcessArchive.test_dir) and "sub1.zh.srt" not in os.listdir(TestProcessArchive.test_dir) ) if __name__ == "__main__": unittest.main()
mohamed--abdel-maksoud/chromium.src
refs/heads/nw12
tools/git/mffr.py
167
#!/usr/bin/env python # Copyright (c) 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. """Usage: mffr.py [-d] [-g *.h] [-g *.cc] REGEXP REPLACEMENT This tool performs a fast find-and-replace operation on files in the current git repository. The -d flag selects a default set of globs (C++ and Objective-C/C++ source files). The -g flag adds a single glob to the list and may be used multiple times. If neither -d nor -g is specified, the tool searches all files (*.*). REGEXP uses full Python regexp syntax. REPLACEMENT can use back-references. """ import optparse import re import subprocess import sys # We need to use shell=True with subprocess on Windows so that it # finds 'git' from the path, but can lead to undesired behavior on # Linux. _USE_SHELL = (sys.platform == 'win32') def MultiFileFindReplace(original, replacement, file_globs): """Implements fast multi-file find and replace. Given an |original| string and a |replacement| string, find matching files by running git grep on |original| in files matching any pattern in |file_globs|. Once files are found, |re.sub| is run to replace |original| with |replacement|. |replacement| may use capture group back-references. Args: original: '(#(include|import)\s*["<])chrome/browser/ui/browser.h([>"])' replacement: '\1chrome/browser/ui/browser/browser.h\3' file_globs: ['*.cc', '*.h', '*.m', '*.mm'] Returns the list of files modified. Raises an exception on error. """ # Posix extended regular expressions do not reliably support the "\s" # shorthand. posix_ere_original = re.sub(r"\\s", "[[:space:]]", original) if sys.platform == 'win32': posix_ere_original = posix_ere_original.replace('"', '""') out, err = subprocess.Popen( ['git', 'grep', '-E', '--name-only', posix_ere_original, '--'] + file_globs, stdout=subprocess.PIPE, shell=_USE_SHELL).communicate() referees = out.splitlines() for referee in referees: with open(referee) as f: original_contents = f.read() contents = re.sub(original, replacement, original_contents) if contents == original_contents: raise Exception('No change in file %s although matched in grep' % referee) with open(referee, 'wb') as f: f.write(contents) return referees def main(): parser = optparse.OptionParser(usage=''' (1) %prog <options> REGEXP REPLACEMENT REGEXP uses full Python regexp syntax. REPLACEMENT can use back-references. (2) %prog <options> -i <file> <file> should contain a list (in Python syntax) of [REGEXP, REPLACEMENT, [GLOBS]] lists, e.g.: [ [r"(foo|bar)", r"\1baz", ["*.cc", "*.h"]], ["54", "42"], ] As shown above, [GLOBS] can be omitted for a given search-replace list, in which case the corresponding search-replace will use the globs specified on the command line.''') parser.add_option('-d', action='store_true', dest='use_default_glob', help='Perform the change on C++ and Objective-C(++) source ' 'and header files.') parser.add_option('-f', action='store_true', dest='force_unsafe_run', help='Perform the run even if there are uncommitted local ' 'changes.') parser.add_option('-g', action='append', type='string', default=[], metavar="<glob>", dest='user_supplied_globs', help='Perform the change on the specified glob. Can be ' 'specified multiple times, in which case the globs are ' 'unioned.') parser.add_option('-i', "--input_file", type='string', action='store', default='', metavar="<file>", dest='input_filename', help='Read arguments from <file> rather than the command ' 'line. NOTE: To be sure of regular expressions being ' 'interpreted correctly, use raw strings.') opts, args = parser.parse_args() if opts.use_default_glob and opts.user_supplied_globs: print '"-d" and "-g" cannot be used together' parser.print_help() return 1 from_file = opts.input_filename != "" if (from_file and len(args) != 0) or (not from_file and len(args) != 2): parser.print_help() return 1 if not opts.force_unsafe_run: out, err = subprocess.Popen(['git', 'status', '--porcelain'], stdout=subprocess.PIPE, shell=_USE_SHELL).communicate() if out: print 'ERROR: This tool does not print any confirmation prompts,' print 'so you should only run it with a clean staging area and cache' print 'so that reverting a bad find/replace is as easy as running' print ' git checkout -- .' print '' print 'To override this safeguard, pass the -f flag.' return 1 global_file_globs = ['*.*'] if opts.use_default_glob: global_file_globs = ['*.cc', '*.h', '*.m', '*.mm'] elif opts.user_supplied_globs: global_file_globs = opts.user_supplied_globs # Construct list of search-replace tasks. search_replace_tasks = [] if opts.input_filename == '': original = args[0] replacement = args[1] search_replace_tasks.append([original, replacement, global_file_globs]) else: f = open(opts.input_filename) search_replace_tasks = eval("".join(f.readlines())) for task in search_replace_tasks: if len(task) == 2: task.append(global_file_globs) f.close() for (original, replacement, file_globs) in search_replace_tasks: print 'File globs: %s' % file_globs print 'Original: %s' % original print 'Replacement: %s' % replacement MultiFileFindReplace(original, replacement, file_globs) return 0 if __name__ == '__main__': sys.exit(main())
vongochung/buiquocviet
refs/heads/master
django/views/i18n.py
57
import os import gettext as gettext_module from django import http from django.conf import settings from django.utils import importlib from django.utils.translation import check_for_language, activate, to_locale, get_language from django.utils.text import javascript_quote from django.utils.encoding import smart_unicode from django.utils.formats import get_format_modules, get_format from django.utils.http import is_safe_url def set_language(request): """ Redirect to a given url while setting the chosen language in the session or cookie. The url and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the page in the request (the 'next' parameter) without changing any state. """ next = request.REQUEST.get('next') if not is_safe_url(url=next, host=request.get_host()): next = request.META.get('HTTP_REFERER') if not is_safe_url(url=next, host=request.get_host()): next = '/' response = http.HttpResponseRedirect(next) if request.method == 'POST': lang_code = request.POST.get('language', None) if lang_code and check_for_language(lang_code): if hasattr(request, 'session'): request.session['django_language'] = lang_code else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) return response def get_formats(): """ Returns all formats strings required for i18n to work """ FORMAT_SETTINGS = ( 'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT', 'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR', 'THOUSAND_SEPARATOR', 'NUMBER_GROUPING', 'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS' ) result = {} for module in [settings] + get_format_modules(reverse=True): for attr in FORMAT_SETTINGS: result[attr] = get_format(attr) src = [] for k, v in result.items(): if isinstance(v, (basestring, int)): src.append("formats['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(smart_unicode(v)))) elif isinstance(v, (tuple, list)): v = [javascript_quote(smart_unicode(value)) for value in v] src.append("formats['%s'] = ['%s'];\n" % (javascript_quote(k), "', '".join(v))) return ''.join(src) NullSource = """ /* gettext identity library */ function gettext(msgid) { return msgid; } function ngettext(singular, plural, count) { return (count == 1) ? singular : plural; } function gettext_noop(msgid) { return msgid; } function pgettext(context, msgid) { return msgid; } function npgettext(context, singular, plural, count) { return (count == 1) ? singular : plural; } """ LibHead = """ /* gettext library */ var catalog = new Array(); """ LibFoot = """ function gettext(msgid) { var value = catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } } function ngettext(singular, plural, count) { value = catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value[pluralidx(count)]; } } function gettext_noop(msgid) { return msgid; } function pgettext(context, msgid) { var value = gettext(context + '\x04' + msgid); if (value.indexOf('\x04') != -1) { value = msgid; } return value; } function npgettext(context, singular, plural, count) { var value = ngettext(context + '\x04' + singular, context + '\x04' + plural, count); if (value.indexOf('\x04') != -1) { value = ngettext(singular, plural, count); } return value; } """ LibFormatHead = """ /* formatting library */ var formats = new Array(); """ LibFormatFoot = """ function get_format(format_type) { var value = formats[format_type]; if (typeof(value) == 'undefined') { return msgid; } else { return value; } } """ SimplePlural = """ function pluralidx(count) { return (count == 1) ? 0 : 1; } """ InterPolate = r""" function interpolate(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } } """ PluralIdx = r""" function pluralidx(n) { var v=%s; if (typeof(v) == 'boolean') { return v ? 1 : 0; } else { return v; } } """ def null_javascript_catalog(request, domain=None, packages=None): """ Returns "identity" versions of the JavaScript i18n functions -- i.e., versions that don't actually do anything. """ src = [NullSource, InterPolate, LibFormatHead, get_formats(), LibFormatFoot] return http.HttpResponse(''.join(src), 'text/javascript') def javascript_catalog(request, domain='djangojs', packages=None): """ Returns the selected language catalog as a javascript library. Receives the list of packages to check for translations in the packages parameter either from an infodict or as a +-delimited string from the request. Default is 'django.conf'. Additionally you can override the gettext domain for this view, but usually you don't want to do that, as JavaScript messages go to the djangojs domain. But this might be needed if you deliver your JavaScript source from Django templates. """ if request.GET: if 'language' in request.GET: if check_for_language(request.GET['language']): activate(request.GET['language']) if packages is None: packages = ['django.conf'] if isinstance(packages, basestring): packages = packages.split('+') packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS] default_locale = to_locale(settings.LANGUAGE_CODE) locale = to_locale(get_language()) t = {} paths = [] en_selected = locale.startswith('en') en_catalog_missing = True # paths of requested packages for package in packages: p = importlib.import_module(package) path = os.path.join(os.path.dirname(p.__file__), 'locale') paths.append(path) # add the filesystem paths listed in the LOCALE_PATHS setting paths.extend(list(reversed(settings.LOCALE_PATHS))) # first load all english languages files for defaults for path in paths: try: catalog = gettext_module.translation(domain, path, ['en']) t.update(catalog._catalog) except IOError: pass else: # 'en' is the selected language and at least one of the packages # listed in `packages` has an 'en' catalog if en_selected: en_catalog_missing = False # next load the settings.LANGUAGE_CODE translations if it isn't english if default_locale != 'en': for path in paths: try: catalog = gettext_module.translation(domain, path, [default_locale]) except IOError: catalog = None if catalog is not None: t.update(catalog._catalog) # last load the currently selected language, if it isn't identical to the default. if locale != default_locale: # If the currently selected language is English but it doesn't have a # translation catalog (presumably due to being the language translated # from) then a wrong language catalog might have been loaded in the # previous step. It needs to be discarded. if en_selected and en_catalog_missing: t = {} else: locale_t = {} for path in paths: try: catalog = gettext_module.translation(domain, path, [locale]) except IOError: catalog = None if catalog is not None: locale_t.update(catalog._catalog) if locale_t: t = locale_t src = [LibHead] plural = None if '' in t: for l in t[''].split('\n'): if l.startswith('Plural-Forms:'): plural = l.split(':',1)[1].strip() if plural is not None: # this should actually be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1] src.append(PluralIdx % plural) else: src.append(SimplePlural) csrc = [] pdict = {} for k, v in t.items(): if k == '': continue if isinstance(k, basestring): csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v))) elif isinstance(k, tuple): if k[0] not in pdict: pdict[k[0]] = k[1] else: pdict[k[0]] = max(k[1], pdict[k[0]]) csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v))) else: raise TypeError(k) csrc.sort() for k, v in pdict.items(): src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1)))) src.extend(csrc) src.append(LibFoot) src.append(InterPolate) src.append(LibFormatHead) src.append(get_formats()) src.append(LibFormatFoot) src = ''.join(src) return http.HttpResponse(src, 'text/javascript')
indashnet/InDashNet.Open.UN2000
refs/heads/master
android/external/v8/test/sputnik/testcfg.py
8
# Copyright 2009 the V8 project authors. 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 from os.path import join, exists import sys import test import time class SputnikTestCase(test.TestCase): def __init__(self, case, path, context, mode): super(SputnikTestCase, self).__init__(context, path, mode) self.case = case self.tmpfile = None self.source = None def IsNegative(self): return '@negative' in self.GetSource() def IsFailureOutput(self, output): if output.exit_code != 0: return True out = output.stdout return "SputnikError" in out def BeforeRun(self): self.tmpfile = sputnik.TempFile(suffix='.js', prefix='sputnik-', text=True) self.tmpfile.Write(self.GetSource()) self.tmpfile.Close() def AfterRun(self, result): # Dispose the temporary file if everything looks okay. if result is None or not result.HasPreciousOutput(): self.tmpfile.Dispose() self.tmpfile = None def GetCommand(self): result = self.context.GetVmCommand(self, self.mode) result.append(self.tmpfile.name) return result def GetLabel(self): return "%s sputnik %s" % (self.mode, self.GetName()) def GetName(self): return self.path[-1] def GetSource(self): if not self.source: self.source = self.case.GetSource() return self.source class SputnikTestConfiguration(test.TestConfiguration): def __init__(self, context, root): super(SputnikTestConfiguration, self).__init__(context, root) def ListTests(self, current_path, path, mode, variant_flags): # Import the sputnik test runner script as a module testroot = join(self.root, 'sputniktests') modroot = join(testroot, 'tools') sys.path.append(modroot) import sputnik globals()['sputnik'] = sputnik # Do not run strict mode tests yet. TODO(mmaly) test_suite = sputnik.TestSuite(testroot, False) test_suite.Validate() tests = test_suite.EnumerateTests([]) result = [] for test in tests: full_path = current_path + [test.GetPath()[-1]] if self.Contains(path, full_path): case = SputnikTestCase(test, full_path, self.context, mode) result.append(case) return result def GetBuildRequirements(self): return ['d8'] def GetTestStatus(self, sections, defs): status_file = join(self.root, 'sputnik.status') if exists(status_file): test.ReadConfigurationInto(status_file, sections, defs) def GetConfiguration(context, root): return SputnikTestConfiguration(context, root)
Itxaka/libcloud
refs/heads/trunk
docs/examples/http_proxy/set_http_proxy_method.py
54
from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver PROXY_URL_NO_AUTH_1 = 'http://<proxy hostname 1>:<proxy port 2>' PROXY_URL_NO_AUTH_2 = 'http://<proxy hostname 1>:<proxy port 2>' PROXY_URL_BASIC_AUTH = 'http://<user>:<pass>@<proxy hostname>:<proxy port>' cls = get_driver(Provider.RACKSPACE) driver = cls('username', 'api key', region='ord') # Use proxy 1 for this request driver.connection.set_http_proxy(proxy_url=PROXY_URL_NO_AUTH_1) pprint(driver.list_nodes()) # Use proxy 2 for this request driver.connection.set_http_proxy(proxy_url=PROXY_URL_NO_AUTH_2) pprint(driver.list_nodes())
ebukoz/thrive
refs/heads/develop
erpnext/patches/v12_0/remove_patient_medical_record_page.py
8
# Copyright (c) 2019 from __future__ import unicode_literals import frappe def execute(): frappe.delete_doc("Page", "medical_record")
dsquareindia/scikit-learn
refs/heads/master
sklearn/gaussian_process/kernels.py
31
"""Kernels for Gaussian process regression and classification. The kernels in this module allow kernel-engineering, i.e., they can be combined via the "+" and "*" operators or be exponentiated with a scalar via "**". These sum and product expressions can also contain scalar values, which are automatically converted to a constant kernel. All kernels allow (analytic) gradient-based hyperparameter optimization. The space of hyperparameters can be specified by giving lower und upper boundaries for the value of each hyperparameter (the search space is thus rectangular). Instead of specifying bounds, hyperparameters can also be declared to be "fixed", which causes these hyperparameters to be excluded from optimization. """ # Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # License: BSD 3 clause # Note: this module is strongly inspired by the kernel module of the george # package. from abc import ABCMeta, abstractmethod from collections import namedtuple import math import numpy as np from scipy.special import kv, gamma from scipy.spatial.distance import pdist, cdist, squareform from ..metrics.pairwise import pairwise_kernels from ..externals import six from ..base import clone from sklearn.externals.funcsigs import signature def _check_length_scale(X, length_scale): length_scale = np.squeeze(length_scale).astype(float) if np.ndim(length_scale) > 1: raise ValueError("length_scale cannot be of dimension greater than 1") if np.ndim(length_scale) == 1 and X.shape[1] != length_scale.shape[0]: raise ValueError("Anisotropic kernel must have the same number of " "dimensions as data (%d!=%d)" % (length_scale.shape[0], X.shape[1])) return length_scale class Hyperparameter(namedtuple('Hyperparameter', ('name', 'value_type', 'bounds', 'n_elements', 'fixed'))): """A kernel hyperparameter's specification in form of a namedtuple. .. versionadded:: 0.18 Attributes ---------- name : string The name of the hyperparameter. Note that a kernel using a hyperparameter with name "x" must have the attributes self.x and self.x_bounds value_type : string The type of the hyperparameter. Currently, only "numeric" hyperparameters are supported. bounds : pair of floats >= 0 or "fixed" The lower and upper bound on the parameter. If n_elements>1, a pair of 1d array with n_elements each may be given alternatively. If the string "fixed" is passed as bounds, the hyperparameter's value cannot be changed. n_elements : int, default=1 The number of elements of the hyperparameter value. Defaults to 1, which corresponds to a scalar hyperparameter. n_elements > 1 corresponds to a hyperparameter which is vector-valued, such as, e.g., anisotropic length-scales. fixed : bool, default: None Whether the value of this hyperparameter is fixed, i.e., cannot be changed during hyperparameter tuning. If None is passed, the "fixed" is derived based on the given bounds. """ # A raw namedtuple is very memory efficient as it packs the attributes # in a struct to get rid of the __dict__ of attributes in particular it # does not copy the string for the keys on each instance. # By deriving a namedtuple class just to introduce the __init__ method we # would also reintroduce the __dict__ on the instance. By telling the # Python interpreter that this subclass uses static __slots__ instead of # dynamic attributes. Furthermore we don't need any additional slot in the # subclass so we set __slots__ to the empty tuple. __slots__ = () def __new__(cls, name, value_type, bounds, n_elements=1, fixed=None): if not isinstance(bounds, six.string_types) or bounds != "fixed": bounds = np.atleast_2d(bounds) if n_elements > 1: # vector-valued parameter if bounds.shape[0] == 1: bounds = np.repeat(bounds, n_elements, 0) elif bounds.shape[0] != n_elements: raise ValueError("Bounds on %s should have either 1 or " "%d dimensions. Given are %d" % (name, n_elements, bounds.shape[0])) if fixed is None: fixed = isinstance(bounds, six.string_types) and bounds == "fixed" return super(Hyperparameter, cls).__new__( cls, name, value_type, bounds, n_elements, fixed) # This is mainly a testing utility to check that two hyperparameters # are equal. def __eq__(self, other): return (self.name == other.name and self.value_type == other.value_type and np.all(self.bounds == other.bounds) and self.n_elements == other.n_elements and self.fixed == other.fixed) class Kernel(six.with_metaclass(ABCMeta)): """Base class for all kernels. .. versionadded:: 0.18 """ def get_params(self, deep=True): """Get parameters of this kernel. Parameters ---------- deep : boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any Parameter names mapped to their values. """ params = dict() # introspect the constructor arguments to find the model parameters # to represent cls = self.__class__ init = getattr(cls.__init__, 'deprecated_original', cls.__init__) init_sign = signature(init) args, varargs = [], [] for parameter in init_sign.parameters.values(): if (parameter.kind != parameter.VAR_KEYWORD and parameter.name != 'self'): args.append(parameter.name) if parameter.kind == parameter.VAR_POSITIONAL: varargs.append(parameter.name) if len(varargs) != 0: raise RuntimeError("scikit-learn kernels should always " "specify their parameters in the signature" " of their __init__ (no varargs)." " %s doesn't follow this convention." % (cls, )) for arg in args: params[arg] = getattr(self, arg, None) return params def set_params(self, **params): """Set the parameters of this kernel. The method works on simple kernels as well as on nested kernels. The latter have parameters of the form ``<component>__<parameter>`` so that it's possible to update each component of a nested object. Returns ------- self """ if not params: # Simple optimisation to gain speed (inspect is slow) return self valid_params = self.get_params(deep=True) for key, value in six.iteritems(params): split = key.split('__', 1) if len(split) > 1: # nested objects case name, sub_name = split if name not in valid_params: raise ValueError('Invalid parameter %s for kernel %s. ' 'Check the list of available parameters ' 'with `kernel.get_params().keys()`.' % (name, self)) sub_object = valid_params[name] sub_object.set_params(**{sub_name: value}) else: # simple objects case if key not in valid_params: raise ValueError('Invalid parameter %s for kernel %s. ' 'Check the list of available parameters ' 'with `kernel.get_params().keys()`.' % (key, self.__class__.__name__)) setattr(self, key, value) return self def clone_with_theta(self, theta): """Returns a clone of self with given hyperparameters theta. """ cloned = clone(self) cloned.theta = theta return cloned @property def n_dims(self): """Returns the number of non-fixed hyperparameters of the kernel.""" return self.theta.shape[0] @property def hyperparameters(self): """Returns a list of all hyperparameter specifications.""" r = [] for attr in dir(self): if attr.startswith("hyperparameter_"): r.append(getattr(self, attr)) return r @property def theta(self): """Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel's hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns ------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel """ theta = [] params = self.get_params() for hyperparameter in self.hyperparameters: if not hyperparameter.fixed: theta.append(params[hyperparameter.name]) if len(theta) > 0: return np.log(np.hstack(theta)) else: return np.array([]) @theta.setter def theta(self, theta): """Sets the (flattened, log-transformed) non-fixed hyperparameters. Parameters ---------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel """ params = self.get_params() i = 0 for hyperparameter in self.hyperparameters: if hyperparameter.fixed: continue if hyperparameter.n_elements > 1: # vector-valued parameter params[hyperparameter.name] = np.exp( theta[i:i + hyperparameter.n_elements]) i += hyperparameter.n_elements else: params[hyperparameter.name] = np.exp(theta[i]) i += 1 if i != len(theta): raise ValueError("theta has not the correct number of entries." " Should be %d; given are %d" % (i, len(theta))) self.set_params(**params) @property def bounds(self): """Returns the log-transformed bounds on the theta. Returns ------- bounds : array, shape (n_dims, 2) The log-transformed bounds on the kernel's hyperparameters theta """ bounds = [] for hyperparameter in self.hyperparameters: if not hyperparameter.fixed: bounds.append(hyperparameter.bounds) if len(bounds) > 0: return np.log(np.vstack(bounds)) else: return np.array([]) def __add__(self, b): if not isinstance(b, Kernel): return Sum(self, ConstantKernel(b)) return Sum(self, b) def __radd__(self, b): if not isinstance(b, Kernel): return Sum(ConstantKernel(b), self) return Sum(b, self) def __mul__(self, b): if not isinstance(b, Kernel): return Product(self, ConstantKernel(b)) return Product(self, b) def __rmul__(self, b): if not isinstance(b, Kernel): return Product(ConstantKernel(b), self) return Product(b, self) def __pow__(self, b): return Exponentiation(self, b) def __eq__(self, b): if type(self) != type(b): return False params_a = self.get_params() params_b = b.get_params() for key in set(list(params_a.keys()) + list(params_b.keys())): if np.any(params_a.get(key, None) != params_b.get(key, None)): return False return True def __repr__(self): return "{0}({1})".format(self.__class__.__name__, ", ".join(map("{0:.3g}".format, self.theta))) @abstractmethod def __call__(self, X, Y=None, eval_gradient=False): """Evaluate the kernel.""" @abstractmethod def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ @abstractmethod def is_stationary(self): """Returns whether the kernel is stationary. """ class NormalizedKernelMixin(object): """Mixin for kernels which are normalized: k(X, X)=1. .. versionadded:: 0.18 """ def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ return np.ones(X.shape[0]) class StationaryKernelMixin(object): """Mixin for kernels which are stationary: k(X, Y)= f(X-Y). .. versionadded:: 0.18 """ def is_stationary(self): """Returns whether the kernel is stationary. """ return True class CompoundKernel(Kernel): """Kernel which is composed of a set of other kernels. .. versionadded:: 0.18 """ def __init__(self, kernels): self.kernels = kernels def get_params(self, deep=True): """Get parameters of this kernel. Parameters ---------- deep : boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any Parameter names mapped to their values. """ return dict(kernels=self.kernels) @property def theta(self): """Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel's hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns ------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel """ return np.hstack([kernel.theta for kernel in self.kernels]) @theta.setter def theta(self, theta): """Sets the (flattened, log-transformed) non-fixed hyperparameters. Parameters ---------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel """ k_dims = self.k1.n_dims for i, kernel in enumerate(self.kernels): kernel.theta = theta[i * k_dims:(i + 1) * k_dims] @property def bounds(self): """Returns the log-transformed bounds on the theta. Returns ------- bounds : array, shape (n_dims, 2) The log-transformed bounds on the kernel's hyperparameters theta """ return np.vstack([kernel.bounds for kernel in self.kernels]) def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Note that this compound kernel returns the results of all simple kernel stacked along an additional axis. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Returns ------- K : array, shape (n_samples_X, n_samples_Y, n_kernels) Kernel k(X, Y) K_gradient : array, shape (n_samples_X, n_samples_X, n_dims, n_kernels) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ if eval_gradient: K = [] K_grad = [] for kernel in self.kernels: K_single, K_grad_single = kernel(X, Y, eval_gradient) K.append(K_single) K_grad.append(K_grad_single[..., np.newaxis]) return np.dstack(K), np.concatenate(K_grad, 3) else: return np.dstack([kernel(X, Y, eval_gradient) for kernel in self.kernels]) def __eq__(self, b): if type(self) != type(b) or len(self.kernels) != len(b.kernels): return False return np.all([self.kernels[i] == b.kernels[i] for i in range(len(self.kernels))]) def is_stationary(self): """Returns whether the kernel is stationary. """ return np.all([kernel.is_stationary() for kernel in self.kernels]) def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X, n_kernels) Diagonal of kernel k(X, X) """ return np.vstack([kernel.diag(X) for kernel in self.kernels]).T class KernelOperator(Kernel): """Base class for all kernel operators. .. versionadded:: 0.18 """ def __init__(self, k1, k2): self.k1 = k1 self.k2 = k2 def get_params(self, deep=True): """Get parameters of this kernel. Parameters ---------- deep : boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any Parameter names mapped to their values. """ params = dict(k1=self.k1, k2=self.k2) if deep: deep_items = self.k1.get_params().items() params.update(('k1__' + k, val) for k, val in deep_items) deep_items = self.k2.get_params().items() params.update(('k2__' + k, val) for k, val in deep_items) return params @property def hyperparameters(self): """Returns a list of all hyperparameter.""" r = [] for hyperparameter in self.k1.hyperparameters: r.append(Hyperparameter("k1__" + hyperparameter.name, hyperparameter.value_type, hyperparameter.bounds, hyperparameter.n_elements)) for hyperparameter in self.k2.hyperparameters: r.append(Hyperparameter("k2__" + hyperparameter.name, hyperparameter.value_type, hyperparameter.bounds, hyperparameter.n_elements)) return r @property def theta(self): """Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel's hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns ------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel """ return np.append(self.k1.theta, self.k2.theta) @theta.setter def theta(self, theta): """Sets the (flattened, log-transformed) non-fixed hyperparameters. Parameters ---------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel """ k1_dims = self.k1.n_dims self.k1.theta = theta[:k1_dims] self.k2.theta = theta[k1_dims:] @property def bounds(self): """Returns the log-transformed bounds on the theta. Returns ------- bounds : array, shape (n_dims, 2) The log-transformed bounds on the kernel's hyperparameters theta """ if self.k1.bounds.size == 0: return self.k2.bounds if self.k2.bounds.size == 0: return self.k1.bounds return np.vstack((self.k1.bounds, self.k2.bounds)) def __eq__(self, b): if type(self) != type(b): return False return (self.k1 == b.k1 and self.k2 == b.k2) \ or (self.k1 == b.k2 and self.k2 == b.k1) def is_stationary(self): """Returns whether the kernel is stationary. """ return self.k1.is_stationary() and self.k2.is_stationary() class Sum(KernelOperator): """Sum-kernel k1 + k2 of two kernels k1 and k2. The resulting kernel is defined as k_sum(X, Y) = k1(X, Y) + k2(X, Y) .. versionadded:: 0.18 Parameters ---------- k1 : Kernel object The first base-kernel of the sum-kernel k2 : Kernel object The second base-kernel of the sum-kernel """ def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ if eval_gradient: K1, K1_gradient = self.k1(X, Y, eval_gradient=True) K2, K2_gradient = self.k2(X, Y, eval_gradient=True) return K1 + K2, np.dstack((K1_gradient, K2_gradient)) else: return self.k1(X, Y) + self.k2(X, Y) def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ return self.k1.diag(X) + self.k2.diag(X) def __repr__(self): return "{0} + {1}".format(self.k1, self.k2) class Product(KernelOperator): """Product-kernel k1 * k2 of two kernels k1 and k2. The resulting kernel is defined as k_prod(X, Y) = k1(X, Y) * k2(X, Y) .. versionadded:: 0.18 Parameters ---------- k1 : Kernel object The first base-kernel of the product-kernel k2 : Kernel object The second base-kernel of the product-kernel """ def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ if eval_gradient: K1, K1_gradient = self.k1(X, Y, eval_gradient=True) K2, K2_gradient = self.k2(X, Y, eval_gradient=True) return K1 * K2, np.dstack((K1_gradient * K2[:, :, np.newaxis], K2_gradient * K1[:, :, np.newaxis])) else: return self.k1(X, Y) * self.k2(X, Y) def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ return self.k1.diag(X) * self.k2.diag(X) def __repr__(self): return "{0} * {1}".format(self.k1, self.k2) class Exponentiation(Kernel): """Exponentiate kernel by given exponent. The resulting kernel is defined as k_exp(X, Y) = k(X, Y) ** exponent .. versionadded:: 0.18 Parameters ---------- kernel : Kernel object The base kernel exponent : float The exponent for the base kernel """ def __init__(self, kernel, exponent): self.kernel = kernel self.exponent = exponent def get_params(self, deep=True): """Get parameters of this kernel. Parameters ---------- deep : boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any Parameter names mapped to their values. """ params = dict(kernel=self.kernel, exponent=self.exponent) if deep: deep_items = self.kernel.get_params().items() params.update(('kernel__' + k, val) for k, val in deep_items) return params @property def hyperparameters(self): """Returns a list of all hyperparameter.""" r = [] for hyperparameter in self.kernel.hyperparameters: r.append(Hyperparameter("kernel__" + hyperparameter.name, hyperparameter.value_type, hyperparameter.bounds, hyperparameter.n_elements)) return r @property def theta(self): """Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel's hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns ------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel """ return self.kernel.theta @theta.setter def theta(self, theta): """Sets the (flattened, log-transformed) non-fixed hyperparameters. Parameters ---------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel """ self.kernel.theta = theta @property def bounds(self): """Returns the log-transformed bounds on the theta. Returns ------- bounds : array, shape (n_dims, 2) The log-transformed bounds on the kernel's hyperparameters theta """ return self.kernel.bounds def __eq__(self, b): if type(self) != type(b): return False return (self.kernel == b.kernel and self.exponent == b.exponent) def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ if eval_gradient: K, K_gradient = self.kernel(X, Y, eval_gradient=True) K_gradient *= \ self.exponent * K[:, :, np.newaxis] ** (self.exponent - 1) return K ** self.exponent, K_gradient else: K = self.kernel(X, Y, eval_gradient=False) return K ** self.exponent def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ return self.kernel.diag(X) ** self.exponent def __repr__(self): return "{0} ** {1}".format(self.kernel, self.exponent) def is_stationary(self): """Returns whether the kernel is stationary. """ return self.kernel.is_stationary() class ConstantKernel(StationaryKernelMixin, Kernel): """Constant kernel. Can be used as part of a product-kernel where it scales the magnitude of the other factor (kernel) or as part of a sum-kernel, where it modifies the mean of the Gaussian process. k(x_1, x_2) = constant_value for all x_1, x_2 .. versionadded:: 0.18 Parameters ---------- constant_value : float, default: 1.0 The constant value which defines the covariance: k(x_1, x_2) = constant_value constant_value_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on constant_value """ def __init__(self, constant_value=1.0, constant_value_bounds=(1e-5, 1e5)): self.constant_value = constant_value self.constant_value_bounds = constant_value_bounds @property def hyperparameter_constant_value(self): return Hyperparameter( "constant_value", "numeric", self.constant_value_bounds) def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Only supported when Y is None. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ X = np.atleast_2d(X) if Y is None: Y = X elif eval_gradient: raise ValueError("Gradient can only be evaluated when Y is None.") K = self.constant_value * np.ones((X.shape[0], Y.shape[0])) if eval_gradient: if not self.hyperparameter_constant_value.fixed: return (K, self.constant_value * np.ones((X.shape[0], X.shape[0], 1))) else: return K, np.empty((X.shape[0], X.shape[0], 0)) else: return K def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ return self.constant_value * np.ones(X.shape[0]) def __repr__(self): return "{0:.3g}**2".format(np.sqrt(self.constant_value)) class WhiteKernel(StationaryKernelMixin, Kernel): """White kernel. The main use-case of this kernel is as part of a sum-kernel where it explains the noise-component of the signal. Tuning its parameter corresponds to estimating the noise-level. k(x_1, x_2) = noise_level if x_1 == x_2 else 0 .. versionadded:: 0.18 Parameters ---------- noise_level : float, default: 1.0 Parameter controlling the noise level noise_level_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on noise_level """ def __init__(self, noise_level=1.0, noise_level_bounds=(1e-5, 1e5)): self.noise_level = noise_level self.noise_level_bounds = noise_level_bounds @property def hyperparameter_noise_level(self): return Hyperparameter( "noise_level", "numeric", self.noise_level_bounds) def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Only supported when Y is None. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ X = np.atleast_2d(X) if Y is not None and eval_gradient: raise ValueError("Gradient can only be evaluated when Y is None.") if Y is None: K = self.noise_level * np.eye(X.shape[0]) if eval_gradient: if not self.hyperparameter_noise_level.fixed: return (K, self.noise_level * np.eye(X.shape[0])[:, :, np.newaxis]) else: return K, np.empty((X.shape[0], X.shape[0], 0)) else: return K else: return np.zeros((X.shape[0], Y.shape[0])) def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ return self.noise_level * np.ones(X.shape[0]) def __repr__(self): return "{0}(noise_level={1:.3g})".format(self.__class__.__name__, self.noise_level) class RBF(StationaryKernelMixin, NormalizedKernelMixin, Kernel): """Radial-basis function kernel (aka squared-exponential kernel). The RBF kernel is a stationary kernel. It is also known as the "squared exponential" kernel. It is parameterized by a length-scale parameter length_scale>0, which can either be a scalar (isotropic variant of the kernel) or a vector with the same number of dimensions as the inputs X (anisotropic variant of the kernel). The kernel is given by: k(x_i, x_j) = exp(-1 / 2 d(x_i / length_scale, x_j / length_scale)^2) This kernel is infinitely differentiable, which implies that GPs with this kernel as covariance function have mean square derivatives of all orders, and are thus very smooth. .. versionadded:: 0.18 Parameters ----------- length_scale : float or array with shape (n_features,), default: 1.0 The length scale of the kernel. If a float, an isotropic kernel is used. If an array, an anisotropic kernel is used where each dimension of l defines the length-scale of the respective feature dimension. length_scale_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on length_scale """ def __init__(self, length_scale=1.0, length_scale_bounds=(1e-5, 1e5)): self.length_scale = length_scale self.length_scale_bounds = length_scale_bounds @property def anisotropic(self): return np.iterable(self.length_scale) and len(self.length_scale) > 1 @property def hyperparameter_length_scale(self): if self.anisotropic: return Hyperparameter("length_scale", "numeric", self.length_scale_bounds, len(self.length_scale)) return Hyperparameter( "length_scale", "numeric", self.length_scale_bounds) def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Only supported when Y is None. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ X = np.atleast_2d(X) length_scale = _check_length_scale(X, self.length_scale) if Y is None: dists = pdist(X / length_scale, metric='sqeuclidean') K = np.exp(-.5 * dists) # convert from upper-triangular matrix to square matrix K = squareform(K) np.fill_diagonal(K, 1) else: if eval_gradient: raise ValueError( "Gradient can only be evaluated when Y is None.") dists = cdist(X / length_scale, Y / length_scale, metric='sqeuclidean') K = np.exp(-.5 * dists) if eval_gradient: if self.hyperparameter_length_scale.fixed: # Hyperparameter l kept fixed return K, np.empty((X.shape[0], X.shape[0], 0)) elif not self.anisotropic or length_scale.shape[0] == 1: K_gradient = \ (K * squareform(dists))[:, :, np.newaxis] return K, K_gradient elif self.anisotropic: # We need to recompute the pairwise dimension-wise distances K_gradient = (X[:, np.newaxis, :] - X[np.newaxis, :, :]) ** 2 \ / (length_scale ** 2) K_gradient *= K[..., np.newaxis] return K, K_gradient else: return K def __repr__(self): if self.anisotropic: return "{0}(length_scale=[{1}])".format( self.__class__.__name__, ", ".join(map("{0:.3g}".format, self.length_scale))) else: # isotropic return "{0}(length_scale={1:.3g})".format( self.__class__.__name__, np.ravel(self.length_scale)[0]) class Matern(RBF): """ Matern kernel. The class of Matern kernels is a generalization of the RBF and the absolute exponential kernel parameterized by an additional parameter nu. The smaller nu, the less smooth the approximated function is. For nu=inf, the kernel becomes equivalent to the RBF kernel and for nu=0.5 to the absolute exponential kernel. Important intermediate values are nu=1.5 (once differentiable functions) and nu=2.5 (twice differentiable functions). See Rasmussen and Williams 2006, pp84 for details regarding the different variants of the Matern kernel. .. versionadded:: 0.18 Parameters ----------- length_scale : float or array with shape (n_features,), default: 1.0 The length scale of the kernel. If a float, an isotropic kernel is used. If an array, an anisotropic kernel is used where each dimension of l defines the length-scale of the respective feature dimension. length_scale_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on length_scale nu: float, default: 1.5 The parameter nu controlling the smoothness of the learned function. The smaller nu, the less smooth the approximated function is. For nu=inf, the kernel becomes equivalent to the RBF kernel and for nu=0.5 to the absolute exponential kernel. Important intermediate values are nu=1.5 (once differentiable functions) and nu=2.5 (twice differentiable functions). Note that values of nu not in [0.5, 1.5, 2.5, inf] incur a considerably higher computational cost (appr. 10 times higher) since they require to evaluate the modified Bessel function. Furthermore, in contrast to l, nu is kept fixed to its initial value and not optimized. """ def __init__(self, length_scale=1.0, length_scale_bounds=(1e-5, 1e5), nu=1.5): super(Matern, self).__init__(length_scale, length_scale_bounds) self.nu = nu def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Only supported when Y is None. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ X = np.atleast_2d(X) length_scale = _check_length_scale(X, self.length_scale) if Y is None: dists = pdist(X / length_scale, metric='euclidean') else: if eval_gradient: raise ValueError( "Gradient can only be evaluated when Y is None.") dists = cdist(X / length_scale, Y / length_scale, metric='euclidean') if self.nu == 0.5: K = np.exp(-dists) elif self.nu == 1.5: K = dists * math.sqrt(3) K = (1. + K) * np.exp(-K) elif self.nu == 2.5: K = dists * math.sqrt(5) K = (1. + K + K ** 2 / 3.0) * np.exp(-K) else: # general case; expensive to evaluate K = dists K[K == 0.0] += np.finfo(float).eps # strict zeros result in nan tmp = (math.sqrt(2 * self.nu) * K) K.fill((2 ** (1. - self.nu)) / gamma(self.nu)) K *= tmp ** self.nu K *= kv(self.nu, tmp) if Y is None: # convert from upper-triangular matrix to square matrix K = squareform(K) np.fill_diagonal(K, 1) if eval_gradient: if self.hyperparameter_length_scale.fixed: # Hyperparameter l kept fixed K_gradient = np.empty((X.shape[0], X.shape[0], 0)) return K, K_gradient # We need to recompute the pairwise dimension-wise distances if self.anisotropic: D = (X[:, np.newaxis, :] - X[np.newaxis, :, :])**2 \ / (length_scale ** 2) else: D = squareform(dists**2)[:, :, np.newaxis] if self.nu == 0.5: K_gradient = K[..., np.newaxis] * D \ / np.sqrt(D.sum(2))[:, :, np.newaxis] K_gradient[~np.isfinite(K_gradient)] = 0 elif self.nu == 1.5: K_gradient = \ 3 * D * np.exp(-np.sqrt(3 * D.sum(-1)))[..., np.newaxis] elif self.nu == 2.5: tmp = np.sqrt(5 * D.sum(-1))[..., np.newaxis] K_gradient = 5.0 / 3.0 * D * (tmp + 1) * np.exp(-tmp) else: # approximate gradient numerically def f(theta): # helper function return self.clone_with_theta(theta)(X, Y) return K, _approx_fprime(self.theta, f, 1e-10) if not self.anisotropic: return K, K_gradient[:, :].sum(-1)[:, :, np.newaxis] else: return K, K_gradient else: return K def __repr__(self): if self.anisotropic: return "{0}(length_scale=[{1}], nu={2:.3g})".format( self.__class__.__name__, ", ".join(map("{0:.3g}".format, self.length_scale)), self.nu) else: return "{0}(length_scale={1:.3g}, nu={2:.3g})".format( self.__class__.__name__, np.ravel(self.length_scale)[0], self.nu) class RationalQuadratic(StationaryKernelMixin, NormalizedKernelMixin, Kernel): """Rational Quadratic kernel. The RationalQuadratic kernel can be seen as a scale mixture (an infinite sum) of RBF kernels with different characteristic length-scales. It is parameterized by a length-scale parameter length_scale>0 and a scale mixture parameter alpha>0. Only the isotropic variant where length_scale is a scalar is supported at the moment. The kernel given by: k(x_i, x_j) = (1 + d(x_i, x_j)^2 / (2*alpha * length_scale^2))^-alpha .. versionadded:: 0.18 Parameters ---------- length_scale : float > 0, default: 1.0 The length scale of the kernel. alpha : float > 0, default: 1.0 Scale mixture parameter length_scale_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on length_scale alpha_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on alpha """ def __init__(self, length_scale=1.0, alpha=1.0, length_scale_bounds=(1e-5, 1e5), alpha_bounds=(1e-5, 1e5)): self.length_scale = length_scale self.alpha = alpha self.length_scale_bounds = length_scale_bounds self.alpha_bounds = alpha_bounds @property def hyperparameter_length_scale(self): return Hyperparameter( "length_scale", "numeric", self.length_scale_bounds) @property def hyperparameter_alpha(self): return Hyperparameter("alpha", "numeric", self.alpha_bounds) def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Only supported when Y is None. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ X = np.atleast_2d(X) if Y is None: dists = squareform(pdist(X, metric='sqeuclidean')) tmp = dists / (2 * self.alpha * self.length_scale ** 2) base = (1 + tmp) K = base ** -self.alpha np.fill_diagonal(K, 1) else: if eval_gradient: raise ValueError( "Gradient can only be evaluated when Y is None.") dists = cdist(X, Y, metric='sqeuclidean') K = (1 + dists / (2 * self.alpha * self.length_scale ** 2)) \ ** -self.alpha if eval_gradient: # gradient with respect to length_scale if not self.hyperparameter_length_scale.fixed: length_scale_gradient = \ dists * K / (self.length_scale ** 2 * base) length_scale_gradient = length_scale_gradient[:, :, np.newaxis] else: # l is kept fixed length_scale_gradient = np.empty((K.shape[0], K.shape[1], 0)) # gradient with respect to alpha if not self.hyperparameter_alpha.fixed: alpha_gradient = \ K * (-self.alpha * np.log(base) + dists / (2 * self.length_scale ** 2 * base)) alpha_gradient = alpha_gradient[:, :, np.newaxis] else: # alpha is kept fixed alpha_gradient = np.empty((K.shape[0], K.shape[1], 0)) return K, np.dstack((alpha_gradient, length_scale_gradient)) else: return K def __repr__(self): return "{0}(alpha={1:.3g}, length_scale={2:.3g})".format( self.__class__.__name__, self.alpha, self.length_scale) class ExpSineSquared(StationaryKernelMixin, NormalizedKernelMixin, Kernel): """Exp-Sine-Squared kernel. The ExpSineSquared kernel allows modeling periodic functions. It is parameterized by a length-scale parameter length_scale>0 and a periodicity parameter periodicity>0. Only the isotropic variant where l is a scalar is supported at the moment. The kernel given by: k(x_i, x_j) = exp(-2 sin(\pi / periodicity * d(x_i, x_j)) / length_scale)^2 .. versionadded:: 0.18 Parameters ---------- length_scale : float > 0, default: 1.0 The length scale of the kernel. periodicity : float > 0, default: 1.0 The periodicity of the kernel. length_scale_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on length_scale periodicity_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on periodicity """ def __init__(self, length_scale=1.0, periodicity=1.0, length_scale_bounds=(1e-5, 1e5), periodicity_bounds=(1e-5, 1e5)): self.length_scale = length_scale self.periodicity = periodicity self.length_scale_bounds = length_scale_bounds self.periodicity_bounds = periodicity_bounds @property def hyperparameter_length_scale(self): return Hyperparameter( "length_scale", "numeric", self.length_scale_bounds) @property def hyperparameter_periodicity(self): return Hyperparameter( "periodicity", "numeric", self.periodicity_bounds) def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Only supported when Y is None. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ X = np.atleast_2d(X) if Y is None: dists = squareform(pdist(X, metric='euclidean')) arg = np.pi * dists / self.periodicity sin_of_arg = np.sin(arg) K = np.exp(- 2 * (sin_of_arg / self.length_scale) ** 2) else: if eval_gradient: raise ValueError( "Gradient can only be evaluated when Y is None.") dists = cdist(X, Y, metric='euclidean') K = np.exp(- 2 * (np.sin(np.pi / self.periodicity * dists) / self.length_scale) ** 2) if eval_gradient: cos_of_arg = np.cos(arg) # gradient with respect to length_scale if not self.hyperparameter_length_scale.fixed: length_scale_gradient = \ 4 / self.length_scale**2 * sin_of_arg**2 * K length_scale_gradient = length_scale_gradient[:, :, np.newaxis] else: # length_scale is kept fixed length_scale_gradient = np.empty((K.shape[0], K.shape[1], 0)) # gradient with respect to p if not self.hyperparameter_periodicity.fixed: periodicity_gradient = \ 4 * arg / self.length_scale**2 * cos_of_arg \ * sin_of_arg * K periodicity_gradient = periodicity_gradient[:, :, np.newaxis] else: # p is kept fixed periodicity_gradient = np.empty((K.shape[0], K.shape[1], 0)) return K, np.dstack((length_scale_gradient, periodicity_gradient)) else: return K def __repr__(self): return "{0}(length_scale={1:.3g}, periodicity={2:.3g})".format( self.__class__.__name__, self.length_scale, self.periodicity) class DotProduct(Kernel): """Dot-Product kernel. The DotProduct kernel is non-stationary and can be obtained from linear regression by putting N(0, 1) priors on the coefficients of x_d (d = 1, . . . , D) and a prior of N(0, \sigma_0^2) on the bias. The DotProduct kernel is invariant to a rotation of the coordinates about the origin, but not translations. It is parameterized by a parameter sigma_0^2. For sigma_0^2 =0, the kernel is called the homogeneous linear kernel, otherwise it is inhomogeneous. The kernel is given by k(x_i, x_j) = sigma_0 ^ 2 + x_i \cdot x_j The DotProduct kernel is commonly combined with exponentiation. .. versionadded:: 0.18 Parameters ---------- sigma_0 : float >= 0, default: 1.0 Parameter controlling the inhomogenity of the kernel. If sigma_0=0, the kernel is homogenous. sigma_0_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on l """ def __init__(self, sigma_0=1.0, sigma_0_bounds=(1e-5, 1e5)): self.sigma_0 = sigma_0 self.sigma_0_bounds = sigma_0_bounds @property def hyperparameter_sigma_0(self): return Hyperparameter("sigma_0", "numeric", self.sigma_0_bounds) def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Only supported when Y is None. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ X = np.atleast_2d(X) if Y is None: K = np.inner(X, X) + self.sigma_0 ** 2 else: if eval_gradient: raise ValueError( "Gradient can only be evaluated when Y is None.") K = np.inner(X, Y) + self.sigma_0 ** 2 if eval_gradient: if not self.hyperparameter_sigma_0.fixed: K_gradient = np.empty((K.shape[0], K.shape[1], 1)) K_gradient[..., 0] = 2 * self.sigma_0 ** 2 return K, K_gradient else: return K, np.empty((X.shape[0], X.shape[0], 0)) else: return K def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ return np.einsum('ij,ij->i', X, X) + self.sigma_0 ** 2 def is_stationary(self): """Returns whether the kernel is stationary. """ return False def __repr__(self): return "{0}(sigma_0={1:.3g})".format( self.__class__.__name__, self.sigma_0) # adapted from scipy/optimize/optimize.py for functions with 2d output def _approx_fprime(xk, f, epsilon, args=()): f0 = f(*((xk,) + args)) grad = np.zeros((f0.shape[0], f0.shape[1], len(xk)), float) ei = np.zeros((len(xk), ), float) for k in range(len(xk)): ei[k] = 1.0 d = epsilon * ei grad[:, :, k] = (f(*((xk + d,) + args)) - f0) / d[k] ei[k] = 0.0 return grad class PairwiseKernel(Kernel): """Wrapper for kernels in sklearn.metrics.pairwise. A thin wrapper around the functionality of the kernels in sklearn.metrics.pairwise. Note: Evaluation of eval_gradient is not analytic but numeric and all kernels support only isotropic distances. The parameter gamma is considered to be a hyperparameter and may be optimized. The other kernel parameters are set directly at initialization and are kept fixed. .. versionadded:: 0.18 Parameters ---------- gamma: float >= 0, default: 1.0 Parameter gamma of the pairwise kernel specified by metric gamma_bounds : pair of floats >= 0, default: (1e-5, 1e5) The lower and upper bound on gamma metric : string, or callable, default: "linear" The metric to use when calculating kernel between instances in a feature array. If metric is a string, it must be one of the metrics in pairwise.PAIRWISE_KERNEL_FUNCTIONS. If metric is "precomputed", X is assumed to be a kernel matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from X as input and return a value indicating the distance between them. pairwise_kernels_kwargs : dict, default: None All entries of this dict (if any) are passed as keyword arguments to the pairwise kernel function. """ def __init__(self, gamma=1.0, gamma_bounds=(1e-5, 1e5), metric="linear", pairwise_kernels_kwargs=None): self.gamma = gamma self.gamma_bounds = gamma_bounds self.metric = metric self.pairwise_kernels_kwargs = pairwise_kernels_kwargs @property def hyperparameter_gamma(self): return Hyperparameter("gamma", "numeric", self.gamma_bounds) def __call__(self, X, Y=None, eval_gradient=False): """Return the kernel k(X, Y) and optionally its gradient. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Y : array, shape (n_samples_Y, n_features), (optional, default=None) Right argument of the returned kernel k(X, Y). If None, k(X, X) if evaluated instead. eval_gradient : bool (optional, default=False) Determines whether the gradient with respect to the kernel hyperparameter is determined. Only supported when Y is None. Returns ------- K : array, shape (n_samples_X, n_samples_Y) Kernel k(X, Y) K_gradient : array (opt.), shape (n_samples_X, n_samples_X, n_dims) The gradient of the kernel k(X, X) with respect to the hyperparameter of the kernel. Only returned when eval_gradient is True. """ pairwise_kernels_kwargs = self.pairwise_kernels_kwargs if self.pairwise_kernels_kwargs is None: pairwise_kernels_kwargs = {} X = np.atleast_2d(X) K = pairwise_kernels(X, Y, metric=self.metric, gamma=self.gamma, filter_params=True, **pairwise_kernels_kwargs) if eval_gradient: if self.hyperparameter_gamma.fixed: return K, np.empty((X.shape[0], X.shape[0], 0)) else: # approximate gradient numerically def f(gamma): # helper function return pairwise_kernels( X, Y, metric=self.metric, gamma=np.exp(gamma), filter_params=True, **pairwise_kernels_kwargs) return K, _approx_fprime(self.theta, f, 1e-10) else: return K def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ # We have to fall back to slow way of computing diagonal return np.apply_along_axis(self, 1, X).ravel() def is_stationary(self): """Returns whether the kernel is stationary. """ return self.metric in ["rbf"] def __repr__(self): return "{0}(gamma={1}, metric={2})".format( self.__class__.__name__, self.gamma, self.metric)
architecture-building-systems/CityEnergyAnalyst
refs/heads/master
cea/interfaces/dashboard/api/utils.py
2
from flask import current_app import cea.config import cea.inputlocator def deconstruct_parameters(p): params = {'name': p.name, 'type': p.typename, 'value': p.get(), 'help': p.help} if isinstance(p, cea.config.ChoiceParameter): params['choices'] = p._choices if p.typename == 'WeatherPathParameter': config = current_app.cea_config locator = cea.inputlocator.InputLocator(config.scenario) params['choices'] = {wn: locator.get_weather( wn) for wn in locator.get_weather_names()} elif p.typename == 'DatabasePathParameter': params['choices'] = p._choices return params
maurossi/deqp
refs/heads/ndk_r10d_compatible
scripts/launchcontrol_build.py
2
# -*- coding: utf-8 -*- #------------------------------------------------------------------------- # drawElements Quality Program utilities # -------------------------------------- # # Copyright 2015 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #------------------------------------------------------------------------- import os from build.common import * from build.build import * from argparse import ArgumentParser import multiprocessing # This is a bit silly, but CMake needs to know the word width prior to # parsing the project files, hence cannot use our own defines. X86_64_ARGS = ["-DDE_CPU=DE_CPU_X86_64", "-DCMAKE_C_FLAGS=-m64", "-DCMAKE_CXX_FLAGS=-m64"] BUILD_CONFIGS = { "gcc-x86_64-x11_glx": X86_64_ARGS + ["-DDEQP_TARGET=x11_glx"], "clang-x86_64-x11_glx": X86_64_ARGS + ["-DDEQP_TARGET=x11_glx", "-DCMAKE_C_COMPILER=clang", "-DCMAKE_CXX_COMPILER=clang++"] } def buildWithMake (workingDir): pushWorkingDir(workingDir) # CMake docs advised this to be the best magic formula... threadCount = multiprocessing.cpu_count() + 1 print "Invoke make with %d threads" % threadCount execute(["make", "-j%d" % threadCount]) popWorkingDir() def parseOptions (): parser = ArgumentParser() parser.add_argument("-d", "--build-dir", dest="buildDir", default="out", help="Temporary build directory") parser.add_argument("-c", "--config", dest="config", choices=BUILD_CONFIGS.keys(), required=True, help="Build configuration name") parser.add_argument("-t", "--build-type", dest="buildType", choices=["Debug", "Release"], default="Debug", help="Build type") return parser.parse_args() if __name__ == "__main__": options = parseOptions() print "\n############################################################" print "# %s %s BUILD" % (options.config.upper(), options.buildType.upper()) print "############################################################\n" buildDir = os.path.realpath(os.path.normpath(options.buildDir)) config = BuildConfig(buildDir, options.buildType, BUILD_CONFIGS[options.config]) initBuildDir(config, MAKEFILE_GENERATOR) buildWithMake(buildDir) print "\n--- BUILD SCRIPT COMPLETE"
mvaled/OpenUpgrade
refs/heads/8.0
addons/base_import_module/controllers/main.py
354
# -*- coding: utf-8 -*- import functools import openerp from openerp.http import Controller, route, request, Response def webservice(f): @functools.wraps(f) def wrap(*args, **kw): try: return f(*args, **kw) except Exception, e: return Response(response=str(e), status=500) return wrap class ImportModule(Controller): def check_user(self, uid=None): if uid is None: uid = request.uid is_admin = request.registry['res.users'].has_group(request.cr, uid, 'base.group_erp_manager') if not is_admin: raise openerp.exceptions.AccessError("Only administrators can upload a module") @route('/base_import_module/login', type='http', auth='none', methods=['POST']) @webservice def login(self, login, password, db=None): if db and db != request.db: raise Exception("Could not select database '%s'" % db) uid = request.session.authenticate(request.db, login, password) if not uid: return Response(response="Wrong login/password", status=401) self.check_user(uid) return "ok" @route('/base_import_module/upload', type='http', auth='user', methods=['POST']) @webservice def upload(self, mod_file=None, force='', **kw): self.check_user() force = True if force == '1' else False return request.registry['ir.module.module'].import_zipfile(request.cr, request.uid, mod_file, force=force, context=request.context)[0]
etherkit/OpenBeacon2
refs/heads/master
client/win/venv/Lib/site-packages/PyInstaller/configure.py
2
#----------------------------------------------------------------------------- # Copyright (c) 2005-2019, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- """ Configure PyInstaller for the current Python installation. """ import os from . import compat from . import log as logging from .compat import is_win, is_darwin logger = logging.getLogger(__name__) def test_UPX(config, upx_dir): logger.debug('Testing for UPX ...') cmd = "upx" if upx_dir: cmd = os.path.normpath(os.path.join(upx_dir, cmd)) hasUPX = 0 try: vers = compat.exec_command( cmd, '-V', __raise_ENOENT__=True).strip().splitlines() if vers: v = vers[0].split()[1] hasUPX = tuple(map(int, v.split("."))) if is_win and hasUPX < (1, 92): logger.error('UPX is too old! Python 2.4 under Windows requires UPX 1.92+') hasUPX = 0 except Exception as e: if isinstance(e, OSError) and e.errno == 2: # No such file or directory pass else: logger.info('An exception occured when testing for UPX:') logger.info(' %r', e) if hasUPX: is_available = 'available' else: is_available = 'not available' logger.info('UPX is %s.', is_available) config['hasUPX'] = hasUPX config['upx_dir'] = upx_dir def _get_pyinst_cache_dir(): old_cache_dir = None if compat.getenv('PYINSTALLER_CONFIG_DIR'): cache_dir = compat.getenv('PYINSTALLER_CONFIG_DIR') elif is_win: cache_dir = compat.getenv('APPDATA') if not cache_dir: cache_dir = os.path.expanduser('~\\Application Data') elif is_darwin: cache_dir = os.path.expanduser('~/Library/Application Support') else: # According to XDG specification # http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html old_cache_dir = compat.getenv('XDG_DATA_HOME') if not old_cache_dir: old_cache_dir = os.path.expanduser('~/.local/share') cache_dir = compat.getenv('XDG_CACHE_HOME') if not cache_dir: cache_dir = os.path.expanduser('~/.cache') cache_dir = os.path.join(cache_dir, 'pyinstaller') # Move old cache-dir, if any, to now location if old_cache_dir and not os.path.exists(cache_dir): old_cache_dir = os.path.join(old_cache_dir, 'pyinstaller') if os.path.exists(old_cache_dir): parent_dir = os.path.dirname(cache_dir) if not os.path.exists(parent_dir): os.makedirs(parent_dir) os.rename(old_cache_dir, cache_dir) return cache_dir #FIXME: Rename to get_official_hooks_dir(). #FIXME: Remove the "hook_type" parameter after unifying hook types. def get_importhooks_dir(hook_type=None): from . import PACKAGEPATH if not hook_type: return os.path.join(PACKAGEPATH, 'hooks') else: return os.path.join(PACKAGEPATH, 'hooks', hook_type) def get_config(upx_dir, **kw): config = {} test_UPX(config, upx_dir) config['cachedir'] = _get_pyinst_cache_dir() return config
gangadharkadam/smrtfrappe
refs/heads/develop
frappe/templates/website_group/settings.py
4
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe from frappe.website.permissions import get_access, clear_permissions from frappe.website.doctype.website_group.website_group import get_pathname from frappe.utils.email_lib.bulk import send @frappe.whitelist() def suggest_user(term, group): pathname = get_pathname(group) if not get_access(pathname).get("admin"): raise frappe.PermissionError users = frappe.db.sql("""select pr.name, pr.first_name, pr.last_name, pr.user_image, pr.location from `tabUser` pr where (pr.first_name like %(term)s or pr.last_name like %(term)s) and pr.user_type = "Website User" and pr.user_image is not null and pr.enabled=1 and not exists(select wsp.name from `tabWebsite Route Permission` wsp where wsp.website_route=%(group)s and wsp.user=pr.name)""", {"term": "%{}%".format(term), "group": pathname}, as_dict=True) template = frappe.get_template("templates/includes/user_display.html") return [{ "value": "{} {}".format(pr.first_name or "", pr.last_name or ""), "user_html": template.render({"user": pr}), "user": pr.name } for pr in users] @frappe.whitelist() def add_sitemap_permission(group, user): pathname = get_pathname(group) if not get_access(pathname).get("admin"): raise frappe.PermissionError permission = frappe.get_doc({ "doctype": "Website Route Permission", "website_route": pathname, "user": user, "read": 1 }) permission.insert(ignore_permissions=True) user = permission.as_dict() user.update(frappe.db.get_value("User", user.user, ["name", "first_name", "last_name", "user_image", "location"], as_dict=True)) return frappe.get_template("templates/includes/sitemap_permission.html").render({ "user": user }) @frappe.whitelist() def update_permission(group, user, perm, value): pathname = get_pathname(group) if not get_access(pathname).get("admin"): raise frappe.PermissionError permission = frappe.get_doc("Website Route Permission", {"website_route": pathname, "user": user}) permission.set(perm, int(value)) permission.save(ignore_permissions=True) # send email if perm=="admin" and int(value): group_title = frappe.db.get_value("Website Route", pathname, "page_title") subject = "You have been made Administrator of Group " + group_title send(recipients=[user], subject= subject, add_unsubscribe_link=False, message="""<h3>Group Notification<h3>\ <p>%s</p>\ <p style="color: #888">This is just for your information.</p>""" % subject) @frappe.whitelist() def update_description(group, description): if not get_access(get_pathname(group)).get("admin"): raise frappe.PermissionError group = frappe.get_doc("Website Group", group) group.group_description = description group.save(ignore_permissions=True) @frappe.whitelist() def add_website_group(group, new_group, public_read, public_write, group_type="Forum"): if not get_access(get_pathname(group)).get("admin"): raise frappe.PermissionError parent_website_route = frappe.db.get_value("Website Route", {"ref_doctype": "Website Group", "docname": group}) frappe.get_doc({ "doctype": "Website Group", "group_name": group + "-" + new_group, "group_title": new_group, "parent_website_route": parent_website_route, "group_type": group_type, "public_read": int(public_read), "public_write": int(public_write) }).insert(ignore_permissions=True)
djangorussia/django-1.3-branch
refs/heads/master
django/contrib/gis/forms/__init__.py
518
from django.forms import * from django.contrib.gis.forms.fields import GeometryField
Destaneon/python-fundamentals
refs/heads/master
challenges/01-Intro/B_data_and_variables.py
3
# your code here is evaluated by py.test test_B_data_and_variables # instructors ## what are our names? instructors = '' # types ## Now define some other types of variables ## some_int should be an integer ## some_float should be a float ## some_bool should be... what do you think? # redefining ## Here, I define a variable my_lucky_number = 7 ## But Dav's lucky number is 9 (and he wrote the test) ## Redefine the value "correctly" below ## Only the most recent variable assignment matters print "Dav's lucky number:", my_lucky_number
NullScope/BorderlessStone
refs/heads/master
tests/multipackage/test_multipackage3.py
77
#----------------------------------------------------------------------------- # Copyright (c) 2013, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import os import sys import httplib import gzip def main(): print('Hello World!') if __name__ == '__main__': main()
mishudark/openhealt
refs/heads/master
mongoengine/base/common.py
43
from mongoengine.errors import NotRegistered __all__ = ('ALLOW_INHERITANCE', 'get_document', '_document_registry') ALLOW_INHERITANCE = False _document_registry = {} def get_document(name): doc = _document_registry.get(name, None) if not doc: # Possible old style name single_end = name.split('.')[-1] compound_end = '.%s' % single_end possible_match = [k for k in _document_registry.keys() if k.endswith(compound_end) or k == single_end] if len(possible_match) == 1: doc = _document_registry.get(possible_match.pop(), None) if not doc: raise NotRegistered(""" `%s` has not been registered in the document registry. Importing the document class automatically registers it, has it been imported? """.strip() % name) return doc
deltreey/ansible
refs/heads/devel
v1/ansible/errors.py
111
# (c) 2012-2014, Michael DeHaan <michael.dehaan@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 # along with Ansible. If not, see <http://www.gnu.org/licenses/>. class AnsibleError(Exception): ''' The base Ansible exception from which all others should subclass ''' pass class AnsibleFileNotFound(AnsibleError): pass class AnsibleConnectionFailed(AnsibleError): pass class AnsibleYAMLValidationFailed(AnsibleError): pass class AnsibleUndefinedVariable(AnsibleError): pass class AnsibleFilterError(AnsibleError): pass
IBCCW/plen2__ble_motion_installer_python
refs/heads/master
make.py
1
# -*- coding: utf-8 -*- from distutils.core import setup import py2exe option = { "compressed" : 1, "optimize" : 2, "bundle_files" : 1 } setup( options = { "py2exe" : option }, console = [ { "script" : "main.py" } ], zipfile = None )
Seeker1911/talent
refs/heads/master
server/talent/migrations/0001_initial.py
1
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-17 23:45 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import phonenumber_field.modelfields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Events', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('email', models.EmailField(max_length=254, verbose_name='email')), ('phone', phonenumber_field.modelfields.PhoneNumberField(blank=True, max_length=128)), ('social', models.CharField(default=0, max_length=200)), ('genre', models.CharField(default=0, max_length=200)), ('location', models.CharField(default=0, max_length=200)), ], options={ 'ordering': ('name',), }, ), migrations.CreateModel( name='Musicians', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('phone', models.CharField(max_length=15, null=True)), ('social', models.CharField(blank=True, max_length=200, null=True)), ('genre', models.CharField(blank=True, max_length=200, null=True)), ('company', models.CharField(blank=True, max_length=200, null=True)), ('engineering', models.BooleanField(default=False)), ('artistDevelopment', models.BooleanField(default=False)), ('bio', models.TextField(blank=True, max_length=500, null=True)), ('location', models.CharField(blank=True, max_length=30, null=True)), ('user', models.OneToOneField(default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('user',), }, ), migrations.CreateModel( name='Song', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('genre', models.CharField(default=0, max_length=200)), ('length', models.CharField(default=0, max_length=8)), ('artist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='songs', to='talent.Musicians')), ], options={ 'ordering': ('title',), }, ), migrations.AddField( model_name='events', name='musician', field=models.ManyToManyField(related_name='events', to='talent.Musicians'), ), ]
thisissoon/Flask-HAL
refs/heads/master
tests/test_init.py
1
#!/usr/bin/env python # encoding: utf-8 """ tests.test_init =============== Tests for the init module. """ # Standard Libs import json # Third Party Libs from flask import Flask, Response # First Party Libs from flask_hal import HAL, HALResponse, document class TestHAL(object): def test_init(self): app = Flask(__name__) HAL(app) assert app.response_class == HALResponse def test_can_set_custom_response_class(self): app = Flask(__name__) HAL(app, Response) assert app.response_class == Response class TestHalResponse(object): def test_returns_document_with_hal_document(self): app = Flask(__name__) with app.test_request_context(): d = document.Document() r = HALResponse.force_type(d, {}) expected = json.dumps({ '_links': { 'self': { 'href': '/' } } }) assert isinstance(r, Response) assert r.headers['Content-Type'] == 'application/hal+json' assert r.data.decode("utf-8") == expected def test_returns_standard_response(self): r = HALResponse.force_type(Response('foo'), {}) assert isinstance(r, Response) assert r.headers['Content-Type'] == 'text/html; charset=utf-8' assert r.data.decode("utf-8") == 'foo'
blacklin/kbengine
refs/heads/master
kbe/res/scripts/common/Lib/site-packages/setuptools/command/install.py
206
import setuptools import sys import glob from distutils.command.install import install as _install from distutils.errors import DistutilsArgError class install(_install): """Use easy_install to install the package, w/dependencies""" user_options = _install.user_options + [ ('old-and-unmanageable', None, "Try not to use this!"), ('single-version-externally-managed', None, "used by system package builders to create 'flat' eggs"), ] boolean_options = _install.boolean_options + [ 'old-and-unmanageable', 'single-version-externally-managed', ] new_commands = [ ('install_egg_info', lambda self: True), ('install_scripts', lambda self: True), ] _nc = dict(new_commands) def initialize_options(self): _install.initialize_options(self) self.old_and_unmanageable = None self.single_version_externally_managed = None self.no_compile = None # make DISTUTILS_DEBUG work right! def finalize_options(self): _install.finalize_options(self) if self.root: self.single_version_externally_managed = True elif self.single_version_externally_managed: if not self.root and not self.record: raise DistutilsArgError( "You must specify --record or --root when building system" " packages" ) def handle_extra_path(self): if self.root or self.single_version_externally_managed: # explicit backward-compatibility mode, allow extra_path to work return _install.handle_extra_path(self) # Ignore extra_path when installing an egg (or being run by another # command without --root or --single-version-externally-managed self.path_file = None self.extra_dirs = '' def run(self): # Explicit request for old-style install? Just do it if self.old_and_unmanageable or self.single_version_externally_managed: return _install.run(self) # Attempt to detect whether we were called from setup() or by another # command. If we were called by setup(), our caller will be the # 'run_command' method in 'distutils.dist', and *its* caller will be # the 'run_commands' method. If we were called any other way, our # immediate caller *might* be 'run_command', but it won't have been # called by 'run_commands'. This is slightly kludgy, but seems to # work. # caller = sys._getframe(2) caller_module = caller.f_globals.get('__name__','') caller_name = caller.f_code.co_name if caller_module != 'distutils.dist' or caller_name!='run_commands': # We weren't called from the command line or setup(), so we # should run in backward-compatibility mode to support bdist_* # commands. _install.run(self) else: self.do_egg_install() def do_egg_install(self): easy_install = self.distribution.get_command_class('easy_install') cmd = easy_install( self.distribution, args="x", root=self.root, record=self.record, ) cmd.ensure_finalized() # finalize before bdist_egg munges install cmd cmd.always_copy_from = '.' # make sure local-dir eggs get installed # pick up setup-dir .egg files only: no .egg-info cmd.package_index.scan(glob.glob('*.egg')) self.run_command('bdist_egg') args = [self.distribution.get_command_obj('bdist_egg').egg_output] if setuptools.bootstrap_install_from: # Bootstrap self-installation of setuptools args.insert(0, setuptools.bootstrap_install_from) cmd.args = args cmd.run() setuptools.bootstrap_install_from = None # XXX Python 3.1 doesn't see _nc if this is inside the class install.sub_commands = [ cmd for cmd in _install.sub_commands if cmd[0] not in install._nc ] + install.new_commands
paxet/pyglins
refs/heads/master
test/__init__.py
1
# -*- coding: utf-8 -*- import pyglins pyglins.scan_for_plugins('test/plugins') for plugin in pyglins.BasePlugin.plugins: loaded_plugin = plugin() print('Starting {}'.format(loaded_plugin.name)) loaded_plugin.run()
Zhongqilong/kbengine
refs/heads/master
kbe/src/lib/python/Tools/pybench/Lookups.py
92
from pybench import Test class SpecialClassAttribute(Test): version = 2.0 operations = 5*(12 + 12) rounds = 100000 def test(self): class c: pass for i in range(self.rounds): c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 c.__a = 2 c.__b = 3 c.__c = 4 x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c x = c.__a x = c.__b x = c.__c def calibrate(self): class c: pass for i in range(self.rounds): pass class NormalClassAttribute(Test): version = 2.0 operations = 5*(12 + 12) rounds = 100000 def test(self): class c: pass for i in range(self.rounds): c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 c.a = 2 c.b = 3 c.c = 4 x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c x = c.a x = c.b x = c.c def calibrate(self): class c: pass for i in range(self.rounds): pass class SpecialInstanceAttribute(Test): version = 2.0 operations = 5*(12 + 12) rounds = 100000 def test(self): class c: pass o = c() for i in range(self.rounds): o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 o.__a__ = 2 o.__b__ = 3 o.__c__ = 4 x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ x = o.__a__ x = o.__b__ x = o.__c__ def calibrate(self): class c: pass o = c() for i in range(self.rounds): pass class NormalInstanceAttribute(Test): version = 2.0 operations = 5*(12 + 12) rounds = 100000 def test(self): class c: pass o = c() for i in range(self.rounds): o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 o.a = 2 o.b = 3 o.c = 4 x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c x = o.a x = o.b x = o.c def calibrate(self): class c: pass o = c() for i in range(self.rounds): pass class BuiltinMethodLookup(Test): version = 2.0 operations = 5*(3*5 + 3*5) rounds = 70000 def test(self): l = [] d = {} for i in range(self.rounds): l.append l.append l.append l.append l.append l.insert l.insert l.insert l.insert l.insert l.sort l.sort l.sort l.sort l.sort # d.has_key # d.has_key # d.has_key # d.has_key # d.has_key d.items d.items d.items d.items d.items d.get d.get d.get d.get d.get l.append l.append l.append l.append l.append l.insert l.insert l.insert l.insert l.insert l.sort l.sort l.sort l.sort l.sort # d.has_key # d.has_key # d.has_key # d.has_key # d.has_key d.items d.items d.items d.items d.items d.get d.get d.get d.get d.get l.append l.append l.append l.append l.append l.insert l.insert l.insert l.insert l.insert l.sort l.sort l.sort l.sort l.sort # d.has_key # d.has_key # d.has_key # d.has_key # d.has_key d.items d.items d.items d.items d.items d.get d.get d.get d.get d.get l.append l.append l.append l.append l.append l.insert l.insert l.insert l.insert l.insert l.sort l.sort l.sort l.sort l.sort # d.has_key # d.has_key # d.has_key # d.has_key # d.has_key d.items d.items d.items d.items d.items d.get d.get d.get d.get d.get l.append l.append l.append l.append l.append l.insert l.insert l.insert l.insert l.insert l.sort l.sort l.sort l.sort l.sort # d.has_key # d.has_key # d.has_key # d.has_key # d.has_key d.items d.items d.items d.items d.items d.get d.get d.get d.get d.get def calibrate(self): l = [] d = {} for i in range(self.rounds): pass
fajran/irclogview
refs/heads/master
irclogview/templatetags/irclogview_tags.py
1
import datetime from collections import defaultdict from datetime import timedelta from django import template from django.core.urlresolvers import reverse from django.conf import settings register = template.Library() def build_calendar_table(year, month): # Determine last day of the month one_day = timedelta(days=1) start = datetime.date(year, month, 1) if month == 12: last = datetime.date(year, 12, 31) else: last = datetime.date(year, month+1, 1) - one_day # Build calendar table date = start weekday = 0 rows = [] cols = [] while date <= last: while weekday < date.weekday(): cols.append(date - timedelta(days=(date.weekday() - weekday))) weekday += 1 cols.append(date) date += one_day weekday += 1 if weekday == 7: rows.append(cols) cols = [] weekday = 0 if weekday != 0 and weekday < 7: add = 1 while weekday < 7: cols.append(last + timedelta(days=add)) add += 1 weekday += 1 rows.append(cols) return rows @register.simple_tag def log_calendar(dates, today): table = build_calendar_table(today.year, today.month) first = datetime.date(today.year, today.month, 1) if today.month == 12: last = datetime.date(today.year, 12, 31) else: last = datetime.date(today.year, today.month+1, 1) - timedelta(days=1) print today, first, last def cell_builder(date, row, col): classes = ['col-%s' % col] if not date in dates: classes.append('empty') elif date == today: classes.append('today') if date < first: classes.append('prev') elif date > last: classes.append('next') content = '&nbsp;' if date in dates: url = '../%04d%02d%02d/' % (date.year, date.month, date.day) content = '<a href="%s">%s</a>' % (url, date.day) elif date is not None: content = date.day return '<td class="%s">%s</td>' % (' '.join(classes), content) # Previous and next months if today.month == 1: url_prev = '../%04d%02d01/' % (today.year-1, 12) else: url_prev = '../%04d%02d01/' % (today.year, today.month-1) if today.month == 12: url_next = '../%04d%02d01/' % (today.year+1, 1) else: url_next = '../%04d%02d01/' % (today.year, today.month+1) # Construct HTML title = today.strftime('%B %Y') day_names = [datetime.date(2011, 5, day+1).strftime('%A')[0] for day in range(7)] link_prev = '<a href="%s"><img src="%simages/resultset_previous.png"/></a>' % \ (url_prev, settings.MEDIA_URL) link_next = '<a href="%s"><img src="%simages/resultset_next.png"/></a>' % \ (url_next, settings.MEDIA_URL) html = [] html.append('<table class="calendar" border="1">') html.append('<tr class="title"><th colspan="7">%s %s %s</th></tr>' % \ (link_prev, title, link_next)) html.append('<tr>') for day in day_names: html.append('<th>%s</th>' % day) html.append('</tr>') for i, cols in enumerate(table): html.append('<tr>') for j, date in enumerate(cols): html.append(cell_builder(date, i, j)) html.append('</tr>') html.append('</table>') return ''.join(html) @register.simple_tag def bookmark_list(bookmarks): data = defaultdict(list) for bookmark in bookmarks: date = bookmark.log.date month = datetime.date(date.year, date.month, 1) data[month].append(bookmark) months = sorted(data.keys()) html = [] for month in months: items = data[month] html.append('<h2>%s</h2>' % month.strftime('%B %Y')) html.append('<ul>') for item in items: html.append('<li><span>%s</span> - <a href="%s">%s</a></li>' % \ (item.log.date.day, item.get_absolute_url(), item.title)) html.append('</ul>') return ''.join(html)
lowks/simoorg
refs/heads/master
build/lib/simoorg/plugins/topology/KafkaTopology/MetaData.py
8
# # Copyright 2015 LinkedIn Corp. 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. # """ This class represents metadata about a failure scenario in kafka """ class MetaData(object): """ The metadata class """ def __init__(self, broker_type): """ Init function for the MetaData class Args: broker_type - The type of kafka node(broker) Return: None Raise: None """ self.broker_type = broker_type self.partition = None self.topic = None def __str__(self): """ Get the metaData about the failure Return: metadata about the failure Raise: None """ if self.topic is None: return str(self.broker_type) else: return (str(self.broker_type) + " for " + str(self.topic) + "/" + str(self.partition)) def get_partition(self): """ Get the partition id if specified in the failure Return: partition id Raise: None """ return self.partition def get_topic(self): """ Get the topic if specified in the failure Return: topic Raise: None """ return self.topic def set_topic(self, topic): """ Set the topic if specified in the failure Return: None Raise: None """ self.topic = topic def set_partition(self, partition): """ Set the partition id if specified in the failure Return: None Raise: None """ self.partition = partition def get_node_type(self): """ Get the kind of kafka node (broker) specified in the failure Return: None Raise: None """ return self.broker_type
av8ramit/tensorflow
refs/heads/master
tensorflow/contrib/estimator/python/estimator/dnn.py
35
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Deep Neural Network estimators.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.estimator import estimator from tensorflow.python.estimator.canned import dnn as dnn_lib from tensorflow.python.ops import nn class DNNEstimator(estimator.Estimator): """An estimator for TensorFlow DNN models with user-specified head. Example: ```python sparse_feature_a = sparse_column_with_hash_bucket(...) sparse_feature_b = sparse_column_with_hash_bucket(...) sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a, ...) sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b, ...) estimator = DNNEstimator( head=tf.contrib.estimator.multi_label_head(n_classes=3), feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], hidden_units=[1024, 512, 256]) # Or estimator using the ProximalAdagradOptimizer optimizer with # regularization. estimator = DNNEstimator( head=tf.contrib.estimator.multi_label_head(n_classes=3), feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], hidden_units=[1024, 512, 256], optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) # Input builders def input_fn_train: # returns x, y pass estimator.train(input_fn=input_fn_train, steps=100) def input_fn_eval: # returns x, y pass metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10) def input_fn_predict: # returns x, None pass predictions = estimator.predict(input_fn=input_fn_predict) ``` Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`: * if `weight_column` is not `None`, a feature with `key=weight_column` whose value is a `Tensor`. * for each `column` in `feature_columns`: - if `column` is a `_CategoricalColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`. - if `column` is a `_WeightedCategoricalColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`. - if `column` is a `_DenseColumn`, a feature with `key=column.name` whose `value` is a `Tensor`. Loss and predicted output are determined by the specified head. """ def __init__(self, head, hidden_units, feature_columns, model_dir=None, optimizer='Adagrad', activation_fn=nn.relu, dropout=None, input_layer_partitioner=None, config=None): """Initializes a `DNNClassifier` instance. Args: head: A `_Head` instance constructed with a method such as `tf.contrib.estimator.multi_label_head`. hidden_units: Iterable of number hidden units per layer. All layers are fully connected. Ex. `[64, 32]` means first layer has 64 nodes and second one has 32. feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `_FeatureColumn`. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. optimizer: An instance of `tf.Optimizer` used to train the model. Defaults to Adagrad optimizer. activation_fn: Activation function applied to each layer. If `None`, will use `tf.nn.relu`. dropout: When not `None`, the probability we will drop out a given coordinate. input_layer_partitioner: Optional. Partitioner for input layer. Defaults to `min_max_variable_partitioner` with `min_slice_size` 64 << 20. config: `RunConfig` object to configure the runtime settings. """ def _model_fn(features, labels, mode, config): return dnn_lib._dnn_model_fn( # pylint: disable=protected-access features=features, labels=labels, mode=mode, head=head, hidden_units=hidden_units, feature_columns=tuple(feature_columns or []), optimizer=optimizer, activation_fn=activation_fn, dropout=dropout, input_layer_partitioner=input_layer_partitioner, config=config) super(DNNEstimator, self).__init__( model_fn=_model_fn, model_dir=model_dir, config=config)
polimediaupv/edx-platform
refs/heads/master
lms/djangoapps/mobile_api/social_facebook/preferences/urls.py
128
""" URLs for users sharing preferences """ from django.conf.urls import patterns, url from .views import UserSharing urlpatterns = patterns( 'mobile_api.social_facebook.preferences.views', url( r'^preferences/$', UserSharing.as_view(), name='preferences' ), )
davy39/eric
refs/heads/master
Helpviewer/Bookmarks/XbelWriter.py
1
# -*- coding: utf-8 -*- # Copyright (c) 2009 - 2014 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing a class to write XBEL bookmark files. """ from __future__ import unicode_literals from PyQt5.QtCore import QXmlStreamWriter, QIODevice, QFile, Qt from .BookmarkNode import BookmarkNode class XbelWriter(QXmlStreamWriter): """ Class implementing a writer object to generate XBEL bookmark files. """ def __init__(self): """ Constructor """ super(XbelWriter, self).__init__() self.setAutoFormatting(True) def write(self, fileNameOrDevice, root): """ Public method to write an XBEL bookmark file. @param fileNameOrDevice name of the file to write (string) or device to write to (QIODevice) @param root root node of the bookmark tree (BookmarkNode) @return flag indicating success (boolean) """ if isinstance(fileNameOrDevice, QIODevice): f = fileNameOrDevice else: f = QFile(fileNameOrDevice) if root is None or not f.open(QFile.WriteOnly): return False self.setDevice(f) return self.__write(root) def __write(self, root): """ Private method to write an XBEL bookmark file. @param root root node of the bookmark tree (BookmarkNode) @return flag indicating success (boolean) """ self.writeStartDocument() self.writeDTD("<!DOCTYPE xbel>") self.writeStartElement("xbel") self.writeAttribute("version", "1.0") if root.type() == BookmarkNode.Root: for child in root.children(): self.__writeItem(child) else: self.__writeItem(root) self.writeEndDocument() return True def __writeItem(self, node): """ Private method to write an entry for a node. @param node reference to the node to be written (BookmarkNode) """ if node.type() == BookmarkNode.Folder: self.writeStartElement("folder") if node.added.isValid(): self.writeAttribute("added", node.added.toString(Qt.ISODate)) self.writeAttribute("folded", node.expanded and "no" or "yes") self.writeTextElement("title", node.title) for child in node.children(): self.__writeItem(child) self.writeEndElement() elif node.type() == BookmarkNode.Bookmark: self.writeStartElement("bookmark") if node.url: self.writeAttribute("href", node.url) if node.added.isValid(): self.writeAttribute("added", node.added.toString(Qt.ISODate)) if node.modified.isValid(): self.writeAttribute( "modified", node.modified.toString(Qt.ISODate)) if node.visited.isValid(): self.writeAttribute( "visited", node.visited.toString(Qt.ISODate)) self.writeTextElement("title", node.title) if node.desc: self.writeTextElement("desc", node.desc) self.writeEndElement() elif node.type() == BookmarkNode.Separator: self.writeEmptyElement("separator") if node.added.isValid(): self.writeAttribute("added", node.added.toString(Qt.ISODate))
an0ninja/xbmc
refs/heads/master
lib/libUPnP/Neptune/Extras/Tools/Logging/NeptuneLogConsoleMulticast.py
202
#!/usr/bin/env python from struct import * from socket import * from optparse import OptionParser UDP_ADDR = "0.0.0.0" UDP_MULTICAST_ADDR = "239.255.255.100" UDP_PORT = 7724 BUFFER_SIZE = 65536 #HEADER_KEYS = ['Logger', 'Level', 'Source-File', 'Source-Function', 'Source-Line', 'TimeStamp'] HEADER_KEYS = { 'mini': ('Level'), 'standard': ('Logger', 'Level', 'Source-Function'), 'long': ('Logger', 'Level', 'Source-File', 'Source-Line', 'Source-Function'), 'all': ('Logger', 'Level', 'Source-File', 'Source-Line', 'Source-Function', 'TimeStamp'), 'custom': () } Senders = {} class LogRecord: def __init__(self, data): offset = 0 self.headers = {} for line in data.split("\r\n"): offset += len(line)+2 if ':' not in line: break key,value=line.split(":",1) self.headers[key] = value.strip() self.body = data[offset:] def __getitem__(self, index): return self.headers[index] def format(self, sender_index, keys): parts = ['['+str(sender_index)+']'] if 'Level' in keys: parts.append('['+self.headers['Level']+']') if 'Logger' in keys: parts.append(self.headers['Logger']) if 'TimeStamp' in keys: parts.append(self.headers['TimeStamp']) if 'Source-File' in keys: if 'Source-Line' in keys: parts.append(self.headers['Source-File']+':'+self.headers['Source-Line']) else: parts.append(self.headers['Source-File']) if 'TimeStamp' in keys: parts.append(self.headers['TimeStamp']) if 'Source-Function' in keys: parts.append(self.headers['Source-Function']) parts.append(self.body) return ' '.join(parts) class Listener: def __init__(self, format='standard', port=UDP_PORT): self.socket = socket(AF_INET,SOCK_DGRAM) self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) mreq = pack("4sl", inet_aton(UDP_MULTICAST_ADDR), INADDR_ANY) self.socket.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) self.socket.bind((UDP_ADDR, port)) self.format_keys = HEADER_KEYS[format] def listen(self): while True: data,addr = self.socket.recvfrom(BUFFER_SIZE) sender_index = len(Senders.keys()) if addr in Senders: sender_index = Senders[addr] else: print "### NEW SENDER:", addr Senders[addr] = sender_index record = LogRecord(data) print record.format(sender_index, self.format_keys) ### main parser = OptionParser(usage="%prog [options]") parser.add_option("-p", "--port", dest="port", help="port number to listen on", type="int", default=UDP_PORT) parser.add_option("-f", "--format", dest="format", help="log format (mini, standard, long, or all)", choices=('mini', 'standard', 'long', 'all'), default='standard') (options, args) = parser.parse_args() print "Listening on port", options.port l = Listener(format=options.format, port=options.port) l.listen()
JCROM-Android/jcrom_external_chromium_org
refs/heads/kitkat
native_client_sdk/src/tools/tests/fix_deps_test.py
104
#!/usr/bin/env python # Copyright (c) 2012 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 import unittest SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PARENT_DIR = os.path.dirname(SCRIPT_DIR) DATA_DIR = os.path.join(SCRIPT_DIR, 'data') CHROME_SRC = os.path.dirname(os.path.dirname(os.path.dirname(PARENT_DIR))) MOCK_DIR = os.path.join(CHROME_SRC, "third_party", "pymock") # For the mock library sys.path.append(MOCK_DIR) sys.path.append(PARENT_DIR) import fix_deps import mock class TestFixDeps(unittest.TestCase): def setUp(self): self.tempfile = None def tearDown(self): if self.tempfile: os.remove(self.tempfile) def testRequiresFile(self): with mock.patch('sys.stderr'): self.assertRaises(SystemExit, fix_deps.main, []) def testInvalidOption(self): with mock.patch('sys.stderr'): self.assertRaises(SystemExit, fix_deps.main, ['--foo', 'bar']) def testMissingFile(self): with mock.patch('sys.stderr'): self.assertRaises(fix_deps.Error, fix_deps.main, ['nonexistent.file']) def testAddsDeps(self): self.tempfile = tempfile.mktemp("_sdktest") with open(self.tempfile, 'w') as out: out.write('foo.o: foo.c foo.h bar.h\n') fix_deps.FixupDepFile(self.tempfile) with open(self.tempfile) as infile: contents = infile.read() lines = contents.splitlines() self.assertEqual(len(lines), 5) self.assertTrue('foo.c:' in lines) self.assertTrue('foo.h:' in lines) self.assertTrue('bar.h:' in lines) def testSpacesInFilenames(self): self.tempfile = tempfile.mktemp("_sdktest") with open(self.tempfile, 'w') as out: out.write('foo.o: foo\\ bar.h\n') fix_deps.FixupDepFile(self.tempfile) with open(self.tempfile) as infile: contents = infile.read() lines = contents.splitlines() self.assertEqual(len(lines), 3) self.assertEqual(lines[2], 'foo\\ bar.h:') def testColonInFilename(self): self.tempfile = tempfile.mktemp("_sdktest") with open(self.tempfile, 'w') as out: out.write('foo.o: c:foo.c\\\n c:bar.h\n') fix_deps.FixupDepFile(self.tempfile) with open(self.tempfile) as infile: contents = infile.read() lines = contents.splitlines() self.assertEqual(len(lines), 5) self.assertEqual(lines[3], 'c:foo.c:') self.assertEqual(lines[4], 'c:bar.h:') def testDoubleInvoke(self): self.tempfile = tempfile.mktemp("_sdktest") with open(self.tempfile, 'w') as out: out.write('foo.o: foo\\ bar.h\n') fix_deps.FixupDepFile(self.tempfile) self.assertRaises(fix_deps.Error, fix_deps.FixupDepFile, self.tempfile) if __name__ == '__main__': unittest.main()
stanta/darfchain
refs/heads/master
darfchain_docker_vagrant/tests/integration/test_integration.py
3
import time import pytest pytestmark = [pytest.mark.bdb, pytest.mark.usefixtures('processes')] def test_double_create(b, user_pk): from bigchaindb.models import Transaction from bigchaindb.backend.query import count_blocks tx = Transaction.create([b.me], [([user_pk], 1)], metadata={'test': 'test'}).sign([b.me_private]) b.write_transaction(tx) time.sleep(2) b.write_transaction(tx) time.sleep(2) tx_returned = b.get_transaction(tx.id) # test that the tx can be queried assert tx_returned == tx # test the transaction appears only once last_voted_block = b.get_last_voted_block() assert len(last_voted_block.transactions) == 1 assert count_blocks(b.connection) == 2 @pytest.mark.usefixtures('inputs') def test_get_owned_ids_works_after_double_spend(b, user_pk, user_sk): """ Test for #633 https://github.com/bigchaindb/bigchaindb/issues/633 """ from bigchaindb.common.exceptions import DoubleSpend from bigchaindb.models import Transaction input_valid = b.get_owned_ids(user_pk).pop() input_valid = b.get_transaction(input_valid.txid) tx_valid = Transaction.transfer(input_valid.to_inputs(), [([user_pk], 1)], input_valid.id, {'1': 1}).sign([user_sk]) # write the valid tx and wait for voting/block to catch up b.write_transaction(tx_valid) time.sleep(2) # doesn't throw an exception b.get_owned_ids(user_pk) # create another transaction with the same input tx_double_spend = Transaction.transfer(input_valid.to_inputs(), [([user_pk], 1)], input_valid.id, {'2': 2}).sign([user_sk]) # write the double spend tx b.write_transaction(tx_double_spend) time.sleep(2) # still doesn't throw an exception b.get_owned_ids(user_pk) with pytest.raises(DoubleSpend): b.validate_transaction(tx_double_spend)
rosenvladimirov/addons
refs/heads/8.0
point_of_sale_bg/res_partner.py
320
import math from openerp.osv import osv, fields import openerp.addons.product.product class res_users(osv.osv): _inherit = 'res.partner' _columns = { 'ean13' : fields.char('EAN13', size=13, help="BarCode"), } def _check_ean(self, cr, uid, ids, context=None): return all( openerp.addons.product.product.check_ean(user.ean13) == True for user in self.browse(cr, uid, ids, context=context) ) _constraints = [ (_check_ean, "Error: Invalid ean code", ['ean13'],), ]
Montana-Studio/PI_Landing
refs/heads/master
node_modules/node-gyp/gyp/pylib/gyp/input.py
578
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from compiler.ast import Const from compiler.ast import Dict from compiler.ast import Discard from compiler.ast import List from compiler.ast import Module from compiler.ast import Node from compiler.ast import Stmt import compiler import gyp.common import gyp.simple_copy import multiprocessing import optparse import os.path import re import shlex import signal import subprocess import sys import threading import time import traceback from gyp.common import GypError from gyp.common import OrderedSet # A list of types that are treated as linkable. linkable_types = [ 'executable', 'shared_library', 'loadable_module', 'mac_kernel_extension', ] # A list of sections that contain links to other targets. dependency_sections = ['dependencies', 'export_dependent_settings'] # base_path_sections is a list of sections defined by GYP that contain # pathnames. The generators can provide more keys, the two lists are merged # into path_sections, but you should call IsPathSection instead of using either # list directly. base_path_sections = [ 'destination', 'files', 'include_dirs', 'inputs', 'libraries', 'outputs', 'sources', ] path_sections = set() # These per-process dictionaries are used to cache build file data when loading # in parallel mode. per_process_data = {} per_process_aux_data = {} def IsPathSection(section): # If section ends in one of the '=+?!' characters, it's applied to a section # without the trailing characters. '/' is notably absent from this list, # because there's no way for a regular expression to be treated as a path. while section and section[-1:] in '=+?!': section = section[:-1] if section in path_sections: return True # Sections mathing the regexp '_(dir|file|path)s?$' are also # considered PathSections. Using manual string matching since that # is much faster than the regexp and this can be called hundreds of # thousands of times so micro performance matters. if "_" in section: tail = section[-6:] if tail[-1] == 's': tail = tail[:-1] if tail[-5:] in ('_file', '_path'): return True return tail[-4:] == '_dir' return False # base_non_configuration_keys is a list of key names that belong in the target # itself and should not be propagated into its configurations. It is merged # with a list that can come from the generator to # create non_configuration_keys. base_non_configuration_keys = [ # Sections that must exist inside targets and not configurations. 'actions', 'configurations', 'copies', 'default_configuration', 'dependencies', 'dependencies_original', 'libraries', 'postbuilds', 'product_dir', 'product_extension', 'product_name', 'product_prefix', 'rules', 'run_as', 'sources', 'standalone_static_library', 'suppress_wildcard', 'target_name', 'toolset', 'toolsets', 'type', # Sections that can be found inside targets or configurations, but that # should not be propagated from targets into their configurations. 'variables', ] non_configuration_keys = [] # Keys that do not belong inside a configuration dictionary. invalid_configuration_keys = [ 'actions', 'all_dependent_settings', 'configurations', 'dependencies', 'direct_dependent_settings', 'libraries', 'link_settings', 'sources', 'standalone_static_library', 'target_name', 'type', ] # Controls whether or not the generator supports multiple toolsets. multiple_toolsets = False # Paths for converting filelist paths to output paths: { # toplevel, # qualified_output_dir, # } generator_filelist_paths = None def GetIncludedBuildFiles(build_file_path, aux_data, included=None): """Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merged into build_file_path's dict. aux_data is a dict containing a key for each build file or included build file. Those keys provide access to dicts whose "included" keys contain lists of all other files included by the build file. included should be left at its default None value by external callers. It is used for recursion. The returned list will not contain any duplicate entries. Each build file in the list will be relative to the current directory. """ if included == None: included = [] if build_file_path in included: return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get('included', []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included def CheckedEval(file_contents): """Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is. """ ast = compiler.parse(file_contents) assert isinstance(ast, Module) c1 = ast.getChildren() assert c1[0] is None assert isinstance(c1[1], Stmt) c2 = c1[1].getChildren() assert isinstance(c2[0], Discard) c3 = c2[0].getChildren() assert len(c3) == 1 return CheckNode(c3[0], []) def CheckNode(node, keypath): if isinstance(node, Dict): c = node.getChildren() dict = {} for n in range(0, len(c), 2): assert isinstance(c[n], Const) key = c[n].getChildren()[0] if key in dict: raise GypError("Key '" + key + "' repeated at level " + repr(len(keypath) + 1) + " with key path '" + '.'.join(keypath) + "'") kp = list(keypath) # Make a copy of the list for descending this node. kp.append(key) dict[key] = CheckNode(c[n + 1], kp) return dict elif isinstance(node, List): c = node.getChildren() children = [] for index, child in enumerate(c): kp = list(keypath) # Copy list. kp.append(repr(index)) children.append(CheckNode(child, kp)) return children elif isinstance(node, Const): return node.getChildren()[0] else: raise TypeError("Unknown AST node at key path '" + '.'.join(keypath) + "': " + repr(node)) def LoadOneBuildFile(build_file_path, data, aux_data, includes, is_target, check): if build_file_path in data: return data[build_file_path] if os.path.exists(build_file_path): # Open the build file for read ('r') with universal-newlines mode ('U') # to make sure platform specific newlines ('\r\n' or '\r') are converted to '\n' # which otherwise will fail eval() build_file_contents = open(build_file_path, 'rU').read() else: raise GypError("%s not found (cwd: %s)" % (build_file_path, os.getcwd())) build_file_data = None try: if check: build_file_data = CheckedEval(build_file_contents) else: build_file_data = eval(build_file_contents, {'__builtins__': None}, None) except SyntaxError, e: e.filename = build_file_path raise except Exception, e: gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path) raise if type(build_file_data) is not dict: raise GypError("%s does not evaluate to a dictionary." % build_file_path) data[build_file_path] = build_file_data aux_data[build_file_path] = {} # Scan for includes and merge them in. if ('skip_includes' not in build_file_data or not build_file_data['skip_includes']): try: if is_target: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, includes, check) else: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, None, check) except Exception, e: gyp.common.ExceptionAppend(e, 'while reading includes of ' + build_file_path) raise return build_file_data def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data, includes, check): includes_list = [] if includes != None: includes_list.extend(includes) if 'includes' in subdict: for include in subdict['includes']: # "include" is specified relative to subdict_path, so compute the real # path to include by appending the provided "include" to the directory # in which subdict_path resides. relative_include = \ os.path.normpath(os.path.join(os.path.dirname(subdict_path), include)) includes_list.append(relative_include) # Unhook the includes list, it's no longer needed. del subdict['includes'] # Merge in the included files. for include in includes_list: if not 'included' in aux_data[subdict_path]: aux_data[subdict_path]['included'] = [] aux_data[subdict_path]['included'].append(include) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'", include) MergeDicts(subdict, LoadOneBuildFile(include, data, aux_data, None, False, check), subdict_path, include) # Recurse into subdictionaries. for k, v in subdict.iteritems(): if type(v) is dict: LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, None, check) elif type(v) is list: LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, check) # This recurses into lists so that it can look for dicts. def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, check): for item in sublist: if type(item) is dict: LoadBuildFileIncludesIntoDict(item, sublist_path, data, aux_data, None, check) elif type(item) is list: LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, check) # Processes toolsets in all the targets. This recurses into condition entries # since they can contain toolsets as well. def ProcessToolsetsInDict(data): if 'targets' in data: target_list = data['targets'] new_target_list = [] for target in target_list: # If this target already has an explicit 'toolset', and no 'toolsets' # list, don't modify it further. if 'toolset' in target and 'toolsets' not in target: new_target_list.append(target) continue if multiple_toolsets: toolsets = target.get('toolsets', ['target']) else: toolsets = ['target'] # Make sure this 'toolsets' definition is only processed once. if 'toolsets' in target: del target['toolsets'] if len(toolsets) > 0: # Optimization: only do copies if more than one toolset is specified. for build in toolsets[1:]: new_target = gyp.simple_copy.deepcopy(target) new_target['toolset'] = build new_target_list.append(new_target) target['toolset'] = toolsets[0] new_target_list.append(target) data['targets'] = new_target_list if 'conditions' in data: for condition in data['conditions']: if type(condition) is list: for condition_dict in condition[1:]: if type(condition_dict) is dict: ProcessToolsetsInDict(condition_dict) # TODO(mark): I don't love this name. It just means that it's going to load # a build file that contains targets and is expected to provide a targets dict # that contains the targets... def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, depth, check, load_dependencies): # If depth is set, predefine the DEPTH variable to be a relative path from # this build file's directory to the directory identified by depth. if depth: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path)) if d == '': variables['DEPTH'] = '.' else: variables['DEPTH'] = d.replace('\\', '/') # The 'target_build_files' key is only set when loading target build files in # the non-parallel code path, where LoadTargetBuildFile is called # recursively. In the parallel code path, we don't need to check whether the # |build_file_path| has already been loaded, because the 'scheduled' set in # ParallelState guarantees that we never load the same |build_file_path| # twice. if 'target_build_files' in data: if build_file_path in data['target_build_files']: # Already loaded. return False data['target_build_files'].add(build_file_path) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Target Build File '%s'", build_file_path) build_file_data = LoadOneBuildFile(build_file_path, data, aux_data, includes, True, check) # Store DEPTH for later use in generators. build_file_data['_DEPTH'] = depth # Set up the included_files key indicating which .gyp files contributed to # this target dict. if 'included_files' in build_file_data: raise GypError(build_file_path + ' must not contain included_files key') included = GetIncludedBuildFiles(build_file_path, aux_data) build_file_data['included_files'] = [] for included_file in included: # included_file is relative to the current directory, but it needs to # be made relative to build_file_path's directory. included_relative = \ gyp.common.RelativePath(included_file, os.path.dirname(build_file_path)) build_file_data['included_files'].append(included_relative) # Do a first round of toolsets expansion so that conditions can be defined # per toolset. ProcessToolsetsInDict(build_file_data) # Apply "pre"/"early" variable expansions and condition evaluations. ProcessVariablesAndConditionsInDict( build_file_data, PHASE_EARLY, variables, build_file_path) # Since some toolsets might have been defined conditionally, perform # a second round of toolsets expansion now. ProcessToolsetsInDict(build_file_data) # Look at each project's target_defaults dict, and merge settings into # targets. if 'target_defaults' in build_file_data: if 'targets' not in build_file_data: raise GypError("Unable to find targets in build file %s" % build_file_path) index = 0 while index < len(build_file_data['targets']): # This procedure needs to give the impression that target_defaults is # used as defaults, and the individual targets inherit from that. # The individual targets need to be merged into the defaults. Make # a deep copy of the defaults for each target, merge the target dict # as found in the input file into that copy, and then hook up the # copy with the target-specific data merged into it as the replacement # target dict. old_target_dict = build_file_data['targets'][index] new_target_dict = gyp.simple_copy.deepcopy( build_file_data['target_defaults']) MergeDicts(new_target_dict, old_target_dict, build_file_path, build_file_path) build_file_data['targets'][index] = new_target_dict index += 1 # No longer needed. del build_file_data['target_defaults'] # Look for dependencies. This means that dependency resolution occurs # after "pre" conditionals and variable expansion, but before "post" - # in other words, you can't put a "dependencies" section inside a "post" # conditional within a target. dependencies = [] if 'targets' in build_file_data: for target_dict in build_file_data['targets']: if 'dependencies' not in target_dict: continue for dependency in target_dict['dependencies']: dependencies.append( gyp.common.ResolveTarget(build_file_path, dependency, None)[0]) if load_dependencies: for dependency in dependencies: try: LoadTargetBuildFile(dependency, data, aux_data, variables, includes, depth, check, load_dependencies) except Exception, e: gyp.common.ExceptionAppend( e, 'while loading dependencies of %s' % build_file_path) raise else: return (build_file_path, dependencies) def CallLoadTargetBuildFile(global_flags, build_file_path, variables, includes, depth, check, generator_input_info): """Wrapper around LoadTargetBuildFile for parallel processing. This wrapper is used when LoadTargetBuildFile is executed in a worker process. """ try: signal.signal(signal.SIGINT, signal.SIG_IGN) # Apply globals so that the worker process behaves the same. for key, value in global_flags.iteritems(): globals()[key] = value SetGeneratorGlobals(generator_input_info) result = LoadTargetBuildFile(build_file_path, per_process_data, per_process_aux_data, variables, includes, depth, check, False) if not result: return result (build_file_path, dependencies) = result # We can safely pop the build_file_data from per_process_data because it # will never be referenced by this process again, so we don't need to keep # it in the cache. build_file_data = per_process_data.pop(build_file_path) # This gets serialized and sent back to the main process via a pipe. # It's handled in LoadTargetBuildFileCallback. return (build_file_path, build_file_data, dependencies) except GypError, e: sys.stderr.write("gyp: %s\n" % e) return None except Exception, e: print >>sys.stderr, 'Exception:', e print >>sys.stderr, traceback.format_exc() return None class ParallelProcessingError(Exception): pass class ParallelState(object): """Class to keep track of state when processing input files in parallel. If build files are loaded in parallel, use this to keep track of state during farming out and processing parallel jobs. It's stored in a global so that the callback function can have access to it. """ def __init__(self): # The multiprocessing pool. self.pool = None # The condition variable used to protect this object and notify # the main loop when there might be more data to process. self.condition = None # The "data" dict that was passed to LoadTargetBuildFileParallel self.data = None # The number of parallel calls outstanding; decremented when a response # was received. self.pending = 0 # The set of all build files that have been scheduled, so we don't # schedule the same one twice. self.scheduled = set() # A list of dependency build file paths that haven't been scheduled yet. self.dependencies = [] # Flag to indicate if there was an error in a child process. self.error = False def LoadTargetBuildFileCallback(self, result): """Handle the results of running LoadTargetBuildFile in another process. """ self.condition.acquire() if not result: self.error = True self.condition.notify() self.condition.release() return (build_file_path0, build_file_data0, dependencies0) = result self.data[build_file_path0] = build_file_data0 self.data['target_build_files'].add(build_file_path0) for new_dependency in dependencies0: if new_dependency not in self.scheduled: self.scheduled.add(new_dependency) self.dependencies.append(new_dependency) self.pending -= 1 self.condition.notify() self.condition.release() def LoadTargetBuildFilesParallel(build_files, data, variables, includes, depth, check, generator_input_info): parallel_state = ParallelState() parallel_state.condition = threading.Condition() # Make copies of the build_files argument that we can modify while working. parallel_state.dependencies = list(build_files) parallel_state.scheduled = set(build_files) parallel_state.pending = 0 parallel_state.data = data try: parallel_state.condition.acquire() while parallel_state.dependencies or parallel_state.pending: if parallel_state.error: break if not parallel_state.dependencies: parallel_state.condition.wait() continue dependency = parallel_state.dependencies.pop() parallel_state.pending += 1 global_flags = { 'path_sections': globals()['path_sections'], 'non_configuration_keys': globals()['non_configuration_keys'], 'multiple_toolsets': globals()['multiple_toolsets']} if not parallel_state.pool: parallel_state.pool = multiprocessing.Pool(multiprocessing.cpu_count()) parallel_state.pool.apply_async( CallLoadTargetBuildFile, args = (global_flags, dependency, variables, includes, depth, check, generator_input_info), callback = parallel_state.LoadTargetBuildFileCallback) except KeyboardInterrupt, e: parallel_state.pool.terminate() raise e parallel_state.condition.release() parallel_state.pool.close() parallel_state.pool.join() parallel_state.pool = None if parallel_state.error: sys.exit(1) # Look for the bracket that matches the first bracket seen in a # string, and return the start and end as a tuple. For example, if # the input is something like "<(foo <(bar)) blah", then it would # return (1, 13), indicating the entire string except for the leading # "<" and trailing " blah". LBRACKETS= set('{[(') BRACKETS = {'}': '{', ']': '[', ')': '('} def FindEnclosingBracketGroup(input_str): stack = [] start = -1 for index, char in enumerate(input_str): if char in LBRACKETS: stack.append(char) if start == -1: start = index elif char in BRACKETS: if not stack: return (-1, -1) if stack.pop() != BRACKETS[char]: return (-1, -1) if not stack: return (start, index + 1) return (-1, -1) def IsStrCanonicalInt(string): """Returns True if |string| is in its canonical integer form. The canonical form is such that str(int(string)) == string. """ if type(string) is str: # This function is called a lot so for maximum performance, avoid # involving regexps which would otherwise make the code much # shorter. Regexps would need twice the time of this function. if string: if string == "0": return True if string[0] == "-": string = string[1:] if not string: return False if '1' <= string[0] <= '9': return string.isdigit() return False # This matches things like "<(asdf)", "<!(cmd)", "<!@(cmd)", "<|(list)", # "<!interpreter(arguments)", "<([list])", and even "<([)" and "<(<())". # In the last case, the inner "<()" is captured in match['content']. early_variable_re = re.compile( r'(?P<replace>(?P<type><(?:(?:!?@?)|\|)?)' r'(?P<command_string>[-a-zA-Z0-9_.]+)?' r'\((?P<is_array>\s*\[?)' r'(?P<content>.*?)(\]?)\))') # This matches the same as early_variable_re, but with '>' instead of '<'. late_variable_re = re.compile( r'(?P<replace>(?P<type>>(?:(?:!?@?)|\|)?)' r'(?P<command_string>[-a-zA-Z0-9_.]+)?' r'\((?P<is_array>\s*\[?)' r'(?P<content>.*?)(\]?)\))') # This matches the same as early_variable_re, but with '^' instead of '<'. latelate_variable_re = re.compile( r'(?P<replace>(?P<type>[\^](?:(?:!?@?)|\|)?)' r'(?P<command_string>[-a-zA-Z0-9_.]+)?' r'\((?P<is_array>\s*\[?)' r'(?P<content>.*?)(\]?)\))') # Global cache of results from running commands so they don't have to be run # more then once. cached_command_results = {} def FixupPlatformCommand(cmd): if sys.platform == 'win32': if type(cmd) is list: cmd = [re.sub('^cat ', 'type ', cmd[0])] + cmd[1:] else: cmd = re.sub('^cat ', 'type ', cmd) return cmd PHASE_EARLY = 0 PHASE_LATE = 1 PHASE_LATELATE = 2 def ExpandVariables(input, phase, variables, build_file): # Look for the pattern that gets expanded into variables if phase == PHASE_EARLY: variable_re = early_variable_re expansion_symbol = '<' elif phase == PHASE_LATE: variable_re = late_variable_re expansion_symbol = '>' elif phase == PHASE_LATELATE: variable_re = latelate_variable_re expansion_symbol = '^' else: assert False input_str = str(input) if IsStrCanonicalInt(input_str): return int(input_str) # Do a quick scan to determine if an expensive regex search is warranted. if expansion_symbol not in input_str: return input_str # Get the entire list of matches as a list of MatchObject instances. # (using findall here would return strings instead of MatchObjects). matches = list(variable_re.finditer(input_str)) if not matches: return input_str output = input_str # Reverse the list of matches so that replacements are done right-to-left. # That ensures that earlier replacements won't mess up the string in a # way that causes later calls to find the earlier substituted text instead # of what's intended for replacement. matches.reverse() for match_group in matches: match = match_group.groupdict() gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %r", match) # match['replace'] is the substring to look for, match['type'] # is the character code for the replacement type (< > <! >! <| >| <@ # >@ <!@ >!@), match['is_array'] contains a '[' for command # arrays, and match['content'] is the name of the variable (< >) # or command to run (<! >!). match['command_string'] is an optional # command string. Currently, only 'pymod_do_main' is supported. # run_command is true if a ! variant is used. run_command = '!' in match['type'] command_string = match['command_string'] # file_list is true if a | variant is used. file_list = '|' in match['type'] # Capture these now so we can adjust them later. replace_start = match_group.start('replace') replace_end = match_group.end('replace') # Find the ending paren, and re-evaluate the contained string. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:]) # Adjust the replacement range to match the entire command # found by FindEnclosingBracketGroup (since the variable_re # probably doesn't match the entire command if it contained # nested variables). replace_end = replace_start + c_end # Find the "real" replacement, matching the appropriate closing # paren, and adjust the replacement start and end. replacement = input_str[replace_start:replace_end] # Figure out what the contents of the variable parens are. contents_start = replace_start + c_start + 1 contents_end = replace_end - 1 contents = input_str[contents_start:contents_end] # Do filter substitution now for <|(). # Admittedly, this is different than the evaluation order in other # contexts. However, since filtration has no chance to run on <|(), # this seems like the only obvious way to give them access to filters. if file_list: processed_variables = gyp.simple_copy.deepcopy(variables) ProcessListFiltersInDict(contents, processed_variables) # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, processed_variables, build_file) else: # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, variables, build_file) # Strip off leading/trailing whitespace so that variable matches are # simpler below (and because they are rarely needed). contents = contents.strip() # expand_to_list is true if an @ variant is used. In that case, # the expansion should result in a list. Note that the caller # is to be expecting a list in return, and not all callers do # because not all are working in list context. Also, for list # expansions, there can be no other text besides the variable # expansion in the input string. expand_to_list = '@' in match['type'] and input_str == replacement if run_command or file_list: # Find the build file's directory, so commands can be run or file lists # generated relative to it. build_file_dir = os.path.dirname(build_file) if build_file_dir == '' and not file_list: # If build_file is just a leaf filename indicating a file in the # current directory, build_file_dir might be an empty string. Set # it to None to signal to subprocess.Popen that it should run the # command in the current directory. build_file_dir = None # Support <|(listfile.txt ...) which generates a file # containing items from a gyp list, generated at gyp time. # This works around actions/rules which have more inputs than will # fit on the command line. if file_list: if type(contents) is list: contents_list = contents else: contents_list = contents.split(' ') replacement = contents_list[0] if os.path.isabs(replacement): raise GypError('| cannot handle absolute paths, got "%s"' % replacement) if not generator_filelist_paths: path = os.path.join(build_file_dir, replacement) else: if os.path.isabs(build_file_dir): toplevel = generator_filelist_paths['toplevel'] rel_build_file_dir = gyp.common.RelativePath(build_file_dir, toplevel) else: rel_build_file_dir = build_file_dir qualified_out_dir = generator_filelist_paths['qualified_out_dir'] path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement) gyp.common.EnsureDirExists(path) replacement = gyp.common.RelativePath(path, build_file_dir) f = gyp.common.WriteOnDiff(path) for i in contents_list[1:]: f.write('%s\n' % i) f.close() elif run_command: use_shell = True if match['is_array']: contents = eval(contents) use_shell = False # Check for a cached value to avoid executing commands, or generating # file lists more than once. The cache key contains the command to be # run as well as the directory to run it from, to account for commands # that depend on their current directory. # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory, # someone could author a set of GYP files where each time the command # is invoked it produces different output by design. When the need # arises, the syntax should be extended to support no caching off a # command's output so it is run every time. cache_key = (str(contents), build_file_dir) cached_value = cached_command_results.get(cache_key, None) if cached_value is None: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Executing command '%s' in directory '%s'", contents, build_file_dir) replacement = '' if command_string == 'pymod_do_main': # <!pymod_do_main(modulename param eters) loads |modulename| as a # python module and then calls that module's DoMain() function, # passing ["param", "eters"] as a single list argument. For modules # that don't load quickly, this can be faster than # <!(python modulename param eters). Do this in |build_file_dir|. oldwd = os.getcwd() # Python doesn't like os.open('.'): no fchdir. if build_file_dir: # build_file_dir may be None (see above). os.chdir(build_file_dir) try: parsed_contents = shlex.split(contents) try: py_module = __import__(parsed_contents[0]) except ImportError as e: raise GypError("Error importing pymod_do_main" "module (%s): %s" % (parsed_contents[0], e)) replacement = str(py_module.DoMain(parsed_contents[1:])).rstrip() finally: os.chdir(oldwd) assert replacement != None elif command_string: raise GypError("Unknown command string '%s' in '%s'." % (command_string, contents)) else: # Fix up command with platform specific workarounds. contents = FixupPlatformCommand(contents) try: p = subprocess.Popen(contents, shell=use_shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=build_file_dir) except Exception, e: raise GypError("%s while executing command '%s' in %s" % (e, contents, build_file)) p_stdout, p_stderr = p.communicate('') if p.wait() != 0 or p_stderr: sys.stderr.write(p_stderr) # Simulate check_call behavior, since check_call only exists # in python 2.5 and later. raise GypError("Call to '%s' returned exit status %d while in %s." % (contents, p.returncode, build_file)) replacement = p_stdout.rstrip() cached_command_results[cache_key] = replacement else: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Had cache value for command '%s' in directory '%s'", contents,build_file_dir) replacement = cached_value else: if not contents in variables: if contents[-1] in ['!', '/']: # In order to allow cross-compiles (nacl) to happen more naturally, # we will allow references to >(sources/) etc. to resolve to # and empty list if undefined. This allows actions to: # 'action!': [ # '>@(_sources!)', # ], # 'action/': [ # '>@(_sources/)', # ], replacement = [] else: raise GypError('Undefined variable ' + contents + ' in ' + build_file) else: replacement = variables[contents] if type(replacement) is list: for item in replacement: if not contents[-1] == '/' and type(item) not in (str, int): raise GypError('Variable ' + contents + ' must expand to a string or list of strings; ' + 'list contains a ' + item.__class__.__name__) # Run through the list and handle variable expansions in it. Since # the list is guaranteed not to contain dicts, this won't do anything # with conditions sections. ProcessVariablesAndConditionsInList(replacement, phase, variables, build_file) elif type(replacement) not in (str, int): raise GypError('Variable ' + contents + ' must expand to a string or list of strings; ' + 'found a ' + replacement.__class__.__name__) if expand_to_list: # Expanding in list context. It's guaranteed that there's only one # replacement to do in |input_str| and that it's this replacement. See # above. if type(replacement) is list: # If it's already a list, make a copy. output = replacement[:] else: # Split it the same way sh would split arguments. output = shlex.split(str(replacement)) else: # Expanding in string context. encoded_replacement = '' if type(replacement) is list: # When expanding a list into string context, turn the list items # into a string in a way that will work with a subprocess call. # # TODO(mark): This isn't completely correct. This should # call a generator-provided function that observes the # proper list-to-argument quoting rules on a specific # platform instead of just calling the POSIX encoding # routine. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement) else: encoded_replacement = replacement output = output[:replace_start] + str(encoded_replacement) + \ output[replace_end:] # Prepare for the next match iteration. input_str = output if output == input: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found only identity matches on %r, avoiding infinite " "recursion.", output) else: # Look for more matches now that we've replaced some, to deal with # expanding local variables (variables defined in the same # variables block as this one). gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %r, recursing.", output) if type(output) is list: if output and type(output[0]) is list: # Leave output alone if it's a list of lists. # We don't want such lists to be stringified. pass else: new_output = [] for item in output: new_output.append( ExpandVariables(item, phase, variables, build_file)) output = new_output else: output = ExpandVariables(output, phase, variables, build_file) # Convert all strings that are canonically-represented integers into integers. if type(output) is list: for index in xrange(0, len(output)): if IsStrCanonicalInt(output[index]): output[index] = int(output[index]) elif IsStrCanonicalInt(output): output = int(output) return output # The same condition is often evaluated over and over again so it # makes sense to cache as much as possible between evaluations. cached_conditions_asts = {} def EvalCondition(condition, conditions_key, phase, variables, build_file): """Returns the dict that should be used or None if the result was that nothing should be used.""" if type(condition) is not list: raise GypError(conditions_key + ' must be a list') if len(condition) < 2: # It's possible that condition[0] won't work in which case this # attempt will raise its own IndexError. That's probably fine. raise GypError(conditions_key + ' ' + condition[0] + ' must be at least length 2, not ' + str(len(condition))) i = 0 result = None while i < len(condition): cond_expr = condition[i] true_dict = condition[i + 1] if type(true_dict) is not dict: raise GypError('{} {} must be followed by a dictionary, not {}'.format( conditions_key, cond_expr, type(true_dict))) if len(condition) > i + 2 and type(condition[i + 2]) is dict: false_dict = condition[i + 2] i = i + 3 if i != len(condition): raise GypError('{} {} has {} unexpected trailing items'.format( conditions_key, cond_expr, len(condition) - i)) else: false_dict = None i = i + 2 if result == None: result = EvalSingleCondition( cond_expr, true_dict, false_dict, phase, variables, build_file) return result def EvalSingleCondition( cond_expr, true_dict, false_dict, phase, variables, build_file): """Returns true_dict if cond_expr evaluates to true, and false_dict otherwise.""" # Do expansions on the condition itself. Since the conditon can naturally # contain variable references without needing to resort to GYP expansion # syntax, this is of dubious value for variables, but someone might want to # use a command expansion directly inside a condition. cond_expr_expanded = ExpandVariables(cond_expr, phase, variables, build_file) if type(cond_expr_expanded) not in (str, int): raise ValueError( 'Variable expansion in this context permits str and int ' + \ 'only, found ' + cond_expr_expanded.__class__.__name__) try: if cond_expr_expanded in cached_conditions_asts: ast_code = cached_conditions_asts[cond_expr_expanded] else: ast_code = compile(cond_expr_expanded, '<string>', 'eval') cached_conditions_asts[cond_expr_expanded] = ast_code if eval(ast_code, {'__builtins__': None}, variables): return true_dict return false_dict except SyntaxError, e: syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s ' 'at character %d.' % (str(e.args[0]), e.text, build_file, e.offset), e.filename, e.lineno, e.offset, e.text) raise syntax_error except NameError, e: gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' % (cond_expr_expanded, build_file)) raise GypError(e) def ProcessConditionsInDict(the_dict, phase, variables, build_file): # Process a 'conditions' or 'target_conditions' section in the_dict, # depending on phase. # early -> conditions # late -> target_conditions # latelate -> no conditions # # Each item in a conditions list consists of cond_expr, a string expression # evaluated as the condition, and true_dict, a dict that will be merged into # the_dict if cond_expr evaluates to true. Optionally, a third item, # false_dict, may be present. false_dict is merged into the_dict if # cond_expr evaluates to false. # # Any dict merged into the_dict will be recursively processed for nested # conditionals and other expansions, also according to phase, immediately # prior to being merged. if phase == PHASE_EARLY: conditions_key = 'conditions' elif phase == PHASE_LATE: conditions_key = 'target_conditions' elif phase == PHASE_LATELATE: return else: assert False if not conditions_key in the_dict: return conditions_list = the_dict[conditions_key] # Unhook the conditions list, it's no longer needed. del the_dict[conditions_key] for condition in conditions_list: merge_dict = EvalCondition(condition, conditions_key, phase, variables, build_file) if merge_dict != None: # Expand variables and nested conditinals in the merge_dict before # merging it. ProcessVariablesAndConditionsInDict(merge_dict, phase, variables, build_file) MergeDicts(the_dict, merge_dict, build_file, build_file) def LoadAutomaticVariablesFromDict(variables, the_dict): # Any keys with plain string values in the_dict become automatic variables. # The variable name is the key name with a "_" character prepended. for key, value in the_dict.iteritems(): if type(value) in (str, int, list): variables['_' + key] = value def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key): # Any keys in the_dict's "variables" dict, if it has one, becomes a # variable. The variable name is the key name in the "variables" dict. # Variables that end with the % character are set only if they are unset in # the variables dict. the_dict_key is the name of the key that accesses # the_dict in the_dict's parent dict. If the_dict's parent is not a dict # (it could be a list or it could be parentless because it is a root dict), # the_dict_key will be None. for key, value in the_dict.get('variables', {}).iteritems(): if type(value) not in (str, int, list): continue if key.endswith('%'): variable_name = key[:-1] if variable_name in variables: # If the variable is already set, don't set it. continue if the_dict_key is 'variables' and variable_name in the_dict: # If the variable is set without a % in the_dict, and the_dict is a # variables dict (making |variables| a varaibles sub-dict of a # variables dict), use the_dict's definition. value = the_dict[variable_name] else: variable_name = key variables[variable_name] = value def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in, build_file, the_dict_key=None): """Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function. """ # Make a copy of the variables_in dict that can be modified during the # loading of automatics and the loading of the variables dict. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) if 'variables' in the_dict: # Make sure all the local variables are added to the variables # list before we process them so that you can reference one # variable from another. They will be fully expanded by recursion # in ExpandVariables. for key, value in the_dict['variables'].iteritems(): variables[key] = value # Handle the associated variables dict first, so that any variable # references within can be resolved prior to using them as variables. # Pass a copy of the variables dict to avoid having it be tainted. # Otherwise, it would have extra automatics added for everything that # should just be an ordinary variable in this scope. ProcessVariablesAndConditionsInDict(the_dict['variables'], phase, variables, build_file, 'variables') LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) for key, value in the_dict.iteritems(): # Skip "variables", which was already processed if present. if key != 'variables' and type(value) is str: expanded = ExpandVariables(value, phase, variables, build_file) if type(expanded) not in (str, int): raise ValueError( 'Variable expansion in this context permits str and int ' + \ 'only, found ' + expanded.__class__.__name__ + ' for ' + key) the_dict[key] = expanded # Variable expansion may have resulted in changes to automatics. Reload. # TODO(mark): Optimization: only reload if no changes were made. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Process conditions in this dict. This is done after variable expansion # so that conditions may take advantage of expanded variables. For example, # if the_dict contains: # {'type': '<(library_type)', # 'conditions': [['_type=="static_library"', { ... }]]}, # _type, as used in the condition, will only be set to the value of # library_type if variable expansion is performed before condition # processing. However, condition processing should occur prior to recursion # so that variables (both automatic and "variables" dict type) may be # adjusted by conditions sections, merged into the_dict, and have the # intended impact on contained dicts. # # This arrangement means that a "conditions" section containing a "variables" # section will only have those variables effective in subdicts, not in # the_dict. The workaround is to put a "conditions" section within a # "variables" section. For example: # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]], # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will not result in "IS_MAC" being appended to the "defines" list in the # current scope but would result in it being appended to the "defines" list # within "my_subdict". By comparison: # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]}, # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will append "IS_MAC" to both "defines" lists. # Evaluate conditions sections, allowing variable expansions within them # as well as nested conditionals. This will process a 'conditions' or # 'target_conditions' section, perform appropriate merging and recursive # conditional and variable processing, and then remove the conditions section # from the_dict if it is present. ProcessConditionsInDict(the_dict, phase, variables, build_file) # Conditional processing may have resulted in changes to automatics or the # variables dict. Reload. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Recurse into child dicts, or process child lists which may result in # further recursion into descendant dicts. for key, value in the_dict.iteritems(): # Skip "variables" and string values, which were already processed if # present. if key == 'variables' or type(value) is str: continue if type(value) is dict: # Pass a copy of the variables dict so that subdicts can't influence # parents. ProcessVariablesAndConditionsInDict(value, phase, variables, build_file, key) elif type(value) is list: # The list itself can't influence the variables dict, and # ProcessVariablesAndConditionsInList will make copies of the variables # dict if it needs to pass it to something that can influence it. No # copy is necessary here. ProcessVariablesAndConditionsInList(value, phase, variables, build_file) elif type(value) is not int: raise TypeError('Unknown type ' + value.__class__.__name__ + \ ' for ' + key) def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file): # Iterate using an index so that new values can be assigned into the_list. index = 0 while index < len(the_list): item = the_list[index] if type(item) is dict: # Make a copy of the variables dict so that it won't influence anything # outside of its own scope. ProcessVariablesAndConditionsInDict(item, phase, variables, build_file) elif type(item) is list: ProcessVariablesAndConditionsInList(item, phase, variables, build_file) elif type(item) is str: expanded = ExpandVariables(item, phase, variables, build_file) if type(expanded) in (str, int): the_list[index] = expanded elif type(expanded) is list: the_list[index:index+1] = expanded index += len(expanded) # index now identifies the next item to examine. Continue right now # without falling into the index increment below. continue else: raise ValueError( 'Variable expansion in this context permits strings and ' + \ 'lists only, found ' + expanded.__class__.__name__ + ' at ' + \ index) elif type(item) is not int: raise TypeError('Unknown type ' + item.__class__.__name__ + \ ' at index ' + index) index = index + 1 def BuildTargetsDict(data): """Builds a dict mapping fully-qualified target names to their target dicts. |data| is a dict mapping loaded build files by pathname relative to the current directory. Values in |data| are build file contents. For each |data| value with a "targets" key, the value of the "targets" key is taken as a list containing target dicts. Each target's fully-qualified name is constructed from the pathname of the build file (|data| key) and its "target_name" property. These fully-qualified names are used as the keys in the returned dict. These keys provide access to the target dicts, the dicts in the "targets" lists. """ targets = {} for build_file in data['target_build_files']: for target in data[build_file].get('targets', []): target_name = gyp.common.QualifiedTarget(build_file, target['target_name'], target['toolset']) if target_name in targets: raise GypError('Duplicate target definitions for ' + target_name) targets[target_name] = target return targets def QualifyDependencies(targets): """Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-qualified and relative to the current directory. All rewritten dependencies are suitable for use as keys to |targets| or a similar dict. """ all_dependency_sections = [dep + op for dep in dependency_sections for op in ('', '!', '/')] for target, target_dict in targets.iteritems(): target_build_file = gyp.common.BuildFile(target) toolset = target_dict['toolset'] for dependency_key in all_dependency_sections: dependencies = target_dict.get(dependency_key, []) for index in xrange(0, len(dependencies)): dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget( target_build_file, dependencies[index], toolset) if not multiple_toolsets: # Ignore toolset specification in the dependency if it is specified. dep_toolset = toolset dependency = gyp.common.QualifiedTarget(dep_file, dep_target, dep_toolset) dependencies[index] = dependency # Make sure anything appearing in a list other than "dependencies" also # appears in the "dependencies" list. if dependency_key != 'dependencies' and \ dependency not in target_dict['dependencies']: raise GypError('Found ' + dependency + ' in ' + dependency_key + ' of ' + target + ', but not in dependencies') def ExpandWildcardDependencies(targets, data): """Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access to build file dicts. Any target that does not wish to be included by wildcard can provide an optional "suppress_wildcard" key in its target dict. When present and true, a wildcard dependency link will not include such targets. All dependency names, including the keys to |targets| and the values in each dependency list, must be qualified when this function is called. """ for target, target_dict in targets.iteritems(): toolset = target_dict['toolset'] target_build_file = gyp.common.BuildFile(target) for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) # Loop this way instead of "for dependency in" or "for index in xrange" # because the dependencies list will be modified within the loop body. index = 0 while index < len(dependencies): (dependency_build_file, dependency_target, dependency_toolset) = \ gyp.common.ParseQualifiedTarget(dependencies[index]) if dependency_target != '*' and dependency_toolset != '*': # Not a wildcard. Keep it moving. index = index + 1 continue if dependency_build_file == target_build_file: # It's an error for a target to depend on all other targets in # the same file, because a target cannot depend on itself. raise GypError('Found wildcard in ' + dependency_key + ' of ' + target + ' referring to same build file') # Take the wildcard out and adjust the index so that the next # dependency in the list will be processed the next time through the # loop. del dependencies[index] index = index - 1 # Loop through the targets in the other build file, adding them to # this target's list of dependencies in place of the removed # wildcard. dependency_target_dicts = data[dependency_build_file]['targets'] for dependency_target_dict in dependency_target_dicts: if int(dependency_target_dict.get('suppress_wildcard', False)): continue dependency_target_name = dependency_target_dict['target_name'] if (dependency_target != '*' and dependency_target != dependency_target_name): continue dependency_target_toolset = dependency_target_dict['toolset'] if (dependency_toolset != '*' and dependency_toolset != dependency_target_toolset): continue dependency = gyp.common.QualifiedTarget(dependency_build_file, dependency_target_name, dependency_target_toolset) index = index + 1 dependencies.insert(index, dependency) index = index + 1 def Unify(l): """Removes duplicate elements from l, keeping the first element.""" seen = {} return [seen.setdefault(e, e) for e in l if e not in seen] def RemoveDuplicateDependencies(targets): """Makes sure every dependency appears only once in all targets's dependency lists.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: target_dict[dependency_key] = Unify(dependencies) def Filter(l, item): """Removes item from l.""" res = {} return [res.setdefault(e, e) for e in l if e != item] def RemoveSelfDependencies(targets): """Remove self dependencies from targets that have the prune_self_dependency variable set.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if t == target_name: if targets[t].get('variables', {}).get('prune_self_dependency', 0): target_dict[dependency_key] = Filter(dependencies, target_name) def RemoveLinkDependenciesFromNoneTargets(targets): """Remove dependencies having the 'link_dependency' attribute from the 'none' targets.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if target_dict.get('type', None) == 'none': if targets[t].get('variables', {}).get('link_dependency', 0): target_dict[dependency_key] = \ Filter(target_dict[dependency_key], t) class DependencyGraphNode(object): """ Attributes: ref: A reference to an object that this DependencyGraphNode represents. dependencies: List of DependencyGraphNodes on which this one depends. dependents: List of DependencyGraphNodes that depend on this one. """ class CircularException(GypError): pass def __init__(self, ref): self.ref = ref self.dependencies = [] self.dependents = [] def __repr__(self): return '<DependencyGraphNode: %r>' % self.ref def FlattenToList(self): # flat_list is the sorted list of dependencies - actually, the list items # are the "ref" attributes of DependencyGraphNodes. Every target will # appear in flat_list after all of its dependencies, and before all of its # dependents. flat_list = OrderedSet() # in_degree_zeros is the list of DependencyGraphNodes that have no # dependencies not in flat_list. Initially, it is a copy of the children # of this node, because when the graph was built, nodes with no # dependencies were made implicit dependents of the root node. in_degree_zeros = set(self.dependents[:]) while in_degree_zeros: # Nodes in in_degree_zeros have no dependencies not in flat_list, so they # can be appended to flat_list. Take these nodes out of in_degree_zeros # as work progresses, so that the next node to process from the list can # always be accessed at a consistent position. node = in_degree_zeros.pop() flat_list.add(node.ref) # Look at dependents of the node just added to flat_list. Some of them # may now belong in in_degree_zeros. for node_dependent in node.dependents: is_in_degree_zero = True # TODO: We want to check through the # node_dependent.dependencies list but if it's long and we # always start at the beginning, then we get O(n^2) behaviour. for node_dependent_dependency in node_dependent.dependencies: if not node_dependent_dependency.ref in flat_list: # The dependent one or more dependencies not in flat_list. There # will be more chances to add it to flat_list when examining # it again as a dependent of those other dependencies, provided # that there are no cycles. is_in_degree_zero = False break if is_in_degree_zero: # All of the dependent's dependencies are already in flat_list. Add # it to in_degree_zeros where it will be processed in a future # iteration of the outer loop. in_degree_zeros.add(node_dependent) return list(flat_list) def FindCycles(self): """ Returns a list of cycles in the graph, where each cycle is its own list. """ results = [] visited = set() def Visit(node, path): for child in node.dependents: if child in path: results.append([child] + path[:path.index(child) + 1]) elif not child in visited: visited.add(child) Visit(child, [child] + path) visited.add(self) Visit(self, [self]) return results def DirectDependencies(self, dependencies=None): """Returns a list of just direct dependencies.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependencies: dependencies.append(dependency.ref) return dependencies def _AddImportedDependencies(self, targets, dependencies=None): """Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point. """ if dependencies == None: dependencies = [] index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Add any dependencies whose settings should be imported to the list # if not already present. Newly-added items will be checked for # their own imports when the list iteration reaches them. # Rather than simply appending new items, insert them after the # dependency that exported them. This is done to more closely match # the depth-first method used by DeepDependencies. add_index = 1 for imported_dependency in \ dependency_dict.get('export_dependent_settings', []): if imported_dependency not in dependencies: dependencies.insert(index + add_index, imported_dependency) add_index = add_index + 1 index = index + 1 return dependencies def DirectAndImportedDependencies(self, targets, dependencies=None): """Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for. """ dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies) def DeepDependencies(self, dependencies=None): """Returns an OrderedSet of all of a target's dependencies, recursively.""" if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref is None: continue if dependency.ref not in dependencies: dependency.DeepDependencies(dependencies) dependencies.add(dependency.ref) return dependencies def _LinkDependenciesInternal(self, targets, include_shared_libraries, dependencies=None, initial=True): """Returns an OrderedSet of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect dependencies that are linked into the linkable target for which the list is being built. If |include_shared_libraries| is False, the resulting dependencies will not include shared_library targets that are linked into this target. """ if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() # Check for None, corresponding to the root node. if self.ref is None: return dependencies # It's kind of sucky that |targets| has to be passed into this function, # but that's presently the easiest way to access the target dicts so that # this function can find target types. if 'target_name' not in targets[self.ref]: raise GypError("Missing 'target_name' field in target.") if 'type' not in targets[self.ref]: raise GypError("Missing 'type' field in target %s" % targets[self.ref]['target_name']) target_type = targets[self.ref]['type'] is_linkable = target_type in linkable_types if initial and not is_linkable: # If this is the first target being examined and it's not linkable, # return an empty list of link dependencies, because the link # dependencies are intended to apply to the target itself (initial is # True) and this target won't be linked. return dependencies # Don't traverse 'none' targets if explicitly excluded. if (target_type == 'none' and not targets[self.ref].get('dependencies_traverse', True)): dependencies.add(self.ref) return dependencies # Executables, mac kernel extensions and loadable modules are already fully # and finally linked. Nothing else can be a link dependency of them, there # can only be dependencies in the sense that a dependent target might run # an executable or load the loadable_module. if not initial and target_type in ('executable', 'loadable_module', 'mac_kernel_extension'): return dependencies # Shared libraries are already fully linked. They should only be included # in |dependencies| when adjusting static library dependencies (in order to # link against the shared_library's import lib), but should not be included # in |dependencies| when propagating link_settings. # The |include_shared_libraries| flag controls which of these two cases we # are handling. if (not initial and target_type == 'shared_library' and not include_shared_libraries): return dependencies # The target is linkable, add it to the list of link dependencies. if self.ref not in dependencies: dependencies.add(self.ref) if initial or not is_linkable: # If this is a subsequent target and it's linkable, don't look any # further for linkable dependencies, as they'll already be linked into # this target linkable. Always look at dependencies of the initial # target, and always look at dependencies of non-linkables. for dependency in self.dependencies: dependency._LinkDependenciesInternal(targets, include_shared_libraries, dependencies, False) return dependencies def DependenciesForLinkSettings(self, targets): """ Returns a list of dependency targets whose link_settings should be merged into this target. """ # TODO(sbaig) Currently, chrome depends on the bug that shared libraries' # link_settings are propagated. So for now, we will allow it, unless the # 'allow_sharedlib_linksettings_propagation' flag is explicitly set to # False. Once chrome is fixed, we can remove this flag. include_shared_libraries = \ targets[self.ref].get('allow_sharedlib_linksettings_propagation', True) return self._LinkDependenciesInternal(targets, include_shared_libraries) def DependenciesToLinkAgainst(self, targets): """ Returns a list of dependency targets that are linked into this target. """ return self._LinkDependenciesInternal(targets, True) def BuildDependencyList(targets): # Create a DependencyGraphNode for each target. Put it into a dict for easy # access. dependency_nodes = {} for target, spec in targets.iteritems(): if target not in dependency_nodes: dependency_nodes[target] = DependencyGraphNode(target) # Set up the dependency links. Targets that have no dependencies are treated # as dependent on root_node. root_node = DependencyGraphNode(None) for target, spec in targets.iteritems(): target_node = dependency_nodes[target] target_build_file = gyp.common.BuildFile(target) dependencies = spec.get('dependencies') if not dependencies: target_node.dependencies = [root_node] root_node.dependents.append(target_node) else: for dependency in dependencies: dependency_node = dependency_nodes.get(dependency) if not dependency_node: raise GypError("Dependency '%s' not found while " "trying to load target %s" % (dependency, target)) target_node.dependencies.append(dependency_node) dependency_node.dependents.append(target_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). if len(flat_list) != len(targets): if not root_node.dependents: # If all targets have dependencies, add the first target as a dependent # of root_node so that the cycle can be discovered from root_node. target = targets.keys()[0] target_node = dependency_nodes[target] target_node.dependencies.append(root_node) root_node.dependents.append(target_node) cycles = [] for cycle in root_node.FindCycles(): paths = [node.ref for node in cycle] cycles.append('Cycle: %s' % ' -> '.join(paths)) raise DependencyGraphNode.CircularException( 'Cycles in dependency graph detected:\n' + '\n'.join(cycles)) return [dependency_nodes, flat_list] def VerifyNoGYPFileCircularDependencies(targets): # Create a DependencyGraphNode for each gyp file containing a target. Put # it into a dict for easy access. dependency_nodes = {} for target in targets.iterkeys(): build_file = gyp.common.BuildFile(target) if not build_file in dependency_nodes: dependency_nodes[build_file] = DependencyGraphNode(build_file) # Set up the dependency links. for target, spec in targets.iteritems(): build_file = gyp.common.BuildFile(target) build_file_node = dependency_nodes[build_file] target_dependencies = spec.get('dependencies', []) for dependency in target_dependencies: try: dependency_build_file = gyp.common.BuildFile(dependency) except GypError, e: gyp.common.ExceptionAppend( e, 'while computing dependencies of .gyp file %s' % build_file) raise if dependency_build_file == build_file: # A .gyp file is allowed to refer back to itself. continue dependency_node = dependency_nodes.get(dependency_build_file) if not dependency_node: raise GypError("Dependancy '%s' not found" % dependency_build_file) if dependency_node not in build_file_node.dependencies: build_file_node.dependencies.append(dependency_node) dependency_node.dependents.append(build_file_node) # Files that have no dependencies are treated as dependent on root_node. root_node = DependencyGraphNode(None) for build_file_node in dependency_nodes.itervalues(): if len(build_file_node.dependencies) == 0: build_file_node.dependencies.append(root_node) root_node.dependents.append(build_file_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). if len(flat_list) != len(dependency_nodes): if not root_node.dependents: # If all files have dependencies, add the first file as a dependent # of root_node so that the cycle can be discovered from root_node. file_node = dependency_nodes.values()[0] file_node.dependencies.append(root_node) root_node.dependents.append(file_node) cycles = [] for cycle in root_node.FindCycles(): paths = [node.ref for node in cycle] cycles.append('Cycle: %s' % ' -> '.join(paths)) raise DependencyGraphNode.CircularException( 'Cycles in .gyp file dependency graph detected:\n' + '\n'.join(cycles)) def DoDependentSettings(key, flat_list, targets, dependency_nodes): # key should be one of all_dependent_settings, direct_dependent_settings, # or link_settings. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) if key == 'all_dependent_settings': dependencies = dependency_nodes[target].DeepDependencies() elif key == 'direct_dependent_settings': dependencies = \ dependency_nodes[target].DirectAndImportedDependencies(targets) elif key == 'link_settings': dependencies = \ dependency_nodes[target].DependenciesForLinkSettings(targets) else: raise GypError("DoDependentSettings doesn't know how to determine " 'dependencies for ' + key) for dependency in dependencies: dependency_dict = targets[dependency] if not key in dependency_dict: continue dependency_build_file = gyp.common.BuildFile(dependency) MergeDicts(target_dict, dependency_dict[key], build_file, dependency_build_file) def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes, sort_dependencies): # Recompute target "dependencies" properties. For each static library # target, remove "dependencies" entries referring to other static libraries, # unless the dependency has the "hard_dependency" attribute set. For each # linkable target, add a "dependencies" entry referring to all of the # target's computed list of link dependencies (including static libraries # if no such entry is already present. for target in flat_list: target_dict = targets[target] target_type = target_dict['type'] if target_type == 'static_library': if not 'dependencies' in target_dict: continue target_dict['dependencies_original'] = target_dict.get( 'dependencies', [])[:] # A static library should not depend on another static library unless # the dependency relationship is "hard," which should only be done when # a dependent relies on some side effect other than just the build # product, like a rule or action output. Further, if a target has a # non-hard dependency, but that dependency exports a hard dependency, # the non-hard dependency can safely be removed, but the exported hard # dependency must be added to the target to keep the same dependency # ordering. dependencies = \ dependency_nodes[target].DirectAndImportedDependencies(targets) index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Remove every non-hard static library dependency and remove every # non-static library dependency that isn't a direct dependency. if (dependency_dict['type'] == 'static_library' and \ not dependency_dict.get('hard_dependency', False)) or \ (dependency_dict['type'] != 'static_library' and \ not dependency in target_dict['dependencies']): # Take the dependency out of the list, and don't increment index # because the next dependency to analyze will shift into the index # formerly occupied by the one being removed. del dependencies[index] else: index = index + 1 # Update the dependencies. If the dependencies list is empty, it's not # needed, so unhook it. if len(dependencies) > 0: target_dict['dependencies'] = dependencies else: del target_dict['dependencies'] elif target_type in linkable_types: # Get a list of dependency targets that should be linked into this # target. Add them to the dependencies list if they're not already # present. link_dependencies = \ dependency_nodes[target].DependenciesToLinkAgainst(targets) for dependency in link_dependencies: if dependency == target: continue if not 'dependencies' in target_dict: target_dict['dependencies'] = [] if not dependency in target_dict['dependencies']: target_dict['dependencies'].append(dependency) # Sort the dependencies list in the order from dependents to dependencies. # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D. # Note: flat_list is already sorted in the order from dependencies to # dependents. if sort_dependencies and 'dependencies' in target_dict: target_dict['dependencies'] = [dep for dep in reversed(flat_list) if dep in target_dict['dependencies']] # Initialize this here to speed up MakePathRelative. exception_re = re.compile(r'''["']?[-/$<>^]''') def MakePathRelative(to_file, fro_file, item): # If item is a relative path, it's relative to the build file dict that it's # coming from. Fix it up to make it relative to the build file dict that # it's going into. # Exception: any |item| that begins with these special characters is # returned without modification. # / Used when a path is already absolute (shortcut optimization; # such paths would be returned as absolute anyway) # $ Used for build environment variables # - Used for some build environment flags (such as -lapr-1 in a # "libraries" section) # < Used for our own variable and command expansions (see ExpandVariables) # > Used for our own variable and command expansions (see ExpandVariables) # ^ Used for our own variable and command expansions (see ExpandVariables) # # "/' Used when a value is quoted. If these are present, then we # check the second character instead. # if to_file == fro_file or exception_re.match(item): return item else: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. ret = os.path.normpath(os.path.join( gyp.common.RelativePath(os.path.dirname(fro_file), os.path.dirname(to_file)), item)).replace('\\', '/') if item[-1] == '/': ret += '/' return ret def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True): # Python documentation recommends objects which do not support hash # set this value to None. Python library objects follow this rule. is_hashable = lambda val: val.__hash__ # If x is hashable, returns whether x is in s. Else returns whether x is in l. def is_in_set_or_list(x, s, l): if is_hashable(x): return x in s return x in l prepend_index = 0 # Make membership testing of hashables in |to| (in particular, strings) # faster. hashable_to_set = set(x for x in to if is_hashable(x)) for item in fro: singleton = False if type(item) in (str, int): # The cheap and easy case. if is_paths: to_item = MakePathRelative(to_file, fro_file, item) else: to_item = item if not (type(item) is str and item.startswith('-')): # Any string that doesn't begin with a "-" is a singleton - it can # only appear once in a list, to be enforced by the list merge append # or prepend. singleton = True elif type(item) is dict: # Make a copy of the dictionary, continuing to look for paths to fix. # The other intelligent aspects of merge processing won't apply because # item is being merged into an empty dict. to_item = {} MergeDicts(to_item, item, to_file, fro_file) elif type(item) is list: # Recurse, making a copy of the list. If the list contains any # descendant dicts, path fixing will occur. Note that here, custom # values for is_paths and append are dropped; those are only to be # applied to |to| and |fro|, not sublists of |fro|. append shouldn't # matter anyway because the new |to_item| list is empty. to_item = [] MergeLists(to_item, item, to_file, fro_file) else: raise TypeError( 'Attempt to merge list item of unsupported type ' + \ item.__class__.__name__) if append: # If appending a singleton that's already in the list, don't append. # This ensures that the earliest occurrence of the item will stay put. if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to): to.append(to_item) if is_hashable(to_item): hashable_to_set.add(to_item) else: # If prepending a singleton that's already in the list, remove the # existing instance and proceed with the prepend. This ensures that the # item appears at the earliest possible position in the list. while singleton and to_item in to: to.remove(to_item) # Don't just insert everything at index 0. That would prepend the new # items to the list in reverse order, which would be an unwelcome # surprise. to.insert(prepend_index, to_item) if is_hashable(to_item): hashable_to_set.add(to_item) prepend_index = prepend_index + 1 def MergeDicts(to, fro, to_file, fro_file): # I wanted to name the parameter "from" but it's a Python keyword... for k, v in fro.iteritems(): # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give # copy semantics. Something else may want to merge from the |fro| dict # later, and having the same dict ref pointed to twice in the tree isn't # what anyone wants considering that the dicts may subsequently be # modified. if k in to: bad_merge = False if type(v) in (str, int): if type(to[k]) not in (str, int): bad_merge = True elif type(v) is not type(to[k]): bad_merge = True if bad_merge: raise TypeError( 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[k].__class__.__name__ + \ ' for key ' + k) if type(v) in (str, int): # Overwrite the existing value, if any. Cheap and easy. is_path = IsPathSection(k) if is_path: to[k] = MakePathRelative(to_file, fro_file, v) else: to[k] = v elif type(v) is dict: # Recurse, guaranteeing copies will be made of objects that require it. if not k in to: to[k] = {} MergeDicts(to[k], v, to_file, fro_file) elif type(v) is list: # Lists in dicts can be merged with different policies, depending on # how the key in the "from" dict (k, the from-key) is written. # # If the from-key has ...the to-list will have this action # this character appended:... applied when receiving the from-list: # = replace # + prepend # ? set, only if to-list does not yet exist # (none) append # # This logic is list-specific, but since it relies on the associated # dict key, it's checked in this dict-oriented function. ext = k[-1] append = True if ext == '=': list_base = k[:-1] lists_incompatible = [list_base, list_base + '?'] to[list_base] = [] elif ext == '+': list_base = k[:-1] lists_incompatible = [list_base + '=', list_base + '?'] append = False elif ext == '?': list_base = k[:-1] lists_incompatible = [list_base, list_base + '=', list_base + '+'] else: list_base = k lists_incompatible = [list_base + '=', list_base + '?'] # Some combinations of merge policies appearing together are meaningless. # It's stupid to replace and append simultaneously, for example. Append # and prepend are the only policies that can coexist. for list_incompatible in lists_incompatible: if list_incompatible in fro: raise GypError('Incompatible list policies ' + k + ' and ' + list_incompatible) if list_base in to: if ext == '?': # If the key ends in "?", the list will only be merged if it doesn't # already exist. continue elif type(to[list_base]) is not list: # This may not have been checked above if merging in a list with an # extension character. raise TypeError( 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[list_base].__class__.__name__ + \ ' for key ' + list_base + '(' + k + ')') else: to[list_base] = [] # Call MergeLists, which will make copies of objects that require it. # MergeLists can recurse back into MergeDicts, although this will be # to make copies of dicts (with paths fixed), there will be no # subsequent dict "merging" once entering a list because lists are # always replaced, appended to, or prepended to. is_paths = IsPathSection(list_base) MergeLists(to[list_base], v, to_file, fro_file, is_paths, append) else: raise TypeError( 'Attempt to merge dict value of unsupported type ' + \ v.__class__.__name__ + ' for key ' + k) def MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, visited): # Skip if previously visted. if configuration in visited: return # Look at this configuration. configuration_dict = target_dict['configurations'][configuration] # Merge in parents. for parent in configuration_dict.get('inherit_from', []): MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, parent, visited + [configuration]) # Merge it into the new config. MergeDicts(new_configuration_dict, configuration_dict, build_file, build_file) # Drop abstract. if 'abstract' in new_configuration_dict: del new_configuration_dict['abstract'] def SetUpConfigurations(target, target_dict): # key_suffixes is a list of key suffixes that might appear on key names. # These suffixes are handled in conditional evaluations (for =, +, and ?) # and rules/exclude processing (for ! and /). Keys with these suffixes # should be treated the same as keys without. key_suffixes = ['=', '+', '?', '!', '/'] build_file = gyp.common.BuildFile(target) # Provide a single configuration by default if none exists. # TODO(mark): Signal an error if default_configurations exists but # configurations does not. if not 'configurations' in target_dict: target_dict['configurations'] = {'Default': {}} if not 'default_configuration' in target_dict: concrete = [i for (i, config) in target_dict['configurations'].iteritems() if not config.get('abstract')] target_dict['default_configuration'] = sorted(concrete)[0] merged_configurations = {} configs = target_dict['configurations'] for (configuration, old_configuration_dict) in configs.iteritems(): # Skip abstract configurations (saves work only). if old_configuration_dict.get('abstract'): continue # Configurations inherit (most) settings from the enclosing target scope. # Get the inheritance relationship right by making a copy of the target # dict. new_configuration_dict = {} for (key, target_val) in target_dict.iteritems(): key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if not key_base in non_configuration_keys: new_configuration_dict[key] = gyp.simple_copy.deepcopy(target_val) # Merge in configuration (with all its parents first). MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, []) merged_configurations[configuration] = new_configuration_dict # Put the new configurations back into the target dict as a configuration. for configuration in merged_configurations.keys(): target_dict['configurations'][configuration] = ( merged_configurations[configuration]) # Now drop all the abstract ones. for configuration in target_dict['configurations'].keys(): old_configuration_dict = target_dict['configurations'][configuration] if old_configuration_dict.get('abstract'): del target_dict['configurations'][configuration] # Now that all of the target's configurations have been built, go through # the target dict's keys and remove everything that's been moved into a # "configurations" section. delete_keys = [] for key in target_dict: key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if not key_base in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del target_dict[key] # Check the configurations to see if they contain invalid keys. for configuration in target_dict['configurations'].keys(): configuration_dict = target_dict['configurations'][configuration] for key in configuration_dict.keys(): if key in invalid_configuration_keys: raise GypError('%s not allowed in the %s configuration, found in ' 'target %s' % (key, configuration, target)) def ProcessListFiltersInDict(name, the_dict): """Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" list in the dict. Regular expression (regex) filters are contained in dict keys named with a trailing "/", such as "sources/" to operate on the "sources" list. Regex filters in a dict take the form: 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'], ['include', '_mac\\.cc$'] ], The first filter says to exclude all files ending in _linux.cc, _mac.cc, and _win.cc. The second filter then includes all files ending in _mac.cc that are now or were once in the "sources" list. Items matching an "exclude" filter are subject to the same processing as would occur if they were listed by name in an exclusion list (ending in "!"). Items matching an "include" filter are brought back into the main list if previously excluded by an exclusion list or exclusion regex filter. Subsequent matching "exclude" patterns can still cause items to be excluded after matching an "include". """ # Look through the dictionary for any lists whose keys end in "!" or "/". # These are lists that will be treated as exclude lists and regular # expression-based exclude/include lists. Collect the lists that are # needed first, looking for the lists that they operate on, and assemble # then into |lists|. This is done in a separate loop up front, because # the _included and _excluded keys need to be added to the_dict, and that # can't be done while iterating through it. lists = [] del_lists = [] for key, value in the_dict.iteritems(): operation = key[-1] if operation != '!' and operation != '/': continue if type(value) is not list: raise ValueError(name + ' key ' + key + ' must be list, not ' + \ value.__class__.__name__) list_key = key[:-1] if list_key not in the_dict: # This happens when there's a list like "sources!" but no corresponding # "sources" list. Since there's nothing for it to operate on, queue up # the "sources!" list for deletion now. del_lists.append(key) continue if type(the_dict[list_key]) is not list: value = the_dict[list_key] raise ValueError(name + ' key ' + list_key + \ ' must be list, not ' + \ value.__class__.__name__ + ' when applying ' + \ {'!': 'exclusion', '/': 'regex'}[operation]) if not list_key in lists: lists.append(list_key) # Delete the lists that are known to be unneeded at this point. for del_list in del_lists: del the_dict[del_list] for list_key in lists: the_list = the_dict[list_key] # Initialize the list_actions list, which is parallel to the_list. Each # item in list_actions identifies whether the corresponding item in # the_list should be excluded, unconditionally preserved (included), or # whether no exclusion or inclusion has been applied. Items for which # no exclusion or inclusion has been applied (yet) have value -1, items # excluded have value 0, and items included have value 1. Includes and # excludes override previous actions. All items in list_actions are # initialized to -1 because no excludes or includes have been processed # yet. list_actions = list((-1,) * len(the_list)) exclude_key = list_key + '!' if exclude_key in the_dict: for exclude_item in the_dict[exclude_key]: for index in xrange(0, len(the_list)): if exclude_item == the_list[index]: # This item matches the exclude_item, so set its action to 0 # (exclude). list_actions[index] = 0 # The "whatever!" list is no longer needed, dump it. del the_dict[exclude_key] regex_key = list_key + '/' if regex_key in the_dict: for regex_item in the_dict[regex_key]: [action, pattern] = regex_item pattern_re = re.compile(pattern) if action == 'exclude': # This item matches an exclude regex, so set its value to 0 (exclude). action_value = 0 elif action == 'include': # This item matches an include regex, so set its value to 1 (include). action_value = 1 else: # This is an action that doesn't make any sense. raise ValueError('Unrecognized action ' + action + ' in ' + name + \ ' key ' + regex_key) for index in xrange(0, len(the_list)): list_item = the_list[index] if list_actions[index] == action_value: # Even if the regex matches, nothing will change so continue (regex # searches are expensive). continue if pattern_re.search(list_item): # Regular expression match. list_actions[index] = action_value # The "whatever/" list is no longer needed, dump it. del the_dict[regex_key] # Add excluded items to the excluded list. # # Note that exclude_key ("sources!") is different from excluded_key # ("sources_excluded"). The exclude_key list is input and it was already # processed and deleted; the excluded_key list is output and it's about # to be created. excluded_key = list_key + '_excluded' if excluded_key in the_dict: raise GypError(name + ' key ' + excluded_key + ' must not be present prior ' ' to applying exclusion/regex filters for ' + list_key) excluded_list = [] # Go backwards through the list_actions list so that as items are deleted, # the indices of items that haven't been seen yet don't shift. That means # that things need to be prepended to excluded_list to maintain them in the # same order that they existed in the_list. for index in xrange(len(list_actions) - 1, -1, -1): if list_actions[index] == 0: # Dump anything with action 0 (exclude). Keep anything with action 1 # (include) or -1 (no include or exclude seen for the item). excluded_list.insert(0, the_list[index]) del the_list[index] # If anything was excluded, put the excluded list into the_dict at # excluded_key. if len(excluded_list) > 0: the_dict[excluded_key] = excluded_list # Now recurse into subdicts and lists that may contain dicts. for key, value in the_dict.iteritems(): if type(value) is dict: ProcessListFiltersInDict(key, value) elif type(value) is list: ProcessListFiltersInList(key, value) def ProcessListFiltersInList(name, the_list): for item in the_list: if type(item) is dict: ProcessListFiltersInDict(name, item) elif type(item) is list: ProcessListFiltersInList(name, item) def ValidateTargetType(target, target_dict): """Ensures the 'type' field on the target is one of the known types. Arguments: target: string, name of target. target_dict: dict, target spec. Raises an exception on error. """ VALID_TARGET_TYPES = ('executable', 'loadable_module', 'static_library', 'shared_library', 'mac_kernel_extension', 'none') target_type = target_dict.get('type', None) if target_type not in VALID_TARGET_TYPES: raise GypError("Target %s has an invalid target type '%s'. " "Must be one of %s." % (target, target_type, '/'.join(VALID_TARGET_TYPES))) if (target_dict.get('standalone_static_library', 0) and not target_type == 'static_library'): raise GypError('Target %s has type %s but standalone_static_library flag is' ' only valid for static_library type.' % (target, target_type)) def ValidateSourcesInTarget(target, target_dict, build_file, duplicate_basename_check): if not duplicate_basename_check: return if target_dict.get('type', None) != 'static_library': return sources = target_dict.get('sources', []) basenames = {} for source in sources: name, ext = os.path.splitext(source) is_compiled_file = ext in [ '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S'] if not is_compiled_file: continue basename = os.path.basename(name) # Don't include extension. basenames.setdefault(basename, []).append(source) error = '' for basename, files in basenames.iteritems(): if len(files) > 1: error += ' %s: %s\n' % (basename, ' '.join(files)) if error: print('static library %s has several files with the same basename:\n' % target + error + 'libtool on Mac cannot handle that. Use ' '--no-duplicate-basename-check to disable this validation.') raise GypError('Duplicate basenames in sources section, see list above') def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): """Ensures that the rules sections in target_dict are valid and consistent, and determines which sources they apply to. Arguments: target: string, name of target. target_dict: dict, target spec containing "rules" and "sources" lists. extra_sources_for_rules: a list of keys to scan for rule matches in addition to 'sources'. """ # Dicts to map between values found in rules' 'rule_name' and 'extension' # keys and the rule dicts themselves. rule_names = {} rule_extensions = {} rules = target_dict.get('rules', []) for rule in rules: # Make sure that there's no conflict among rule names and extensions. rule_name = rule['rule_name'] if rule_name in rule_names: raise GypError('rule %s exists in duplicate, target %s' % (rule_name, target)) rule_names[rule_name] = rule rule_extension = rule['extension'] if rule_extension.startswith('.'): rule_extension = rule_extension[1:] if rule_extension in rule_extensions: raise GypError(('extension %s associated with multiple rules, ' + 'target %s rules %s and %s') % (rule_extension, target, rule_extensions[rule_extension]['rule_name'], rule_name)) rule_extensions[rule_extension] = rule # Make sure rule_sources isn't already there. It's going to be # created below if needed. if 'rule_sources' in rule: raise GypError( 'rule_sources must not exist in input, target %s rule %s' % (target, rule_name)) rule_sources = [] source_keys = ['sources'] source_keys.extend(extra_sources_for_rules) for source_key in source_keys: for source in target_dict.get(source_key, []): (source_root, source_extension) = os.path.splitext(source) if source_extension.startswith('.'): source_extension = source_extension[1:] if source_extension == rule_extension: rule_sources.append(source) if len(rule_sources) > 0: rule['rule_sources'] = rule_sources def ValidateRunAsInTarget(target, target_dict, build_file): target_name = target_dict.get('target_name') run_as = target_dict.get('run_as') if not run_as: return if type(run_as) is not dict: raise GypError("The 'run_as' in target %s from file %s should be a " "dictionary." % (target_name, build_file)) action = run_as.get('action') if not action: raise GypError("The 'run_as' in target %s from file %s must have an " "'action' section." % (target_name, build_file)) if type(action) is not list: raise GypError("The 'action' for 'run_as' in target %s from file %s " "must be a list." % (target_name, build_file)) working_directory = run_as.get('working_directory') if working_directory and type(working_directory) is not str: raise GypError("The 'working_directory' for 'run_as' in target %s " "in file %s should be a string." % (target_name, build_file)) environment = run_as.get('environment') if environment and type(environment) is not dict: raise GypError("The 'environment' for 'run_as' in target %s " "in file %s should be a dictionary." % (target_name, build_file)) def ValidateActionsInTarget(target, target_dict, build_file): '''Validates the inputs to the actions in a target.''' target_name = target_dict.get('target_name') actions = target_dict.get('actions', []) for action in actions: action_name = action.get('action_name') if not action_name: raise GypError("Anonymous action in target %s. " "An action must have an 'action_name' field." % target_name) inputs = action.get('inputs', None) if inputs is None: raise GypError('Action in target %s has no inputs.' % target_name) action_command = action.get('action') if action_command and not action_command[0]: raise GypError("Empty action as command in target %s." % target_name) def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if type(v) is int: v = str(v) the_dict[k] = v elif type(v) is dict: TurnIntIntoStrInDict(v) elif type(v) is list: TurnIntIntoStrInList(v) if type(k) is int: del the_dict[k] the_dict[str(k)] = v def TurnIntIntoStrInList(the_list): """Given list the_list, recursively converts all integers into strings. """ for index in xrange(0, len(the_list)): item = the_list[index] if type(item) is int: the_list[index] = str(item) elif type(item) is dict: TurnIntIntoStrInDict(item) elif type(item) is list: TurnIntIntoStrInList(item) def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, data): """Return only the targets that are deep dependencies of |root_targets|.""" qualified_root_targets = [] for target in root_targets: target = target.strip() qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list) if not qualified_targets: raise GypError("Could not find target %s" % target) qualified_root_targets.extend(qualified_targets) wanted_targets = {} for target in qualified_root_targets: wanted_targets[target] = targets[target] for dependency in dependency_nodes[target].DeepDependencies(): wanted_targets[dependency] = targets[dependency] wanted_flat_list = [t for t in flat_list if t in wanted_targets] # Prune unwanted targets from each build_file's data dict. for build_file in data['target_build_files']: if not 'targets' in data[build_file]: continue new_targets = [] for target in data[build_file]['targets']: qualified_name = gyp.common.QualifiedTarget(build_file, target['target_name'], target['toolset']) if qualified_name in wanted_targets: new_targets.append(target) data[build_file]['targets'] = new_targets return wanted_targets, wanted_flat_list def VerifyNoCollidingTargets(targets): """Verify that no two targets in the same directory share the same name. Arguments: targets: A list of targets in the form 'path/to/file.gyp:target_name'. """ # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'. used = {} for target in targets: # Separate out 'path/to/file.gyp, 'target_name' from # 'path/to/file.gyp:target_name'. path, name = target.rsplit(':', 1) # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'. subdir, gyp = os.path.split(path) # Use '.' for the current directory '', so that the error messages make # more sense. if not subdir: subdir = '.' # Prepare a key like 'path/to:target_name'. key = subdir + ':' + name if key in used: # Complain if this target is already used. raise GypError('Duplicate target name "%s" in directory "%s" used both ' 'in "%s" and "%s".' % (name, subdir, gyp, used[key])) used[key] = gyp def SetGeneratorGlobals(generator_input_info): # Set up path_sections and non_configuration_keys with the default data plus # the generator-specific data. global path_sections path_sections = set(base_path_sections) path_sections.update(generator_input_info['path_sections']) global non_configuration_keys non_configuration_keys = base_non_configuration_keys[:] non_configuration_keys.extend(generator_input_info['non_configuration_keys']) global multiple_toolsets multiple_toolsets = generator_input_info[ 'generator_supports_multiple_toolsets'] global generator_filelist_paths generator_filelist_paths = generator_input_info['generator_filelist_paths'] def Load(build_files, variables, includes, depth, generator_input_info, check, circular_check, duplicate_basename_check, parallel, root_targets): SetGeneratorGlobals(generator_input_info) # A generator can have other lists (in addition to sources) be processed # for rules. extra_sources_for_rules = generator_input_info['extra_sources_for_rules'] # Load build files. This loads every target-containing build file into # the |data| dictionary such that the keys to |data| are build file names, # and the values are the entire build file contents after "early" or "pre" # processing has been done and includes have been resolved. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps # track of the keys corresponding to "target" files. data = {'target_build_files': set()} # Normalize paths everywhere. This is important because paths will be # used as keys to the data dict and for references between input files. build_files = set(map(os.path.normpath, build_files)) if parallel: LoadTargetBuildFilesParallel(build_files, data, variables, includes, depth, check, generator_input_info) else: aux_data = {} for build_file in build_files: try: LoadTargetBuildFile(build_file, data, aux_data, variables, includes, depth, check, True) except Exception, e: gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file) raise # Build a dict to access each target's subdict by qualified name. targets = BuildTargetsDict(data) # Fully qualify all dependency links. QualifyDependencies(targets) # Remove self-dependencies from targets that have 'prune_self_dependencies' # set to 1. RemoveSelfDependencies(targets) # Expand dependencies specified as build_file:*. ExpandWildcardDependencies(targets, data) # Remove all dependencies marked as 'link_dependency' from the targets of # type 'none'. RemoveLinkDependenciesFromNoneTargets(targets) # Apply exclude (!) and regex (/) list filters only for dependency_sections. for target_name, target_dict in targets.iteritems(): tmp_dict = {} for key_base in dependency_sections: for op in ('', '!', '/'): key = key_base + op if key in target_dict: tmp_dict[key] = target_dict[key] del target_dict[key] ProcessListFiltersInDict(target_name, tmp_dict) # Write the results back to |target_dict|. for key in tmp_dict: target_dict[key] = tmp_dict[key] # Make sure every dependency appears at most once. RemoveDuplicateDependencies(targets) if circular_check: # Make sure that any targets in a.gyp don't contain dependencies in other # .gyp files that further depend on a.gyp. VerifyNoGYPFileCircularDependencies(targets) [dependency_nodes, flat_list] = BuildDependencyList(targets) if root_targets: # Remove, from |targets| and |flat_list|, the targets that are not deep # dependencies of the targets specified in |root_targets|. targets, flat_list = PruneUnwantedTargets( targets, flat_list, dependency_nodes, root_targets, data) # Check that no two targets in the same directory have the same name. VerifyNoCollidingTargets(flat_list) # Handle dependent settings of various types. for settings_type in ['all_dependent_settings', 'direct_dependent_settings', 'link_settings']: DoDependentSettings(settings_type, flat_list, targets, dependency_nodes) # Take out the dependent settings now that they've been published to all # of the targets that require them. for target in flat_list: if settings_type in targets[target]: del targets[target][settings_type] # Make sure static libraries don't declare dependencies on other static # libraries, but that linkables depend on all unlinked static libraries # that they need so that their link steps will be correct. gii = generator_input_info if gii['generator_wants_static_library_dependencies_adjusted']: AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes, gii['generator_wants_sorted_dependencies']) # Apply "post"/"late"/"target" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATE, variables, build_file) # Move everything that can go into a "configurations" section into one. for target in flat_list: target_dict = targets[target] SetUpConfigurations(target, target_dict) # Apply exclude (!) and regex (/) list filters. for target in flat_list: target_dict = targets[target] ProcessListFiltersInDict(target, target_dict) # Apply "latelate" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATELATE, variables, build_file) # Make sure that the rules make sense, and build up rule_sources lists as # needed. Not all generators will need to use the rule_sources lists, but # some may, and it seems best to build the list in a common spot. # Also validate actions and run_as elements in targets. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ValidateTargetType(target, target_dict) ValidateSourcesInTarget(target, target_dict, build_file, duplicate_basename_check) ValidateRulesInTarget(target, target_dict, extra_sources_for_rules) ValidateRunAsInTarget(target, target_dict, build_file) ValidateActionsInTarget(target, target_dict, build_file) # Generators might not expect ints. Turn them into strs. TurnIntIntoStrInDict(data) # TODO(mark): Return |data| for now because the generator needs a list of # build files that came in. In the future, maybe it should just accept # a list, and not the whole data dict. return [flat_list, targets, data]
jackm/Kijiji-Repost-Headless
refs/heads/master
kijiji_repost_headless/kijiji_api.py
1
import json import re import sys from time import strftime from random import choice import bs4 import requests import yaml user_agents = [ # Random list of top UAs for mac and windows/ chrome & FF "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/74.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/74.0" ] session_ua = choice(user_agents) request_headers = {"User-Agent": session_ua} if sys.version_info < (3, 0): raise Exception("This program requires Python 3.0 or greater") class KijijiApiException(Exception): """ Custom KijijiApi exception class """ def __init__(self, msg="KijijiApi exception encountered.", dump=None): self.msg = msg self.dumpfilepath = "" if dump: self.dumpfilepath = "kijijiapi_dump_{}.html".format(strftime("%Y%m%dT%H%M%S")) with open(self.dumpfilepath, 'a', encoding='utf-8') as f: f.write(dump) def __str__(self): if self.dumpfilepath: return "{}\nSee {} in current directory for latest dumpfile.".format(self.msg, self.dumpfilepath) else: return self.msg def get_token(html, attrib_name): """ Return value of first match for element with name attribute """ soup = bs4.BeautifulSoup(html, 'html.parser') res = soup.select("[name='{}']".format(attrib_name)) if not res: raise KijijiApiException("Element with name attribute '{}' not found in html text.".format(attrib_name), html) return res[0]['value'] def get_kj_data(html): """ Return dict of Kijiji page data The 'window.__data' JSON object contains many useful key/values """ soup = bs4.BeautifulSoup(html, 'html.parser') p = re.compile('window.__data=(.*);') script_list = soup.find_all("script", {"src": False}) for script in script_list: if script: m = p.search(script.string) if m: return json.loads(m.group(1)) raise KijijiApiException("'__data' JSON object not found in html text.", html) def get_xsrf_token(html): """ Return XSRF token This function is only necessary for the 'm-my-ads.html' page, as this particular page does not contain the usual 'ca.kijiji.xsrf.token' hidden HTML form input element, which is easier to scrape """ soup = bs4.BeautifulSoup(html, 'html.parser') p = re.compile('Zoop\.init\(.*config: ({.+?}).*\);') for script in soup.find_all("script", {"src": False}): if script: m = p.search(script.string.replace("\n", "")) if m: # Using yaml to load since this is not valid JSON return yaml.load(m.group(1), Loader=yaml.FullLoader)['token'] raise KijijiApiException("XSRF token not found in html text.", html) class KijijiApi: """ All functions require to be logged in to Kijiji first in order to function correctly """ def __init__(self): config = {} self.session = requests.Session() def login(self, username, password): """ Login to Kijiji for the current session """ login_url = 'https://www.kijiji.ca/t-login.html' resp = self.session.get(login_url, headers=request_headers) payload = { 'emailOrNickname': username, 'password': password, 'rememberMe': 'true', '_rememberMe': 'on', 'ca.kijiji.xsrf.token': get_token(resp.text, 'ca.kijiji.xsrf.token'), 'targetUrl': get_kj_data(resp.text)['config']['targetUrl'], } resp = self.session.post(login_url, data=payload) if not self.is_logged_in(): raise KijijiApiException("Could not log in.", resp.text) def is_logged_in(self): """ Return true if logged into Kijiji for the current session """ resp = self.session.get('https://www.kijiji.ca/my/ads.json', headers=request_headers) try: resp.json() return True except: return False def logout(self): """ Logout of Kijiji for the current session """ self.session.get('https://www.kijiji.ca/m-logout.html', headers=request_headers) def delete_ad(self, ad_id): """ Delete ad based on ad ID """ my_ads_page = self.session.get('https://www.kijiji.ca/m-my-ads.html', headers=request_headers) params = { 'Action': 'DELETE_ADS', 'Mode': 'ACTIVE', 'needsRedirect': 'false', 'ads': '[{{"adId":"{}","reason":"PREFER_NOT_TO_SAY","otherReason":""}}]'.format(ad_id), 'ca.kijiji.xsrf.token': get_xsrf_token(my_ads_page.text), } resp = self.session.post('https://www.kijiji.ca/j-delete-ad.json', data=params, headers=request_headers) if "OK" not in resp.text: raise KijijiApiException("Could not delete ad.", resp.text) def delete_ad_using_title(self, title): """ Delete ad based on ad title """ all_ads = self.get_all_ads() [self.delete_ad(ad['id']) for ad in all_ads if ad['title'].strip() == title.strip()] def upload_image(self, token, image_files=[]): """ Upload one or more photos to Kijiji 'image_files' is a list of binary objects corresponding to images """ image_urls = [] image_upload_url = 'https://www.kijiji.ca/p-upload-image.html' for img_file in image_files: for i in range(0, 3): r = self.session.post( image_upload_url, files={'file': img_file}, headers={ "X-Ebay-Box-Token": token, "User-Agent": session_ua}) r.raise_for_status() try: image_tree = json.loads(r.text) img_url = image_tree['thumbnailUrl'] print("Image upload success on try #{}".format(i+1)) image_urls.append(img_url) break except (KeyError, ValueError): print("Image upload failed on try #{}".format(i+1)) return [image for image in image_urls if image is not None] def post_ad_using_data(self, data, image_files=[]): """ Post new ad 'data' is a dictionary of ad data that to be posted 'image_files' is a list of binary objects corresponding to images to upload """ # Load ad posting page (arbitrary category) resp = self.session.get('https://www.kijiji.ca/p-admarkt-post-ad.html?categoryId=15', headers=request_headers) # Get token required for upload m = re.search(r"initialXsrfToken: '(\S+)'", resp.text) if m: image_upload_token = m.group(1) else: raise KijijiApiException("'initialXsrfToken' not found in html text.", resp.text) # Upload the images image_list = self.upload_image(image_upload_token, image_files) data['images'] = ",".join(image_list) # Retrieve XSRF tokens data['ca.kijiji.xsrf.token'] = get_token(resp.text, 'ca.kijiji.xsrf.token') data['postAdForm.fraudToken'] = get_token(resp.text, 'postAdForm.fraudToken') # Select basic package and confirm terms data['postAdForm.confirmedTerms'] = True data['featuresForm.featurePackage'] = "PKG_BASIC" # Format ad data and check constraints data['postAdForm.description'] = data['postAdForm.description'].replace("\\n", "\n") title_len = len(data.get("postAdForm.title", "")) if not title_len >= 8: raise KijijiApiException("Your ad title is too short! (min 8 chars)") if title_len > 64: raise KijijiApiException("Your ad title is too long! (max 64 chars)") # Upload the ad itself new_ad_url = "https://www.kijiji.ca/p-submit-ad.html" resp = self.session.post(new_ad_url, data=data, headers=request_headers) resp.raise_for_status() if "deleteWithoutSurvey" not in resp.text: if "There was an issue posting your ad, please contact Customer Service." in resp.text: raise KijijiApiException("Could not post ad; this user is banned.", resp.text) else: raise KijijiApiException("Could not post ad.", resp.text) # Extract ad ID from response set-cookie ad_id = re.search('kjrva=(\d+)', resp.headers['Set-Cookie']).group(1) return ad_id def get_all_ads(self): """ Return a list of dicts with properties for every active ad """ resp = self.session.get('https://www.kijiji.ca/my/ads.json', headers=request_headers) resp.raise_for_status() ads_json = json.loads(resp.text) ads_info = ads_json['ads'] if ads_info: # Get rank (ie. page number) for each ad # Can't use dict comprehension for building params because every key has the same name, # must use a list of key-value tuples instead params = [("ids", ad['id']) for ad in ads_info.values()] resp = self.session.get('https://www.kijiji.ca/my/ranks', params=params, headers=request_headers) resp.raise_for_status() ranks_json = json.loads(resp.text) # Add ranks to existing ad properties dict for ad_id, rank in ranks_json['ranks'].items(): ads_info[ad_id]['rank'] = rank return [ad for ad in ads_info.values()]
Lekanich/intellij-community
refs/heads/master
python/testData/surround/CustomFoldingRegionSingleStatementInFile.py
79
<selection>print('foo') </selection>
brockwhittaker/zulip
refs/heads/master
zerver/signals.py
3
from django.dispatch import receiver from django.contrib.auth.signals import user_logged_in from django.conf import settings from django.template import loader from django.utils.timezone import get_current_timezone_name as timezone_get_current_timezone_name from django.utils.timezone import now as timezone_now from typing import Any, Dict, Optional from zerver.lib.send_email import send_email, FromAddress from zerver.models import UserProfile def get_device_browser(user_agent): # type: (str) -> Optional[str] user_agent = user_agent.lower() if "zulip" in user_agent: return "Zulip" elif "edge" in user_agent: return "Edge" elif "opera" in user_agent or "opr/" in user_agent: return "Opera" elif "chrome" in user_agent and "chromium" not in user_agent: return 'Chrome' elif "firefox" in user_agent and "seamonkey" not in user_agent and "chrome" not in user_agent: return "Firefox" elif "chromium" in user_agent: return "Chromium" elif "safari" in user_agent and "chrome" not in user_agent and "chromium" not in user_agent: return "Safari" elif "msie" in user_agent or "trident" in user_agent: return "Internet Explorer" else: return None def get_device_os(user_agent): # type: (str) -> Optional[str] user_agent = user_agent.lower() if "windows" in user_agent: return "Windows" elif "macintosh" in user_agent: return "macOS" elif "linux" in user_agent and "android" not in user_agent: return "Linux" elif "android" in user_agent: return "Android" elif "ios" in user_agent: return "iOS" elif "like mac os x" in user_agent: return "iOS" else: return None @receiver(user_logged_in, dispatch_uid="only_on_login") def email_on_new_login(sender, user, request, **kwargs): # type: (Any, UserProfile, Any, **Any) -> None # We import here to minimize the dependencies of this module, # since it runs as part of `manage.py` initialization from zerver.context_processors import common_context if not settings.SEND_LOGIN_EMAILS: return if request: # If the user's account was just created, avoid sending an email. if getattr(user, "just_registered", False): return login_time = timezone_now().strftime('%A, %B %d, %Y at %I:%M%p ') + \ timezone_get_current_timezone_name() user_agent = request.META.get('HTTP_USER_AGENT', "").lower() device_browser = get_device_browser(user_agent) device_os = get_device_os(user_agent) device_ip = request.META.get('REMOTE_ADDR') or "Uknown IP address" device_info = {"device_browser": device_browser, "device_os": device_os, "device_ip": device_ip, "login_time": login_time } context = common_context(user) context['device_info'] = device_info context['user'] = user send_email('zerver/emails/notify_new_login', to_user_id=user.id, from_name='Zulip Account Security', from_address=FromAddress.NOREPLY, context=context)
hryamzik/ansible
refs/heads/devel
lib/ansible/modules/remote_management/ucs/ucs_vlans.py
33
#!/usr/bin/python # -*- coding: utf-8 -*- # 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 = r''' --- module: ucs_vlans short_description: Configures VLANs on Cisco UCS Manager description: - Configures VLANs on Cisco UCS Manager. - Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe). extends_documentation_fragment: ucs options: state: description: - If C(present), will verify VLANs are present and will create if needed. - If C(absent), will verify VLANs are absent and will delete if needed. choices: [present, absent] default: present name: description: - The name assigned to the VLAN. - The VLAN name is case sensitive. - This name can be between 1 and 32 alphanumeric characters. - "You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period)." - You cannot change this name after the VLAN is created. required: yes multicast_policy: description: - The multicast policy associated with this VLAN. - This option is only valid if the Sharing Type field is set to None or Primary. default: '' fabric: description: - "The fabric configuration of the VLAN. This can be one of the following:" - "common - The VLAN applies to both fabrics and uses the same configuration parameters in both cases." - "A — The VLAN only applies to fabric A." - "B — The VLAN only applies to fabric B." - For upstream disjoint L2 networks, Cisco recommends that you choose common to create VLANs that apply to both fabrics. choices: [common, A, B] default: common id: description: - The unique string identifier assigned to the VLAN. - A VLAN ID can be between '1' and '3967', or between '4048' and '4093'. - You cannot create VLANs with IDs from 4030 to 4047. This range of VLAN IDs is reserved. - The VLAN IDs you specify must also be supported on the switch that you are using. - VLANs in the LAN cloud and FCoE VLANs in the SAN cloud must have different IDs. - Optional if state is absent. required: yes sharing: description: - The Sharing Type field. - "Whether this VLAN is subdivided into private or secondary VLANs. This can be one of the following:" - "none - This VLAN does not have any secondary or private VLANs. This is a regular VLAN." - "primary - This VLAN can have one or more secondary VLANs, as shown in the Secondary VLANs area. This VLAN is a primary VLAN in the private VLAN domain." - "isolated - This is a private VLAN associated with a primary VLAN. This VLAN is an Isolated VLAN." - "community - This VLAN can communicate with other ports on the same community VLAN as well as the promiscuous port. This VLAN is a Community VLAN." choices: [none, primary, isolated, community] default: none native: description: - Designates the VLAN as a native VLAN. choices: ['yes', 'no'] default: 'no' requirements: - ucsmsdk author: - David Soper (@dsoper2) - CiscoUcs (@CiscoUcs) version_added: '2.5' ''' EXAMPLES = r''' - name: Configure VLAN ucs_vlans: hostname: 172.16.143.150 username: admin password: password name: vlan2 id: '2' native: 'yes' - name: Remove VLAN ucs_vlans: hostname: 172.16.143.150 username: admin password: password name: vlan2 state: absent ''' RETURN = r''' # ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.remote_management.ucs import UCSModule, ucs_argument_spec def main(): argument_spec = ucs_argument_spec argument_spec.update( name=dict(type='str', required=True), multicast_policy=dict(type='str', default=''), fabric=dict(type='str', default='common', choices=['common', 'A', 'B']), id=dict(type='str'), sharing=dict(type='str', default='none', choices=['none', 'primary', 'isolated', 'community']), native=dict(type='str', default='no', choices=['yes', 'no']), state=dict(type='str', default='present', choices=['present', 'absent']), ) module = AnsibleModule( argument_spec, supports_check_mode=True, required_if=[ ['state', 'present', ['id']], ], ) ucs = UCSModule(module) err = False # UCSModule creation above verifies ucsmsdk is present and exits on failure, so additional imports are done below. from ucsmsdk.mometa.fabric.FabricVlan import FabricVlan changed = False try: mo_exists = False props_match = False # dn is fabric/lan/net-<name> for common vlans or fabric/lan/[A or B]/net-<name> for A or B dn_base = 'fabric/lan' if module.params['fabric'] != 'common': dn_base += '/' + module.params['fabric'] dn = dn_base + '/net-' + module.params['name'] mo = ucs.login_handle.query_dn(dn) if mo: mo_exists = True if module.params['state'] == 'absent': # mo must exist but all properties do not have to match if mo_exists: if not module.check_mode: ucs.login_handle.remove_mo(mo) ucs.login_handle.commit() changed = True else: if mo_exists: # check top-level mo props kwargs = dict(id=module.params['id']) kwargs['default_net'] = module.params['native'] kwargs['sharing'] = module.params['sharing'] kwargs['mcast_policy_name'] = module.params['multicast_policy'] if (mo.check_prop_match(**kwargs)): props_match = True if not props_match: if not module.check_mode: # create if mo does not already exist mo = FabricVlan( parent_mo_or_dn=dn_base, name=module.params['name'], id=module.params['id'], default_net=module.params['native'], sharing=module.params['sharing'], mcast_policy_name=module.params['multicast_policy'], ) ucs.login_handle.add_mo(mo, True) ucs.login_handle.commit() changed = True except Exception as e: err = True ucs.result['msg'] = "setup error: %s " % str(e) ucs.result['changed'] = changed if err: module.fail_json(**ucs.result) module.exit_json(**ucs.result) if __name__ == '__main__': main()
ContextLogic/luigi
refs/heads/master
luigi/contrib/sparkey.py
92
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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 import luigi class SparkeyExportTask(luigi.Task): """ A luigi task that writes to a local sparkey log file. Subclasses should implement the requires and output methods. The output must be a luigi.LocalTarget. The resulting sparkey log file will contain one entry for every line in the input, mapping from the first value to a tab-separated list of the rest of the line. To generate a simple key-value index, yield "key", "value" pairs from the input(s) to this task. """ # the separator used to split input lines separator = '\t' def __init__(self, *args, **kwargs): super(SparkeyExportTask, self).__init__(*args, **kwargs) def run(self): self._write_sparkey_file() def _write_sparkey_file(self): import sparkey infile = self.input() outfile = self.output() if not isinstance(outfile, luigi.LocalTarget): raise TypeError("output must be a LocalTarget") # write job output to temporary sparkey file temp_output = luigi.LocalTarget(is_tmp=True) w = sparkey.LogWriter(temp_output.path) for line in infile.open('r'): k, v = line.strip().split(self.separator, 1) w[k] = v w.close() # move finished sparkey file to final destination temp_output.move(outfile.path)
chirilo/kitsune
refs/heads/master
kitsune/tags/tests/test_helpers.py
17
from mock import Mock from nose.tools import eq_ from taggit.models import Tag from kitsune.sumo.tests import TestCase from kitsune.tags.helpers import tags_to_text class TestTagsToText(TestCase): def test_no_tags(self): eq_('', tags_to_text([])) def test_one_tag(self): eq_('tag1', tags_to_text([_tag('tag1')])) def test_two_tags(self): eq_('tag1,tag2', tags_to_text([_tag('tag1'), _tag('tag2')])) def test_three_tags(self): eq_('tag1,tag2,tag3', tags_to_text( [_tag('tag1'), _tag('tag2'), _tag('tag3')])) def _tag(slug): tag = Mock(spec=Tag) tag.slug = slug return tag
mims2707/bite-project
refs/heads/master
deps/gdata-python-client/samples/contentforshopping/add_batch_products.py
39
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import getpass from gdata.contentforshopping.data import build_entry from gdata.contentforshopping.client import ContentForShoppingClient # Gather merchant information account_id = raw_input('Merchant Account ID? ').strip() email = raw_input('Google Email Address? ').strip() # Create a client client = ContentForShoppingClient(account_id) # Perform programmatic login client.client_login(email, getpass.getpass('Google Password? '), 'Shopping API for Content sample', 'structuredcontent') products = [] for color in ['red', 'green', 'white', 'black', 'purple', 'brown', 'yellow', 'orange', 'magenta']: # Generate a product entry product_entry = build_entry( product_id='ipod%s' % color, target_country = 'US', content_language = 'EN', title='iPod Nano 8GB, %s' % color, content='A nice small mp3 player, in %s' % color, price='149', price_unit='USD', shipping_price = '5', shipping_price_unit = 'USD', tax_rate='17.5', condition = 'new', link = 'http://pseudoscience.co.uk/google4e823e35f032f011.html', color = color, ) products.append(product_entry) # Post it to the service client.insert_products(products)
geniusgogo/rt-thread
refs/heads/master
tools/codelite.py
6
# # File : codelite.py # This file is part of RT-Thread RTOS # COPYRIGHT (C) 2006 - 2020, RT-Thread Development Team # # 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. # # Change Logs: # Date Author Notes # 2020-10-14 LiuMin Add copyright information # import os import sys import string import building import rtconfig import xml.etree.ElementTree as etree from xml.etree.ElementTree import SubElement from utils import _make_path_relative from utils import xml_indent import utils fs_encoding = sys.getfilesystemencoding() def CLSetCFlags(root, flags): node = root.find('Settings').find('Configuration').find('Compiler') node.attrib['C_Options'] = flags def CLSetCxxFlags(root, flags): node = root.find('Settings').find('Configuration').find('Compiler') node.attrib['Options'] = flags def CLSetAsFlags(root, flags): node = root.find('Settings').find('Configuration').find('Compiler') node.attrib['Assembler'] = flags def CLAddIncludePath(root, path): node = root.find('Settings').find('Configuration').find('Compiler') node = SubElement(node, 'IncludePath') node.attrib['Value'] = path def CLAddPreprocessor(root, value): node = root.find('Settings').find('Configuration').find('Compiler') node = SubElement(node, 'Preprocessor') node.attrib['Value'] = value def CLSetLdFlags(root, flags): node = root.find('Settings').find('Configuration').find('Linker') node.attrib['Options'] = flags def CLAddLibrary_path(root, path): node = root.find('Settings').find('Configuration').find('Linker') node = SubElement(node, 'LibraryPath') node.attrib['Value'] = path def CLAddLibrary(root, lib): node = root.find('Settings').find('Configuration').find('Linker') node = SubElement(node, 'Library') node.attrib['Value'] = lib def CLAddFile(root, file_path): file_path = file_path.replace('\\', '/') dir_list = file_path.split('/') dir_list.pop() if not len(dir_list): dir_list.append(os.path.abspath('.').replace('\\', '/').split('/')[-1]) parent = root for dir_name in dir_list: if dir_name == '..': continue node = None nodes = parent.findall('VirtualDirectory') for iter in nodes: if iter.attrib['Name'] == dir_name: node = iter break if node is None: node = SubElement(parent, 'VirtualDirectory') node.attrib['Name'] = dir_name parent = node if parent != root: node = SubElement(parent, 'File') node.attrib['Name'] = file_path def CLAddHeaderFiles(parent, program, project_path): utils.source_ext = [] utils.source_ext = ["h"] for item in program: utils.walk_children(item) utils.source_list.sort() for f in utils.source_list: path = _make_path_relative(project_path, f) CLAddFile(parent, path) def CLAddCFiles(parent, files, project_path): for f in files: fn = f.rfile() name = fn.name path = os.path.dirname(fn.abspath) path = _make_path_relative(project_path, path) path = os.path.join(path, name) CLAddFile(parent, path) def CLGenWorkspace(project_name, project_path): if os.path.isfile('codelite_template.workspace'): tree = etree.parse('codelite_template.workspace') else: tree = etree.parse(os.path.join(os.path.dirname(__file__), 'codelite_template.workspace')) root = tree.getroot() root.attrib['Name'] = project_name node = root.find('Project') node.attrib['Name'] = project_name node.attrib['Path'] = project_name + '.project' node = root.find('BuildMatrix').find('WorkspaceConfiguration').find('Project') node.attrib['Name'] = project_name out = open(project_name + '.workspace', 'w') out.write('<?xml version="1.0" encoding="UTF-8"?>\n') xml_indent(root) out.write(etree.tostring(root, encoding='utf-8')) out.close() def TargetCodelite(script, program): project_name = os.path.abspath('.').replace('\\', '/').split('/')[-1] #project_name.replace('-', '_') project_path = os.path.abspath('.') CLGenWorkspace(project_name, project_path) if os.path.isfile('codelite_template.project'): tree = etree.parse('codelite_template.project') else: tree = etree.parse(os.path.join(os.path.dirname(__file__), 'codelite_template.project')) root = tree.getroot() root.attrib['Name'] = project_name out = open(project_name + '.project', 'w') out.write('<?xml version="1.0" encoding="UTF-8"?>\n') # add files for group in script: CLAddCFiles(root, group['src'], project_path) # add header file CLAddHeaderFiles(root, program, project_path) # SECTION 2. # write head include path if 'CPPPATH' in building.Env: cpp_path = building.Env['CPPPATH'] paths = set() for path in cpp_path: inc = _make_path_relative(project_path, os.path.normpath(path)) paths.add(inc) #.replace('\\', '/') paths = [i for i in paths] paths.sort() # write include path, definitions for elem in tree.iter(tag='Compiler'): break for path in paths: CLAddIncludePath(root, path) #print building.Env.get('LIBPATH', []) #print building.Env.get('LIBS', []) CLSetCFlags(root, building.Env.get('CCFLAGS', [])) CLSetCxxFlags(root, building.Env.get('CCFLAGS', [])) asflags = building.Env.get('ASFLAGS', []) asflags = asflags.replace('-ffunction-sections', '') asflags = asflags.replace('-fdata-sections', '') asflags = asflags.replace('-x', '') asflags = asflags.replace('-Wa,', '') asflags = asflags.replace('assembler-with-cpp', '') CLSetAsFlags(root, asflags) CLSetLdFlags(root, building.Env.get('LINKFLAGS', [])) for macro in building.Env.get('CPPDEFINES', []): for d in macro: CLAddPreprocessor(root, d) xml_indent(root) out.write(etree.tostring(root, encoding='utf-8')) out.close()
jreigel/saleor
refs/heads/master
saleor/core/management/commands/populatedb.py
6
from __future__ import unicode_literals from django.core.management import call_command from django.core.management.base import BaseCommand from django.db import connection from ...utils.random_data import ( create_orders, create_users, create_shipping_methods, create_products_by_schema, create_product_sales, create_vouchers, set_featured_products, add_address_to_admin) from ...utils import create_superuser class Command(BaseCommand): help = 'Populate database with test objects' placeholders_dir = r'saleor/static/placeholders/' def add_arguments(self, parser): parser.add_argument( '--createsuperuser', action='store_true', dest='createsuperuser', default=False, help='Create admin account') parser.add_argument( '--withoutimages', action='store_true', dest='withoutimages', default=False, help='Don\'t create product images') parser.add_argument( '--withoutsearch', action='store_true', dest='withoutsearch', default=False, help='Don\'t update search index') def make_database_faster(self): '''Sacrifices some of the safeguards of sqlite3 for speed Users are not likely to run this command in a production environment. They are even less likely to run it in production while using sqlite3. ''' if 'sqlite3' in connection.settings_dict['ENGINE']: cursor = connection.cursor() cursor.execute('PRAGMA temp_store = MEMORY;') cursor.execute('PRAGMA synchronous = OFF;') def populate_search_index(self): call_command('update_index') def handle(self, *args, **options): self.make_database_faster() create_images = not options['withoutimages'] for msg in create_shipping_methods(): self.stdout.write(msg) create_products_by_schema(self.placeholders_dir, 10, create_images, stdout=self.stdout) for msg in create_product_sales(5): self.stdout.write(msg) for msg in create_vouchers(): self.stdout.write(msg) for msg in create_users(20): self.stdout.write(msg) for msg in create_orders(20): self.stdout.write(msg) for msg in set_featured_products(16): self.stdout.write(msg) if options['createsuperuser']: credentials = {'email': 'admin@example.com', 'password': 'admin'} msg = create_superuser(credentials) self.stdout.write(msg) add_address_to_admin(credentials['email']) if not options['withoutsearch']: self.populate_search_index()
caotianwei/django
refs/heads/master
tests/gis_tests/geoapp/test_functions.py
262
from __future__ import unicode_literals import re from decimal import Decimal from django.contrib.gis.db.models import functions from django.contrib.gis.geos import ( LineString, Point, Polygon, fromstr, geos_version_info, ) from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.utils import six from ..utils import mysql, oracle, postgis, spatialite from .models import City, Country, State, Track @skipUnlessDBFeature("gis_enabled") class GISFunctionsTests(TestCase): """ Testing functions from django/contrib/gis/db/models/functions.py. Several tests are taken and adapted from GeoQuerySetTest. Area/Distance/Length/Perimeter are tested in distapp/tests. Please keep the tests in function's alphabetic order. """ fixtures = ['initial'] def test_asgeojson(self): # Only PostGIS and SpatiaLite 3.0+ support GeoJSON. if not connection.ops.geojson: with self.assertRaises(NotImplementedError): list(Country.objects.annotate(json=functions.AsGeoJSON('mpoly'))) return pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}' houston_json = ( '{"type":"Point","crs":{"type":"name","properties":' '{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}' ) victoria_json = ( '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],' '"coordinates":[-123.305196,48.462611]}' ) chicago_json = ( '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},' '"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}' ) if spatialite: victoria_json = ( '{"type":"Point","bbox":[-123.305196,48.462611,-123.305196,48.462611],' '"coordinates":[-123.305196,48.462611]}' ) # Precision argument should only be an integer with self.assertRaises(TypeError): City.objects.annotate(geojson=functions.AsGeoJSON('point', precision='foo')) # Reference queries and values. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0) # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo'; self.assertEqual( pueblo_json, City.objects.annotate(geojson=functions.AsGeoJSON('point')).get(name='Pueblo').geojson ) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we want to include the CRS by using the `crs` keyword. self.assertEqual( houston_json, City.objects.annotate(json=functions.AsGeoJSON('point', crs=True)).get(name='Houston').json ) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we include the bounding box by using the `bbox` keyword. self.assertEqual( victoria_json, City.objects.annotate( geojson=functions.AsGeoJSON('point', bbox=True) ).get(name='Victoria').geojson ) # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Chicago'; # Finally, we set every available keyword. self.assertEqual( chicago_json, City.objects.annotate( geojson=functions.AsGeoJSON('point', bbox=True, crs=True, precision=5) ).get(name='Chicago').geojson ) @skipUnlessDBFeature("has_AsGML_function") def test_asgml(self): # Should throw a TypeError when tyring to obtain GML from a # non-geometry field. qs = City.objects.all() with self.assertRaises(TypeError): qs.annotate(gml=functions.AsGML('name')) ptown = City.objects.annotate(gml=functions.AsGML('point', precision=9)).get(name='Pueblo') if oracle: # No precision parameter for Oracle :-/ gml_regex = re.compile( r'^<gml:Point srsName="SDO:4326" xmlns:gml="http://www.opengis.net/gml">' r'<gml:coordinates decimal="\." cs="," ts=" ">-104.60925\d+,38.25500\d+ ' r'</gml:coordinates></gml:Point>' ) elif spatialite and connection.ops.spatial_version < (3, 0, 0): # Spatialite before 3.0 has extra colon in SrsName gml_regex = re.compile( r'^<gml:Point SrsName="EPSG::4326"><gml:coordinates decimal="\." ' r'cs="," ts=" ">-104.609251\d+,38.255001</gml:coordinates></gml:Point>' ) else: gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>' r'-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>' ) self.assertTrue(gml_regex.match(ptown.gml)) if postgis: self.assertIn( '<gml:pos srsDimension="2">', City.objects.annotate(gml=functions.AsGML('point', version=3)).get(name='Pueblo').gml ) @skipUnlessDBFeature("has_AsKML_function") def test_askml(self): # Should throw a TypeError when trying to obtain KML from a # non-geometry field. with self.assertRaises(TypeError): City.objects.annotate(kml=functions.AsKML('name')) # Ensuring the KML is as expected. ptown = City.objects.annotate(kml=functions.AsKML('point', precision=9)).get(name='Pueblo') self.assertEqual('<Point><coordinates>-104.609252,38.255001</coordinates></Point>', ptown.kml) @skipUnlessDBFeature("has_AsSVG_function") def test_assvg(self): with self.assertRaises(TypeError): City.objects.annotate(svg=functions.AsSVG('point', precision='foo')) # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo'; svg1 = 'cx="-104.609252" cy="-38.255001"' # Even though relative, only one point so it's practically the same except for # the 'c' letter prefix on the x,y values. svg2 = svg1.replace('c', '') self.assertEqual(svg1, City.objects.annotate(svg=functions.AsSVG('point')).get(name='Pueblo').svg) self.assertEqual(svg2, City.objects.annotate(svg=functions.AsSVG('point', relative=5)).get(name='Pueblo').svg) @skipUnlessDBFeature("has_BoundingCircle_function") def test_bounding_circle(self): qs = Country.objects.annotate(circle=functions.BoundingCircle('mpoly')).order_by('name') self.assertAlmostEqual(qs[0].circle.area, 168.89, 2) self.assertAlmostEqual(qs[1].circle.area, 135.95, 2) qs = Country.objects.annotate(circle=functions.BoundingCircle('mpoly', num_seg=12)).order_by('name') self.assertAlmostEqual(qs[0].circle.area, 168.44, 2) self.assertAlmostEqual(qs[1].circle.area, 135.59, 2) @skipUnlessDBFeature("has_Centroid_function") def test_centroid(self): qs = State.objects.exclude(poly__isnull=True).annotate(centroid=functions.Centroid('poly')) tol = 1.8 if mysql else (0.1 if oracle else 0.00001) for state in qs: self.assertTrue(state.poly.centroid.equals_exact(state.centroid, tol)) @skipUnlessDBFeature("has_Difference_function") def test_difference(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(diff=functions.Difference('mpoly', geom)) # For some reason SpatiaLite does something screwy with the Texas geometry here. if spatialite: qs = qs.exclude(name='Texas') for c in qs: self.assertEqual(c.mpoly.difference(geom), c.diff) @skipUnlessDBFeature("has_Difference_function") def test_difference_mixed_srid(self): """Testing with mixed SRID (Country has default 4326).""" geom = Point(556597.4, 2632018.6, srid=3857) # Spherical mercator qs = Country.objects.annotate(difference=functions.Difference('mpoly', geom)) # For some reason SpatiaLite does something screwy with the Texas geometry here. if spatialite: qs = qs.exclude(name='Texas') for c in qs: self.assertEqual(c.mpoly.difference(geom), c.difference) @skipUnlessDBFeature("has_Envelope_function") def test_envelope(self): countries = Country.objects.annotate(envelope=functions.Envelope('mpoly')) for country in countries: self.assertIsInstance(country.envelope, Polygon) @skipUnlessDBFeature("has_ForceRHR_function") def test_force_rhr(self): rings = ( ((0, 0), (5, 0), (0, 5), (0, 0)), ((1, 1), (1, 3), (3, 1), (1, 1)), ) rhr_rings = ( ((0, 0), (0, 5), (5, 0), (0, 0)), ((1, 1), (3, 1), (1, 3), (1, 1)), ) State.objects.create(name='Foo', poly=Polygon(*rings)) st = State.objects.annotate(force_rhr=functions.ForceRHR('poly')).get(name='Foo') self.assertEqual(rhr_rings, st.force_rhr.coords) @skipUnlessDBFeature("has_GeoHash_function") def test_geohash(self): # Reference query: # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston'; # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston'; ref_hash = '9vk1mfq8jx0c8e0386z6' h1 = City.objects.annotate(geohash=functions.GeoHash('point')).get(name='Houston') h2 = City.objects.annotate(geohash=functions.GeoHash('point', precision=5)).get(name='Houston') self.assertEqual(ref_hash, h1.geohash) self.assertEqual(ref_hash[:5], h2.geohash) @skipUnlessDBFeature("has_Intersection_function") def test_intersection(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(inter=functions.Intersection('mpoly', geom)) for c in qs: if spatialite: # When the intersection is empty, Spatialite returns None expected = None else: expected = c.mpoly.intersection(geom) self.assertEqual(c.inter, expected) @skipUnlessDBFeature("has_MemSize_function") def test_memsize(self): ptown = City.objects.annotate(size=functions.MemSize('point')).get(name='Pueblo') self.assertTrue(20 <= ptown.size <= 40) # Exact value may depend on PostGIS version @skipUnlessDBFeature("has_NumGeom_function") def test_num_geom(self): # Both 'countries' only have two geometries. for c in Country.objects.annotate(num_geom=functions.NumGeometries('mpoly')): self.assertEqual(2, c.num_geom) qs = City.objects.filter(point__isnull=False).annotate(num_geom=functions.NumGeometries('point')) for city in qs: # Oracle and PostGIS 2.0+ will return 1 for the number of # geometries on non-collections, whereas PostGIS < 2.0.0 and MySQL # will return None. if (postgis and connection.ops.spatial_version < (2, 0, 0)) or mysql: self.assertIsNone(city.num_geom) else: self.assertEqual(1, city.num_geom) @skipUnlessDBFeature("has_NumPoint_function") def test_num_points(self): coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name='Foo', line=LineString(coords)) qs = Track.objects.annotate(num_points=functions.NumPoints('line')) self.assertEqual(qs.first().num_points, 2) if spatialite or mysql: # Spatialite and MySQL can only count points on LineStrings return for c in Country.objects.annotate(num_points=functions.NumPoints('mpoly')): self.assertEqual(c.mpoly.num_points, c.num_points) if not oracle: # Oracle cannot count vertices in Point geometries. for c in City.objects.annotate(num_points=functions.NumPoints('point')): self.assertEqual(1, c.num_points) @skipUnlessDBFeature("has_PointOnSurface_function") def test_point_on_surface(self): # Reference values. if oracle: # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_GEOM.SDO_POINTONSURFACE(GEOAPP_COUNTRY.MPOLY, 0.05)) # FROM GEOAPP_COUNTRY; ref = {'New Zealand': fromstr('POINT (174.616364 -36.100861)', srid=4326), 'Texas': fromstr('POINT (-103.002434 36.500397)', srid=4326), } else: # Using GEOSGeometry to compute the reference point on surface values # -- since PostGIS also uses GEOS these should be the same. ref = {'New Zealand': Country.objects.get(name='New Zealand').mpoly.point_on_surface, 'Texas': Country.objects.get(name='Texas').mpoly.point_on_surface } qs = Country.objects.annotate(point_on_surface=functions.PointOnSurface('mpoly')) for country in qs: tol = 0.00001 # Spatialite might have WKT-translation-related precision issues self.assertTrue(ref[country.name].equals_exact(country.point_on_surface, tol)) @skipUnlessDBFeature("has_Reverse_function") def test_reverse_geom(self): coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name='Foo', line=LineString(coords)) track = Track.objects.annotate(reverse_geom=functions.Reverse('line')).get(name='Foo') coords.reverse() self.assertEqual(tuple(coords), track.reverse_geom.coords) @skipUnlessDBFeature("has_Scale_function") def test_scale(self): xfac, yfac = 2, 3 tol = 5 # The low precision tolerance is for SpatiaLite qs = Country.objects.annotate(scaled=functions.Scale('mpoly', xfac, yfac)) for country in qs: for p1, p2 in zip(country.mpoly, country.scaled): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): self.assertAlmostEqual(c1[0] * xfac, c2[0], tol) self.assertAlmostEqual(c1[1] * yfac, c2[1], tol) # Test float/Decimal values qs = Country.objects.annotate(scaled=functions.Scale('mpoly', 1.5, Decimal('2.5'))) self.assertGreater(qs[0].scaled.area, qs[0].mpoly.area) @skipUnlessDBFeature("has_SnapToGrid_function") def test_snap_to_grid(self): # Let's try and break snap_to_grid() with bad combinations of arguments. for bad_args in ((), range(3), range(5)): with self.assertRaises(ValueError): Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args)) for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))): with self.assertRaises(TypeError): Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args)) # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org # from the world borders dataset he provides. wkt = ('MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,' '12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,' '12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,' '12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,' '12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,' '12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,' '12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,' '12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))') Country.objects.create(name='San Marino', mpoly=fromstr(wkt)) # Because floating-point arithmetic isn't exact, we set a tolerance # to pass into GEOS `equals_exact`. tol = 0.000000001 # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))') self.assertTrue( ref.equals_exact( Country.objects.annotate( snap=functions.SnapToGrid('mpoly', 0.1) ).get(name='San Marino').snap, tol ) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))') self.assertTrue( ref.equals_exact( Country.objects.annotate( snap=functions.SnapToGrid('mpoly', 0.05, 0.23) ).get(name='San Marino').snap, tol ) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr( 'MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))' ) self.assertTrue( ref.equals_exact( Country.objects.annotate( snap=functions.SnapToGrid('mpoly', 0.05, 0.23, 0.5, 0.17) ).get(name='San Marino').snap, tol ) ) @skipUnlessDBFeature("has_SymDifference_function") def test_sym_difference(self): if geos_version_info()['version'] < '3.3.0': self.skipTest("GEOS >= 3.3 required") geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(sym_difference=functions.SymDifference('mpoly', geom)) for country in qs: # Ordering might differ in collections self.assertSetEqual(set(g.wkt for g in country.mpoly.sym_difference(geom)), set(g.wkt for g in country.sym_difference)) @skipUnlessDBFeature("has_Transform_function") def test_transform(self): # Pre-transformed points for Houston and Pueblo. ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774) prec = 3 # Precision is low due to version variations in PROJ and GDAL. # Asserting the result of the transform operation with the values in # the pre-transformed points. h = City.objects.annotate(pt=functions.Transform('point', ptown.srid)).get(name='Pueblo') self.assertEqual(2774, h.pt.srid) self.assertAlmostEqual(ptown.x, h.pt.x, prec) self.assertAlmostEqual(ptown.y, h.pt.y, prec) @skipUnlessDBFeature("has_Translate_function") def test_translate(self): xfac, yfac = 5, -23 qs = Country.objects.annotate(translated=functions.Translate('mpoly', xfac, yfac)) for c in qs: for p1, p2 in zip(c.mpoly, c.translated): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): # The low precision is for SpatiaLite self.assertAlmostEqual(c1[0] + xfac, c2[0], 5) self.assertAlmostEqual(c1[1] + yfac, c2[1], 5) # Some combined function tests @skipUnlessDBFeature( "has_Difference_function", "has_Intersection_function", "has_SymDifference_function", "has_Union_function") def test_diff_intersection_union(self): "Testing the `difference`, `intersection`, `sym_difference`, and `union` GeoQuerySet methods." geom = Point(5, 23, srid=4326) qs = Country.objects.all().annotate( difference=functions.Difference('mpoly', geom), sym_difference=functions.SymDifference('mpoly', geom), union=functions.Union('mpoly', geom), ) # For some reason SpatiaLite does something screwey with the Texas geometry here. # Also, it doesn't like the null intersection. if spatialite: qs = qs.exclude(name='Texas') else: qs = qs.annotate(intersection=functions.Intersection('mpoly', geom)) if oracle: # Should be able to execute the queries; however, they won't be the same # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or # SpatiaLite). return for c in qs: self.assertEqual(c.mpoly.difference(geom), c.difference) if not spatialite: self.assertEqual(c.mpoly.intersection(geom), c.intersection) # Ordering might differ in collections self.assertSetEqual(set(g.wkt for g in c.mpoly.sym_difference(geom)), set(g.wkt for g in c.sym_difference)) self.assertSetEqual(set(g.wkt for g in c.mpoly.union(geom)), set(g.wkt for g in c.union)) @skipUnlessDBFeature("has_Union_function") def test_union(self): geom = Point(-95.363151, 29.763374, srid=4326) ptown = City.objects.annotate(union=functions.Union('point', geom)).get(name='Dallas') tol = 0.00001 # Undefined ordering expected1 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)', srid=4326) expected2 = fromstr('MULTIPOINT(-95.363151 29.763374,-96.801611 32.782057)', srid=4326) self.assertTrue(expected1.equals_exact(ptown.union, tol) or expected2.equals_exact(ptown.union, tol))
kelle/astropy
refs/heads/master
astropy/units/astrophys.py
1
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This package defines the astrophysics-specific units. They are also available in the `astropy.units` namespace. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from . import si from ..constants import si as _si from .core import (UnitBase, def_unit, si_prefixes, binary_prefixes, set_enabled_units) # To ensure si units of the constants can be interpreted. set_enabled_units([si]) import numpy as _numpy _ns = globals() ########################################################################### # LENGTH def_unit((['AU', 'au'], ['astronomical_unit']), _si.au, namespace=_ns, prefixes=True, doc="astronomical unit: approximately the mean Earth--Sun " "distance.") def_unit(['pc', 'parsec'], _si.pc, namespace=_ns, prefixes=True, doc="parsec: approximately 3.26 light-years.") def_unit(['solRad', 'R_sun', 'Rsun'], _si.R_sun, namespace=_ns, doc="Solar radius", prefixes=False, format={'latex': r'R_{\odot}', 'unicode': 'R⊙'}) def_unit(['jupiterRad', 'R_jup', 'Rjup','R_jupiter', 'Rjupiter'], _si.R_jup, namespace=_ns, prefixes=False, doc="Jupiter radius", # LaTeX jupiter symbol requires wasysym format={'latex': r'R_{\rm J}', 'unicode': 'R♃'}) def_unit(['earthRad', 'R_earth', 'Rearth'], _si.R_earth, namespace=_ns, prefixes=False, doc="Earth radius", # LaTeX earth symbol requires wasysym format={'latex': r'R_{\oplus}', 'unicode': 'R⊕'}) def_unit(['lyr', 'lightyear'], (_si.c * si.yr).to(si.m), namespace=_ns, prefixes=True, doc="Light year") ########################################################################### # AREAS def_unit(['barn', 'barn'], 10 ** -28 * si.m ** 2, namespace=_ns, prefixes=True, doc="barn: unit of area used in HEP") ########################################################################### # ANGULAR MEASUREMENTS def_unit(['cycle', 'cy'], 2.0 * _numpy.pi * si.rad, namespace=_ns, prefixes=False, doc="cycle: angular measurement, a full turn or rotation") ########################################################################### # MASS def_unit(['solMass', 'M_sun', 'Msun'], _si.M_sun, namespace=_ns, prefixes=False, doc="Solar mass", format={'latex': r'M_{\odot}', 'unicode': 'M⊙'}) def_unit(['jupiterMass', 'M_jup', 'Mjup','M_jupiter', 'Mjupiter'], _si.M_jup, namespace=_ns, prefixes=False, doc="Jupiter mass", # LaTeX jupiter symbol requires wasysym format={'latex': r'M_{\rm J}', 'unicode': 'M♃'}) def_unit(['earthMass', 'M_earth', 'Mearth'], _si.M_earth, namespace=_ns, prefixes=False, doc="Earth mass", # LaTeX earth symbol requires wasysym format={'latex': r'M_{\oplus}', 'unicode': 'M⊕'}) def_unit(['M_p'], _si.m_p, namespace=_ns, doc="Proton mass", format={'latex': r'M_{p}', 'unicode': 'Mₚ'}) def_unit(['M_e'], _si.m_e, namespace=_ns, doc="Electron mass", format={'latex': r'M_{e}', 'unicode': 'Mₑ'}) # Unified atomic mass unit def_unit(['u', 'Da', 'Dalton'], _si.u, namespace=_ns, prefixes=True, exclude_prefixes=['a', 'da'], doc="Unified atomic mass unit") ########################################################################## # ENERGY # Here, explicitly convert the planck constant to 'eV s' since the constant # can override that to give a more precise value that takes into account # covariances between e and h. Eventually, this may also be replaced with # just `_si.Ryd.to(eV)`. def_unit(['Ry', 'rydberg'], (_si.Ryd * _si.c * _si.h.to(si.eV * si.s)).to(si.eV), namespace=_ns, prefixes=True, doc="Rydberg: Energy of a photon whose wavenumber is the Rydberg " "constant", format={'latex': r'R_{\infty}', 'unicode': 'R∞'}) ########################################################################### # ILLUMINATION def_unit(['solLum', 'L_sun', 'Lsun'], _si.L_sun, namespace=_ns, prefixes=False, doc="Solar luminance", format={'latex': r'L_{\odot}', 'unicode': 'L⊙'}) ########################################################################### # SPECTRAL DENSITY def_unit((['ph', 'photon'], ['photon']), format={'ogip': 'photon', 'vounit': 'photon'}, namespace=_ns, prefixes=True) def_unit(['Jy', 'Jansky', 'jansky'], 1e-26 * si.W / si.m ** 2 / si.Hz, namespace=_ns, prefixes=True, doc="Jansky: spectral flux density") def_unit(['R', 'Rayleigh', 'rayleigh'], (1e10 / (4 * _numpy.pi)) * ph * si.m ** -2 * si.s ** -1 * si.sr ** -1, namespace=_ns, prefixes=True, doc="Rayleigh: photon flux") ########################################################################### # MISCELLANEOUS # Some of these are very FITS-specific and perhaps considered a mistake. # Maybe they should be moved into the FITS format class? # TODO: This is defined by the FITS standard as "relative to the sun". # Is that mass, volume, what? def_unit(['Sun'], namespace=_ns) ########################################################################### # EVENTS def_unit((['ct', 'count'], ['count']), format={'fits': 'count', 'ogip': 'count', 'vounit': 'count'}, namespace=_ns, prefixes=True, exclude_prefixes=['p']) def_unit((['pix', 'pixel'], ['pixel']), format={'ogip': 'pixel', 'vounit': 'pixel'}, namespace=_ns, prefixes=True) ########################################################################### # MISCELLANEOUS def_unit(['chan'], namespace=_ns, prefixes=True) def_unit(['bin'], namespace=_ns, prefixes=True) def_unit((['vox', 'voxel'], ['voxel']), format={'fits': 'voxel', 'ogip': 'voxel', 'vounit': 'voxel'}, namespace=_ns, prefixes=True) def_unit((['bit', 'b'], ['bit']), namespace=_ns, prefixes=si_prefixes + binary_prefixes) def_unit((['byte', 'B'], ['byte']), 8 * bit, namespace=_ns, format={'vounit': 'byte'}, prefixes=si_prefixes + binary_prefixes, exclude_prefixes=['d']) def_unit(['adu'], namespace=_ns, prefixes=True) def_unit(['beam'], namespace=_ns, prefixes=True) def_unit(['electron'], doc="Number of electrons", namespace=_ns, format={'latex': r'e^{-}', 'unicode': 'e⁻'}) ########################################################################### # CLEANUP del UnitBase del def_unit del si ########################################################################### # DOCSTRING # This generates a docstring for this module that describes all of the # standard units defined here. from .utils import generate_unit_summary as _generate_unit_summary if __doc__ is not None: __doc__ += _generate_unit_summary(globals())
DANCEcollaborative/forum-xblock
refs/heads/master
XBlock Integration Files/xdjangobb/xblock/lib/python2.7/site-packages/mock/__init__.py
53
from __future__ import absolute_import import mock.mock as _mock from mock.mock import * __all__ = _mock.__all__ #import mock.mock as _mock #for name in dir(_mock): # globals()[name] = getattr(_mock, name)
nealtodd/django
refs/heads/master
django/conf/locale/zh_Hant/formats.py
1008
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'Y年n月j日' # 2016年9月5日 TIME_FORMAT = 'H:i' # 20:45 DATETIME_FORMAT = 'Y年n月j日 H:i' # 2016年9月5日 20:45 YEAR_MONTH_FORMAT = 'Y年n月' # 2016年9月 MONTH_DAY_FORMAT = 'm月j日' # 9月5日 SHORT_DATE_FORMAT = 'Y年n月j日' # 2016年9月5日 SHORT_DATETIME_FORMAT = 'Y年n月j日 H:i' # 2016年9月5日 20:45 FIRST_DAY_OF_WEEK = 1 # 星期一 (Monday) # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%Y/%m/%d', # '2016/09/05' '%Y-%m-%d', # '2016-09-05' '%Y年%n月%j日', # '2016年9月5日' ] TIME_INPUT_FORMATS = [ '%H:%M', # '20:45' '%H:%M:%S', # '20:45:29' '%H:%M:%S.%f', # '20:45:29.000200' ] DATETIME_INPUT_FORMATS = [ '%Y/%m/%d %H:%M', # '2016/09/05 20:45' '%Y-%m-%d %H:%M', # '2016-09-05 20:45' '%Y年%n月%j日 %H:%M', # '2016年9月5日 14:45' '%Y/%m/%d %H:%M:%S', # '2016/09/05 20:45:29' '%Y-%m-%d %H:%M:%S', # '2016-09-05 20:45:29' '%Y年%n月%j日 %H:%M:%S', # '2016年9月5日 20:45:29' '%Y/%m/%d %H:%M:%S.%f', # '2016/09/05 20:45:29.000200' '%Y-%m-%d %H:%M:%S.%f', # '2016-09-05 20:45:29.000200' '%Y年%n月%j日 %H:%n:%S.%f', # '2016年9月5日 20:45:29.000200' ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = '' NUMBER_GROUPING = 4
MartinDelzant/scikit-learn
refs/heads/master
sklearn/utils/arpack.py
265
""" This contains a copy of the future version of scipy.sparse.linalg.eigen.arpack.eigsh It's an upgraded wrapper of the ARPACK library which allows the use of shift-invert mode for symmetric matrices. Find a few eigenvectors and eigenvalues of a matrix. Uses ARPACK: http://www.caam.rice.edu/software/ARPACK/ """ # Wrapper implementation notes # # ARPACK Entry Points # ------------------- # The entry points to ARPACK are # - (s,d)seupd : single and double precision symmetric matrix # - (s,d,c,z)neupd: single,double,complex,double complex general matrix # This wrapper puts the *neupd (general matrix) interfaces in eigs() # and the *seupd (symmetric matrix) in eigsh(). # There is no Hermetian complex/double complex interface. # To find eigenvalues of a Hermetian matrix you # must use eigs() and not eigsh() # It might be desirable to handle the Hermetian case differently # and, for example, return real eigenvalues. # Number of eigenvalues returned and complex eigenvalues # ------------------------------------------------------ # The ARPACK nonsymmetric real and double interface (s,d)naupd return # eigenvalues and eigenvectors in real (float,double) arrays. # Since the eigenvalues and eigenvectors are, in general, complex # ARPACK puts the real and imaginary parts in consecutive entries # in real-valued arrays. This wrapper puts the real entries # into complex data types and attempts to return the requested eigenvalues # and eigenvectors. # Solver modes # ------------ # ARPACK and handle shifted and shift-inverse computations # for eigenvalues by providing a shift (sigma) and a solver. __docformat__ = "restructuredtext en" __all__ = ['eigs', 'eigsh', 'svds', 'ArpackError', 'ArpackNoConvergence'] import warnings from scipy.sparse.linalg.eigen.arpack import _arpack import numpy as np from scipy.sparse.linalg.interface import aslinearoperator, LinearOperator from scipy.sparse import identity, isspmatrix, isspmatrix_csr from scipy.linalg import lu_factor, lu_solve from scipy.sparse.sputils import isdense from scipy.sparse.linalg import gmres, splu import scipy from distutils.version import LooseVersion _type_conv = {'f': 's', 'd': 'd', 'F': 'c', 'D': 'z'} _ndigits = {'f': 5, 'd': 12, 'F': 5, 'D': 12} DNAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found. IPARAM(5) " "returns the number of wanted converged Ritz values.", 2: "No longer an informational error. Deprecated starting " "with release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the " "Implicitly restarted Arnoldi iteration. One possibility " "is to increase the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: " WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation;", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible.", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated." } SNAUPD_ERRORS = DNAUPD_ERRORS ZNAUPD_ERRORS = DNAUPD_ERRORS.copy() ZNAUPD_ERRORS[-10] = "IPARAM(7) must be 1,2,3." CNAUPD_ERRORS = ZNAUPD_ERRORS DSAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found.", 2: "No longer an informational error. Deprecated starting with " "release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the Implicitly " "restarted Arnoldi iteration. One possibility is to increase " "the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from trid. eigenvalue calculation; " "Informational error from LAPACK routine dsteqr .", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible. ", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated.", } SSAUPD_ERRORS = DSAUPD_ERRORS DNEUPD_ERRORS = { 0: "Normal exit.", 1: "The Schur form computed by LAPACK routine dlahqr " "could not be reordered by LAPACK routine dtrsen. " "Re-enter subroutine dneupd with IPARAM(5)NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least NCV " "columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from calculation of a real Schur form. " "Informational error from LAPACK routine dlahqr .", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine dtrevc.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "DNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "DNEUPD got a different count of the number of converged " "Ritz values than DNAUPD got. This indicates the user " "probably made an error in passing data from DNAUPD to " "DNEUPD or that the data was modified before entering " "DNEUPD", } SNEUPD_ERRORS = DNEUPD_ERRORS.copy() SNEUPD_ERRORS[1] = ("The Schur form computed by LAPACK routine slahqr " "could not be reordered by LAPACK routine strsen . " "Re-enter subroutine dneupd with IPARAM(5)=NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.") SNEUPD_ERRORS[-14] = ("SNAUPD did not find any eigenvalues to sufficient " "accuracy.") SNEUPD_ERRORS[-15] = ("SNEUPD got a different count of the number of " "converged Ritz values than SNAUPD got. This indicates " "the user probably made an error in passing data from " "SNAUPD to SNEUPD or that the data was modified before " "entering SNEUPD") ZNEUPD_ERRORS = {0: "Normal exit.", 1: "The Schur form computed by LAPACK routine csheqr " "could not be reordered by LAPACK routine ztrsen. " "Re-enter subroutine zneupd with IPARAM(5)=NCV and " "increase the size of the array D to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 1 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation. " "This should never happened.", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine ztrevc.", -10: "IPARAM(7) must be 1,2,3", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "ZNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "ZNEUPD got a different count of the number of " "converged Ritz values than ZNAUPD got. This " "indicates the user probably made an error in passing " "data from ZNAUPD to ZNEUPD or that the data was " "modified before entering ZNEUPD"} CNEUPD_ERRORS = ZNEUPD_ERRORS.copy() CNEUPD_ERRORS[-14] = ("CNAUPD did not find any eigenvalues to sufficient " "accuracy.") CNEUPD_ERRORS[-15] = ("CNEUPD got a different count of the number of " "converged Ritz values than CNAUPD got. This indicates " "the user probably made an error in passing data from " "CNAUPD to CNEUPD or that the data was modified before " "entering CNEUPD") DSEUPD_ERRORS = { 0: "Normal exit.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: ("Error return from trid. eigenvalue calculation; " "Information error from LAPACK routine dsteqr."), -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "NEV and WHICH = 'BE' are incompatible.", -14: "DSAUPD did not find any eigenvalues to sufficient accuracy.", -15: "HOWMNY must be one of 'A' or 'S' if RVEC = .true.", -16: "HOWMNY = 'S' not yet implemented", -17: ("DSEUPD got a different count of the number of converged " "Ritz values than DSAUPD got. This indicates the user " "probably made an error in passing data from DSAUPD to " "DSEUPD or that the data was modified before entering " "DSEUPD.") } SSEUPD_ERRORS = DSEUPD_ERRORS.copy() SSEUPD_ERRORS[-14] = ("SSAUPD did not find any eigenvalues " "to sufficient accuracy.") SSEUPD_ERRORS[-17] = ("SSEUPD got a different count of the number of " "converged " "Ritz values than SSAUPD got. This indicates the user " "probably made an error in passing data from SSAUPD to " "SSEUPD or that the data was modified before entering " "SSEUPD.") _SAUPD_ERRORS = {'d': DSAUPD_ERRORS, 's': SSAUPD_ERRORS} _NAUPD_ERRORS = {'d': DNAUPD_ERRORS, 's': SNAUPD_ERRORS, 'z': ZNAUPD_ERRORS, 'c': CNAUPD_ERRORS} _SEUPD_ERRORS = {'d': DSEUPD_ERRORS, 's': SSEUPD_ERRORS} _NEUPD_ERRORS = {'d': DNEUPD_ERRORS, 's': SNEUPD_ERRORS, 'z': ZNEUPD_ERRORS, 'c': CNEUPD_ERRORS} # accepted values of parameter WHICH in _SEUPD _SEUPD_WHICH = ['LM', 'SM', 'LA', 'SA', 'BE'] # accepted values of parameter WHICH in _NAUPD _NEUPD_WHICH = ['LM', 'SM', 'LR', 'SR', 'LI', 'SI'] class ArpackError(RuntimeError): """ ARPACK error """ def __init__(self, info, infodict=_NAUPD_ERRORS): msg = infodict.get(info, "Unknown error") RuntimeError.__init__(self, "ARPACK error %d: %s" % (info, msg)) class ArpackNoConvergence(ArpackError): """ ARPACK iteration did not converge Attributes ---------- eigenvalues : ndarray Partial result. Converged eigenvalues. eigenvectors : ndarray Partial result. Converged eigenvectors. """ def __init__(self, msg, eigenvalues, eigenvectors): ArpackError.__init__(self, -1, {-1: msg}) self.eigenvalues = eigenvalues self.eigenvectors = eigenvectors class _ArpackParams(object): def __init__(self, n, k, tp, mode=1, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): if k <= 0: raise ValueError("k must be positive, k=%d" % k) if maxiter is None: maxiter = n * 10 if maxiter <= 0: raise ValueError("maxiter must be positive, maxiter=%d" % maxiter) if tp not in 'fdFD': raise ValueError("matrix type must be 'f', 'd', 'F', or 'D'") if v0 is not None: # ARPACK overwrites its initial resid, make a copy self.resid = np.array(v0, copy=True) info = 1 else: self.resid = np.zeros(n, tp) info = 0 if sigma is None: #sigma not used self.sigma = 0 else: self.sigma = sigma if ncv is None: ncv = 2 * k + 1 ncv = min(ncv, n) self.v = np.zeros((n, ncv), tp) # holds Ritz vectors self.iparam = np.zeros(11, "int") # set solver mode and parameters ishfts = 1 self.mode = mode self.iparam[0] = ishfts self.iparam[2] = maxiter self.iparam[3] = 1 self.iparam[6] = mode self.n = n self.tol = tol self.k = k self.maxiter = maxiter self.ncv = ncv self.which = which self.tp = tp self.info = info self.converged = False self.ido = 0 def _raise_no_convergence(self): msg = "No convergence (%d iterations, %d/%d eigenvectors converged)" k_ok = self.iparam[4] num_iter = self.iparam[2] try: ev, vec = self.extract(True) except ArpackError as err: msg = "%s [%s]" % (msg, err) ev = np.zeros((0,)) vec = np.zeros((self.n, 0)) k_ok = 0 raise ArpackNoConvergence(msg % (num_iter, k_ok, self.k), ev, vec) class _SymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x : # A - symmetric # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the general eigenvalue problem: # A*x = lambda*M*x # A - symmetric # M - symmetric positive definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # # mode = 4: # Solve the general eigenvalue problem in Buckling mode: # A*x = lambda*AG*x # A - symmetric positive semi-definite # AG - symmetric indefinite # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = left multiplication by [A-sigma*AG]^-1 # # mode = 5: # Solve the general eigenvalue problem in Cayley-transformed mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode == 3: if matvec is not None: raise ValueError("matvec must not be specified for mode=3") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=3") if M_matvec is None: self.OP = Minv_matvec self.OPa = Minv_matvec self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(M_matvec(x)) self.OPa = Minv_matvec self.B = M_matvec self.bmat = 'G' elif mode == 4: if matvec is None: raise ValueError("matvec must be specified for mode=4") if M_matvec is not None: raise ValueError("M_matvec must not be specified for mode=4") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=4") self.OPa = Minv_matvec self.OP = lambda x: self.OPa(matvec(x)) self.B = matvec self.bmat = 'G' elif mode == 5: if matvec is None: raise ValueError("matvec must be specified for mode=5") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=5") self.OPa = Minv_matvec self.A_matvec = matvec if M_matvec is None: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * x) self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * M_matvec(x)) self.B = M_matvec self.bmat = 'G' else: raise ValueError("mode=%i not implemented" % mode) if which not in _SEUPD_WHICH: raise ValueError("which must be one of %s" % ' '.join(_SEUPD_WHICH)) if k >= n: raise ValueError("k must be less than rank(A), k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k: raise ValueError("ncv must be k<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(self.ncv * (self.ncv + 8), self.tp) ltr = _type_conv[self.tp] if ltr not in ["s", "d"]: raise ValueError("Input matrix is not real-valued.") self._arpack_solver = _arpack.__dict__[ltr + 'saupd'] self._arpack_extract = _arpack.__dict__[ltr + 'seupd'] self.iterate_infodict = _SAUPD_ERRORS[ltr] self.extract_infodict = _SEUPD_ERRORS[ltr] self.ipntr = np.zeros(11, "int") def iterate(self): self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info = \ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode == 1: self.workd[yslice] = self.OP(self.workd[xslice]) elif self.mode == 2: self.workd[xslice] = self.OPb(self.workd[xslice]) self.workd[yslice] = self.OPa(self.workd[xslice]) elif self.mode == 5: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) Ax = self.A_matvec(self.workd[xslice]) self.workd[yslice] = self.OPa(Ax + (self.sigma * self.workd[Bxslice])) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): rvec = return_eigenvectors ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused d, z, ierr = self._arpack_extract(rvec, howmny, sselect, self.sigma, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam[0:7], self.ipntr, self.workd[0:2 * self.n], self.workl, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d class _UnsymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x # A - square matrix # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the generalized eigenvalue problem: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3,4: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # if A is real and mode==3, use the real part of Minv_matvec # if A is real and mode==4, use the imag part of Minv_matvec # if A is complex and mode==3, # use real and imag parts of Minv_matvec if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode in (3, 4): if matvec is None: raise ValueError("matvec must be specified " "for mode in (3,4)") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified " "for mode in (3,4)") self.matvec = matvec if tp in 'DF': # complex type if mode == 3: self.OPa = Minv_matvec else: raise ValueError("mode=4 invalid for complex A") else: # real type if mode == 3: self.OPa = lambda x: np.real(Minv_matvec(x)) else: self.OPa = lambda x: np.imag(Minv_matvec(x)) if M_matvec is None: self.B = lambda x: x self.bmat = 'I' self.OP = self.OPa else: self.B = M_matvec self.bmat = 'G' self.OP = lambda x: self.OPa(M_matvec(x)) else: raise ValueError("mode=%i not implemented" % mode) if which not in _NEUPD_WHICH: raise ValueError("Parameter which must be one of %s" % ' '.join(_NEUPD_WHICH)) if k >= n - 1: raise ValueError("k must be less than rank(A)-1, k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k + 1: raise ValueError("ncv must be k+1<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(3 * self.ncv * (self.ncv + 2), self.tp) ltr = _type_conv[self.tp] self._arpack_solver = _arpack.__dict__[ltr + 'naupd'] self._arpack_extract = _arpack.__dict__[ltr + 'neupd'] self.iterate_infodict = _NAUPD_ERRORS[ltr] self.extract_infodict = _NEUPD_ERRORS[ltr] self.ipntr = np.zeros(14, "int") if self.tp in 'FD': self.rwork = np.zeros(self.ncv, self.tp.lower()) else: self.rwork = None def iterate(self): if self.tp in 'fd': self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) else: self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode in (1, 2): self.workd[yslice] = self.OP(self.workd[xslice]) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): k, n = self.k, self.n ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused sigmar = np.real(self.sigma) sigmai = np.imag(self.sigma) workev = np.zeros(3 * self.ncv, self.tp) if self.tp in 'fd': dr = np.zeros(k + 1, self.tp) di = np.zeros(k + 1, self.tp) zr = np.zeros((n, k + 1), self.tp) dr, di, zr, ierr = \ self._arpack_extract( return_eigenvectors, howmny, sselect, sigmar, sigmai, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) nreturned = self.iparam[4] # number of good eigenvalues returned # Build complex eigenvalues from real and imaginary parts d = dr + 1.0j * di # Arrange the eigenvectors: complex eigenvectors are stored as # real,imaginary in consecutive columns z = zr.astype(self.tp.upper()) # The ARPACK nonsymmetric real and double interface (s,d)naupd # return eigenvalues and eigenvectors in real (float,double) # arrays. # Efficiency: this should check that return_eigenvectors == True # before going through this construction. if sigmai == 0: i = 0 while i <= k: # check if complex if abs(d[i].imag) != 0: # this is a complex conjugate pair with eigenvalues # in consecutive columns if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 else: # real matrix, mode 3 or 4, imag(sigma) is nonzero: # see remark 3 in <s,d>neupd.f # Build complex eigenvalues from real and imaginary parts i = 0 while i <= k: if abs(d[i].imag) == 0: d[i] = np.dot(zr[:, i], self.matvec(zr[:, i])) else: if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() d[i] = ((np.dot(zr[:, i], self.matvec(zr[:, i])) + np.dot(zr[:, i + 1], self.matvec(zr[:, i + 1]))) + 1j * (np.dot(zr[:, i], self.matvec(zr[:, i + 1])) - np.dot(zr[:, i + 1], self.matvec(zr[:, i])))) d[i + 1] = d[i].conj() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 # Now we have k+1 possible eigenvalues and eigenvectors # Return the ones specified by the keyword "which" if nreturned <= k: # we got less or equal as many eigenvalues we wanted d = d[:nreturned] z = z[:, :nreturned] else: # we got one extra eigenvalue (likely a cc pair, but which?) # cut at approx precision for sorting rd = np.round(d, decimals=_ndigits[self.tp]) if self.which in ['LR', 'SR']: ind = np.argsort(rd.real) elif self.which in ['LI', 'SI']: # for LI,SI ARPACK returns largest,smallest # abs(imaginary) why? ind = np.argsort(abs(rd.imag)) else: ind = np.argsort(abs(rd)) if self.which in ['LR', 'LM', 'LI']: d = d[ind[-k:]] z = z[:, ind[-k:]] if self.which in ['SR', 'SM', 'SI']: d = d[ind[:k]] z = z[:, ind[:k]] else: # complex is so much simpler... d, z, ierr =\ self._arpack_extract( return_eigenvectors, howmny, sselect, self.sigma, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d def _aslinearoperator_with_dtype(m): m = aslinearoperator(m) if not hasattr(m, 'dtype'): x = np.zeros(m.shape[1]) m.dtype = (m * x).dtype return m class SpLuInv(LinearOperator): """ SpLuInv: helper class to repeatedly solve M*x=b using a sparse LU-decopposition of M """ def __init__(self, M): self.M_lu = splu(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) self.isreal = not np.issubdtype(self.dtype, np.complexfloating) def _matvec(self, x): # careful here: splu.solve will throw away imaginary # part of x if M is real if self.isreal and np.issubdtype(x.dtype, np.complexfloating): return (self.M_lu.solve(np.real(x)) + 1j * self.M_lu.solve(np.imag(x))) else: return self.M_lu.solve(x) class LuInv(LinearOperator): """ LuInv: helper class to repeatedly solve M*x=b using an LU-decomposition of M """ def __init__(self, M): self.M_lu = lu_factor(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) def _matvec(self, x): return lu_solve(self.M_lu, x) class IterInv(LinearOperator): """ IterInv: helper class to repeatedly solve M*x=b using an iterative method. """ def __init__(self, M, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(M.dtype).eps self.M = M self.ifunc = ifunc self.tol = tol if hasattr(M, 'dtype'): dtype = M.dtype else: x = np.zeros(M.shape[1]) dtype = (M * x).dtype LinearOperator.__init__(self, M.shape, self._matvec, dtype=dtype) def _matvec(self, x): b, info = self.ifunc(self.M, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting M: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b class IterOpInv(LinearOperator): """ IterOpInv: helper class to repeatedly solve [A-sigma*M]*x = b using an iterative method """ def __init__(self, A, M, sigma, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(A.dtype).eps self.A = A self.M = M self.sigma = sigma self.ifunc = ifunc self.tol = tol x = np.zeros(A.shape[1]) if M is None: dtype = self.mult_func_M_None(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func_M_None, dtype=dtype) else: dtype = self.mult_func(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func, dtype=dtype) LinearOperator.__init__(self, A.shape, self._matvec, dtype=dtype) def mult_func(self, x): return self.A.matvec(x) - self.sigma * self.M.matvec(x) def mult_func_M_None(self, x): return self.A.matvec(x) - self.sigma * x def _matvec(self, x): b, info = self.ifunc(self.OP, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting [A-sigma*M]: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b def get_inv_matvec(M, symmetric=False, tol=0): if isdense(M): return LuInv(M).matvec elif isspmatrix(M): if isspmatrix_csr(M) and symmetric: M = M.T return SpLuInv(M).matvec else: return IterInv(M, tol=tol).matvec def get_OPinv_matvec(A, M, sigma, symmetric=False, tol=0): if sigma == 0: return get_inv_matvec(A, symmetric=symmetric, tol=tol) if M is None: #M is the identity matrix if isdense(A): if (np.issubdtype(A.dtype, np.complexfloating) or np.imag(sigma) == 0): A = np.copy(A) else: A = A + 0j A.flat[::A.shape[1] + 1] -= sigma return LuInv(A).matvec elif isspmatrix(A): A = A - sigma * identity(A.shape[0]) if symmetric and isspmatrix_csr(A): A = A.T return SpLuInv(A.tocsc()).matvec else: return IterOpInv(_aslinearoperator_with_dtype(A), M, sigma, tol=tol).matvec else: if ((not isdense(A) and not isspmatrix(A)) or (not isdense(M) and not isspmatrix(M))): return IterOpInv(_aslinearoperator_with_dtype(A), _aslinearoperator_with_dtype(M), sigma, tol=tol).matvec elif isdense(A) or isdense(M): return LuInv(A - sigma * M).matvec else: OP = A - sigma * M if symmetric and isspmatrix_csr(OP): OP = OP.T return SpLuInv(OP.tocsc()).matvec def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, OPpart=None): """ Find k eigenvalues and eigenvectors of the square matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing \ the operation A * x, where A is a real or complex square matrix. k : int, default 6 The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. return_eigenvectors : boolean, default True Whether to return the eigenvectors along with the eigenvalues. M : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation M*x for the generalized eigenvalue problem ``A * x = w * M * x`` M must represent a real symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma==None, M is positive definite * If sigma is specified, M is positive semi-definite If sigma==None, eigs requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real or complex Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] * x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. For a real matrix A, shift-invert can either be done in imaginary mode or real mode, specified by the parameter OPpart ('r' or 'i'). Note that when sigma is specified, the keyword 'which' (below) refers to the shifted eigenvalues w'[i] where: * If A is real and OPpart == 'r' (default), w'[i] = 1/2 * [ 1/(w[i]-sigma) + 1/(w[i]-conj(sigma)) ] * If A is real and OPpart == 'i', w'[i] = 1/2i * [ 1/(w[i]-sigma) - 1/(w[i]-conj(sigma)) ] * If A is complex, w'[i] = 1/(w[i]-sigma) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated `ncv` must be greater than `k`; it is recommended that ``ncv > 2*k``. which : string ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'] Which `k` eigenvectors and eigenvalues to find: - 'LM' : largest magnitude - 'SM' : smallest magnitude - 'LR' : largest real part - 'SR' : smallest real part - 'LI' : largest imaginary part - 'SI' : smallest imaginary part When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion) The default value of 0 implies machine precision. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues Minv : N x N matrix, array, sparse matrix, or linear operator See notes in M, above. OPinv : N x N matrix, array, sparse matrix, or linear operator See notes in sigma, above. OPpart : 'r' or 'i'. See notes in sigma, above Returns ------- w : array Array of k eigenvalues. v : array An array of `k` eigenvectors. ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i]. Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigsh : eigenvalues and eigenvectors for symmetric matrix A svds : singular value decomposition for a matrix A Examples -------- Find 6 eigenvectors of the identity matrix: >>> from sklearn.utils.arpack import eigs >>> id = np.identity(13) >>> vals, vecs = eigs(id, k=6) >>> vals array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> vecs.shape (13, 6) Notes ----- This function is a wrapper to the ARPACK [1]_ SNEUPD, DNEUPD, CNEUPD, ZNEUPD, functions which use the Implicitly Restarted Arnoldi Method to find the eigenvalues and eigenvectors [2]_. References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if OPpart is not None: raise ValueError("OPpart should not be specified with " "sigma = None or complex A") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: #sigma is not None: shift-invert mode if np.issubdtype(A.dtype, np.complexfloating): if OPpart is not None: raise ValueError("OPpart should not be specified " "with sigma=None or complex A") mode = 3 elif OPpart is None or OPpart.lower() == 'r': mode = 3 elif OPpart.lower() == 'i': if np.imag(sigma) == 0: raise ValueError("OPpart cannot be 'i' if sigma is real") mode = 4 else: raise ValueError("OPpart must be one of ('r','i')") matvec = _aslinearoperator_with_dtype(A).matvec if Minv is not None: raise ValueError("Minv should not be specified when sigma is") if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=False, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec params = _UnsymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, mode='normal'): """ Find k eigenvalues and eigenvectors of the real symmetric square matrix or complex hermitian matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation A * x, where A is a real symmetric matrix For buckling mode (see below) A must additionally be positive-definite k : integer The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. M : An N x N matrix, array, sparse matrix, or linear operator representing the operation M * x for the generalized eigenvalue problem ``A * x = w * M * x``. M must represent a real, symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma == None, M is symmetric positive definite * If sigma is specified, M is symmetric positive semi-definite * In buckling mode, M is symmetric indefinite. If sigma == None, eigsh requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. Note that when sigma is specified, the keyword 'which' refers to the shifted eigenvalues w'[i] where: - if mode == 'normal', w'[i] = 1 / (w[i] - sigma) - if mode == 'cayley', w'[i] = (w[i] + sigma) / (w[i] - sigma) - if mode == 'buckling', w'[i] = w[i] / (w[i] - sigma) (see further discussion in 'mode' below) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated ncv must be greater than k and smaller than n; it is recommended that ncv > 2*k which : string ['LM' | 'SM' | 'LA' | 'SA' | 'BE'] If A is a complex hermitian matrix, 'BE' is invalid. Which `k` eigenvectors and eigenvalues to find - 'LM' : Largest (in magnitude) eigenvalues - 'SM' : Smallest (in magnitude) eigenvalues - 'LA' : Largest (algebraic) eigenvalues - 'SA' : Smallest (algebraic) eigenvalues - 'BE' : Half (k/2) from each end of the spectrum When k is odd, return one more (k/2+1) from the high end When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion). The default value of 0 implies machine precision. Minv : N x N matrix, array, sparse matrix, or LinearOperator See notes in M, above OPinv : N x N matrix, array, sparse matrix, or LinearOperator See notes in sigma, above. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues mode : string ['normal' | 'buckling' | 'cayley'] Specify strategy to use for shift-invert mode. This argument applies only for real-valued A and sigma != None. For shift-invert mode, ARPACK internally solves the eigenvalue problem ``OP * x'[i] = w'[i] * B * x'[i]`` and transforms the resulting Ritz vectors x'[i] and Ritz values w'[i] into the desired eigenvectors and eigenvalues of the problem ``A * x[i] = w[i] * M * x[i]``. The modes are as follows: - 'normal' : OP = [A - sigma * M]^-1 * M B = M w'[i] = 1 / (w[i] - sigma) - 'buckling' : OP = [A - sigma * M]^-1 * A B = A w'[i] = w[i] / (w[i] - sigma) - 'cayley' : OP = [A - sigma * M]^-1 * [A + sigma * M] B = M w'[i] = (w[i] + sigma) / (w[i] - sigma) The choice of mode will affect which eigenvalues are selected by the keyword 'which', and can also impact the stability of convergence (see [2] for a discussion) Returns ------- w : array Array of k eigenvalues v : array An array of k eigenvectors The v[i] is the eigenvector corresponding to the eigenvector w[i] Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigs : eigenvalues and eigenvectors for a general (nonsymmetric) matrix A svds : singular value decomposition for a matrix A Notes ----- This function is a wrapper to the ARPACK [1]_ SSEUPD and DSEUPD functions which use the Implicitly Restarted Lanczos Method to find the eigenvalues and eigenvectors [2]_. Examples -------- >>> from sklearn.utils.arpack import eigsh >>> id = np.identity(13) >>> vals, vecs = eigsh(id, k=6) >>> vals # doctest: +SKIP array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> print(vecs.shape) (13, 6) References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ # complex hermitian matrices should be solved with eigs if np.issubdtype(A.dtype, np.complexfloating): if mode != 'normal': raise ValueError("mode=%s cannot be used with " "complex matrix A" % mode) if which == 'BE': raise ValueError("which='BE' cannot be used with complex matrix A") elif which == 'LA': which = 'LR' elif which == 'SA': which = 'SR' ret = eigs(A, k, M=M, sigma=sigma, which=which, v0=v0, ncv=ncv, maxiter=maxiter, tol=tol, return_eigenvectors=return_eigenvectors, Minv=Minv, OPinv=OPinv) if return_eigenvectors: return ret[0].real, ret[1] else: return ret.real if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: A = _aslinearoperator_with_dtype(A) matvec = A.matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: # sigma is not None: shift-invert mode if Minv is not None: raise ValueError("Minv should not be specified when sigma is") # normal mode if mode == 'normal': mode = 3 matvec = None if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M = _aslinearoperator_with_dtype(M) M_matvec = M.matvec # buckling mode elif mode == 'buckling': mode = 4 if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec matvec = _aslinearoperator_with_dtype(A).matvec M_matvec = None # cayley-transform mode elif mode == 'cayley': mode = 5 matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec # unrecognized mode else: raise ValueError("unrecognized mode '%s'" % mode) params = _SymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _svds(A, k=6, ncv=None, tol=0): """Compute k singular values/vectors for a sparse matrix using ARPACK. Parameters ---------- A : sparse matrix Array to compute the SVD on k : int, optional Number of singular values and vectors to compute. ncv : integer The number of Lanczos vectors generated ncv must be greater than k+1 and smaller than n; it is recommended that ncv > 2*k tol : float, optional Tolerance for singular values. Zero (default) means machine precision. Notes ----- This is a naive implementation using an eigensolver on A.H * A or A * A.H, depending on which one is more efficient. """ if not (isinstance(A, np.ndarray) or isspmatrix(A)): A = np.asarray(A) n, m = A.shape if np.issubdtype(A.dtype, np.complexfloating): herm = lambda x: x.T.conjugate() eigensolver = eigs else: herm = lambda x: x.T eigensolver = eigsh if n > m: X = A XH = herm(A) else: XH = A X = herm(A) if hasattr(XH, 'dot'): def matvec_XH_X(x): return XH.dot(X.dot(x)) else: def matvec_XH_X(x): return np.dot(XH, np.dot(X, x)) XH_X = LinearOperator(matvec=matvec_XH_X, dtype=X.dtype, shape=(X.shape[1], X.shape[1])) # Ignore deprecation warnings here: dot on matrices is deprecated, # but this code is a backport anyhow with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) eigvals, eigvec = eigensolver(XH_X, k=k, tol=tol ** 2) s = np.sqrt(eigvals) if n > m: v = eigvec if hasattr(X, 'dot'): u = X.dot(v) / s else: u = np.dot(X, v) / s vh = herm(v) else: u = eigvec if hasattr(X, 'dot'): vh = herm(X.dot(u) / s) else: vh = herm(np.dot(X, u) / s) return u, s, vh # check if backport is actually needed: if scipy.version.version >= LooseVersion('0.10'): from scipy.sparse.linalg import eigs, eigsh, svds else: eigs, eigsh, svds = _eigs, _eigsh, _svds
neraliu/tainted-phantomjs
refs/heads/master
src/breakpad/src/tools/gyp/pylib/gyp/MSVSProject.py
137
#!/usr/bin/python2.4 # 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. """Visual Studio project reader/writer.""" import common import xml.dom import xml.dom.minidom import MSVSNew #------------------------------------------------------------------------------ class Tool(object): """Visual Studio tool.""" def __init__(self, name, attrs=None): """Initializes the tool. Args: name: Tool name. attrs: Dict of tool attributes; may be None. """ self.name = name self.attrs = attrs or {} def CreateElement(self, doc): """Creates an element for the tool. Args: doc: xml.dom.Document object to use for node creation. Returns: A new xml.dom.Element for the tool. """ node = doc.createElement('Tool') node.setAttribute('Name', self.name) for k, v in self.attrs.items(): node.setAttribute(k, v) return node class Filter(object): """Visual Studio filter - that is, a virtual folder.""" def __init__(self, name, contents=None): """Initializes the folder. Args: name: Filter (folder) name. contents: List of filenames and/or Filter objects contained. """ self.name = name self.contents = list(contents or []) #------------------------------------------------------------------------------ class Writer(object): """Visual Studio XML project writer.""" def __init__(self, project_path, version): """Initializes the project. Args: project_path: Path to the project file. version: Format version to emit. """ self.project_path = project_path self.doc = None self.version = version def Create(self, name, guid=None, platforms=None): """Creates the project document. Args: name: Name of the project. guid: GUID to use for project, if not None. """ self.name = name self.guid = guid or MSVSNew.MakeGuid(self.project_path) # Default to Win32 for platforms. if not platforms: platforms = ['Win32'] # Create XML doc xml_impl = xml.dom.getDOMImplementation() self.doc = xml_impl.createDocument(None, 'VisualStudioProject', None) # Add attributes to root element self.n_root = self.doc.documentElement self.n_root.setAttribute('ProjectType', 'Visual C++') self.n_root.setAttribute('Version', self.version.ProjectVersion()) self.n_root.setAttribute('Name', self.name) self.n_root.setAttribute('ProjectGUID', self.guid) self.n_root.setAttribute('RootNamespace', self.name) self.n_root.setAttribute('Keyword', 'Win32Proj') # Add platform list n_platform = self.doc.createElement('Platforms') self.n_root.appendChild(n_platform) for platform in platforms: n = self.doc.createElement('Platform') n.setAttribute('Name', platform) n_platform.appendChild(n) # Add tool files section self.n_tool_files = self.doc.createElement('ToolFiles') self.n_root.appendChild(self.n_tool_files) # Add configurations section self.n_configs = self.doc.createElement('Configurations') self.n_root.appendChild(self.n_configs) # Add empty References section self.n_root.appendChild(self.doc.createElement('References')) # Add files section self.n_files = self.doc.createElement('Files') self.n_root.appendChild(self.n_files) # Keep a dict keyed on filename to speed up access. self.n_files_dict = dict() # Add empty Globals section self.n_root.appendChild(self.doc.createElement('Globals')) def AddToolFile(self, path): """Adds a tool file to the project. Args: path: Relative path from project to tool file. """ n_tool = self.doc.createElement('ToolFile') n_tool.setAttribute('RelativePath', path) self.n_tool_files.appendChild(n_tool) def _AddConfigToNode(self, parent, config_type, config_name, attrs=None, tools=None): """Adds a configuration to the parent node. Args: parent: Destination node. config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. """ # Handle defaults if not attrs: attrs = {} if not tools: tools = [] # Add configuration node and its attributes n_config = self.doc.createElement(config_type) n_config.setAttribute('Name', config_name) for k, v in attrs.items(): n_config.setAttribute(k, v) parent.appendChild(n_config) # Add tool nodes and their attributes if tools: for t in tools: if isinstance(t, Tool): n_config.appendChild(t.CreateElement(self.doc)) else: n_config.appendChild(Tool(t).CreateElement(self.doc)) def AddConfig(self, name, attrs=None, tools=None): """Adds a configuration to the project. Args: name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. """ self._AddConfigToNode(self.n_configs, 'Configuration', name, attrs, tools) def _AddFilesToNode(self, parent, files): """Adds files and/or filters to the parent node. Args: parent: Destination node files: A list of Filter objects and/or relative paths to files. Will call itself recursively, if the files list contains Filter objects. """ for f in files: if isinstance(f, Filter): node = self.doc.createElement('Filter') node.setAttribute('Name', f.name) self._AddFilesToNode(node, f.contents) else: node = self.doc.createElement('File') node.setAttribute('RelativePath', f) self.n_files_dict[f] = node parent.appendChild(node) def AddFiles(self, files): """Adds files to the project. Args: files: A list of Filter objects and/or relative paths to files. This makes a copy of the file/filter tree at the time of this call. If you later add files to a Filter object which was passed into a previous call to AddFiles(), it will not be reflected in this project. """ self._AddFilesToNode(self.n_files, files) # TODO(rspangler) This also doesn't handle adding files to an existing # filter. That is, it doesn't merge the trees. def AddFileConfig(self, path, config, attrs=None, tools=None): """Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles(). """ # Find the file node with the right relative path parent = self.n_files_dict.get(path) if not parent: raise ValueError('AddFileConfig: file "%s" not in project.' % path) # Add the config to the file node self._AddConfigToNode(parent, 'FileConfiguration', config, attrs, tools) def Write(self, writer=common.WriteOnDiff): """Writes the project file.""" f = writer(self.project_path) self.doc.writexml(f, encoding='Windows-1252', addindent=' ', newl='\r\n') f.close() #------------------------------------------------------------------------------
ging/horizon
refs/heads/master
horizon/contrib/bootstrap_datepicker.py
87
# Copyright 2014 IBM Corp. # # 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. # Map Horizon languages to datepicker locales LOCALE_MAPPING = { 'ar': 'ar', 'az': 'az', 'bg': 'bg', 'ca': 'ca', 'cs': 'cs', 'cy': 'cy', 'da': 'da', 'de': 'de', 'el': 'el', 'es': 'es', 'et': 'et', 'fa': 'fa', 'fi': 'fi', 'fr': 'fr', 'gl': 'gl', 'he': 'he', 'hr': 'hr', 'hu': 'hu', 'id': 'id', 'is': 'is', 'it': 'it', 'ja': 'ja', 'ka': 'ka', 'kk': 'kk', 'ko': 'kr', # difference between horizon and datepicker 'lt': 'lt', 'lv': 'lv', 'mk': 'mk', 'ms': 'ms', 'nb': 'nb', 'nl-be': 'nl-BE', 'nl': 'nl', 'no': 'no', 'pl': 'pl', 'pt-br': 'pt-BR', 'pt': 'pt', 'ro': 'ro', 'rs-latin': 'rs-latin', 'sr': 'rs', # difference between horizon and datepicker 'ru': 'ru', 'sk': 'sk', 'sl': 'sl', 'sq': 'sq', 'sv': 'sv', 'sw': 'sw', 'th': 'th', 'tr': 'tr', 'ua': 'ua', 'vi': 'vi', 'zh-cn': 'zh-CN', 'zh-tw': 'zh-TW', }
kingvuplus/enigma2
refs/heads/master
lib/python/Components/Element.py
47
from Tools.CList import CList # down up # Render Converter Converter Source # a bidirectional connection def cached(f): name = f.__name__ def wrapper(self): cache = self.cache if cache is None: return f(self) if name not in cache: cache[name] = (True, f(self)) return cache[name][1] return wrapper class ElementError(Exception): def __init__(self, message): self.msg = message def __str__(self): return self.msg class Element(object): CHANGED_DEFAULT = 0 # initial "pull" state CHANGED_ALL = 1 # really everything changed CHANGED_CLEAR = 2 # we're expecting a real update soon. don't bother polling NOW, but clear data. CHANGED_SPECIFIC = 3 # second tuple will specify what exactly changed CHANGED_POLL = 4 # a timer expired SINGLE_SOURCE = True def __init__(self): self.downstream_elements = CList() self.master = None self.sources = [ ] self.source = None self.__suspended = True self.cache = None def connectDownstream(self, downstream): self.downstream_elements.append(downstream) if self.master is None: self.master = downstream def connectUpstream(self, upstream): assert not self.SINGLE_SOURCE or self.source is None self.sources.append(upstream) # self.source always refers to the last recent source added. self.source = upstream self.changed((self.CHANGED_DEFAULT,)) def connect(self, upstream): self.connectUpstream(upstream) upstream.connectDownstream(self) # we disconnect from down to up def disconnectAll(self): # we should not disconnect from upstream if # there are still elements depending on us. assert len(self.downstream_elements) == 0, "there are still downstream elements left" # Sources don't have a source themselves. don't do anything here. for s in self.sources: s.disconnectDownstream(self) if self.source: # sources are owned by the Screen, so don't destroy them here. self.destroy() self.source = None self.sources = [ ] def disconnectDownstream(self, downstream): self.downstream_elements.remove(downstream) if self.master == downstream: self.master = None if len(self.downstream_elements) == 0: self.disconnectAll() # default action: push downstream def changed(self, *args, **kwargs): self.cache = { } self.downstream_elements.changed(*args, **kwargs) self.cache = None def setSuspend(self, suspended): changed = self.__suspended != suspended if not self.__suspended and suspended: self.doSuspend(1) elif self.__suspended and not suspended: self.doSuspend(0) self.__suspended = suspended if changed: for s in self.sources: s.checkSuspend() suspended = property(lambda self: self.__suspended, setSuspend) def checkSuspend(self): self.suspended = reduce(lambda x, y: x and y.__suspended, self.downstream_elements, True) def doSuspend(self, suspend): pass def destroy(self): pass
ilc/imgserv
refs/heads/master
bottle.py
71
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Bottle is a fast and simple micro-framework for small web applications. It offers request dispatching (Routes) with url parameter support, templates, a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and template engines - all in a single file and with no dependencies other than the Python Standard Library. Homepage and documentation: http://bottlepy.org/ Copyright (c) 2012, Marcel Hellkamp. License: MIT (see LICENSE for details) """ from __future__ import with_statement __author__ = 'Marcel Hellkamp' __version__ = '0.11.6' __license__ = 'MIT' # The gevent server adapter needs to patch some modules before they are imported # This is why we parse the commandline parameters here but handle them later if __name__ == '__main__': from optparse import OptionParser _cmd_parser = OptionParser(usage="usage: %prog [options] package.module:app") _opt = _cmd_parser.add_option _opt("--version", action="store_true", help="show version number.") _opt("-b", "--bind", metavar="ADDRESS", help="bind socket to ADDRESS.") _opt("-s", "--server", default='wsgiref', help="use SERVER as backend.") _opt("-p", "--plugin", action="append", help="install additional plugin/s.") _opt("--debug", action="store_true", help="start server in debug mode.") _opt("--reload", action="store_true", help="auto-reload on file changes.") _cmd_options, _cmd_args = _cmd_parser.parse_args() if _cmd_options.server and _cmd_options.server.startswith('gevent'): import gevent.monkey; gevent.monkey.patch_all() import base64, cgi, email.utils, functools, hmac, imp, itertools, mimetypes,\ os, re, subprocess, sys, tempfile, threading, time, urllib, warnings from datetime import date as datedate, datetime, timedelta from tempfile import TemporaryFile from traceback import format_exc, print_exc try: from json import dumps as json_dumps, loads as json_lds except ImportError: # pragma: no cover try: from simplejson import dumps as json_dumps, loads as json_lds except ImportError: try: from django.utils.simplejson import dumps as json_dumps, loads as json_lds except ImportError: def json_dumps(data): raise ImportError("JSON support requires Python 2.6 or simplejson.") json_lds = json_dumps # We now try to fix 2.5/2.6/3.1/3.2 incompatibilities. # It ain't pretty but it works... Sorry for the mess. py = sys.version_info py3k = py >= (3,0,0) py25 = py < (2,6,0) py31 = (3,1,0) <= py < (3,2,0) # Workaround for the missing "as" keyword in py3k. def _e(): return sys.exc_info()[1] # Workaround for the "print is a keyword/function" Python 2/3 dilemma # and a fallback for mod_wsgi (resticts stdout/err attribute access) try: _stdout, _stderr = sys.stdout.write, sys.stderr.write except IOError: _stdout = lambda x: sys.stdout.write(x) _stderr = lambda x: sys.stderr.write(x) # Lots of stdlib and builtin differences. if py3k: import http.client as httplib import _thread as thread from urllib.parse import urljoin, SplitResult as UrlSplitResult from urllib.parse import urlencode, quote as urlquote, unquote as urlunquote urlunquote = functools.partial(urlunquote, encoding='latin1') from http.cookies import SimpleCookie from collections import MutableMapping as DictMixin import pickle from io import BytesIO basestring = str unicode = str json_loads = lambda s: json_lds(touni(s)) callable = lambda x: hasattr(x, '__call__') imap = map else: # 2.x import httplib import thread from urlparse import urljoin, SplitResult as UrlSplitResult from urllib import urlencode, quote as urlquote, unquote as urlunquote from Cookie import SimpleCookie from itertools import imap import cPickle as pickle from StringIO import StringIO as BytesIO if py25: msg = "Python 2.5 support may be dropped in future versions of Bottle." warnings.warn(msg, DeprecationWarning) from UserDict import DictMixin def next(it): return it.next() bytes = str else: # 2.6, 2.7 from collections import MutableMapping as DictMixin json_loads = json_lds # Some helpers for string/byte handling def tob(s, enc='utf8'): return s.encode(enc) if isinstance(s, unicode) else bytes(s) def touni(s, enc='utf8', err='strict'): return s.decode(enc, err) if isinstance(s, bytes) else unicode(s) tonat = touni if py3k else tob # 3.2 fixes cgi.FieldStorage to accept bytes (which makes a lot of sense). # 3.1 needs a workaround. if py31: from io import TextIOWrapper class NCTextIOWrapper(TextIOWrapper): def close(self): pass # Keep wrapped buffer open. # File uploads (which are implemented as empty FiledStorage instances...) # have a negative truth value. That makes no sense, here is a fix. class FieldStorage(cgi.FieldStorage): def __nonzero__(self): return bool(self.list or self.file) if py3k: __bool__ = __nonzero__ # A bug in functools causes it to break if the wrapper is an instance method def update_wrapper(wrapper, wrapped, *a, **ka): try: functools.update_wrapper(wrapper, wrapped, *a, **ka) except AttributeError: pass # These helpers are used at module level and need to be defined first. # And yes, I know PEP-8, but sometimes a lower-case classname makes more sense. def depr(message): warnings.warn(message, DeprecationWarning, stacklevel=3) def makelist(data): # This is just to handy if isinstance(data, (tuple, list, set, dict)): return list(data) elif data: return [data] else: return [] class DictProperty(object): ''' Property that maps to a key in a local dict-like attribute. ''' def __init__(self, attr, key=None, read_only=False): self.attr, self.key, self.read_only = attr, key, read_only def __call__(self, func): functools.update_wrapper(self, func, updated=[]) self.getter, self.key = func, self.key or func.__name__ return self def __get__(self, obj, cls): if obj is None: return self key, storage = self.key, getattr(obj, self.attr) if key not in storage: storage[key] = self.getter(obj) return storage[key] def __set__(self, obj, value): if self.read_only: raise AttributeError("Read-Only property.") getattr(obj, self.attr)[self.key] = value def __delete__(self, obj): if self.read_only: raise AttributeError("Read-Only property.") del getattr(obj, self.attr)[self.key] class cached_property(object): ''' A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. ''' def __init__(self, func): self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value class lazy_attribute(object): ''' A property that caches itself to the class object. ''' def __init__(self, func): functools.update_wrapper(self, func, updated=[]) self.getter = func def __get__(self, obj, cls): value = self.getter(cls) setattr(cls, self.__name__, value) return value ############################################################################### # Exceptions and Events ######################################################## ############################################################################### class BottleException(Exception): """ A base class for exceptions used by bottle. """ pass ############################################################################### # Routing ###################################################################### ############################################################################### class RouteError(BottleException): """ This is a base class for all routing related exceptions """ class RouteReset(BottleException): """ If raised by a plugin or request handler, the route is reset and all plugins are re-applied. """ class RouterUnknownModeError(RouteError): pass class RouteSyntaxError(RouteError): """ The route parser found something not supported by this router """ class RouteBuildError(RouteError): """ The route could not been built """ class Router(object): ''' A Router is an ordered collection of route->target pairs. It is used to efficiently match WSGI requests against a number of routes and return the first target that satisfies the request. The target may be anything, usually a string, ID or callable object. A route consists of a path-rule and a HTTP method. The path-rule is either a static path (e.g. `/contact`) or a dynamic path that contains wildcards (e.g. `/wiki/<page>`). The wildcard syntax and details on the matching order are described in docs:`routing`. ''' default_pattern = '[^/]+' default_filter = 're' #: Sorry for the mess. It works. Trust me. rule_syntax = re.compile('(\\\\*)'\ '(?:(?::([a-zA-Z_][a-zA-Z_0-9]*)?()(?:#(.*?)#)?)'\ '|(?:<([a-zA-Z_][a-zA-Z_0-9]*)?(?::([a-zA-Z_]*)'\ '(?::((?:\\\\.|[^\\\\>]+)+)?)?)?>))') def __init__(self, strict=False): self.rules = {} # A {rule: Rule} mapping self.builder = {} # A rule/name->build_info mapping self.static = {} # Cache for static routes: {path: {method: target}} self.dynamic = [] # Cache for dynamic routes. See _compile() #: If true, static routes are no longer checked first. self.strict_order = strict self.filters = {'re': self.re_filter, 'int': self.int_filter, 'float': self.float_filter, 'path': self.path_filter} def re_filter(self, conf): return conf or self.default_pattern, None, None def int_filter(self, conf): return r'-?\d+', int, lambda x: str(int(x)) def float_filter(self, conf): return r'-?[\d.]+', float, lambda x: str(float(x)) def path_filter(self, conf): return r'.+?', None, None def add_filter(self, name, func): ''' Add a filter. The provided function is called with the configuration string as parameter and must return a (regexp, to_python, to_url) tuple. The first element is a string, the last two are callables or None. ''' self.filters[name] = func def parse_rule(self, rule): ''' Parses a rule into a (name, filter, conf) token stream. If mode is None, name contains a static rule part. ''' offset, prefix = 0, '' for match in self.rule_syntax.finditer(rule): prefix += rule[offset:match.start()] g = match.groups() if len(g[0])%2: # Escaped wildcard prefix += match.group(0)[len(g[0]):] offset = match.end() continue if prefix: yield prefix, None, None name, filtr, conf = g[1:4] if not g[2] is None else g[4:7] if not filtr: filtr = self.default_filter yield name, filtr, conf or None offset, prefix = match.end(), '' if offset <= len(rule) or prefix: yield prefix+rule[offset:], None, None def add(self, rule, method, target, name=None): ''' Add a new route or replace the target for an existing route. ''' if rule in self.rules: self.rules[rule][method] = target if name: self.builder[name] = self.builder[rule] return target = self.rules[rule] = {method: target} # Build pattern and other structures for dynamic routes anons = 0 # Number of anonymous wildcards pattern = '' # Regular expression pattern filters = [] # Lists of wildcard input filters builder = [] # Data structure for the URL builder is_static = True for key, mode, conf in self.parse_rule(rule): if mode: is_static = False mask, in_filter, out_filter = self.filters[mode](conf) if key: pattern += '(?P<%s>%s)' % (key, mask) else: pattern += '(?:%s)' % mask key = 'anon%d' % anons; anons += 1 if in_filter: filters.append((key, in_filter)) builder.append((key, out_filter or str)) elif key: pattern += re.escape(key) builder.append((None, key)) self.builder[rule] = builder if name: self.builder[name] = builder if is_static and not self.strict_order: self.static[self.build(rule)] = target return def fpat_sub(m): return m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:' flat_pattern = re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', fpat_sub, pattern) try: re_match = re.compile('^(%s)$' % pattern).match except re.error: raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, _e())) def match(path): """ Return an url-argument dictionary. """ url_args = re_match(path).groupdict() for name, wildcard_filter in filters: try: url_args[name] = wildcard_filter(url_args[name]) except ValueError: raise HTTPError(400, 'Path has wrong format.') return url_args try: combined = '%s|(^%s$)' % (self.dynamic[-1][0].pattern, flat_pattern) self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1]) self.dynamic[-1][1].append((match, target)) except (AssertionError, IndexError): # AssertionError: Too many groups self.dynamic.append((re.compile('(^%s$)' % flat_pattern), [(match, target)])) return match def build(self, _name, *anons, **query): ''' Build an URL by filling the wildcards in a rule. ''' builder = self.builder.get(_name) if not builder: raise RouteBuildError("No route with that name.", _name) try: for i, value in enumerate(anons): query['anon%d'%i] = value url = ''.join([f(query.pop(n)) if n else f for (n,f) in builder]) return url if not query else url+'?'+urlencode(query) except KeyError: raise RouteBuildError('Missing URL argument: %r' % _e().args[0]) def match(self, environ): ''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). ''' path, targets, urlargs = environ['PATH_INFO'] or '/', None, {} if path in self.static: targets = self.static[path] else: for combined, rules in self.dynamic: match = combined.match(path) if not match: continue getargs, targets = rules[match.lastindex - 1] urlargs = getargs(path) if getargs else {} break if not targets: raise HTTPError(404, "Not found: " + repr(environ['PATH_INFO'])) method = environ['REQUEST_METHOD'].upper() if method in targets: return targets[method], urlargs if method == 'HEAD' and 'GET' in targets: return targets['GET'], urlargs if 'ANY' in targets: return targets['ANY'], urlargs allowed = [verb for verb in targets if verb != 'ANY'] if 'GET' in allowed and 'HEAD' not in allowed: allowed.append('HEAD') raise HTTPError(405, "Method not allowed.", Allow=",".join(allowed)) class Route(object): ''' This class wraps a route callback along with route specific metadata and configuration and applies Plugins on demand. It is also responsible for turing an URL path rule into a regular expression usable by the Router. ''' def __init__(self, app, rule, method, callback, name=None, plugins=None, skiplist=None, **config): #: The application this route is installed to. self.app = app #: The path-rule string (e.g. ``/wiki/:page``). self.rule = rule #: The HTTP method as a string (e.g. ``GET``). self.method = method #: The original callback with no plugins applied. Useful for introspection. self.callback = callback #: The name of the route (if specified) or ``None``. self.name = name or None #: A list of route-specific plugins (see :meth:`Bottle.route`). self.plugins = plugins or [] #: A list of plugins to not apply to this route (see :meth:`Bottle.route`). self.skiplist = skiplist or [] #: Additional keyword arguments passed to the :meth:`Bottle.route` #: decorator are stored in this dictionary. Used for route-specific #: plugin configuration and meta-data. self.config = ConfigDict(config) def __call__(self, *a, **ka): depr("Some APIs changed to return Route() instances instead of"\ " callables. Make sure to use the Route.call method and not to"\ " call Route instances directly.") return self.call(*a, **ka) @cached_property def call(self): ''' The route callback with all plugins applied. This property is created on demand and then cached to speed up subsequent requests.''' return self._make_callback() def reset(self): ''' Forget any cached values. The next time :attr:`call` is accessed, all plugins are re-applied. ''' self.__dict__.pop('call', None) def prepare(self): ''' Do all on-demand work immediately (useful for debugging).''' self.call @property def _context(self): depr('Switch to Plugin API v2 and access the Route object directly.') return dict(rule=self.rule, method=self.method, callback=self.callback, name=self.name, app=self.app, config=self.config, apply=self.plugins, skip=self.skiplist) def all_plugins(self): ''' Yield all Plugins affecting this route. ''' unique = set() for p in reversed(self.app.plugins + self.plugins): if True in self.skiplist: break name = getattr(p, 'name', False) if name and (name in self.skiplist or name in unique): continue if p in self.skiplist or type(p) in self.skiplist: continue if name: unique.add(name) yield p def _make_callback(self): callback = self.callback for plugin in self.all_plugins(): try: if hasattr(plugin, 'apply'): api = getattr(plugin, 'api', 1) context = self if api > 1 else self._context callback = plugin.apply(callback, context) else: callback = plugin(callback) except RouteReset: # Try again with changed configuration. return self._make_callback() if not callback is self.callback: update_wrapper(callback, self.callback) return callback def __repr__(self): return '<%s %r %r>' % (self.method, self.rule, self.callback) ############################################################################### # Application Object ########################################################### ############################################################################### class Bottle(object): """ Each Bottle object represents a single, distinct web application and consists of routes, callbacks, plugins, resources and configuration. Instances are callable WSGI applications. :param catchall: If true (default), handle all exceptions. Turn off to let debugging middleware handle exceptions. """ def __init__(self, catchall=True, autojson=True): #: If true, most exceptions are caught and returned as :exc:`HTTPError` self.catchall = catchall #: A :class:`ResourceManager` for application files self.resources = ResourceManager() #: A :class:`ConfigDict` for app specific configuration. self.config = ConfigDict() self.config.autojson = autojson self.routes = [] # List of installed :class:`Route` instances. self.router = Router() # Maps requests to :class:`Route` instances. self.error_handler = {} # Core plugins self.plugins = [] # List of installed plugins. self.hooks = HooksPlugin() self.install(self.hooks) if self.config.autojson: self.install(JSONPlugin()) self.install(TemplatePlugin()) def mount(self, prefix, app, **options): ''' Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is mandatory. :param app: an instance of :class:`Bottle` or a WSGI application. All other parameters are passed to the underlying :meth:`route` call. ''' if isinstance(app, basestring): prefix, app = app, prefix depr('Parameter order of Bottle.mount() changed.') # 0.10 segments = [p for p in prefix.split('/') if p] if not segments: raise ValueError('Empty path prefix.') path_depth = len(segments) def mountpoint_wrapper(): try: request.path_shift(path_depth) rs = HTTPResponse([]) def start_response(status, headerlist): rs.status = status for name, value in headerlist: rs.add_header(name, value) return rs.body.append body = app(request.environ, start_response) if body and rs.body: body = itertools.chain(rs.body, body) rs.body = body or rs.body return rs finally: request.path_shift(-path_depth) options.setdefault('skip', True) options.setdefault('method', 'ANY') options.setdefault('mountpoint', {'prefix': prefix, 'target': app}) options['callback'] = mountpoint_wrapper self.route('/%s/<:re:.*>' % '/'.join(segments), **options) if not prefix.endswith('/'): self.route('/' + '/'.join(segments), **options) def merge(self, routes): ''' Merge the routes of another :class:`Bottle` application or a list of :class:`Route` objects into this application. The routes keep their 'owner', meaning that the :data:`Route.app` attribute is not changed. ''' if isinstance(routes, Bottle): routes = routes.routes for route in routes: self.add_route(route) def install(self, plugin): ''' Add a plugin to the list of plugins and prepare it for being applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API. ''' if hasattr(plugin, 'setup'): plugin.setup(self) if not callable(plugin) and not hasattr(plugin, 'apply'): raise TypeError("Plugins must be callable or implement .apply()") self.plugins.append(plugin) self.reset() return plugin def uninstall(self, plugin): ''' Uninstall plugins. Pass an instance to remove a specific plugin, a type object to remove all plugins that match that type, a string to remove all plugins with a matching ``name`` attribute or ``True`` to remove all plugins. Return the list of removed plugins. ''' removed, remove = [], plugin for i, plugin in list(enumerate(self.plugins))[::-1]: if remove is True or remove is plugin or remove is type(plugin) \ or getattr(plugin, 'name', True) == remove: removed.append(plugin) del self.plugins[i] if hasattr(plugin, 'close'): plugin.close() if removed: self.reset() return removed def run(self, **kwargs): ''' Calls :func:`run` with the same parameters. ''' run(self, **kwargs) def reset(self, route=None): ''' Reset all routes (force plugins to be re-applied) and clear all caches. If an ID or route object is given, only that specific route is affected. ''' if route is None: routes = self.routes elif isinstance(route, Route): routes = [route] else: routes = [self.routes[route]] for route in routes: route.reset() if DEBUG: for route in routes: route.prepare() self.hooks.trigger('app_reset') def close(self): ''' Close the application and all installed plugins. ''' for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() self.stopped = True def match(self, environ): """ Search for a matching route and return a (:class:`Route` , urlargs) tuple. The second value is a dictionary with parameters extracted from the URL. Raise :exc:`HTTPError` (404/405) on a non-match.""" return self.router.match(environ) def get_url(self, routename, **kargs): """ Return a string that matches a named route """ scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/' location = self.router.build(routename, **kargs).lstrip('/') return urljoin(urljoin('/', scriptname), location) def add_route(self, route): ''' Add a route object, but do not change the :data:`Route.app` attribute.''' self.routes.append(route) self.router.add(route.rule, route.method, route, name=route.name) if DEBUG: route.prepare() def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path or a list of paths to listen to. If no path is specified, it is automatically generated from the signature of the function. :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of methods to listen to. (default: `GET`) :param callback: An optional shortcut to avoid the decorator syntax. ``route(..., callback=func)`` equals ``route(...)(func)`` :param name: The name for this route. (default: None) :param apply: A decorator or plugin or a list of plugins. These are applied to the route callback in addition to installed plugins. :param skip: A list of plugins, plugin classes or names. Matching plugins are not installed to this route. ``True`` skips all. Any additional keyword arguments are stored as route-specific configuration and passed to plugins (see :meth:`Plugin.apply`). """ if callable(path): path, callback = None, path plugins = makelist(apply) skiplist = makelist(skip) def decorator(callback): # TODO: Documentation and tests if isinstance(callback, basestring): callback = load(callback) for rule in makelist(path) or yieldroutes(callback): for verb in makelist(method): verb = verb.upper() route = Route(self, rule, verb, callback, name=name, plugins=plugins, skiplist=skiplist, **config) self.add_route(route) return callback return decorator(callback) if callback else decorator def get(self, path=None, method='GET', **options): """ Equals :meth:`route`. """ return self.route(path, method, **options) def post(self, path=None, method='POST', **options): """ Equals :meth:`route` with a ``POST`` method parameter. """ return self.route(path, method, **options) def put(self, path=None, method='PUT', **options): """ Equals :meth:`route` with a ``PUT`` method parameter. """ return self.route(path, method, **options) def delete(self, path=None, method='DELETE', **options): """ Equals :meth:`route` with a ``DELETE`` method parameter. """ return self.route(path, method, **options) def error(self, code=500): """ Decorator: Register an output handler for a HTTP error code""" def wrapper(handler): self.error_handler[int(code)] = handler return handler return wrapper def hook(self, name): """ Return a decorator that attaches a callback to a hook. Three hooks are currently implemented: - before_request: Executed once before each request - after_request: Executed once after each request - app_reset: Called whenever :meth:`reset` is called. """ def wrapper(func): self.hooks.add(name, func) return func return wrapper def handle(self, path, method='GET'): """ (deprecated) Execute the first matching route callback and return the result. :exc:`HTTPResponse` exceptions are caught and returned. If :attr:`Bottle.catchall` is true, other exceptions are caught as well and returned as :exc:`HTTPError` instances (500). """ depr("This method will change semantics in 0.10. Try to avoid it.") if isinstance(path, dict): return self._handle(path) return self._handle({'PATH_INFO': path, 'REQUEST_METHOD': method.upper()}) def default_error_handler(self, res): return tob(template(ERROR_PAGE_TEMPLATE, e=res)) def _handle(self, environ): try: environ['bottle.app'] = self request.bind(environ) response.bind() route, args = self.router.match(environ) environ['route.handle'] = route environ['bottle.route'] = route environ['route.url_args'] = args return route.call(**args) except HTTPResponse: return _e() except RouteReset: route.reset() return self._handle(environ) except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception: if not self.catchall: raise stacktrace = format_exc() environ['wsgi.errors'].write(stacktrace) return HTTPError(500, "Internal Server Error", _e(), stacktrace) def _cast(self, out, peek=None): """ Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes """ # Empty output is done here if not out: if 'Content-Length' not in response: response['Content-Length'] = 0 return [] # Join lists of byte or unicode strings. Mixed lists are NOT supported if isinstance(out, (tuple, list))\ and isinstance(out[0], (bytes, unicode)): out = out[0][0:0].join(out) # b'abc'[0:0] -> b'' # Encode unicode strings if isinstance(out, unicode): out = out.encode(response.charset) # Byte Strings are just returned if isinstance(out, bytes): if 'Content-Length' not in response: response['Content-Length'] = len(out) return [out] # HTTPError or HTTPException (recursive, because they may wrap anything) # TODO: Handle these explicitly in handle() or make them iterable. if isinstance(out, HTTPError): out.apply(response) out = self.error_handler.get(out.status_code, self.default_error_handler)(out) return self._cast(out) if isinstance(out, HTTPResponse): out.apply(response) return self._cast(out.body) # File-like objects. if hasattr(out, 'read'): if 'wsgi.file_wrapper' in request.environ: return request.environ['wsgi.file_wrapper'](out) elif hasattr(out, 'close') or not hasattr(out, '__iter__'): return WSGIFileWrapper(out) # Handle Iterables. We peek into them to detect their inner type. try: out = iter(out) first = next(out) while not first: first = next(out) except StopIteration: return self._cast('') except HTTPResponse: first = _e() except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception: if not self.catchall: raise first = HTTPError(500, 'Unhandled exception', _e(), format_exc()) # These are the inner types allowed in iterator or generator objects. if isinstance(first, HTTPResponse): return self._cast(first) if isinstance(first, bytes): return itertools.chain([first], out) if isinstance(first, unicode): return imap(lambda x: x.encode(response.charset), itertools.chain([first], out)) return self._cast(HTTPError(500, 'Unsupported response type: %s'\ % type(first))) def wsgi(self, environ, start_response): """ The bottle WSGI-interface. """ try: out = self._cast(self._handle(environ)) # rfc2616 section 4.3 if response._status_code in (100, 101, 204, 304)\ or environ['REQUEST_METHOD'] == 'HEAD': if hasattr(out, 'close'): out.close() out = [] start_response(response._status_line, response.headerlist) return out except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception: if not self.catchall: raise err = '<h1>Critical error while processing request: %s</h1>' \ % html_escape(environ.get('PATH_INFO', '/')) if DEBUG: err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \ '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \ % (html_escape(repr(_e())), html_escape(format_exc())) environ['wsgi.errors'].write(err) headers = [('Content-Type', 'text/html; charset=UTF-8')] start_response('500 INTERNAL SERVER ERROR', headers) return [tob(err)] def __call__(self, environ, start_response): ''' Each instance of :class:'Bottle' is a WSGI application. ''' return self.wsgi(environ, start_response) ############################################################################### # HTTP and WSGI Tools ########################################################## ############################################################################### class BaseRequest(object): """ A wrapper for WSGI environment dictionaries that adds a lot of convenient access methods and properties. Most of them are read-only. Adding new attributes to a request actually adds them to the environ dictionary (as 'bottle.request.ext.<name>'). This is the recommended way to store and access request-specific data. """ __slots__ = ('environ') #: Maximum size of memory buffer for :attr:`body` in bytes. MEMFILE_MAX = 102400 #: Maximum number pr GET or POST parameters per request MAX_PARAMS = 100 def __init__(self, environ=None): """ Wrap a WSGI environ dictionary. """ #: The wrapped WSGI environ dictionary. This is the only real attribute. #: All other attributes actually are read-only properties. self.environ = {} if environ is None else environ self.environ['bottle.request'] = self @DictProperty('environ', 'bottle.app', read_only=True) def app(self): ''' Bottle application handling this request. ''' raise RuntimeError('This request is not connected to an application.') @property def path(self): ''' The value of ``PATH_INFO`` with exactly one prefixed slash (to fix broken clients and avoid the "empty path" edge case). ''' return '/' + self.environ.get('PATH_INFO','').lstrip('/') @property def method(self): ''' The ``REQUEST_METHOD`` value as an uppercase string. ''' return self.environ.get('REQUEST_METHOD', 'GET').upper() @DictProperty('environ', 'bottle.request.headers', read_only=True) def headers(self): ''' A :class:`WSGIHeaderDict` that provides case-insensitive access to HTTP request headers. ''' return WSGIHeaderDict(self.environ) def get_header(self, name, default=None): ''' Return the value of a request header, or a given default value. ''' return self.headers.get(name, default) @DictProperty('environ', 'bottle.request.cookies', read_only=True) def cookies(self): """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies. """ cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')) cookies = list(cookies.values())[:self.MAX_PARAMS] return FormsDict((c.key, c.value) for c in cookies) def get_cookie(self, key, default=None, secret=None): """ Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default value. """ value = self.cookies.get(key) if secret and value: dec = cookie_decode(value, secret) # (key, value) tuple or None return dec[1] if dec and dec[0] == key else default return value or default @DictProperty('environ', 'bottle.request.query', read_only=True) def query(self): ''' The :attr:`query_string` parsed into a :class:`FormsDict`. These values are sometimes called "URL arguments" or "GET parameters", but not to be confused with "URL wildcards" as they are provided by the :class:`Router`. ''' get = self.environ['bottle.get'] = FormsDict() pairs = _parse_qsl(self.environ.get('QUERY_STRING', '')) for key, value in pairs[:self.MAX_PARAMS]: get[key] = value return get @DictProperty('environ', 'bottle.request.forms', read_only=True) def forms(self): """ Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is retuned as a :class:`FormsDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`. """ forms = FormsDict() for name, item in self.POST.allitems(): if not hasattr(item, 'filename'): forms[name] = item return forms @DictProperty('environ', 'bottle.request.params', read_only=True) def params(self): """ A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`. """ params = FormsDict() for key, value in self.query.allitems(): params[key] = value for key, value in self.forms.allitems(): params[key] = value return params @DictProperty('environ', 'bottle.request.files', read_only=True) def files(self): """ File uploads parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`cgi.FieldStorage`. The most important attributes are: filename The filename, if specified; otherwise None; this is the client side filename, *not* the file name on which it is stored (that's a temporary file you don't deal with) file The file(-like) object from which you can read the data. value The value as a *string*; for file uploads, this transparently reads the file every time you request the value. Do not do this on big files. """ files = FormsDict() for name, item in self.POST.allitems(): if hasattr(item, 'filename'): files[name] = item return files @DictProperty('environ', 'bottle.request.json', read_only=True) def json(self): ''' If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. ''' if 'application/json' in self.environ.get('CONTENT_TYPE', '') \ and 0 < self.content_length < self.MEMFILE_MAX: return json_loads(self.body.read(self.MEMFILE_MAX)) return None @DictProperty('environ', 'bottle.request.body', read_only=True) def _body(self): maxread = max(0, self.content_length) stream = self.environ['wsgi.input'] body = BytesIO() if maxread < self.MEMFILE_MAX else TemporaryFile(mode='w+b') while maxread > 0: part = stream.read(min(maxread, self.MEMFILE_MAX)) if not part: break body.write(part) maxread -= len(part) self.environ['wsgi.input'] = body body.seek(0) return body @property def body(self): """ The HTTP request body as a seek-able file-like object. Depending on :attr:`MEMFILE_MAX`, this is either a temporary file or a :class:`io.BytesIO` instance. Accessing this property for the first time reads and replaces the ``wsgi.input`` environ variable. Subsequent accesses just do a `seek(0)` on the file object. """ self._body.seek(0) return self._body #: An alias for :attr:`query`. GET = query @DictProperty('environ', 'bottle.request.post', read_only=True) def POST(self): """ The values of :attr:`forms` and :attr:`files` combined into a single :class:`FormsDict`. Values are either strings (form values) or instances of :class:`cgi.FieldStorage` (file uploads). """ post = FormsDict() # We default to application/x-www-form-urlencoded for everything that # is not multipart and take the fast path (also: 3.1 workaround) if not self.content_type.startswith('multipart/'): maxlen = max(0, min(self.content_length, self.MEMFILE_MAX)) pairs = _parse_qsl(tonat(self.body.read(maxlen), 'latin1')) for key, value in pairs[:self.MAX_PARAMS]: post[key] = value return post safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'): if key in self.environ: safe_env[key] = self.environ[key] args = dict(fp=self.body, environ=safe_env, keep_blank_values=True) if py31: args['fp'] = NCTextIOWrapper(args['fp'], encoding='ISO-8859-1', newline='\n') elif py3k: args['encoding'] = 'ISO-8859-1' data = FieldStorage(**args) for item in (data.list or [])[:self.MAX_PARAMS]: post[item.name] = item if item.filename else item.value return post @property def COOKIES(self): ''' Alias for :attr:`cookies` (deprecated). ''' depr('BaseRequest.COOKIES was renamed to BaseRequest.cookies (lowercase).') return self.cookies @property def url(self): """ The full request URI including hostname and scheme. If your app lives behind a reverse proxy or load balancer and you get confusing results, make sure that the ``X-Forwarded-Host`` header is set correctly. """ return self.urlparts.geturl() @DictProperty('environ', 'bottle.request.urlparts', read_only=True) def urlparts(self): ''' The :attr:`url` string as an :class:`urlparse.SplitResult` tuple. The tuple contains (scheme, host, path, query_string and fragment), but the fragment is always empty because it is not visible to the server. ''' env = self.environ http = env.get('HTTP_X_FORWARDED_PROTO') or env.get('wsgi.url_scheme', 'http') host = env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST') if not host: # HTTP 1.1 requires a Host-header. This is for HTTP/1.0 clients. host = env.get('SERVER_NAME', '127.0.0.1') port = env.get('SERVER_PORT') if port and port != ('80' if http == 'http' else '443'): host += ':' + port path = urlquote(self.fullpath) return UrlSplitResult(http, host, path, env.get('QUERY_STRING'), '') @property def fullpath(self): """ Request path including :attr:`script_name` (if present). """ return urljoin(self.script_name, self.path.lstrip('/')) @property def query_string(self): """ The raw :attr:`query` part of the URL (everything in between ``?`` and ``#``) as a string. """ return self.environ.get('QUERY_STRING', '') @property def script_name(self): ''' The initial portion of the URL's `path` that was removed by a higher level (server or routing middleware) before the application was called. This script path is returned with leading and tailing slashes. ''' script_name = self.environ.get('SCRIPT_NAME', '').strip('/') return '/' + script_name + '/' if script_name else '/' def path_shift(self, shift=1): ''' Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1) ''' script = self.environ.get('SCRIPT_NAME','/') self['SCRIPT_NAME'], self['PATH_INFO'] = path_shift(script, self.path, shift) @property def content_length(self): ''' The request body length as an integer. The client is responsible to set this header. Otherwise, the real length of the body is unknown and -1 is returned. In this case, :attr:`body` will be empty. ''' return int(self.environ.get('CONTENT_LENGTH') or -1) @property def content_type(self): ''' The Content-Type header as a lowercase-string (default: empty). ''' return self.environ.get('CONTENT_TYPE', '').lower() @property def is_xhr(self): ''' True if the request was triggered by a XMLHttpRequest. This only works with JavaScript libraries that support the `X-Requested-With` header (most of the popular libraries do). ''' requested_with = self.environ.get('HTTP_X_REQUESTED_WITH','') return requested_with.lower() == 'xmlhttprequest' @property def is_ajax(self): ''' Alias for :attr:`is_xhr`. "Ajax" is not the right term. ''' return self.is_xhr @property def auth(self): """ HTTP authentication data as a (user, password) tuple. This implementation currently supports basic (not digest) authentication only. If the authentication happened at a higher level (e.g. in the front web-server or a middleware), the password field is None, but the user field is looked up from the ``REMOTE_USER`` environ variable. On any errors, None is returned. """ basic = parse_auth(self.environ.get('HTTP_AUTHORIZATION','')) if basic: return basic ruser = self.environ.get('REMOTE_USER') if ruser: return (ruser, None) return None @property def remote_route(self): """ A list of all IPs that were involved in this request, starting with the client IP and followed by zero or more proxies. This does only work if all proxies support the ```X-Forwarded-For`` header. Note that this information can be forged by malicious clients. """ proxy = self.environ.get('HTTP_X_FORWARDED_FOR') if proxy: return [ip.strip() for ip in proxy.split(',')] remote = self.environ.get('REMOTE_ADDR') return [remote] if remote else [] @property def remote_addr(self): """ The client IP as a string. Note that this information can be forged by malicious clients. """ route = self.remote_route return route[0] if route else None def copy(self): """ Return a new :class:`Request` with a shallow :attr:`environ` copy. """ return Request(self.environ.copy()) def get(self, value, default=None): return self.environ.get(value, default) def __getitem__(self, key): return self.environ[key] def __delitem__(self, key): self[key] = ""; del(self.environ[key]) def __iter__(self): return iter(self.environ) def __len__(self): return len(self.environ) def keys(self): return self.environ.keys() def __setitem__(self, key, value): """ Change an environ value and clear all caches that depend on it. """ if self.environ.get('bottle.request.readonly'): raise KeyError('The environ dictionary is read-only.') self.environ[key] = value todelete = () if key == 'wsgi.input': todelete = ('body', 'forms', 'files', 'params', 'post', 'json') elif key == 'QUERY_STRING': todelete = ('query', 'params') elif key.startswith('HTTP_'): todelete = ('headers', 'cookies') for key in todelete: self.environ.pop('bottle.request.'+key, None) def __repr__(self): return '<%s: %s %s>' % (self.__class__.__name__, self.method, self.url) def __getattr__(self, name): ''' Search in self.environ for additional user defined attributes. ''' try: var = self.environ['bottle.request.ext.%s'%name] return var.__get__(self) if hasattr(var, '__get__') else var except KeyError: raise AttributeError('Attribute %r not defined.' % name) def __setattr__(self, name, value): if name == 'environ': return object.__setattr__(self, name, value) self.environ['bottle.request.ext.%s'%name] = value def _hkey(s): return s.title().replace('_','-') class HeaderProperty(object): def __init__(self, name, reader=None, writer=str, default=''): self.name, self.default = name, default self.reader, self.writer = reader, writer self.__doc__ = 'Current value of the %r header.' % name.title() def __get__(self, obj, cls): if obj is None: return self value = obj.headers.get(self.name, self.default) return self.reader(value) if self.reader else value def __set__(self, obj, value): obj.headers[self.name] = self.writer(value) def __delete__(self, obj): del obj.headers[self.name] class BaseResponse(object): """ Storage class for a response body as well as headers and cookies. This class does support dict-like case-insensitive item-access to headers, but is NOT a dict. Most notably, iterating over a response yields parts of the body and not the headers. """ default_status = 200 default_content_type = 'text/html; charset=UTF-8' # Header blacklist for specific response codes # (rfc2616 section 10.2.3 and 10.3.5) bad_headers = { 204: set(('Content-Type',)), 304: set(('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Range', 'Content-Type', 'Content-Md5', 'Last-Modified'))} def __init__(self, body='', status=None, **headers): self._cookies = None self._headers = {} self.body = body self.status = status or self.default_status if headers: for name, value in headers.items(): self[name] = value def copy(self): ''' Returns a copy of self. ''' copy = Response() copy.status = self.status copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) return copy def __iter__(self): return iter(self.body) def close(self): if hasattr(self.body, 'close'): self.body.close() @property def status_line(self): ''' The HTTP status line as a string (e.g. ``404 Not Found``).''' return self._status_line @property def status_code(self): ''' The HTTP status code as an integer (e.g. 404).''' return self._status_code def _set_status(self, status): if isinstance(status, int): code, status = status, _HTTP_STATUS_LINES.get(status) elif ' ' in status: status = status.strip() code = int(status.split()[0]) else: raise ValueError('String status line without a reason phrase.') if not 100 <= code <= 999: raise ValueError('Status code out of range.') self._status_code = code self._status_line = str(status or ('%d Unknown' % code)) def _get_status(self): return self._status_line status = property(_get_status, _set_status, None, ''' A writeable property to change the HTTP response status. It accepts either a numeric code (100-999) or a string with a custom reason phrase (e.g. "404 Brain not found"). Both :data:`status_line` and :data:`status_code` are updated accordingly. The return value is always a status string. ''') del _get_status, _set_status @property def headers(self): ''' An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers. ''' hdict = HeaderDict() hdict.dict = self._headers return hdict def __contains__(self, name): return _hkey(name) in self._headers def __delitem__(self, name): del self._headers[_hkey(name)] def __getitem__(self, name): return self._headers[_hkey(name)][-1] def __setitem__(self, name, value): self._headers[_hkey(name)] = [str(value)] def get_header(self, name, default=None): ''' Return the value of a previously defined header. If there is no header with that name, return a default value. ''' return self._headers.get(_hkey(name), [default])[-1] def set_header(self, name, value): ''' Create a new response header, replacing any previously defined headers with the same name. ''' self._headers[_hkey(name)] = [str(value)] def add_header(self, name, value): ''' Add an additional response header, not removing duplicates. ''' self._headers.setdefault(_hkey(name), []).append(str(value)) def iter_headers(self): ''' Yield (header, value) tuples, skipping headers that are not allowed with the current response status code. ''' return self.headerlist def wsgiheader(self): depr('The wsgiheader method is deprecated. See headerlist.') #0.10 return self.headerlist @property def headerlist(self): ''' WSGI conform list of (header, value) tuples. ''' out = [] headers = list(self._headers.items()) if 'Content-Type' not in self._headers: headers.append(('Content-Type', [self.default_content_type])) if self._status_code in self.bad_headers: bad_headers = self.bad_headers[self._status_code] headers = [h for h in headers if h[0] not in bad_headers] out += [(name, val) for name, vals in headers for val in vals] if self._cookies: for c in self._cookies.values(): out.append(('Set-Cookie', c.OutputString())) return out content_type = HeaderProperty('Content-Type') content_length = HeaderProperty('Content-Length', reader=int) @property def charset(self): """ Return the charset specified in the content-type header (default: utf8). """ if 'charset=' in self.content_type: return self.content_type.split('charset=')[-1].split(';')[0].strip() return 'UTF-8' @property def COOKIES(self): """ A dict-like SimpleCookie instance. This should not be used directly. See :meth:`set_cookie`. """ depr('The COOKIES dict is deprecated. Use `set_cookie()` instead.') # 0.10 if not self._cookies: self._cookies = SimpleCookie() return self._cookies def set_cookie(self, name, value, secret=None, **options): ''' Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signature key required for signed cookies. Additionally, this method accepts all RFC 2109 attributes that are supported by :class:`cookie.Morsel`, including: :param max_age: maximum age in seconds. (default: None) :param expires: a datetime object or UNIX timestamp. (default: None) :param domain: the domain that is allowed to read the cookie. (default: current domain) :param path: limits the cookie to a given path (default: current path) :param secure: limit the cookie to HTTPS connections (default: off). :param httponly: prevents client-side javascript to read this cookie (default: off, requires Python 2.6 or newer). If neither `expires` nor `max_age` is set (default), the cookie will expire at the end of the browser session (as soon as the browser window is closed). Signed cookies may store any pickle-able object and are cryptographically signed to prevent manipulation. Keep in mind that cookies are limited to 4kb in most browsers. Warning: Signed cookies are not encrypted (the client can still see the content) and not copy-protected (the client can restore an old cookie). The main intention is to make pickling and unpickling save, not to store secret information at client side. ''' if not self._cookies: self._cookies = SimpleCookie() if secret: value = touni(cookie_encode((name, value), secret)) elif not isinstance(value, basestring): raise TypeError('Secret key missing for non-string Cookie.') if len(value) > 4096: raise ValueError('Cookie value to long.') self._cookies[name] = value for key, value in options.items(): if key == 'max_age': if isinstance(value, timedelta): value = value.seconds + value.days * 24 * 3600 if key == 'expires': if isinstance(value, (datedate, datetime)): value = value.timetuple() elif isinstance(value, (int, float)): value = time.gmtime(value) value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value) self._cookies[name][key.replace('_', '-')] = value def delete_cookie(self, key, **kwargs): ''' Delete a cookie. Be sure to use the same `domain` and `path` settings as used to create the cookie. ''' kwargs['max_age'] = -1 kwargs['expires'] = 0 self.set_cookie(key, '', **kwargs) def __repr__(self): out = '' for name, value in self.headerlist: out += '%s: %s\n' % (name.title(), value.strip()) return out #: Thread-local storage for :class:`LocalRequest` and :class:`LocalResponse` #: attributes. _lctx = threading.local() def local_property(name): def fget(self): try: return getattr(_lctx, name) except AttributeError: raise RuntimeError("Request context not initialized.") def fset(self, value): setattr(_lctx, name, value) def fdel(self): delattr(_lctx, name) return property(fget, fset, fdel, 'Thread-local property stored in :data:`_lctx.%s`' % name) class LocalRequest(BaseRequest): ''' A thread-local subclass of :class:`BaseRequest` with a different set of attribues for each thread. There is usually only one global instance of this class (:data:`request`). If accessed during a request/response cycle, this instance always refers to the *current* request (even on a multithreaded server). ''' bind = BaseRequest.__init__ environ = local_property('request_environ') class LocalResponse(BaseResponse): ''' A thread-local subclass of :class:`BaseResponse` with a different set of attribues for each thread. There is usually only one global instance of this class (:data:`response`). Its attributes are used to build the HTTP response at the end of the request/response cycle. ''' bind = BaseResponse.__init__ _status_line = local_property('response_status_line') _status_code = local_property('response_status_code') _cookies = local_property('response_cookies') _headers = local_property('response_headers') body = local_property('response_body') Request = BaseRequest Response = BaseResponse class HTTPResponse(Response, BottleException): def __init__(self, body='', status=None, header=None, **headers): if header or 'output' in headers: depr('Call signature changed (for the better)') if header: headers.update(header) if 'output' in headers: body = headers.pop('output') super(HTTPResponse, self).__init__(body, status, **headers) def apply(self, response): response._status_code = self._status_code response._status_line = self._status_line response._headers = self._headers response._cookies = self._cookies response.body = self.body def _output(self, value=None): depr('Use HTTPResponse.body instead of HTTPResponse.output') if value is None: return self.body self.body = value output = property(_output, _output, doc='Alias for .body') class HTTPError(HTTPResponse): default_status = 500 def __init__(self, status=None, body=None, exception=None, traceback=None, header=None, **headers): self.exception = exception self.traceback = traceback super(HTTPError, self).__init__(body, status, header, **headers) ############################################################################### # Plugins ###################################################################### ############################################################################### class PluginError(BottleException): pass class JSONPlugin(object): name = 'json' api = 2 def __init__(self, json_dumps=json_dumps): self.json_dumps = json_dumps def apply(self, callback, route): dumps = self.json_dumps if not dumps: return callback def wrapper(*a, **ka): rv = callback(*a, **ka) if isinstance(rv, dict): #Attempt to serialize, raises exception on failure json_response = dumps(rv) #Set content type only if serialization succesful response.content_type = 'application/json' return json_response return rv return wrapper class HooksPlugin(object): name = 'hooks' api = 2 _names = 'before_request', 'after_request', 'app_reset' def __init__(self): self.hooks = dict((name, []) for name in self._names) self.app = None def _empty(self): return not (self.hooks['before_request'] or self.hooks['after_request']) def setup(self, app): self.app = app def add(self, name, func): ''' Attach a callback to a hook. ''' was_empty = self._empty() self.hooks.setdefault(name, []).append(func) if self.app and was_empty and not self._empty(): self.app.reset() def remove(self, name, func): ''' Remove a callback from a hook. ''' was_empty = self._empty() if name in self.hooks and func in self.hooks[name]: self.hooks[name].remove(func) if self.app and not was_empty and self._empty(): self.app.reset() def trigger(self, name, *a, **ka): ''' Trigger a hook and return a list of results. ''' hooks = self.hooks[name] if ka.pop('reversed', False): hooks = hooks[::-1] return [hook(*a, **ka) for hook in hooks] def apply(self, callback, route): if self._empty(): return callback def wrapper(*a, **ka): self.trigger('before_request') rv = callback(*a, **ka) self.trigger('after_request', reversed=True) return rv return wrapper class TemplatePlugin(object): ''' This plugin applies the :func:`view` decorator to all routes with a `template` config parameter. If the parameter is a tuple, the second element must be a dict with additional options (e.g. `template_engine`) or default variables for the template. ''' name = 'template' api = 2 def apply(self, callback, route): conf = route.config.get('template') if isinstance(conf, (tuple, list)) and len(conf) == 2: return view(conf[0], **conf[1])(callback) elif isinstance(conf, str) and 'template_opts' in route.config: depr('The `template_opts` parameter is deprecated.') #0.9 return view(conf, **route.config['template_opts'])(callback) elif isinstance(conf, str): return view(conf)(callback) else: return callback #: Not a plugin, but part of the plugin API. TODO: Find a better place. class _ImportRedirect(object): def __init__(self, name, impmask): ''' Create a virtual package that redirects imports (see PEP 302). ''' self.name = name self.impmask = impmask self.module = sys.modules.setdefault(name, imp.new_module(name)) self.module.__dict__.update({'__file__': __file__, '__path__': [], '__all__': [], '__loader__': self}) sys.meta_path.append(self) def find_module(self, fullname, path=None): if '.' not in fullname: return packname, modname = fullname.rsplit('.', 1) if packname != self.name: return return self def load_module(self, fullname): if fullname in sys.modules: return sys.modules[fullname] packname, modname = fullname.rsplit('.', 1) realname = self.impmask % modname __import__(realname) module = sys.modules[fullname] = sys.modules[realname] setattr(self.module, modname, module) module.__loader__ = self return module ############################################################################### # Common Utilities ############################################################# ############################################################################### class MultiDict(DictMixin): """ This dict stores multiple values per key, but behaves exactly like a normal dict in that it returns only the newest value for any given key. There are special methods available to access the full list of values. """ def __init__(self, *a, **k): self.dict = dict((k, [v]) for (k, v) in dict(*a, **k).items()) def __len__(self): return len(self.dict) def __iter__(self): return iter(self.dict) def __contains__(self, key): return key in self.dict def __delitem__(self, key): del self.dict[key] def __getitem__(self, key): return self.dict[key][-1] def __setitem__(self, key, value): self.append(key, value) def keys(self): return self.dict.keys() if py3k: def values(self): return (v[-1] for v in self.dict.values()) def items(self): return ((k, v[-1]) for k, v in self.dict.items()) def allitems(self): return ((k, v) for k, vl in self.dict.items() for v in vl) iterkeys = keys itervalues = values iteritems = items iterallitems = allitems else: def values(self): return [v[-1] for v in self.dict.values()] def items(self): return [(k, v[-1]) for k, v in self.dict.items()] def iterkeys(self): return self.dict.iterkeys() def itervalues(self): return (v[-1] for v in self.dict.itervalues()) def iteritems(self): return ((k, v[-1]) for k, v in self.dict.iteritems()) def iterallitems(self): return ((k, v) for k, vl in self.dict.iteritems() for v in vl) def allitems(self): return [(k, v) for k, vl in self.dict.iteritems() for v in vl] def get(self, key, default=None, index=-1, type=None): ''' Return the most recent value for a key. :param default: The default value to be returned if the key is not present or the type conversion fails. :param index: An index for the list of available values. :param type: If defined, this callable is used to cast the value into a specific type. Exception are suppressed and result in the default value to be returned. ''' try: val = self.dict[key][index] return type(val) if type else val except Exception: pass return default def append(self, key, value): ''' Add a new value to the list of values for this key. ''' self.dict.setdefault(key, []).append(value) def replace(self, key, value): ''' Replace the list of values with a single value. ''' self.dict[key] = [value] def getall(self, key): ''' Return a (possibly empty) list of values for a key. ''' return self.dict.get(key) or [] #: Aliases for WTForms to mimic other multi-dict APIs (Django) getone = get getlist = getall class FormsDict(MultiDict): ''' This :class:`MultiDict` subclass is used to store request form data. Additionally to the normal dict-like item access methods (which return unmodified data as native strings), this container also supports attribute-like access to its values. Attributes are automatically de- or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing attributes default to an empty string. ''' #: Encoding used for attribute values. input_encoding = 'utf8' #: If true (default), unicode strings are first encoded with `latin1` #: and then decoded to match :attr:`input_encoding`. recode_unicode = True def _fix(self, s, encoding=None): if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI s = s.encode('latin1') if isinstance(s, bytes): # Python 2 WSGI return s.decode(encoding or self.input_encoding) return s def decode(self, encoding=None): ''' Returns a copy with all keys and values de- or recoded to match :attr:`input_encoding`. Some libraries (e.g. WTForms) want a unicode dictionary. ''' copy = FormsDict() enc = copy.input_encoding = encoding or self.input_encoding copy.recode_unicode = False for key, value in self.allitems(): copy.append(self._fix(key, enc), self._fix(value, enc)) return copy def getunicode(self, name, default=None, encoding=None): try: return self._fix(self[name], encoding) except (UnicodeError, KeyError): return default def __getattr__(self, name, default=unicode()): # Without this guard, pickle generates a cryptic TypeError: if name.startswith('__') and name.endswith('__'): return super(FormsDict, self).__getattr__(name) return self.getunicode(name, default=default) class HeaderDict(MultiDict): """ A case-insensitive version of :class:`MultiDict` that defaults to replace the old value instead of appending it. """ def __init__(self, *a, **ka): self.dict = {} if a or ka: self.update(*a, **ka) def __contains__(self, key): return _hkey(key) in self.dict def __delitem__(self, key): del self.dict[_hkey(key)] def __getitem__(self, key): return self.dict[_hkey(key)][-1] def __setitem__(self, key, value): self.dict[_hkey(key)] = [str(value)] def append(self, key, value): self.dict.setdefault(_hkey(key), []).append(str(value)) def replace(self, key, value): self.dict[_hkey(key)] = [str(value)] def getall(self, key): return self.dict.get(_hkey(key)) or [] def get(self, key, default=None, index=-1): return MultiDict.get(self, _hkey(key), default, index) def filter(self, names): for name in [_hkey(n) for n in names]: if name in self.dict: del self.dict[name] class WSGIHeaderDict(DictMixin): ''' This dict-like class wraps a WSGI environ dict and provides convenient access to HTTP_* fields. Keys and values are native strings (2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI environment contains non-native string values, these are de- or encoded using a lossless 'latin1' character set. The API will remain stable even on changes to the relevant PEPs. Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one that uses non-native strings.) ''' #: List of keys that do not have a ``HTTP_`` prefix. cgikeys = ('CONTENT_TYPE', 'CONTENT_LENGTH') def __init__(self, environ): self.environ = environ def _ekey(self, key): ''' Translate header field name to CGI/WSGI environ key. ''' key = key.replace('-','_').upper() if key in self.cgikeys: return key return 'HTTP_' + key def raw(self, key, default=None): ''' Return the header value as is (may be bytes or unicode). ''' return self.environ.get(self._ekey(key), default) def __getitem__(self, key): return tonat(self.environ[self._ekey(key)], 'latin1') def __setitem__(self, key, value): raise TypeError("%s is read-only." % self.__class__) def __delitem__(self, key): raise TypeError("%s is read-only." % self.__class__) def __iter__(self): for key in self.environ: if key[:5] == 'HTTP_': yield key[5:].replace('_', '-').title() elif key in self.cgikeys: yield key.replace('_', '-').title() def keys(self): return [x for x in self] def __len__(self): return len(self.keys()) def __contains__(self, key): return self._ekey(key) in self.environ class ConfigDict(dict): ''' A dict-subclass with some extras: You can access keys like attributes. Uppercase attributes create new ConfigDicts and act as name-spaces. Other missing attributes return None. Calling a ConfigDict updates its values and returns itself. >>> cfg = ConfigDict() >>> cfg.Namespace.value = 5 >>> cfg.OtherNamespace(a=1, b=2) >>> cfg {'Namespace': {'value': 5}, 'OtherNamespace': {'a': 1, 'b': 2}} ''' def __getattr__(self, key): if key not in self and key[0].isupper(): self[key] = ConfigDict() return self.get(key) def __setattr__(self, key, value): if hasattr(dict, key): raise AttributeError('Read-only attribute.') if key in self and self[key] and isinstance(self[key], ConfigDict): raise AttributeError('Non-empty namespace attribute.') self[key] = value def __delattr__(self, key): if key in self: del self[key] def __call__(self, *a, **ka): for key, value in dict(*a, **ka).items(): setattr(self, key, value) return self class AppStack(list): """ A stack-like list. Calling it returns the head of the stack. """ def __call__(self): """ Return the current default application. """ return self[-1] def push(self, value=None): """ Add a new :class:`Bottle` instance to the stack """ if not isinstance(value, Bottle): value = Bottle() self.append(value) return value class WSGIFileWrapper(object): def __init__(self, fp, buffer_size=1024*64): self.fp, self.buffer_size = fp, buffer_size for attr in ('fileno', 'close', 'read', 'readlines', 'tell', 'seek'): if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr)) def __iter__(self): buff, read = self.buffer_size, self.read while True: part = read(buff) if not part: return yield part class ResourceManager(object): ''' This class manages a list of search paths and helps to find and open application-bound resources (files). :param base: default value for :meth:`add_path` calls. :param opener: callable used to open resources. :param cachemode: controls which lookups are cached. One of 'all', 'found' or 'none'. ''' def __init__(self, base='./', opener=open, cachemode='all'): self.opener = open self.base = base self.cachemode = cachemode #: A list of search paths. See :meth:`add_path` for details. self.path = [] #: A cache for resolved paths. ``res.cache.clear()`` clears the cache. self.cache = {} def add_path(self, path, base=None, index=None, create=False): ''' Add a new path to the list of search paths. Return False if the path does not exist. :param path: The new search path. Relative paths are turned into an absolute and normalized form. If the path looks like a file (not ending in `/`), the filename is stripped off. :param base: Path used to absolutize relative search paths. Defaults to :attr:`base` which defaults to ``os.getcwd()``. :param index: Position within the list of search paths. Defaults to last index (appends to the list). The `base` parameter makes it easy to reference files installed along with a python module or package:: res.add_path('./resources/', __file__) ''' base = os.path.abspath(os.path.dirname(base or self.base)) path = os.path.abspath(os.path.join(base, os.path.dirname(path))) path += os.sep if path in self.path: self.path.remove(path) if create and not os.path.isdir(path): os.makedirs(path) if index is None: self.path.append(path) else: self.path.insert(index, path) self.cache.clear() return os.path.exists(path) def __iter__(self): ''' Iterate over all existing files in all registered paths. ''' search = self.path[:] while search: path = search.pop() if not os.path.isdir(path): continue for name in os.listdir(path): full = os.path.join(path, name) if os.path.isdir(full): search.append(full) else: yield full def lookup(self, name): ''' Search for a resource and return an absolute file path, or `None`. The :attr:`path` list is searched in order. The first match is returend. Symlinks are followed. The result is cached to speed up future lookups. ''' if name not in self.cache or DEBUG: for path in self.path: fpath = os.path.join(path, name) if os.path.isfile(fpath): if self.cachemode in ('all', 'found'): self.cache[name] = fpath return fpath if self.cachemode == 'all': self.cache[name] = None return self.cache[name] def open(self, name, mode='r', *args, **kwargs): ''' Find a resource and return a file object, or raise IOError. ''' fname = self.lookup(name) if not fname: raise IOError("Resource %r not found." % name) return self.opener(name, mode=mode, *args, **kwargs) ############################################################################### # Application Helper ########################################################### ############################################################################### def abort(code=500, text='Unknown Error: Application stopped.'): """ Aborts execution and causes a HTTP error. """ raise HTTPError(code, text) def redirect(url, code=None): """ Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version. """ if code is None: code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302 location = urljoin(request.url, url) res = HTTPResponse("", status=code, Location=location) if response._cookies: res._cookies = response._cookies raise res def _file_iter_range(fp, offset, bytes, maxread=1024*1024): ''' Yield chunks from a range in a file. No chunk is bigger than maxread.''' fp.seek(offset) while bytes > 0: part = fp.read(min(bytes, maxread)) if not part: break bytes -= len(part) yield part def static_file(filename, root, mimetype='auto', download=False): """ Open a file in a safe way and return :exc:`HTTPResponse` with status code 200, 305, 401 or 404. Set Content-Type, Content-Encoding, Content-Length and Last-Modified header. Obey If-Modified-Since header and HEAD requests. """ root = os.path.abspath(root) + os.sep filename = os.path.abspath(os.path.join(root, filename.strip('/\\'))) headers = dict() if not filename.startswith(root): return HTTPError(403, "Access denied.") if not os.path.exists(filename) or not os.path.isfile(filename): return HTTPError(404, "File does not exist.") if not os.access(filename, os.R_OK): return HTTPError(403, "You do not have permission to access this file.") if mimetype == 'auto': mimetype, encoding = mimetypes.guess_type(filename) if mimetype: headers['Content-Type'] = mimetype if encoding: headers['Content-Encoding'] = encoding elif mimetype: headers['Content-Type'] = mimetype if download: download = os.path.basename(filename if download == True else download) headers['Content-Disposition'] = 'attachment; filename="%s"' % download stats = os.stat(filename) headers['Content-Length'] = clen = stats.st_size lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime)) headers['Last-Modified'] = lm ims = request.environ.get('HTTP_IF_MODIFIED_SINCE') if ims: ims = parse_date(ims.split(";")[0].strip()) if ims is not None and ims >= int(stats.st_mtime): headers['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()) return HTTPResponse(status=304, **headers) body = '' if request.method == 'HEAD' else open(filename, 'rb') headers["Accept-Ranges"] = "bytes" ranges = request.environ.get('HTTP_RANGE') if 'HTTP_RANGE' in request.environ: ranges = list(parse_range_header(request.environ['HTTP_RANGE'], clen)) if not ranges: return HTTPError(416, "Requested Range Not Satisfiable") offset, end = ranges[0] headers["Content-Range"] = "bytes %d-%d/%d" % (offset, end-1, clen) headers["Content-Length"] = str(end-offset) if body: body = _file_iter_range(body, offset, end-offset) return HTTPResponse(body, status=206, **headers) return HTTPResponse(body, **headers) ############################################################################### # HTTP Utilities and MISC (TODO) ############################################### ############################################################################### def debug(mode=True): """ Change the debug level. There is only one debug level supported at the moment.""" global DEBUG DEBUG = bool(mode) def parse_date(ims): """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """ try: ts = email.utils.parsedate_tz(ims) return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone except (TypeError, ValueError, IndexError, OverflowError): return None def parse_auth(header): """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None""" try: method, data = header.split(None, 1) if method.lower() == 'basic': user, pwd = touni(base64.b64decode(tob(data))).split(':',1) return user, pwd except (KeyError, ValueError): return None def parse_range_header(header, maxlen=0): ''' Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.''' if not header or header[:6] != 'bytes=': return ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r] for start, end in ranges: try: if not start: # bytes=-100 -> last 100 bytes start, end = max(0, maxlen-int(end)), maxlen elif not end: # bytes=100- -> all but the first 99 bytes start, end = int(start), maxlen else: # bytes=100-200 -> bytes 100-200 (inclusive) start, end = int(start), min(int(end)+1, maxlen) if 0 <= start < end <= maxlen: yield start, end except ValueError: pass def _parse_qsl(qs): r = [] for pair in qs.replace(';','&').split('&'): if not pair: continue nv = pair.split('=', 1) if len(nv) != 2: nv.append('') key = urlunquote(nv[0].replace('+', ' ')) value = urlunquote(nv[1].replace('+', ' ')) r.append((key, value)) return r def _lscmp(a, b): ''' Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix. ''' return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b) def cookie_encode(data, key): ''' Encode and sign a pickle-able object. Return a (byte) string ''' msg = base64.b64encode(pickle.dumps(data, -1)) sig = base64.b64encode(hmac.new(tob(key), msg).digest()) return tob('!') + sig + tob('?') + msg def cookie_decode(data, key): ''' Verify and decode an encoded string. Return an object or None.''' data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg).digest())): return pickle.loads(base64.b64decode(msg)) return None def cookie_is_encoded(data): ''' Return True if the argument looks like a encoded cookie.''' return bool(data.startswith(tob('!')) and tob('?') in data) def html_escape(string): ''' Escape HTML special characters ``&<>`` and quotes ``'"``. ''' return string.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')\ .replace('"','&quot;').replace("'",'&#039;') def html_quote(string): ''' Escape and quote a string to be used as an HTTP attribute.''' return '"%s"' % html_escape(string).replace('\n','%#10;')\ .replace('\r','&#13;').replace('\t','&#9;') def yieldroutes(func): """ Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example:: a() -> '/a' b(x, y) -> '/b/:x/:y' c(x, y=5) -> '/c/:x' and '/c/:x/:y' d(x=5, y=6) -> '/d' and '/d/:x' and '/d/:x/:y' """ import inspect # Expensive module. Only import if necessary. path = '/' + func.__name__.replace('__','/').lstrip('/') spec = inspect.getargspec(func) argc = len(spec[0]) - len(spec[3] or []) path += ('/:%s' * argc) % tuple(spec[0][:argc]) yield path for arg in spec[0][argc:]: path += '/:%s' % arg yield path def path_shift(script_name, path_info, shift=1): ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1) ''' if shift == 0: return script_name, path_info pathlist = path_info.strip('/').split('/') scriptlist = script_name.strip('/').split('/') if pathlist and pathlist[0] == '': pathlist = [] if scriptlist and scriptlist[0] == '': scriptlist = [] if shift > 0 and shift <= len(pathlist): moved = pathlist[:shift] scriptlist = scriptlist + moved pathlist = pathlist[shift:] elif shift < 0 and shift >= -len(scriptlist): moved = scriptlist[shift:] pathlist = moved + pathlist scriptlist = scriptlist[:shift] else: empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO' raise AssertionError("Cannot shift. Nothing left from %s" % empty) new_script_name = '/' + '/'.join(scriptlist) new_path_info = '/' + '/'.join(pathlist) if path_info.endswith('/') and pathlist: new_path_info += '/' return new_script_name, new_path_info def validate(**vkargs): """ Validates and manipulates keyword arguments by user defined callables. Handles ValueError and missing arguments by raising HTTPError(403). """ depr('Use route wildcard filters instead.') def decorator(func): @functools.wraps(func) def wrapper(*args, **kargs): for key, value in vkargs.items(): if key not in kargs: abort(403, 'Missing parameter: %s' % key) try: kargs[key] = value(kargs[key]) except ValueError: abort(403, 'Wrong parameter format for: %s' % key) return func(*args, **kargs) return wrapper return decorator def auth_basic(check, realm="private", text="Access denied"): ''' Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter. ''' def decorator(func): def wrapper(*a, **ka): user, password = request.auth or (None, None) if user is None or not check(user, password): response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm return HTTPError(401, text) return func(*a, **ka) return wrapper return decorator # Shortcuts for common Bottle methods. # They all refer to the current default application. def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper route = make_default_app_wrapper('route') get = make_default_app_wrapper('get') post = make_default_app_wrapper('post') put = make_default_app_wrapper('put') delete = make_default_app_wrapper('delete') error = make_default_app_wrapper('error') mount = make_default_app_wrapper('mount') hook = make_default_app_wrapper('hook') install = make_default_app_wrapper('install') uninstall = make_default_app_wrapper('uninstall') url = make_default_app_wrapper('get_url') ############################################################################### # Server Adapter ############################################################### ############################################################################### class ServerAdapter(object): quiet = False def __init__(self, host='127.0.0.1', port=8080, **config): self.options = config self.host = host self.port = int(port) def run(self, handler): # pragma: no cover pass def __repr__(self): args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.options.items()]) return "%s(%s)" % (self.__class__.__name__, args) class CGIServer(ServerAdapter): quiet = True def run(self, handler): # pragma: no cover from wsgiref.handlers import CGIHandler def fixed_environ(environ, start_response): environ.setdefault('PATH_INFO', '') return handler(environ, start_response) CGIHandler().run(fixed_environ) class FlupFCGIServer(ServerAdapter): def run(self, handler): # pragma: no cover import flup.server.fcgi self.options.setdefault('bindAddress', (self.host, self.port)) flup.server.fcgi.WSGIServer(handler, **self.options).run() class WSGIRefServer(ServerAdapter): def run(self, handler): # pragma: no cover from wsgiref.simple_server import make_server, WSGIRequestHandler if self.quiet: class QuietHandler(WSGIRequestHandler): def log_request(*args, **kw): pass self.options['handler_class'] = QuietHandler srv = make_server(self.host, self.port, handler, **self.options) srv.serve_forever() class CherryPyServer(ServerAdapter): def run(self, handler): # pragma: no cover from cherrypy import wsgiserver server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler) try: server.start() finally: server.stop() class WaitressServer(ServerAdapter): def run(self, handler): from waitress import serve serve(handler, host=self.host, port=self.port) class PasteServer(ServerAdapter): def run(self, handler): # pragma: no cover from paste import httpserver if not self.quiet: from paste.translogger import TransLogger handler = TransLogger(handler) httpserver.serve(handler, host=self.host, port=str(self.port), **self.options) class MeinheldServer(ServerAdapter): def run(self, handler): from meinheld import server server.listen((self.host, self.port)) server.run(handler) class FapwsServer(ServerAdapter): """ Extremely fast webserver using libev. See http://www.fapws.org/ """ def run(self, handler): # pragma: no cover import fapws._evwsgi as evwsgi from fapws import base, config port = self.port if float(config.SERVER_IDENT[-2:]) > 0.4: # fapws3 silently changed its API in 0.5 port = str(port) evwsgi.start(self.host, port) # fapws3 never releases the GIL. Complain upstream. I tried. No luck. if 'BOTTLE_CHILD' in os.environ and not self.quiet: _stderr("WARNING: Auto-reloading does not work with Fapws3.\n") _stderr(" (Fapws3 breaks python thread support)\n") evwsgi.set_base_module(base) def app(environ, start_response): environ['wsgi.multiprocess'] = False return handler(environ, start_response) evwsgi.wsgi_cb(('', app)) evwsgi.run() class TornadoServer(ServerAdapter): """ The super hyped asynchronous server by facebook. Untested. """ def run(self, handler): # pragma: no cover import tornado.wsgi, tornado.httpserver, tornado.ioloop container = tornado.wsgi.WSGIContainer(handler) server = tornado.httpserver.HTTPServer(container) server.listen(port=self.port) tornado.ioloop.IOLoop.instance().start() class AppEngineServer(ServerAdapter): """ Adapter for Google App Engine. """ quiet = True def run(self, handler): from google.appengine.ext.webapp import util # A main() function in the handler script enables 'App Caching'. # Lets makes sure it is there. This _really_ improves performance. module = sys.modules.get('__main__') if module and not hasattr(module, 'main'): module.main = lambda: util.run_wsgi_app(handler) util.run_wsgi_app(handler) class TwistedServer(ServerAdapter): """ Untested. """ def run(self, handler): from twisted.web import server, wsgi from twisted.python.threadpool import ThreadPool from twisted.internet import reactor thread_pool = ThreadPool() thread_pool.start() reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler)) reactor.listenTCP(self.port, factory, interface=self.host) reactor.run() class DieselServer(ServerAdapter): """ Untested. """ def run(self, handler): from diesel.protocols.wsgi import WSGIApplication app = WSGIApplication(handler, port=self.port) app.run() class GeventServer(ServerAdapter): """ Untested. Options: * `fast` (default: False) uses libevent's http server, but has some issues: No streaming, no pipelining, no SSL. """ def run(self, handler): from gevent import wsgi, pywsgi, local if not isinstance(_lctx, local.local): msg = "Bottle requires gevent.monkey.patch_all() (before import)" raise RuntimeError(msg) if not self.options.get('fast'): wsgi = pywsgi log = None if self.quiet else 'default' wsgi.WSGIServer((self.host, self.port), handler, log=log).serve_forever() class GunicornServer(ServerAdapter): """ Untested. See http://gunicorn.org/configure.html for options. """ def run(self, handler): from gunicorn.app.base import Application config = {'bind': "%s:%d" % (self.host, int(self.port))} config.update(self.options) class GunicornApplication(Application): def init(self, parser, opts, args): return config def load(self): return handler GunicornApplication().run() class EventletServer(ServerAdapter): """ Untested """ def run(self, handler): from eventlet import wsgi, listen try: wsgi.server(listen((self.host, self.port)), handler, log_output=(not self.quiet)) except TypeError: # Fallback, if we have old version of eventlet wsgi.server(listen((self.host, self.port)), handler) class RocketServer(ServerAdapter): """ Untested. """ def run(self, handler): from rocket import Rocket server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler }) server.start() class BjoernServer(ServerAdapter): """ Fast server written in C: https://github.com/jonashaag/bjoern """ def run(self, handler): from bjoern import run run(handler, self.host, self.port) class AutoServer(ServerAdapter): """ Untested. """ adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer, WSGIRefServer] def run(self, handler): for sa in self.adapters: try: return sa(self.host, self.port, **self.options).run(handler) except ImportError: pass server_names = { 'cgi': CGIServer, 'flup': FlupFCGIServer, 'wsgiref': WSGIRefServer, 'waitress': WaitressServer, 'cherrypy': CherryPyServer, 'paste': PasteServer, 'fapws3': FapwsServer, 'tornado': TornadoServer, 'gae': AppEngineServer, 'twisted': TwistedServer, 'diesel': DieselServer, 'meinheld': MeinheldServer, 'gunicorn': GunicornServer, 'eventlet': EventletServer, 'gevent': GeventServer, 'rocket': RocketServer, 'bjoern' : BjoernServer, 'auto': AutoServer, } ############################################################################### # Application Control ########################################################## ############################################################################### def load(target, **namespace): """ Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. The last form accepts not only function calls, but any type of expression. Keyword arguments passed to this function are available as local variables. Example: ``import_string('re:compile(x)', x='[a-z]')`` """ module, target = target.split(":", 1) if ':' in target else (target, None) if module not in sys.modules: __import__(module) if not target: return sys.modules[module] if target.isalnum(): return getattr(sys.modules[module], target) package_name = module.split('.')[0] namespace[package_name] = sys.modules[package_name] return eval('%s.%s' % (module, target), namespace) def load_app(target): """ Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter. """ global NORUN; NORUN, nr_old = True, NORUN try: tmp = default_app.push() # Create a new "default application" rv = load(target) # Import the target module return rv if callable(rv) else tmp finally: default_app.remove(tmp) # Remove the temporary added default application NORUN = nr_old _debug = debug def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=False, **kargs): """ Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`) :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1) :param port: Server port to bind to. Values below 1024 require root privileges. (default: 8080) :param reloader: Start auto-reloading server? (default: False) :param interval: Auto-reloader interval in seconds (default: 1) :param quiet: Suppress output to stdout and stderr? (default: False) :param options: Options passed to the server adapter. """ if NORUN: return if reloader and not os.environ.get('BOTTLE_CHILD'): try: lockfile = None fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock') os.close(fd) # We only need this file to exist. We never write to it while os.path.exists(lockfile): args = [sys.executable] + sys.argv environ = os.environ.copy() environ['BOTTLE_CHILD'] = 'true' environ['BOTTLE_LOCKFILE'] = lockfile p = subprocess.Popen(args, env=environ) while p.poll() is None: # Busy wait... os.utime(lockfile, None) # I am alive! time.sleep(interval) if p.poll() != 3: if os.path.exists(lockfile): os.unlink(lockfile) sys.exit(p.poll()) except KeyboardInterrupt: pass finally: if os.path.exists(lockfile): os.unlink(lockfile) return try: _debug(debug) app = app or default_app() if isinstance(app, basestring): app = load_app(app) if not callable(app): raise ValueError("Application is not callable: %r" % app) for plugin in plugins or []: app.install(plugin) if server in server_names: server = server_names.get(server) if isinstance(server, basestring): server = load(server) if isinstance(server, type): server = server(host=host, port=port, **kargs) if not isinstance(server, ServerAdapter): raise ValueError("Unknown or unsupported server: %r" % server) server.quiet = server.quiet or quiet if not server.quiet: _stderr("Bottle v%s server starting up (using %s)...\n" % (__version__, repr(server))) _stderr("Listening on http://%s:%d/\n" % (server.host, server.port)) _stderr("Hit Ctrl-C to quit.\n\n") if reloader: lockfile = os.environ.get('BOTTLE_LOCKFILE') bgcheck = FileCheckerThread(lockfile, interval) with bgcheck: server.run(app) if bgcheck.status == 'reload': sys.exit(3) else: server.run(app) except KeyboardInterrupt: pass except (SystemExit, MemoryError): raise except: if not reloader: raise if not getattr(server, 'quiet', quiet): print_exc() time.sleep(interval) sys.exit(3) class FileCheckerThread(threading.Thread): ''' Interrupt main-thread as soon as a changed module file is detected, the lockfile gets deleted or gets to old. ''' def __init__(self, lockfile, interval): threading.Thread.__init__(self) self.lockfile, self.interval = lockfile, interval #: Is one of 'reload', 'error' or 'exit' self.status = None def run(self): exists = os.path.exists mtime = lambda path: os.stat(path).st_mtime files = dict() for module in list(sys.modules.values()): path = getattr(module, '__file__', '') if path[-4:] in ('.pyo', '.pyc'): path = path[:-1] if path and exists(path): files[path] = mtime(path) while not self.status: if not exists(self.lockfile)\ or mtime(self.lockfile) < time.time() - self.interval - 5: self.status = 'error' thread.interrupt_main() for path, lmtime in list(files.items()): if not exists(path) or mtime(path) > lmtime: self.status = 'reload' thread.interrupt_main() break time.sleep(self.interval) def __enter__(self): self.start() def __exit__(self, exc_type, exc_val, exc_tb): if not self.status: self.status = 'exit' # silent exit self.join() return exc_type is not None and issubclass(exc_type, KeyboardInterrupt) ############################################################################### # Template Adapters ############################################################ ############################################################################### class TemplateError(HTTPError): def __init__(self, message): HTTPError.__init__(self, 500, message) class BaseTemplate(object): """ Base class and minimal API for template adapters """ extensions = ['tpl','html','thtml','stpl'] settings = {} #used in prepare() defaults = {} #used in render() def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings): """ Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance variables. The lookup parameter stores a list containing directory paths. The encoding parameter should be used to decode byte strings or files. The settings parameter contains a dict for engine-specific settings. """ self.name = name self.source = source.read() if hasattr(source, 'read') else source self.filename = source.filename if hasattr(source, 'filename') else None self.lookup = [os.path.abspath(x) for x in lookup] self.encoding = encoding self.settings = self.settings.copy() # Copy from class variable self.settings.update(settings) # Apply if not self.source and self.name: self.filename = self.search(self.name, self.lookup) if not self.filename: raise TemplateError('Template %s not found.' % repr(name)) if not self.source and not self.filename: raise TemplateError('No template specified.') self.prepare(**self.settings) @classmethod def search(cls, name, lookup=[]): """ Search name in all directories specified in lookup. First without, then with common extensions. Return first hit. """ if not lookup: depr('The template lookup path list should not be empty.') lookup = ['.'] if os.path.isabs(name) and os.path.isfile(name): depr('Absolute template path names are deprecated.') return os.path.abspath(name) for spath in lookup: spath = os.path.abspath(spath) + os.sep fname = os.path.abspath(os.path.join(spath, name)) if not fname.startswith(spath): continue if os.path.isfile(fname): return fname for ext in cls.extensions: if os.path.isfile('%s.%s' % (fname, ext)): return '%s.%s' % (fname, ext) @classmethod def global_config(cls, key, *args): ''' This reads or sets the global settings stored in class.settings. ''' if args: cls.settings = cls.settings.copy() # Make settings local to class cls.settings[key] = args[0] else: return cls.settings[key] def prepare(self, **options): """ Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings. """ raise NotImplementedError def render(self, *args, **kwargs): """ Render the template with the specified local variables and return a single byte or unicode string. If it is a byte string, the encoding must match self.encoding. This method must be thread-safe! Local variables may be provided in dictionaries (*args) or directly, as keywords (**kwargs). """ raise NotImplementedError class MakoTemplate(BaseTemplate): def prepare(self, **options): from mako.template import Template from mako.lookup import TemplateLookup options.update({'input_encoding':self.encoding}) options.setdefault('format_exceptions', bool(DEBUG)) lookup = TemplateLookup(directories=self.lookup, **options) if self.source: self.tpl = Template(self.source, lookup=lookup, **options) else: self.tpl = Template(uri=self.name, filename=self.filename, lookup=lookup, **options) def render(self, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) _defaults = self.defaults.copy() _defaults.update(kwargs) return self.tpl.render(**_defaults) class CheetahTemplate(BaseTemplate): def prepare(self, **options): from Cheetah.Template import Template self.context = threading.local() self.context.vars = {} options['searchList'] = [self.context.vars] if self.source: self.tpl = Template(source=self.source, **options) else: self.tpl = Template(file=self.filename, **options) def render(self, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) self.context.vars.update(self.defaults) self.context.vars.update(kwargs) out = str(self.tpl) self.context.vars.clear() return out class Jinja2Template(BaseTemplate): def prepare(self, filters=None, tests=None, **kwargs): from jinja2 import Environment, FunctionLoader if 'prefix' in kwargs: # TODO: to be removed after a while raise RuntimeError('The keyword argument `prefix` has been removed. ' 'Use the full jinja2 environment name line_statement_prefix instead.') self.env = Environment(loader=FunctionLoader(self.loader), **kwargs) if filters: self.env.filters.update(filters) if tests: self.env.tests.update(tests) if self.source: self.tpl = self.env.from_string(self.source) else: self.tpl = self.env.get_template(self.filename) def render(self, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) _defaults = self.defaults.copy() _defaults.update(kwargs) return self.tpl.render(**_defaults) def loader(self, name): fname = self.search(name, self.lookup) if not fname: return with open(fname, "rb") as f: return f.read().decode(self.encoding) class SimpleTALTemplate(BaseTemplate): ''' Deprecated, do not use. ''' def prepare(self, **options): depr('The SimpleTAL template handler is deprecated'\ ' and will be removed in 0.12') from simpletal import simpleTAL if self.source: self.tpl = simpleTAL.compileHTMLTemplate(self.source) else: with open(self.filename, 'rb') as fp: self.tpl = simpleTAL.compileHTMLTemplate(tonat(fp.read())) def render(self, *args, **kwargs): from simpletal import simpleTALES for dictarg in args: kwargs.update(dictarg) context = simpleTALES.Context() for k,v in self.defaults.items(): context.addGlobal(k, v) for k,v in kwargs.items(): context.addGlobal(k, v) output = StringIO() self.tpl.expand(context, output) return output.getvalue() class SimpleTemplate(BaseTemplate): blocks = ('if', 'elif', 'else', 'try', 'except', 'finally', 'for', 'while', 'with', 'def', 'class') dedent_blocks = ('elif', 'else', 'except', 'finally') @lazy_attribute def re_pytokens(cls): ''' This matches comments and all kinds of quoted strings but does NOT match comments (#...) within quoted strings. (trust me) ''' return re.compile(r''' (''(?!')|""(?!")|'{6}|"{6} # Empty strings (all 4 types) |'(?:[^\\']|\\.)+?' # Single quotes (') |"(?:[^\\"]|\\.)+?" # Double quotes (") |'{3}(?:[^\\]|\\.|\n)+?'{3} # Triple-quoted strings (') |"{3}(?:[^\\]|\\.|\n)+?"{3} # Triple-quoted strings (") |\#.* # Comments )''', re.VERBOSE) def prepare(self, escape_func=html_escape, noescape=False, **kwargs): self.cache = {} enc = self.encoding self._str = lambda x: touni(x, enc) self._escape = lambda x: escape_func(touni(x, enc)) if noescape: self._str, self._escape = self._escape, self._str @classmethod def split_comment(cls, code): """ Removes comments (#...) from python code. """ if '#' not in code: return code #: Remove comments only (leave quoted strings as they are) subf = lambda m: '' if m.group(0)[0]=='#' else m.group(0) return re.sub(cls.re_pytokens, subf, code) @cached_property def co(self): return compile(self.code, self.filename or '<string>', 'exec') @cached_property def code(self): stack = [] # Current Code indentation lineno = 0 # Current line of code ptrbuffer = [] # Buffer for printable strings and token tuple instances codebuffer = [] # Buffer for generated python code multiline = dedent = oneline = False template = self.source or open(self.filename, 'rb').read() def yield_tokens(line): for i, part in enumerate(re.split(r'\{\{(.*?)\}\}', line)): if i % 2: if part.startswith('!'): yield 'RAW', part[1:] else: yield 'CMD', part else: yield 'TXT', part def flush(): # Flush the ptrbuffer if not ptrbuffer: return cline = '' for line in ptrbuffer: for token, value in line: if token == 'TXT': cline += repr(value) elif token == 'RAW': cline += '_str(%s)' % value elif token == 'CMD': cline += '_escape(%s)' % value cline += ', ' cline = cline[:-2] + '\\\n' cline = cline[:-2] if cline[:-1].endswith('\\\\\\\\\\n'): cline = cline[:-7] + cline[-1] # 'nobr\\\\\n' --> 'nobr' cline = '_printlist([' + cline + '])' del ptrbuffer[:] # Do this before calling code() again code(cline) def code(stmt): for line in stmt.splitlines(): codebuffer.append(' ' * len(stack) + line.strip()) for line in template.splitlines(True): lineno += 1 line = touni(line, self.encoding) sline = line.lstrip() if lineno <= 2: m = re.match(r"%\s*#.*coding[:=]\s*([-\w.]+)", sline) if m: self.encoding = m.group(1) if m: line = line.replace('coding','coding (removed)') if sline and sline[0] == '%' and sline[:2] != '%%': line = line.split('%',1)[1].lstrip() # Full line following the % cline = self.split_comment(line).strip() cmd = re.split(r'[^a-zA-Z0-9_]', cline)[0] flush() # You are actually reading this? Good luck, it's a mess :) if cmd in self.blocks or multiline: cmd = multiline or cmd dedent = cmd in self.dedent_blocks # "else:" if dedent and not oneline and not multiline: cmd = stack.pop() code(line) oneline = not cline.endswith(':') # "if 1: pass" multiline = cmd if cline.endswith('\\') else False if not oneline and not multiline: stack.append(cmd) elif cmd == 'end' and stack: code('#end(%s) %s' % (stack.pop(), line.strip()[3:])) elif cmd == 'include': p = cline.split(None, 2)[1:] if len(p) == 2: code("_=_include(%s, _stdout, %s)" % (repr(p[0]), p[1])) elif p: code("_=_include(%s, _stdout)" % repr(p[0])) else: # Empty %include -> reverse of %rebase code("_printlist(_base)") elif cmd == 'rebase': p = cline.split(None, 2)[1:] if len(p) == 2: code("globals()['_rebase']=(%s, dict(%s))" % (repr(p[0]), p[1])) elif p: code("globals()['_rebase']=(%s, {})" % repr(p[0])) else: code(line) else: # Line starting with text (not '%') or '%%' (escaped) if line.strip().startswith('%%'): line = line.replace('%%', '%', 1) ptrbuffer.append(yield_tokens(line)) flush() return '\n'.join(codebuffer) + '\n' def subtemplate(self, _name, _stdout, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) if _name not in self.cache: self.cache[_name] = self.__class__(name=_name, lookup=self.lookup) return self.cache[_name].execute(_stdout, kwargs) def execute(self, _stdout, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) env = self.defaults.copy() env.update({'_stdout': _stdout, '_printlist': _stdout.extend, '_include': self.subtemplate, '_str': self._str, '_escape': self._escape, 'get': env.get, 'setdefault': env.setdefault, 'defined': env.__contains__}) env.update(kwargs) eval(self.co, env) if '_rebase' in env: subtpl, rargs = env['_rebase'] rargs['_base'] = _stdout[:] #copy stdout del _stdout[:] # clear stdout return self.subtemplate(subtpl,_stdout,rargs) return env def render(self, *args, **kwargs): """ Render the template using keyword arguments as local variables. """ for dictarg in args: kwargs.update(dictarg) stdout = [] self.execute(stdout, kwargs) return ''.join(stdout) def template(*args, **kwargs): ''' Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments). ''' tpl = args[0] if args else None adapter = kwargs.pop('template_adapter', SimpleTemplate) lookup = kwargs.pop('template_lookup', TEMPLATE_PATH) tplid = (id(lookup), tpl) if tplid not in TEMPLATES or DEBUG: settings = kwargs.pop('template_settings', {}) if isinstance(tpl, adapter): TEMPLATES[tplid] = tpl if settings: TEMPLATES[tplid].prepare(**settings) elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings) else: TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings) if not TEMPLATES[tplid]: abort(500, 'Template (%s) not found' % tpl) for dictarg in args[1:]: kwargs.update(dictarg) return TEMPLATES[tplid].render(kwargs) mako_template = functools.partial(template, template_adapter=MakoTemplate) cheetah_template = functools.partial(template, template_adapter=CheetahTemplate) jinja2_template = functools.partial(template, template_adapter=Jinja2Template) simpletal_template = functools.partial(template, template_adapter=SimpleTALTemplate) def view(tpl_name, **defaults): ''' Decorator: renders a template for a handler. The handler can control its behavior like that: - return a dict of template vars to fill out the template - return something other than a dict and the view decorator will not process the template, but return the handler result as is. This includes returning a HTTPResponse(dict) to get, for instance, JSON with autojson or other castfilters. ''' def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) if isinstance(result, (dict, DictMixin)): tplvars = defaults.copy() tplvars.update(result) return template(tpl_name, **tplvars) return result return wrapper return decorator mako_view = functools.partial(view, template_adapter=MakoTemplate) cheetah_view = functools.partial(view, template_adapter=CheetahTemplate) jinja2_view = functools.partial(view, template_adapter=Jinja2Template) simpletal_view = functools.partial(view, template_adapter=SimpleTALTemplate) ############################################################################### # Constants and Globals ######################################################## ############################################################################### TEMPLATE_PATH = ['./', './views/'] TEMPLATES = {} DEBUG = False NORUN = False # If set, run() does nothing. Used by load_app() #: A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found') HTTP_CODES = httplib.responses HTTP_CODES[418] = "I'm a teapot" # RFC 2324 HTTP_CODES[428] = "Precondition Required" HTTP_CODES[429] = "Too Many Requests" HTTP_CODES[431] = "Request Header Fields Too Large" HTTP_CODES[511] = "Network Authentication Required" _HTTP_STATUS_LINES = dict((k, '%d %s'%(k,v)) for (k,v) in HTTP_CODES.items()) #: The default template used for error pages. Override with @error() ERROR_PAGE_TEMPLATE = """ %%try: %%from %s import DEBUG, HTTP_CODES, request, touni <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html> <head> <title>Error: {{e.status}}</title> <style type="text/css"> html {background-color: #eee; font-family: sans;} body {background-color: #fff; border: 1px solid #ddd; padding: 15px; margin: 15px;} pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;} </style> </head> <body> <h1>Error: {{e.status}}</h1> <p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt> caused an error:</p> <pre>{{e.body}}</pre> %%if DEBUG and e.exception: <h2>Exception:</h2> <pre>{{repr(e.exception)}}</pre> %%end %%if DEBUG and e.traceback: <h2>Traceback:</h2> <pre>{{e.traceback}}</pre> %%end </body> </html> %%except ImportError: <b>ImportError:</b> Could not generate the error page. Please add bottle to the import path. %%end """ % __name__ #: A thread-safe instance of :class:`LocalRequest`. If accessed from within a #: request callback, this instance always refers to the *current* request #: (even on a multithreaded server). request = LocalRequest() #: A thread-safe instance of :class:`LocalResponse`. It is used to change the #: HTTP response for the *current* request. response = LocalResponse() #: A thread-safe namespace. Not used by Bottle. local = threading.local() # Initialize app stack (create first empty Bottle app) # BC: 0.6.4 and needed for run() app = default_app = AppStack() app.push() #: A virtual package that redirects import statements. #: Example: ``import bottle.ext.sqlite`` actually imports `bottle_sqlite`. ext = _ImportRedirect('bottle.ext' if __name__ == '__main__' else __name__+".ext", 'bottle_%s').module if __name__ == '__main__': opt, args, parser = _cmd_options, _cmd_args, _cmd_parser if opt.version: _stdout('Bottle %s\n'%__version__) sys.exit(0) if not args: parser.print_help() _stderr('\nError: No application specified.\n') sys.exit(1) sys.path.insert(0, '.') sys.modules.setdefault('bottle', sys.modules['__main__']) host, port = (opt.bind or 'localhost'), 8080 if ':' in host: host, port = host.rsplit(':', 1) run(args[0], host=host, port=port, server=opt.server, reloader=opt.reload, plugins=opt.plugin, debug=opt.debug) # THE END
jimcunderwood/MissionPlanner
refs/heads/master
Lib/site-packages/scipy/ndimage/tests/test_io.py
61
from numpy.testing import assert_array_equal, dec, run_module_suite import scipy.ndimage as ndi import os try: from PIL import Image pil_missing = False except ImportError: pil_missing = True @dec.skipif(pil_missing, msg="The Python Image Library could not be found.") def test_imread(): lp = os.path.join(os.path.dirname(__file__), 'dots.png') img = ndi.imread(lp) assert_array_equal(img.shape, (300, 420, 3)) img = ndi.imread(lp, flatten=True) assert_array_equal(img.shape, (300, 420)) if __name__ == "__main__": run_module_suite()
open-aerospace/openrocketdoc
refs/heads/master
tests/test_document.py
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_document ---------------------------------- Tests for `document` module. """ import unittest from openrocketdoc import document class TestOpenrocketdoc(unittest.TestCase): def setUp(self): pass def test_spec_a_rocket(self): rocket = document.Rocket("Rocket") stage0 = document.Stage("Booster") stage0.components = [ document.Nosecone(document.Noseshape.VONKARMAN, 1, 0.7, 1.2), document.Bodytube("body", 1.2, 0.5), ] rocket.stages = [stage0] def test_stage_mass_sum(self): stage0 = document.Stage("Booster") stage0.components = [ document.Nosecone(document.Noseshape.CONE, 0, 0.7, 1.4), document.Bodytube("body", 0, 1), document.Bodytube("body", 24.1, 1), ] self.assertEqual(24.8, stage0.mass) def test_rocket_mass_sum(self): stage0 = document.Stage("Booster") stage0.components = [ document.Nosecone("", 1, 0.7, 1.2), document.Bodytube("body", 0, 1), document.Bodytube("body", 24.1, 1), ] stage1 = document.Stage("Booster") stage1.components = [ document.Bodytube("body", 4.87, 1), document.Fin('fin', 1, 1, 1, sweepangle=45.0, mass=0.1), ] rocket = document.Rocket("Rocket") rocket.stages = [stage0, stage1] self.assertEqual(29.77, rocket.mass) def test_rocket_aero_exist(self): rocket = document.Rocket("Rocket") self.assertEqual(rocket.aero_properties, {}) # add some properties rocket.aero_properties['CD'] = [0.8] self.assertEqual(rocket.aero_properties, {'CD': [0.8]}) def test_rocket_length_sum_0(self): # just rocket rocket = document.Rocket("Rocket") self.assertEqual(rocket.length, 0) # rocket and a stage stage0 = document.Stage("sustainer") rocket.stages = [stage0] self.assertEqual(rocket.length, 0) # zero length components in rocket stage0.components = [ document.Nosecone("", 1, 0.7, 0), document.Bodytube("body", 0, 0), document.Bodytube("body", 24.1, 0) ] self.assertEqual(rocket.length, 0) def test_rocket_length_sum(self): stage0 = document.Stage("Booster") stage0.components = [ document.Nosecone("", 1, 0.7, 1.2), document.Bodytube("body", 0, 1), document.Bodytube("body", 24.1, 1), ] stage1 = document.Stage("Booster") stage1.components = [ document.Bodytube("body", 4.87, 1), document.Fin('fin', 1, 1, 1, sweepangle=45.0, mass=0.1), ] rocket = document.Rocket("Rocket") rocket.stages = [stage0, stage1] self.assertAlmostEqual(rocket.length, 5.2) def test_fins(self): fin = document.Fin('fin', 1, 1, 1, sweep=0.234) self.assertEqual(0, fin.mass) self.assertAlmostEqual(fin.root, 1.0) self.assertAlmostEqual(fin.tip, 1.0) self.assertAlmostEqual(fin.span, 1.0) self.assertAlmostEqual(fin.sweep, 0.234) self.assertAlmostEqual(fin.sweepangle, 13.170241897951414) def test_no_color(self): tube = document.Bodytube("body", 24.1, 1) # No color defined self.assertEqual(tube.color, None) def test_color(self): tube = document.Bodytube("body", 24.1, 1) # As string: tube.color = "Brown" self.assertEqual(tube.color, "Brown") # As tuple: tube.color = (240, 12, 0) self.assertEqual(tube.color, (240, 12, 0)) def test_engine_length(self): engine = document.Engine("test") # length not set self.assertEqual(engine.length, 0) # set directly engine.length = 25.4 self.assertEqual(engine.length, 25.4) def test_engine_t_burn(self): engine = document.Engine("test Name") engine.t_burn = 123.456 self.assertAlmostEqual(engine.t_burn, 123.456) def test_engine_ve(self): engine = document.Engine("test Name") engine.Isp = 123 self.assertAlmostEqual(engine.V_e, 1206.21795) def test_engine_simple_0(self): engine = document.Engine("test Name") # minimum to set up real engine engine.Isp = 123 engine.thrust_avg = 4567 engine.t_burn = 89 self.assertAlmostEqual(engine.Isp, 123) self.assertAlmostEqual(engine.thrust_avg, 4567) self.assertAlmostEqual(engine.t_burn, 89) self.assertAlmostEqual(engine.m_prop, 336.9730984354) self.assertAlmostEqual(engine.I_total, 406463) self.assertAlmostEqual(engine.thrust_peak, 4567) self.assertAlmostEqual(engine.V_e, 1206.21795) def test_engine_simple_1(self): engine = document.Engine("test Name") # minimum to set up real engine engine.Isp = 123 engine.thrust_avg = 4567 engine.I_total = 15000 self.assertAlmostEqual(engine.Isp, 123) self.assertAlmostEqual(engine.thrust_avg, 4567) self.assertAlmostEqual(engine.I_total, 15000) self.assertAlmostEqual(engine.m_prop, 12.435563572901) self.assertAlmostEqual(engine.t_burn, 3.2844317932997593) self.assertAlmostEqual(engine.thrust_peak, 4567) self.assertAlmostEqual(engine.V_e, 1206.21795) def test_engine_name(self): engine = document.Engine("test Name") self.assertEqual(engine.name, "test Name") self.assertEqual(engine.manufacturer, "") engine.manufacturer = "python" self.assertEqual(engine.manufacturer, "python") def test_engine_nar_code(self): # blank engine case engine = document.Engine("test Name") self.assertEqual(engine.nar_code, "") # NAR B motor spec: 2.51 –- 5.00 Ns # 0% B motor, it's almost zero engine.thrust_avg = 2.501 engine.t_burn = 1 self.assertEqual(engine.nar_code, "B") self.assertAlmostEqual(engine.nar_percent, 0, places=1) # 50% B motor engine.thrust_avg = 3.755 engine.t_burn = 1 self.assertEqual(engine.nar_code, "B") self.assertAlmostEqual(engine.nar_percent, 50, places=0) # 100% B motor, but it rounds up, that's okay I guess engine.thrust_avg = 4.99999 engine.t_burn = 1 self.assertEqual(engine.nar_code, "B") self.assertAlmostEqual(engine.nar_percent, 100, places=0) # NAR N motor spec: 10,200 -- 20,500 Ns # 0% N motor engine.thrust_avg = 10200 engine.t_burn = 1 engine.nar_percent self.assertEqual(engine.nar_code, "M") self.assertAlmostEqual(engine.nar_percent, 99, places=0) # 50% N motor engine.thrust_avg = 10240 + 5150 engine.t_burn = 1 self.assertEqual(engine.nar_code, "N") self.assertAlmostEqual(engine.nar_percent, 50, places=0) # 100% N motor engine.thrust_avg = 20450 engine.t_burn = 1 self.assertEqual(engine.nar_code, "N") self.assertAlmostEqual(engine.nar_percent, 100, places=0) # NAR Z motor spec: 41,900,000 -- 83,900,000 Ns # 0% N motor engine.thrust_avg = 41.9e6 engine.t_burn = 1 engine.nar_percent self.assertEqual(engine.nar_code, "Y") self.assertAlmostEqual(engine.nar_percent, 100, places=0) # 50% N motor engine.thrust_avg = 41.9e6 + 10e6 engine.t_burn = 1 self.assertEqual(engine.nar_code, "Z") self.assertAlmostEqual(engine.nar_percent, 24, places=0) # 100% N motor engine.thrust_avg = 83.8e6 engine.t_burn = 1 self.assertEqual(engine.nar_code, "Z") self.assertAlmostEqual(engine.nar_percent, 100, places=0) # Greater than Z: engine.thrust_avg = 500e6 engine.t_burn = 1 self.assertEqual(engine.nar_code, "AC") self.assertAlmostEqual(engine.nar_percent, 49, places=0) def test_engine_name_slug(self): # replace spaces with dashes engine = document.Engine("My Rocket Motor 12") self.assertEqual(engine.name_slug, "my-rocket-motor-12") # one word, not much to do engine = document.Engine("Motor") self.assertEqual(engine.name_slug, "motor") # trailing space engine = document.Engine("Motor ") self.assertEqual(engine.name_slug, "motor") # leading space engine = document.Engine(" Motor") self.assertEqual(engine.name_slug, "motor") # blank name engine = document.Engine("") self.assertEqual(engine.name_slug, "engine") # blank name engine = document.Engine(" ") self.assertEqual(engine.name_slug, "engine") # blank name engine = document.Engine(" ") self.assertEqual(engine.name_slug, "engine") # Illegal characters engine = document.Engine("my **engIne: ") self.assertEqual(engine.name_slug, "my-engine") def test_component_name_slug(self): # replace spaces with dashes c = document.Bodytube("My Rocket Tube", 1, 1) self.assertEqual(c.name_slug, "my-rocket-tube") def test_rocket_name_slug(self): # replace spaces with dashes c = document.Rocket("My Rocket") self.assertEqual(c.name_slug, "my-rocket") def test_stage_name_slug(self): # replace spaces with dashes c = document.Stage("Stage-0") self.assertEqual(c.name_slug, "stage-0") def test_engine_isp(self): engine = document.Engine("test Name") self.assertEqual(engine.Isp, 0) engine.Isp = 169 self.assertAlmostEqual(engine.Isp, 169) def test_engine_Itot(self): engine = document.Engine("test Name") self.assertEqual(engine.I_total, 0) engine.thrustcurve.append({'t': 0, 'thrust': 500}) engine.thrustcurve.append({'t': 1, 'thrust': 500}) self.assertAlmostEqual(engine.I_total, 500) def test_engine_avgthrust(self): engine = document.Engine("test Name") self.assertEqual(engine.thrust_avg, 0) engine.thrustcurve.append({'t': 0, 'thrust': 500}) engine.thrustcurve.append({'t': 1, 'thrust': 500}) self.assertAlmostEqual(engine.thrust_avg, 500) def tearDown(self): pass if __name__ == '__main__': unittest.main()
open-synergy/opnsynid-l10n-indonesia
refs/heads/8.0
l10n_id_djbc_kb_lap_pemasukan/reports/__init__.py
1
# -*- coding: utf-8 -*- # Copyright 2018 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import lap_kb_lap_pemasukan
vivekanand1101/pontoon
refs/heads/master
pontoon/base/migrations/0007_auto_20150710_0944.py
8
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import pontoon.base.models class Migration(migrations.Migration): dependencies = [ ('base', '0006_auto_20150602_0616'), ] operations = [ migrations.AddField( model_name='locale', name='cldr_plurals', field=models.CommaSeparatedIntegerField(blank=True, max_length=11, verbose_name=b'CLDR Plurals', validators=[pontoon.base.models.validate_cldr]), ), migrations.AlterField( model_name='resource', name='format', field=models.CharField(blank=True, max_length=20, verbose_name=b'Format', choices=[(b'po', b'po'), (b'xliff', b'xliff'), (b'properties', b'properties'), (b'dtd', b'dtd'), (b'inc', b'inc'), (b'ini', b'ini'), (b'lang', b'lang'), (b'l20n', b'l20n')]), ), migrations.AlterField( model_name='translation', name='date', field=models.DateTimeField(auto_now_add=True), ), ]
onitake/Uranium
refs/heads/debian
UM/InputDevice.py
1
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from UM.Signal import Signal, signalemitter from UM.PluginObject import PluginObject ## Abstract base class for all input devices (Human Input Devices) # Examples of this are mouse & keyboard @signalemitter class InputDevice(PluginObject): def __init__(self): super().__init__() ## Emitted whenever the device produces an event. # All actions performed with the device should be seen as an event. # \param event The event that is emitted. event = Signal()
throwable-one/lettuce
refs/heads/master
tests/integration/lib/Django-1.2.5/django/contrib/gis/db/models/sql/where.py
309
from django.db.models.fields import Field, FieldDoesNotExist from django.db.models.sql.constants import LOOKUP_SEP from django.db.models.sql.expressions import SQLEvaluator from django.db.models.sql.where import Constraint, WhereNode from django.contrib.gis.db.models.fields import GeometryField class GeoConstraint(Constraint): """ This subclass overrides `process` to better handle geographic SQL construction. """ def __init__(self, init_constraint): self.alias = init_constraint.alias self.col = init_constraint.col self.field = init_constraint.field def process(self, lookup_type, value, connection): if isinstance(value, SQLEvaluator): # Make sure the F Expression destination field exists, and # set an `srid` attribute with the same as that of the # destination. geo_fld = GeoWhereNode._check_geo_field(value.opts, value.expression.name) if not geo_fld: raise ValueError('No geographic field found in expression.') value.srid = geo_fld.srid db_type = self.field.db_type(connection=connection) params = self.field.get_db_prep_lookup(lookup_type, value, connection=connection) return (self.alias, self.col, db_type), params class GeoWhereNode(WhereNode): """ Used to represent the SQL where-clause for spatial databases -- these are tied to the GeoQuery class that created it. """ def add(self, data, connector): if isinstance(data, (list, tuple)): obj, lookup_type, value = data if ( isinstance(obj, Constraint) and isinstance(obj.field, GeometryField) ): data = (GeoConstraint(obj), lookup_type, value) super(GeoWhereNode, self).add(data, connector) def make_atom(self, child, qn, connection): lvalue, lookup_type, value_annot, params_or_value = child if isinstance(lvalue, GeoConstraint): data, params = lvalue.process(lookup_type, params_or_value, connection) spatial_sql = connection.ops.spatial_lookup_sql(data, lookup_type, params_or_value, lvalue.field, qn) return spatial_sql, params else: return super(GeoWhereNode, self).make_atom(child, qn, connection) @classmethod def _check_geo_field(cls, opts, lookup): """ Utility for checking the given lookup with the given model options. The lookup is a string either specifying the geographic field, e.g. 'point, 'the_geom', or a related lookup on a geographic field like 'address__point'. If a GeometryField exists according to the given lookup on the model options, it will be returned. Otherwise returns None. """ # This takes into account the situation where the lookup is a # lookup to a related geographic field, e.g., 'address__point'. field_list = lookup.split(LOOKUP_SEP) # Reversing so list operates like a queue of related lookups, # and popping the top lookup. field_list.reverse() fld_name = field_list.pop() try: geo_fld = opts.get_field(fld_name) # If the field list is still around, then it means that the # lookup was for a geometry field across a relationship -- # thus we keep on getting the related model options and the # model field associated with the next field in the list # until there's no more left. while len(field_list): opts = geo_fld.rel.to._meta geo_fld = opts.get_field(field_list.pop()) except (FieldDoesNotExist, AttributeError): return False # Finally, make sure we got a Geographic field and return. if isinstance(geo_fld, GeometryField): return geo_fld else: return False
ahmedetefy/AccountTracker
refs/heads/master
projects/AccountTracker/main/models.py
1
from django.db import models from django.core.urlresolvers import reverse from django.utils.encoding import python_2_unicode_compatible from django.conf import settings from localflavor.generic.models import IBANField @python_2_unicode_compatible class Account(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) iban_number = IBANField() author = models.ForeignKey(settings.AUTH_USER_MODEL) created_at = models.DateTimeField(auto_now_add=True) created_at.editable = True class Meta: verbose_name_plural = "accounts" def __str__(self): return self.first_name def get_absolute_url(self): return reverse('main:account_edit', kwargs={'pk': self.pk})
encukou/cython
refs/heads/master
tests/run/purecdef.py
28
import cython from cython import cfunc, cclass, ccall @cython.test_assert_path_exists('//CFuncDefNode') @cython.cfunc def ftang(): x = 0 @cython.test_assert_path_exists('//CFuncDefNode') @cfunc def fpure(a): return a*2 def test(): """ >>> test() 4 """ ftang() return fpure(2) with cfunc: @cython.test_assert_path_exists('//CFuncDefNode') def fwith1(a): return a*3 @cython.test_assert_path_exists('//CFuncDefNode') def fwith2(a): return a*4 with cclass: @cython.test_assert_path_exists('//CClassDefNode') class Egg(object): pass @cython.test_assert_path_exists('//CClassDefNode') class BigEgg(object): @cython.test_assert_path_exists('//CFuncDefNode') @cython.cfunc def f(self, a): return a*10 def test_with(): """ >>> test_with() (3, 4, 50) """ return fwith1(1), fwith2(1), BigEgg().f(5) @cython.test_assert_path_exists('//CClassDefNode') @cython.cclass class PureFoo(object): a = cython.declare(cython.double) def __init__(self, a): self.a = a def __call__(self): return self.a @cython.test_assert_path_exists('//CFuncDefNode') @cython.cfunc def puremeth(self, a): return a*2 def test_method(): """ >>> test_method() 4 True """ x = PureFoo(2) print(x.puremeth(2)) if cython.compiled: print(isinstance(x(), float)) else: print(True) return @cython.ccall def ccall_sqr(x): return x*x @cclass class Overidable(object): @ccall def meth(self): return 0 def test_ccall(): """ >>> test_ccall() 25 >>> ccall_sqr(5) 25 """ return ccall_sqr(5) def test_ccall_method(x): """ >>> test_ccall_method(Overidable()) 0 >>> Overidable().meth() 0 >>> class Foo(Overidable): ... def meth(self): ... return 1 >>> test_ccall_method(Foo()) 1 >>> Foo().meth() 1 """ return x.meth() @cython.cfunc @cython.returns(cython.p_int) @cython.locals(xptr=cython.p_int) def typed_return(xptr): return xptr def test_typed_return(): """ >>> test_typed_return() """ x = cython.declare(int, 5) assert typed_return(cython.address(x))[0] is x
ChodeGames/bitfl
refs/heads/master
menu.py
1
"""Billy in the Fat Lane - A Lame Life Simulation Game Copyright (C) 2013 Chris Parlette, Matt Parlette This file is part of Billy in the Fat Lane. Billy in the Fat Lane 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. Billy in the Fat Lane 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 Billy in the Fat Lane. If not, see http://www.gnu.org/licenses/.""" class Menu(object): def __init__(self): self.title = None self.options = dict() self.indent = 2 self.getch = _Getch() self.allow_cancel = False def display(self,sort = True): """Show the menu to the user and return their selection.""" if self.title: print self.title print '=' * len(self.title) if self.options: def print_menu(): #Print the list, either sorted or just as is if sort: for key,value in sorted(self.options.iteritems()): print "%s. %s" % (key,value) else: for key,value in self.options.iteritems(): print "%s. %s" % (key,value) if self.allow_cancel: print "(Enter to cancel)" while True: print_menu() selected = self.getch() print "\n" if selected in self.options: return selected elif selected == "\r" and self.allow_cancel: return '' elif selected == "?": pass else: print "Invalid Option\n" else: print "No options available!\n" def add_option(self,key,value): """Add an option to the menu. The key is a character the player can use to select this option. The value is a friendly name for this option.""" if key not in self.options: self.options[key] = value class MainMenu(Menu): def __init__(self): Menu.__init__(self) self.title = "Main Menu" self.options = {'n':'New Game','q':'Quit'} class NewGameMenu(Menu): def __init__(self): Menu.__init__(self) self.title = "New Game Menu" self.options = {'a':'Add Player','l':'List Players','s':'Start Game','q':'Quit'} class TurnMenu(Menu): def __init__(self): Menu.__init__(self) self.title = "Turn Menu" self.options = {'m':'Move','e':'End Turn','q':'Quit','i':'Player Info'} def display(self,turn_number,player,time_left): self.title = "Turn Menu: %s: Turn %s\nTime Left: %s hours\nLocation: %s" % (player.name,turn_number,time_left,player.location.name) return super(TurnMenu,self).display() class MoveMenu(Menu): def __init__(self,locations): super(MoveMenu,self).__init__() self.title = "Move Player" self.options = {} #Build the options from the locations list for location in locations: self.options[location.symbol] = location.name #We want the user to be able to cancel self.allow_cancel = True def display(self,map): print map return super(MoveMenu,self).display() class JobMenu(Menu): def __init__(self): super(JobMenu,self).__init__() self.title = "Job Menu" self.options = {} def display(self,job = None,job_list = None): if job and job_list: print "Error in JobMenu.display(): job and job_list cannot both be provided" return None if job: self.title = "Job Menu: %s" % job.name self.options = {'w':'Work','q':'Quit'} if job_list: self.title = "Apply for job" for j in job_list: self.options[str(j.rank)] = "%s ($%s pay per unit)" % (j.name,str(j.pay)) self.allow_cancel = True return super(JobMenu,self).display(sort=True) class CourseMenu(Menu): def __init__(self): super(CourseMenu,self).__init__() self.title = "Education Menu" self.options = {} def display(self,course_list, player): self.title = "Enroll in a course" for c in course_list: #Check if the player has the knowledge required, class required, or has already taken the course player_can_take_course = True if player.attributes['knowledge'].get() < c.knowledge_required: player_can_take_course = False if c.course_required: if c.course_required not in player.completed_education: player_can_take_course = False if c.name in player.completed_education: player_can_take_course = False #Add course as an option if player is qualified and hasn't already taken it if player_can_take_course: self.options[str(c.symbol)] = "%s - %s time spent - %s knowledge gained - $%s to enroll" % (c.name,str(abs(c.time)),str(c.knowledge_value),str(abs(c.cost))) self.allow_cancel = True return super(CourseMenu,self).display(sort=True) class BuyMenu(Menu): def __init__(self): super(BuyMenu,self).__init__() self.title = "Buying An Item" self.options = {} def display(self,item_list): if item_list: for i in item_list: #We use a string representation of the index of each item self.options[str(item_list.index(i))] = "%s ($%s)" % (i.name,str(abs(i.cost))) self.allow_cancel = True selection = super(BuyMenu,self).display(sort=True) if selection: #Convert the selection from string (above) to int for lookup return item_list[int(selection)] class ListMenu(Menu): """A generic menu that allows the user to select items from a list. Note that this returns the object in the list, not the index of that item.""" def __init__(self,title = "List Menu",options = []): super(ListMenu,self).__init__() self.title = title #Convert the passed list into a dictionary self.options = {} i = 1 for item in options: self.options[str(i)] = item i += 1 def display(self): """Return the object from the list rather than the index of that item.""" return self.options[super(ListMenu,self).display(sort=False)] class QuitMenu(Menu): def __init__(self, options={'q':'Quit BITFL completely'}): Menu.__init__(self) self.title = "Quit Menu" self.options = options self.allow_cancel = True def display(self): choice = super(QuitMenu, self).display(sort=False) if choice == 'q': return True, True elif choice == 'm': return False, True else: return False, False ## {{{ http://code.activestate.com/recipes/134892/ (r2) class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() ## end of http://code.activestate.com/recipes/134892/ }}}
carljm/django
refs/heads/master
tests/forms_tests/field_tests/test_typedchoicefield.py
42
from __future__ import unicode_literals import decimal from django.forms import TypedChoiceField, ValidationError from django.test import SimpleTestCase from django.utils import six class TypedChoiceFieldTest(SimpleTestCase): def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) msg = "'Select a valid choice. 2 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('2') def test_typedchoicefield_2(self): # Different coercion, same validation. f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual(1.0, f.clean('1')) def test_typedchoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertTrue(f.clean('-1')) def test_typedchoicefield_4(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) msg = "'Select a valid choice. B is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('B') # Required fields require values with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') def test_typedchoicefield_5(self): # Non-required fields aren't required f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual('', f.clean('')) # If you want cleaning an empty value to return a different type, tell the field def test_typedchoicefield_6(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None) self.assertIsNone(f.clean('')) def test_typedchoicefield_has_changed(self): # has_changed should not trigger required validation f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=True) self.assertFalse(f.has_changed(None, '')) self.assertFalse(f.has_changed(1, '1')) self.assertFalse(f.has_changed('1', '1')) f = TypedChoiceField( choices=[('', '---------'), ('a', "a"), ('b', "b")], coerce=six.text_type, required=False, initial=None, empty_value=None, ) self.assertFalse(f.has_changed(None, '')) self.assertTrue(f.has_changed('', 'a')) self.assertFalse(f.has_changed('a', 'a')) def test_typedchoicefield_special_coerce(self): """ A coerce function which results in a value not present in choices should raise an appropriate error (#21397). """ def coerce_func(val): return decimal.Decimal('1.%s' % val) f = TypedChoiceField(choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True) self.assertEqual(decimal.Decimal('1.2'), f.clean('2')) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('3')
axltxl/kaoru
refs/heads/develop
kaoru/commands/screenlock.py
1
# -*- coding: utf-8 -*- """ kaoru.commands.screenlock ~~~~~~~~ /screenlock implementation :copyright: (c) 2015 by Alejandro Ricoveri :license: MIT, see LICENSE for more details. """ from telegram import Update from .. import utils from .. import config from .. import log from . import bot_command from ..procutils import proc_exec_async # /screenlock command: @bot_command def _cmd_handler(bot, update): """ it basically runs a screen locker """ # check for executables set for commands screenlock_exec = config.get('screenlock_cmd') if screenlock_exec is None: screenlock_exec = proc_select([ 'xlock', 'xscreensaver', 'i3lock' ], ) # only execute the thing if existent if screenlock_exec is None: err_msg = "A suitable 'screenlock_cmd' has bot been found." utils.echo_msg(err_msg) log.msg_err(err_msg) return proc_exec_async(screenlock_exec) utils.echo_msg(bot, update, "Your screen(s) are now LOCKED") desc = 'See if I "live"' # This command's description cmd_handler = _cmd_handler # command handler cmd_str = 'screenlock' # command /string
nodakai/watchman
refs/heads/master
python/setup.py
1
#!/usr/bin/env python # vim:ts=4:sw=4:et: from __future__ import absolute_import, division, print_function, unicode_literals import os from distutils.core import Extension, setup watchman_src_dir = os.environ.get("CMAKE_CURRENT_SOURCE_DIR") if watchman_src_dir is None: watchman_src_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..") # The python source dir. # On Windows, this has to be relative to the cwd otherwise something # in the setuptools machinery does the wrong thing and produces a # path like `Z:blah` which on windows resolves ambiguously depending # on the cwd. py_dir = os.path.join(watchman_src_dir, "python") if os.name == "nt": py_dir = os.path.relpath(py_dir) def srcs(names): """ transform a list of sources to be relative to py_dir """ return ["%s/%s" % (py_dir, n) for n in names] setup( name="pywatchman", version="1.4.1", package_dir={"": py_dir}, description="Watchman client for python", author="Wez Furlong, Rain", author_email="wez@fb.com", maintainer="Wez Furlong", maintainer_email="wez@fb.com", url="https://github.com/facebook/watchman", long_description="Connect and query Watchman to discover file changes", keywords=("watchman inotify fsevents kevent kqueue portfs filesystem watcher"), license="BSD", packages=["pywatchman"], ext_modules=[Extension("pywatchman.bser", sources=srcs(["pywatchman/bser.c"]))], platforms="Platform Independent", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: System :: Filesystems", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], zip_safe=True, scripts=srcs( [ "bin/watchman-make", "bin/watchman-wait", "bin/watchman-replicate-subscription", ] ), test_suite="tests", )
xin3liang/platform_external_chromium-trace
refs/heads/master
trace-viewer/third_party/closure_linter/closure_linter/requireprovidesorter_test.py
135
#!/usr/bin/env python # # Copyright 2012 The Closure Linter Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for RequireProvideSorter.""" import unittest as googletest from closure_linter import ecmametadatapass from closure_linter import javascripttokenizer from closure_linter import javascripttokens from closure_linter import requireprovidesorter # pylint: disable-msg=C6409 TokenType = javascripttokens.JavaScriptTokenType class RequireProvideSorterTest(googletest.TestCase): """Tests for RequireProvideSorter.""" _tokenizer = javascripttokenizer.JavaScriptTokenizer() _metadata_pass = ecmametadatapass.EcmaMetaDataPass() def testFixRequires_removeBlankLines(self): """Tests that blank lines are omitted in sorted goog.require statements.""" input_lines = [ 'goog.provide(\'package.subpackage.Whatever\');', '', 'goog.require(\'package.subpackage.ClassB\');', '', 'goog.require(\'package.subpackage.ClassA\');' ] expected_lines = [ 'goog.provide(\'package.subpackage.Whatever\');', '', 'goog.require(\'package.subpackage.ClassA\');', 'goog.require(\'package.subpackage.ClassB\');' ] token = self._tokenizer.TokenizeFile(input_lines) self._metadata_pass.Reset() self._metadata_pass.Process(token) sorter = requireprovidesorter.RequireProvideSorter() sorter.FixRequires(token) self.assertEquals(expected_lines, self._GetLines(token)) def _GetLines(self, token): """Returns an array of lines based on the specified token stream.""" lines = [] line = '' while token: line += token.string if token.IsLastInLine(): lines.append(line) line = '' token = token.next return lines if __name__ == '__main__': googletest.main()
Basler/linux-usb-zerocopy
refs/heads/linux-4.2.y-usb-zerocopy
Documentation/target/tcm_mod_builder.py
337
#!/usr/bin/python # The TCM v4 multi-protocol fabric module generation script for drivers/target/$NEW_MOD # # Copyright (c) 2010 Rising Tide Systems # Copyright (c) 2010 Linux-iSCSI.org # # Author: nab@kernel.org # import os, sys import subprocess as sub import string import re import optparse tcm_dir = "" fabric_ops = [] fabric_mod_dir = "" fabric_mod_port = "" fabric_mod_init_port = "" def tcm_mod_err(msg): print msg sys.exit(1) def tcm_mod_create_module_subdir(fabric_mod_dir_var): if os.path.isdir(fabric_mod_dir_var) == True: return 1 print "Creating fabric_mod_dir: " + fabric_mod_dir_var ret = os.mkdir(fabric_mod_dir_var) if ret: tcm_mod_err("Unable to mkdir " + fabric_mod_dir_var) return def tcm_mod_build_FC_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* FC lport target portal group tag for TCM */\n" buf += " u16 lport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_lport */\n" buf += " struct " + fabric_mod_name + "_lport *lport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n" buf += "\n" buf += "struct " + fabric_mod_name + "_lport {\n" buf += " /* Binary World Wide unique Port Name for FC Target Lport */\n" buf += " u64 lport_wwpn;\n" buf += " /* ASCII formatted WWPN for FC Target Lport */\n" buf += " char lport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_lport() */\n" buf += " struct se_wwn lport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "lport" fabric_mod_init_port = "nport" return def tcm_mod_build_SAS_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* SAS port target portal group tag for TCM */\n" buf += " u16 tport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_tport */\n" buf += " struct " + fabric_mod_name + "_tport *tport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tport {\n" buf += " /* Binary World Wide unique Port Name for SAS Target port */\n" buf += " u64 tport_wwpn;\n" buf += " /* ASCII formatted WWPN for SAS Target port */\n" buf += " char tport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_tport() */\n" buf += " struct se_wwn tport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "tport" fabric_mod_init_port = "iport" return def tcm_mod_build_iSCSI_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* iSCSI target portal group tag for TCM */\n" buf += " u16 tport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_tport */\n" buf += " struct " + fabric_mod_name + "_tport *tport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tport {\n" buf += " /* ASCII formatted TargetName for IQN */\n" buf += " char tport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_tport() */\n" buf += " struct se_wwn tport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "tport" fabric_mod_init_port = "iport" return def tcm_mod_build_base_includes(proto_ident, fabric_mod_dir_val, fabric_mod_name): if proto_ident == "FC": tcm_mod_build_FC_include(fabric_mod_dir_val, fabric_mod_name) elif proto_ident == "SAS": tcm_mod_build_SAS_include(fabric_mod_dir_val, fabric_mod_name) elif proto_ident == "iSCSI": tcm_mod_build_iSCSI_include(fabric_mod_dir_val, fabric_mod_name) else: print "Unsupported proto_ident: " + proto_ident sys.exit(1) return def tcm_mod_build_configfs(proto_ident, fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_configfs.c" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#include <linux/module.h>\n" buf += "#include <linux/moduleparam.h>\n" buf += "#include <linux/version.h>\n" buf += "#include <generated/utsrelease.h>\n" buf += "#include <linux/utsname.h>\n" buf += "#include <linux/init.h>\n" buf += "#include <linux/slab.h>\n" buf += "#include <linux/kthread.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/string.h>\n" buf += "#include <linux/configfs.h>\n" buf += "#include <linux/ctype.h>\n" buf += "#include <asm/unaligned.h>\n" buf += "#include <scsi/scsi_proto.h>\n\n" buf += "#include <target/target_core_base.h>\n" buf += "#include <target/target_core_fabric.h>\n" buf += "#include <target/target_core_fabric_configfs.h>\n" buf += "#include <target/configfs_macros.h>\n\n" buf += "#include \"" + fabric_mod_name + "_base.h\"\n" buf += "#include \"" + fabric_mod_name + "_fabric.h\"\n\n" buf += "static const struct target_core_fabric_ops " + fabric_mod_name + "_ops;\n\n" buf += "static struct se_portal_group *" + fabric_mod_name + "_make_tpg(\n" buf += " struct se_wwn *wwn,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + "*" + fabric_mod_port + " = container_of(wwn,\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + ", " + fabric_mod_port + "_wwn);\n\n" buf += " struct " + fabric_mod_name + "_tpg *tpg;\n" buf += " unsigned long tpgt;\n" buf += " int ret;\n\n" buf += " if (strstr(name, \"tpgt_\") != name)\n" buf += " return ERR_PTR(-EINVAL);\n" buf += " if (kstrtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)\n" buf += " return ERR_PTR(-EINVAL);\n\n" buf += " tpg = kzalloc(sizeof(struct " + fabric_mod_name + "_tpg), GFP_KERNEL);\n" buf += " if (!tpg) {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_tpg\");\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += " }\n" buf += " tpg->" + fabric_mod_port + " = " + fabric_mod_port + ";\n" buf += " tpg->" + fabric_mod_port + "_tpgt = tpgt;\n\n" if proto_ident == "FC": buf += " ret = core_tpg_register(wwn, &tpg->se_tpg, SCSI_PROTOCOL_FCP);\n" elif proto_ident == "SAS": buf += " ret = core_tpg_register(wwn, &tpg->se_tpg, SCSI_PROTOCOL_SAS);\n" elif proto_ident == "iSCSI": buf += " ret = core_tpg_register(wwn, &tpg->se_tpg, SCSI_PROTOCOL_ISCSI);\n" buf += " if (ret < 0) {\n" buf += " kfree(tpg);\n" buf += " return NULL;\n" buf += " }\n" buf += " return &tpg->se_tpg;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_tpg(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n\n" buf += " core_tpg_deregister(se_tpg);\n" buf += " kfree(tpg);\n" buf += "}\n\n" buf += "static struct se_wwn *" + fabric_mod_name + "_make_" + fabric_mod_port + "(\n" buf += " struct target_fabric_configfs *tf,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + ";\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " u64 wwpn = 0;\n\n" buf += " /* if (" + fabric_mod_name + "_parse_wwn(name, &wwpn, 1) < 0)\n" buf += " return ERR_PTR(-EINVAL); */\n\n" buf += " " + fabric_mod_port + " = kzalloc(sizeof(struct " + fabric_mod_name + "_" + fabric_mod_port + "), GFP_KERNEL);\n" buf += " if (!" + fabric_mod_port + ") {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_" + fabric_mod_port + "\");\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += " }\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " " + fabric_mod_port + "->" + fabric_mod_port + "_wwpn = wwpn;\n" buf += " /* " + fabric_mod_name + "_format_wwn(&" + fabric_mod_port + "->" + fabric_mod_port + "_name[0], " + fabric_mod_name.upper() + "_NAMELEN, wwpn); */\n\n" buf += " return &" + fabric_mod_port + "->" + fabric_mod_port + "_wwn;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_" + fabric_mod_port + "(struct se_wwn *wwn)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = container_of(wwn,\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + ", " + fabric_mod_port + "_wwn);\n" buf += " kfree(" + fabric_mod_port + ");\n" buf += "}\n\n" buf += "static ssize_t " + fabric_mod_name + "_wwn_show_attr_version(\n" buf += " struct target_fabric_configfs *tf,\n" buf += " char *page)\n" buf += "{\n" buf += " return sprintf(page, \"" + fabric_mod_name.upper() + " fabric module %s on %s/%s\"\n" buf += " \"on \"UTS_RELEASE\"\\n\", " + fabric_mod_name.upper() + "_VERSION, utsname()->sysname,\n" buf += " utsname()->machine);\n" buf += "}\n\n" buf += "TF_WWN_ATTR_RO(" + fabric_mod_name + ", version);\n\n" buf += "static struct configfs_attribute *" + fabric_mod_name + "_wwn_attrs[] = {\n" buf += " &" + fabric_mod_name + "_wwn_version.attr,\n" buf += " NULL,\n" buf += "};\n\n" buf += "static const struct target_core_fabric_ops " + fabric_mod_name + "_ops = {\n" buf += " .module = THIS_MODULE,\n" buf += " .name = \"" + fabric_mod_name + "\",\n" buf += " .get_fabric_name = " + fabric_mod_name + "_get_fabric_name,\n" buf += " .tpg_get_wwn = " + fabric_mod_name + "_get_fabric_wwn,\n" buf += " .tpg_get_tag = " + fabric_mod_name + "_get_tag,\n" buf += " .tpg_check_demo_mode = " + fabric_mod_name + "_check_false,\n" buf += " .tpg_check_demo_mode_cache = " + fabric_mod_name + "_check_true,\n" buf += " .tpg_check_demo_mode_write_protect = " + fabric_mod_name + "_check_true,\n" buf += " .tpg_check_prod_mode_write_protect = " + fabric_mod_name + "_check_false,\n" buf += " .tpg_get_inst_index = " + fabric_mod_name + "_tpg_get_inst_index,\n" buf += " .release_cmd = " + fabric_mod_name + "_release_cmd,\n" buf += " .shutdown_session = " + fabric_mod_name + "_shutdown_session,\n" buf += " .close_session = " + fabric_mod_name + "_close_session,\n" buf += " .sess_get_index = " + fabric_mod_name + "_sess_get_index,\n" buf += " .sess_get_initiator_sid = NULL,\n" buf += " .write_pending = " + fabric_mod_name + "_write_pending,\n" buf += " .write_pending_status = " + fabric_mod_name + "_write_pending_status,\n" buf += " .set_default_node_attributes = " + fabric_mod_name + "_set_default_node_attrs,\n" buf += " .get_cmd_state = " + fabric_mod_name + "_get_cmd_state,\n" buf += " .queue_data_in = " + fabric_mod_name + "_queue_data_in,\n" buf += " .queue_status = " + fabric_mod_name + "_queue_status,\n" buf += " .queue_tm_rsp = " + fabric_mod_name + "_queue_tm_rsp,\n" buf += " .aborted_task = " + fabric_mod_name + "_aborted_task,\n" buf += " /*\n" buf += " * Setup function pointers for generic logic in target_core_fabric_configfs.c\n" buf += " */\n" buf += " .fabric_make_wwn = " + fabric_mod_name + "_make_" + fabric_mod_port + ",\n" buf += " .fabric_drop_wwn = " + fabric_mod_name + "_drop_" + fabric_mod_port + ",\n" buf += " .fabric_make_tpg = " + fabric_mod_name + "_make_tpg,\n" buf += " .fabric_drop_tpg = " + fabric_mod_name + "_drop_tpg,\n" buf += "\n" buf += " .tfc_wwn_attrs = " + fabric_mod_name + "_wwn_attrs,\n" buf += "};\n\n" buf += "static int __init " + fabric_mod_name + "_init(void)\n" buf += "{\n" buf += " return target_register_template(&" + fabric_mod_name + "_ops);\n" buf += "};\n\n" buf += "static void __exit " + fabric_mod_name + "_exit(void)\n" buf += "{\n" buf += " target_unregister_template(&" + fabric_mod_name + "_ops);\n" buf += "};\n\n" buf += "MODULE_DESCRIPTION(\"" + fabric_mod_name.upper() + " series fabric driver\");\n" buf += "MODULE_LICENSE(\"GPL\");\n" buf += "module_init(" + fabric_mod_name + "_init);\n" buf += "module_exit(" + fabric_mod_name + "_exit);\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_scan_fabric_ops(tcm_dir): fabric_ops_api = tcm_dir + "include/target/target_core_fabric.h" print "Using tcm_mod_scan_fabric_ops: " + fabric_ops_api process_fo = 0; p = open(fabric_ops_api, 'r') line = p.readline() while line: if process_fo == 0 and re.search('struct target_core_fabric_ops {', line): line = p.readline() continue if process_fo == 0: process_fo = 1; line = p.readline() # Search for function pointer if not re.search('\(\*', line): continue fabric_ops.append(line.rstrip()) continue line = p.readline() # Search for function pointer if not re.search('\(\*', line): continue fabric_ops.append(line.rstrip()) p.close() return def tcm_mod_dump_fabric_ops(proto_ident, fabric_mod_dir_var, fabric_mod_name): buf = "" bufi = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_fabric.c" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) fi = fabric_mod_dir_var + "/" + fabric_mod_name + "_fabric.h" print "Writing file: " + fi pi = open(fi, 'w') if not pi: tcm_mod_err("Unable to open file: " + fi) buf = "#include <linux/slab.h>\n" buf += "#include <linux/kthread.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/list.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/string.h>\n" buf += "#include <linux/ctype.h>\n" buf += "#include <asm/unaligned.h>\n" buf += "#include <scsi/scsi_common.h>\n" buf += "#include <scsi/scsi_proto.h>\n" buf += "#include <target/target_core_base.h>\n" buf += "#include <target/target_core_fabric.h>\n" buf += "#include \"" + fabric_mod_name + "_base.h\"\n" buf += "#include \"" + fabric_mod_name + "_fabric.h\"\n\n" buf += "int " + fabric_mod_name + "_check_true(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_check_true(struct se_portal_group *);\n" buf += "int " + fabric_mod_name + "_check_false(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_check_false(struct se_portal_group *);\n" total_fabric_ops = len(fabric_ops) i = 0 while i < total_fabric_ops: fo = fabric_ops[i] i += 1 # print "fabric_ops: " + fo if re.search('get_fabric_name', fo): buf += "char *" + fabric_mod_name + "_get_fabric_name(void)\n" buf += "{\n" buf += " return \"" + fabric_mod_name + "\";\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_get_fabric_name(void);\n" continue if re.search('get_wwn', fo): buf += "char *" + fabric_mod_name + "_get_fabric_wwn(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n\n" buf += " return &" + fabric_mod_port + "->" + fabric_mod_port + "_name[0];\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_get_fabric_wwn(struct se_portal_group *);\n" if re.search('get_tag', fo): buf += "u16 " + fabric_mod_name + "_get_tag(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " return tpg->" + fabric_mod_port + "_tpgt;\n" buf += "}\n\n" bufi += "u16 " + fabric_mod_name + "_get_tag(struct se_portal_group *);\n" if re.search('tpg_get_inst_index\)\(', fo): buf += "u32 " + fabric_mod_name + "_tpg_get_inst_index(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_tpg_get_inst_index(struct se_portal_group *);\n" if re.search('\*release_cmd\)\(', fo): buf += "void " + fabric_mod_name + "_release_cmd(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_release_cmd(struct se_cmd *);\n" if re.search('shutdown_session\)\(', fo): buf += "int " + fabric_mod_name + "_shutdown_session(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_shutdown_session(struct se_session *);\n" if re.search('close_session\)\(', fo): buf += "void " + fabric_mod_name + "_close_session(struct se_session *se_sess)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_close_session(struct se_session *);\n" if re.search('sess_get_index\)\(', fo): buf += "u32 " + fabric_mod_name + "_sess_get_index(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_sess_get_index(struct se_session *);\n" if re.search('write_pending\)\(', fo): buf += "int " + fabric_mod_name + "_write_pending(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_write_pending(struct se_cmd *);\n" if re.search('write_pending_status\)\(', fo): buf += "int " + fabric_mod_name + "_write_pending_status(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_write_pending_status(struct se_cmd *);\n" if re.search('set_default_node_attributes\)\(', fo): buf += "void " + fabric_mod_name + "_set_default_node_attrs(struct se_node_acl *nacl)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_set_default_node_attrs(struct se_node_acl *);\n" if re.search('get_cmd_state\)\(', fo): buf += "int " + fabric_mod_name + "_get_cmd_state(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_get_cmd_state(struct se_cmd *);\n" if re.search('queue_data_in\)\(', fo): buf += "int " + fabric_mod_name + "_queue_data_in(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_data_in(struct se_cmd *);\n" if re.search('queue_status\)\(', fo): buf += "int " + fabric_mod_name + "_queue_status(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_status(struct se_cmd *);\n" if re.search('queue_tm_rsp\)\(', fo): buf += "void " + fabric_mod_name + "_queue_tm_rsp(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_queue_tm_rsp(struct se_cmd *);\n" if re.search('aborted_task\)\(', fo): buf += "void " + fabric_mod_name + "_aborted_task(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_aborted_task(struct se_cmd *);\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() ret = pi.write(bufi) if ret: tcm_mod_err("Unable to write fi: " + fi) pi.close() return def tcm_mod_build_kbuild(fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/Makefile" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) buf += fabric_mod_name + "-objs := " + fabric_mod_name + "_fabric.o \\\n" buf += " " + fabric_mod_name + "_configfs.o\n" buf += "obj-$(CONFIG_" + fabric_mod_name.upper() + ") += " + fabric_mod_name + ".o\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_build_kconfig(fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/Kconfig" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) buf = "config " + fabric_mod_name.upper() + "\n" buf += " tristate \"" + fabric_mod_name.upper() + " fabric module\"\n" buf += " depends on TARGET_CORE && CONFIGFS_FS\n" buf += " default n\n" buf += " ---help---\n" buf += " Say Y here to enable the " + fabric_mod_name.upper() + " fabric module\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_add_kbuild(tcm_dir, fabric_mod_name): buf = "obj-$(CONFIG_" + fabric_mod_name.upper() + ") += " + fabric_mod_name.lower() + "/\n" kbuild = tcm_dir + "/drivers/target/Makefile" f = open(kbuild, 'a') f.write(buf) f.close() return def tcm_mod_add_kconfig(tcm_dir, fabric_mod_name): buf = "source \"drivers/target/" + fabric_mod_name.lower() + "/Kconfig\"\n" kconfig = tcm_dir + "/drivers/target/Kconfig" f = open(kconfig, 'a') f.write(buf) f.close() return def main(modname, proto_ident): # proto_ident = "FC" # proto_ident = "SAS" # proto_ident = "iSCSI" tcm_dir = os.getcwd(); tcm_dir += "/../../" print "tcm_dir: " + tcm_dir fabric_mod_name = modname fabric_mod_dir = tcm_dir + "drivers/target/" + fabric_mod_name print "Set fabric_mod_name: " + fabric_mod_name print "Set fabric_mod_dir: " + fabric_mod_dir print "Using proto_ident: " + proto_ident if proto_ident != "FC" and proto_ident != "SAS" and proto_ident != "iSCSI": print "Unsupported proto_ident: " + proto_ident sys.exit(1) ret = tcm_mod_create_module_subdir(fabric_mod_dir) if ret: print "tcm_mod_create_module_subdir() failed because module already exists!" sys.exit(1) tcm_mod_build_base_includes(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_scan_fabric_ops(tcm_dir) tcm_mod_dump_fabric_ops(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_build_configfs(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_build_kbuild(fabric_mod_dir, fabric_mod_name) tcm_mod_build_kconfig(fabric_mod_dir, fabric_mod_name) input = raw_input("Would you like to add " + fabric_mod_name + " to drivers/target/Makefile..? [yes,no]: ") if input == "yes" or input == "y": tcm_mod_add_kbuild(tcm_dir, fabric_mod_name) input = raw_input("Would you like to add " + fabric_mod_name + " to drivers/target/Kconfig..? [yes,no]: ") if input == "yes" or input == "y": tcm_mod_add_kconfig(tcm_dir, fabric_mod_name) return parser = optparse.OptionParser() parser.add_option('-m', '--modulename', help='Module name', dest='modname', action='store', nargs=1, type='string') parser.add_option('-p', '--protoident', help='Protocol Ident', dest='protoident', action='store', nargs=1, type='string') (opts, args) = parser.parse_args() mandatories = ['modname', 'protoident'] for m in mandatories: if not opts.__dict__[m]: print "mandatory option is missing\n" parser.print_help() exit(-1) if __name__ == "__main__": main(str(opts.modname), opts.protoident)
adieu/django-nonrel
refs/heads/master
tests/modeltests/mutually_referential/models.py
92
""" 24. Mutually referential many-to-one relationships Strings can be used instead of model literals to set up "lazy" relations. """ from django.db.models import * class Parent(Model): name = CharField(max_length=100) # Use a simple string for forward declarations. bestchild = ForeignKey("Child", null=True, related_name="favoured_by") class Child(Model): name = CharField(max_length=100) # You can also explicitally specify the related app. parent = ForeignKey("mutually_referential.Parent")
linuxmcu/ardupilot
refs/heads/master
Tools/LogAnalyzer/tests/TestAutotune.py
265
from LogAnalyzer import Test,TestResult import DataflashLog # from ArduCopter/defines.h AUTOTUNE_INITIALISED = 30 AUTOTUNE_OFF = 31 AUTOTUNE_RESTART = 32 AUTOTUNE_SUCCESS = 33 AUTOTUNE_FAILED = 34 AUTOTUNE_REACHED_LIMIT = 35 AUTOTUNE_PILOT_TESTING = 36 AUTOTUNE_SAVEDGAINS = 37 AUTOTUNE_EVENTS = frozenset([AUTOTUNE_INITIALISED, AUTOTUNE_OFF, AUTOTUNE_RESTART, AUTOTUNE_SUCCESS, AUTOTUNE_FAILED, AUTOTUNE_REACHED_LIMIT, AUTOTUNE_PILOT_TESTING, AUTOTUNE_SAVEDGAINS]) class TestAutotune(Test): '''test for autotune success (copter only)''' class AutotuneSession(object): def __init__(self, events): self.events = events @property def linestart(self): return self.events[0][0] @property def linestop(self): return self.events[-1][0] @property def success(self): return AUTOTUNE_SUCCESS in [i for _,i in self.events] @property def failure(self): return AUTOTUNE_FAILED in [i for _,i in self.events] @property def limit(self): return AUTOTUNE_REACHED_LIMIT in [i for _,i in self.events] def __repr__(self): return "<AutotuneSession {}-{}>".format(self.linestart,self.linestop) def __init__(self): Test.__init__(self) self.name = "Autotune" def run(self, logdata, verbose): self.result = TestResult() self.result.status = TestResult.StatusType.GOOD if logdata.vehicleType != "ArduCopter": self.result.status = TestResult.StatusType.NA return for i in ['EV','ATDE','ATUN']: r = False if not i in logdata.channels: self.result.status = TestResult.StatusType.UNKNOWN self.result.statusMessage = "No {} log data".format(i) r = True if r: return events = filter(lambda x: x[1] in AUTOTUNE_EVENTS, logdata.channels["EV"]["Id"].listData) attempts = [] j = None for i in range(0,len(events)): line,ev = events[i] if ev == AUTOTUNE_INITIALISED: if j is not None: attempts.append(TestAutotune.AutotuneSession(events[j:i])) j = i # last attempt if j is not None: attempts.append(TestAutotune.AutotuneSession(events[j:])) for a in attempts: # this should not be necessary! def class_from_channel(c): members = dict({'__init__':lambda x: setattr(x,i,None) for i in logdata.channels[c]}) cls = type(\ 'Channel__{:s}'.format(c), (object,), members ) return cls # last wins if a.success: self.result.status = TestResult.StatusType.GOOD s = "[+]" elif a.failure: self.result.status = TestResult.StatusType.FAIL s = "[-]" else: self.result.status = TestResult.StatusType.UNKNOWN s = "[?]" s += " Autotune {}-{}\n".format(a.linestart,a.linestop) self.result.statusMessage += s if verbose: linenext = a.linestart + 1 while linenext < a.linestop: try: line = logdata.channels['ATUN']['RateMax'].getNearestValueFwd(linenext)[1] if line > a.linestop: break except: break atun = class_from_channel('ATUN')() for key in logdata.channels['ATUN']: setattr(atun, key, logdata.channels['ATUN'][key].getNearestValueFwd(linenext)[0]) linenext = logdata.channels['ATUN'][key].getNearestValueFwd(linenext)[1] + 1 self.result.statusMessage += 'ATUN Axis:{atun.Axis} TuneStep:{atun.TuneStep} RateMin:{atun.RateMin:5.0f} RateMax:{atun.RateMax:5.0f} RPGain:{atun.RPGain:1.4f} RDGain:{atun.RDGain:1.4f} SPGain:{atun.SPGain:1.1f} (@line:{l})\n'.format(l=linenext,s=s, atun=atun) self.result.statusMessage += '\n'
ZipperCoin/zippercoin
refs/heads/master
share/qt/extract_strings_qt.py
2945
#!/usr/bin/python ''' Extract _("...") strings for translation and convert to Qt4 stringdefs so that they can be picked up by Qt linguist. ''' from subprocess import Popen, PIPE import glob import operator OUT_CPP="src/qt/bitcoinstrings.cpp" EMPTY=['""'] def parse_po(text): """ Parse 'po' format produced by xgettext. Return a list of (msgid,msgstr) tuples. """ messages = [] msgid = [] msgstr = [] in_msgid = False in_msgstr = False for line in text.split('\n'): line = line.rstrip('\r') if line.startswith('msgid '): if in_msgstr: messages.append((msgid, msgstr)) in_msgstr = False # message start in_msgid = True msgid = [line[6:]] elif line.startswith('msgstr '): in_msgid = False in_msgstr = True msgstr = [line[7:]] elif line.startswith('"'): if in_msgid: msgid.append(line) if in_msgstr: msgstr.append(line) if in_msgstr: messages.append((msgid, msgstr)) return messages files = glob.glob('src/*.cpp') + glob.glob('src/*.h') # xgettext -n --keyword=_ $FILES child = Popen(['xgettext','--output=-','-n','--keyword=_'] + files, stdout=PIPE) (out, err) = child.communicate() messages = parse_po(out) f = open(OUT_CPP, 'w') f.write("""#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif """) f.write('static const char UNUSED *bitcoin_strings[] = {\n') messages.sort(key=operator.itemgetter(0)) for (msgid, msgstr) in messages: if msgid != EMPTY: f.write('QT_TRANSLATE_NOOP("bitcoin-core", %s),\n' % ('\n'.join(msgid))) f.write('};') f.close()
RohitDas/cubeproject
refs/heads/master
lib/django/contrib/gis/management/commands/ogrinspect.py
111
import argparse import inspect from django.contrib.gis import gdal from django.core.management.base import BaseCommand, CommandError class LayerOptionAction(argparse.Action): """ Custom argparse action for the `ogrinspect` `layer_key` keyword option which may be an integer or a string. """ def __call__(self, parser, namespace, value, option_string=None): try: setattr(namespace, self.dest, int(value)) except ValueError: setattr(namespace, self.dest, value) class ListOptionAction(argparse.Action): """ Custom argparse action for `ogrinspect` keywords that require a string list. If the string is 'True'/'true' then the option value will be a boolean instead. """ def __call__(self, parser, namespace, value, option_string=None): if value.lower() == 'true': setattr(namespace, self.dest, True) else: setattr(namespace, self.dest, value.split(',')) class Command(BaseCommand): help = ('Inspects the given OGR-compatible data source (e.g., a shapefile) and outputs\n' 'a GeoDjango model with the given model name. For example:\n' ' ./manage.py ogrinspect zipcode.shp Zipcode') requires_system_checks = False def add_arguments(self, parser): parser.add_argument('data_source', help='Path to the data source.') parser.add_argument('model_name', help='Name of the model to create.') parser.add_argument('--blank', dest='blank', action=ListOptionAction, default=False, help='Use a comma separated list of OGR field names to add ' 'the `blank=True` option to the field definition. Set to `true` ' 'to apply to all applicable fields.') parser.add_argument('--decimal', dest='decimal', action=ListOptionAction, default=False, help='Use a comma separated list of OGR float fields to ' 'generate `DecimalField` instead of the default ' '`FloatField`. Set to `true` to apply to all OGR float fields.') parser.add_argument('--geom-name', dest='geom_name', default='geom', help='Specifies the model name for the Geometry Field ' '(defaults to `geom`)') parser.add_argument('--layer', dest='layer_key', action=LayerOptionAction, default=0, help='The key for specifying which layer in the OGR data ' 'source to use. Defaults to 0 (the first layer). May be ' 'an integer or a string identifier for the layer.') parser.add_argument('--multi-geom', action='store_true', dest='multi_geom', default=False, help='Treat the geometry in the data source as a geometry collection.') parser.add_argument('--name-field', dest='name_field', help='Specifies a field name to return for the `__unicode__`/`__str__` function.') parser.add_argument('--no-imports', action='store_false', dest='imports', default=True, help='Do not include `from django.contrib.gis.db import models` statement.') parser.add_argument('--null', dest='null', action=ListOptionAction, default=False, help='Use a comma separated list of OGR field names to add ' 'the `null=True` option to the field definition. Set to `true` ' 'to apply to all applicable fields.') parser.add_argument('--srid', dest='srid', help='The SRID to use for the Geometry Field. If it can be ' 'determined, the SRID of the data source is used.') parser.add_argument('--mapping', action='store_true', dest='mapping', help='Generate mapping dictionary for use with `LayerMapping`.') def handle(self, *args, **options): data_source, model_name = options.pop('data_source'), options.pop('model_name') if not gdal.HAS_GDAL: raise CommandError('GDAL is required to inspect geospatial data sources.') # Getting the OGR DataSource from the string parameter. try: ds = gdal.DataSource(data_source) except gdal.GDALException as msg: raise CommandError(msg) # Returning the output of ogrinspect with the given arguments # and options. from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping # Filter options to params accepted by `_ogrinspect` ogr_options = {k: v for k, v in options.items() if k in inspect.getargspec(_ogrinspect).args and v is not None} output = [s for s in _ogrinspect(ds, model_name, **ogr_options)] if options['mapping']: # Constructing the keyword arguments for `mapping`, and # calling it on the data source. kwargs = {'geom_name': options['geom_name'], 'layer_key': options['layer_key'], 'multi_geom': options['multi_geom'], } mapping_dict = mapping(ds, **kwargs) # This extra legwork is so that the dictionary definition comes # out in the same order as the fields in the model definition. rev_mapping = {v: k for k, v in mapping_dict.items()} output.extend(['', '# Auto-generated `LayerMapping` dictionary for %s model' % model_name, '%s_mapping = {' % model_name.lower()]) output.extend(" '%s' : '%s'," % ( rev_mapping[ogr_fld], ogr_fld) for ogr_fld in ds[options['layer_key']].fields ) output.extend([" '%s' : '%s'," % (options['geom_name'], mapping_dict[options['geom_name']]), '}']) return '\n'.join(output) + '\n'
BBN-Q/pyqgl2
refs/heads/master
src/python/pyqgl2/ast_qgl2.py
1
# Copyright 2016 by Raytheon BBN Technologies Corp. All Rights Reserved. """ AST utilities related to QGL2 nodes (primarily with-statements) """ import ast import os import sys from pyqgl2.debugmsg import DebugMsg from pyqgl2.lang import QGL2 def is_with_label(node, label): """ Return True if the given node is a with-statement that has as its "item", an ast.Name with the given label, else False A with-statement may have multiple items, but we ignore this and only consider the first. TODO: we should reject with-statements that have more than one item (although they are perfectly valid to Python, they cannot be valid as QGL2 statements). """ if not node: DebugMsg.log('unexpected None node', level=DebugMsg.ALL) return False elif not isinstance(node, ast.With): # DebugMsg.log('unexpected non-With node', level=DebugMsg.ALL) return False item = node.items[0].context_expr if not isinstance(item, ast.Name): return False elif item.id != label: return False else: return True def is_with_call(node, funcname): """ Return True if the given node is a with-statement that has as its "item", an ast.Call to a function with the given funcname, else False A with-statement may have multiple items, but we ignore this and only consider the first. TODO: we should reject with-statements that have more than one item (although they are perfectly valid to Python, they cannot be valid as QGL2 statements). """ if not node: DebugMsg.log('unexpected None node', level=DebugMsg.ALL) return False elif not isinstance(node, ast.With): # DebugMsg.log('unexpected non-With node', level=DebugMsg.ALL) return False item = node.items[0].context_expr if not isinstance(item, ast.Call): return False elif not isinstance(item.func, ast.Name): return False elif item.func.id != funcname: return False else: return True def is_concur(node): """ Returns True if the node is a with-concur statement, False otherwise. A convenience wrapper for is_with_label. """ return is_with_label(node, QGL2.QCONCUR) def is_infunc(node): """ Return True if the node is a with-infunc statement, False otherwise. A convenience wrapper for is_with_call. """ return is_with_call(node, QGL2.QINFUNC) def is_seq(node): """ Return True if the node is a with-seq statement, False otherwise. TODO: determine whetehr this is still used anywhere. It's probably dead. """ return is_with_label(node, QGL2.QSEQ)
BDAsdeCorazones/TestAirlines
refs/heads/master
tabo/cherrypy/cherrypy/test/test_wsgi_ns.py
22
import cherrypy from cherrypy._cpcompat import ntob from cherrypy.test import helper class WSGI_Namespace_Test(helper.CPWebCase): def setup_server(): class WSGIResponse(object): def __init__(self, appresults): self.appresults = appresults self.iter = iter(appresults) def __iter__(self): return self def next(self): return self.iter.next() def __next__(self): return next(self.iter) def close(self): if hasattr(self.appresults, "close"): self.appresults.close() class ChangeCase(object): def __init__(self, app, to=None): self.app = app self.to = to def __call__(self, environ, start_response): res = self.app(environ, start_response) class CaseResults(WSGIResponse): def next(this): return getattr(this.iter.next(), self.to)() def __next__(this): return getattr(next(this.iter), self.to)() return CaseResults(res) class Replacer(object): def __init__(self, app, map={}): self.app = app self.map = map def __call__(self, environ, start_response): res = self.app(environ, start_response) class ReplaceResults(WSGIResponse): def next(this): line = this.iter.next() for k, v in self.map.iteritems(): line = line.replace(k, v) return line def __next__(this): line = next(this.iter) for k, v in self.map.items(): line = line.replace(k, v) return line return ReplaceResults(res) class Root(object): def index(self): return "HellO WoRlD!" index.exposed = True root_conf = {'wsgi.pipeline': [('replace', Replacer)], 'wsgi.replace.map': {ntob('L'): ntob('X'), ntob('l'): ntob('r')}, } app = cherrypy.Application(Root()) app.wsgiapp.pipeline.append(('changecase', ChangeCase)) app.wsgiapp.config['changecase'] = {'to': 'upper'} cherrypy.tree.mount(app, config={'/': root_conf}) setup_server = staticmethod(setup_server) def test_pipeline(self): if not cherrypy.server.httpserver: return self.skip() self.getPage("/") # If body is "HEXXO WORXD!", the middleware was applied out of order. self.assertBody("HERRO WORRD!")
eunchong/build
refs/heads/master
scripts/slave/apply_svn_patch.py
3
#!/usr/bin/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. """Apply a Subversion patch to the checkout. This script can optionally pass the patch contents through an external filter script to alter the contents. As this script involves multiple subprocesses, the exit code of this script is a result of the different subprocess exit codes. Each failing subprocess will get its exit code printed to stdout and add a unique number to the script's combined exit code (in order to make debugging easier). """ import optparse import subprocess import sys SVN_CAT_FAILED = 1 << 0 FILTERING_FAILED = 1 << 1 PATCH_FAILED = 1 << 2 def main(): parser = optparse.OptionParser() parser.add_option('-p', '--patch-url', help='The SVN URL to download the patch from.') parser.add_option('-r', '--root-dir', help='The root dir in which to apply patch.') parser.add_option('', '--filter-script', help=('Path to a Python script to be used to manipulate ' 'the contents of the patch. One example could be to ' 'remove parts of the patch matching certain file ' 'paths. The script must use stdin for input and ' 'stdout for output. To pass flags to the script, ' 'use: -- --flag1 --flag2')) parser.add_option('', '--strip-level', type='int', default=0, help=('The number of path components to be stripped from ' 'the filenames in the patch. Default: %default.')) options, args = parser.parse_args() if args and not options.filter_script: parser.error('Unused args: %s' % args) if not (options.patch_url and options.root_dir): parser.error('A patch URL and root directory should be specified.') svn_cat = subprocess.Popen(['svn', 'cat', options.patch_url], stdout=subprocess.PIPE) patch_input = svn_cat.stdout filtering = None if options.filter_script: extra_args = args or [] filtering = subprocess.Popen([sys.executable, options.filter_script] + extra_args, stdin=svn_cat.stdout, stdout=subprocess.PIPE, stderr=sys.stdout) patch_input = filtering.stdout patch = subprocess.Popen(['patch', '-t', '-p', str(options.strip_level), '-d', options.root_dir], stdin=patch_input) # Ensure we wait for the subprocesses to finish their execution and that we # check all their exit codes properly. procs = [('svn cat', svn_cat, SVN_CAT_FAILED)] if filtering: procs.append(('filtering', filtering, FILTERING_FAILED)) procs.append(('patch', patch, PATCH_FAILED)) patch.communicate() exit_code = 0 for name, proc, fail_code in procs: proc.wait() if proc.returncode != 0: print '%s subprocess failed. Exit code: %s' % (name, proc.returncode) exit_code += fail_code return exit_code if __name__ == '__main__': sys.exit(main())
darouwan/shadowsocks
refs/heads/master
shadowsocks/asyncdns.py
655
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014-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 socket import struct import re import logging from shadowsocks import common, lru_cache, eventloop, shell CACHE_SWEEP_INTERVAL = 30 VALID_HOSTNAME = re.compile(br"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE) common.patch_socket() # rfc1035 # format # +---------------------+ # | Header | # +---------------------+ # | Question | the question for the name server # +---------------------+ # | Answer | RRs answering the question # +---------------------+ # | Authority | RRs pointing toward an authority # +---------------------+ # | Additional | RRs holding additional information # +---------------------+ # # header # 1 1 1 1 1 1 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | ID | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # |QR| Opcode |AA|TC|RD|RA| Z | RCODE | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | QDCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | ANCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | NSCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | ARCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ QTYPE_ANY = 255 QTYPE_A = 1 QTYPE_AAAA = 28 QTYPE_CNAME = 5 QTYPE_NS = 2 QCLASS_IN = 1 def build_address(address): address = address.strip(b'.') labels = address.split(b'.') results = [] for label in labels: l = len(label) if l > 63: return None results.append(common.chr(l)) results.append(label) results.append(b'\0') return b''.join(results) def build_request(address, qtype): request_id = os.urandom(2) header = struct.pack('!BBHHHH', 1, 0, 1, 0, 0, 0) addr = build_address(address) qtype_qclass = struct.pack('!HH', qtype, QCLASS_IN) return request_id + header + addr + qtype_qclass def parse_ip(addrtype, data, length, offset): if addrtype == QTYPE_A: return socket.inet_ntop(socket.AF_INET, data[offset:offset + length]) elif addrtype == QTYPE_AAAA: return socket.inet_ntop(socket.AF_INET6, data[offset:offset + length]) elif addrtype in [QTYPE_CNAME, QTYPE_NS]: return parse_name(data, offset)[1] else: return data[offset:offset + length] def parse_name(data, offset): p = offset labels = [] l = common.ord(data[p]) while l > 0: if (l & (128 + 64)) == (128 + 64): # pointer pointer = struct.unpack('!H', data[p:p + 2])[0] pointer &= 0x3FFF r = parse_name(data, pointer) labels.append(r[1]) p += 2 # pointer is the end return p - offset, b'.'.join(labels) else: labels.append(data[p + 1:p + 1 + l]) p += 1 + l l = common.ord(data[p]) return p - offset + 1, b'.'.join(labels) # rfc1035 # record # 1 1 1 1 1 1 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | | # / / # / NAME / # | | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | TYPE | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | CLASS | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | TTL | # | | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | RDLENGTH | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--| # / RDATA / # / / # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ def parse_record(data, offset, question=False): nlen, name = parse_name(data, offset) if not question: record_type, record_class, record_ttl, record_rdlength = struct.unpack( '!HHiH', data[offset + nlen:offset + nlen + 10] ) ip = parse_ip(record_type, data, record_rdlength, offset + nlen + 10) return nlen + 10 + record_rdlength, \ (name, ip, record_type, record_class, record_ttl) else: record_type, record_class = struct.unpack( '!HH', data[offset + nlen:offset + nlen + 4] ) return nlen + 4, (name, None, record_type, record_class, None, None) def parse_header(data): if len(data) >= 12: header = struct.unpack('!HBBHHHH', data[:12]) res_id = header[0] res_qr = header[1] & 128 res_tc = header[1] & 2 res_ra = header[2] & 128 res_rcode = header[2] & 15 # assert res_tc == 0 # assert res_rcode in [0, 3] res_qdcount = header[3] res_ancount = header[4] res_nscount = header[5] res_arcount = header[6] return (res_id, res_qr, res_tc, res_ra, res_rcode, res_qdcount, res_ancount, res_nscount, res_arcount) return None def parse_response(data): try: if len(data) >= 12: header = parse_header(data) if not header: return None res_id, res_qr, res_tc, res_ra, res_rcode, res_qdcount, \ res_ancount, res_nscount, res_arcount = header qds = [] ans = [] offset = 12 for i in range(0, res_qdcount): l, r = parse_record(data, offset, True) offset += l if r: qds.append(r) for i in range(0, res_ancount): l, r = parse_record(data, offset) offset += l if r: ans.append(r) for i in range(0, res_nscount): l, r = parse_record(data, offset) offset += l for i in range(0, res_arcount): l, r = parse_record(data, offset) offset += l response = DNSResponse() if qds: response.hostname = qds[0][0] for an in qds: response.questions.append((an[1], an[2], an[3])) for an in ans: response.answers.append((an[1], an[2], an[3])) return response except Exception as e: shell.print_exception(e) return None def is_valid_hostname(hostname): if len(hostname) > 255: return False if hostname[-1] == b'.': hostname = hostname[:-1] return all(VALID_HOSTNAME.match(x) for x in hostname.split(b'.')) class DNSResponse(object): def __init__(self): self.hostname = None self.questions = [] # each: (addr, type, class) self.answers = [] # each: (addr, type, class) def __str__(self): return '%s: %s' % (self.hostname, str(self.answers)) STATUS_IPV4 = 0 STATUS_IPV6 = 1 class DNSResolver(object): def __init__(self, server_list=None): self._loop = None self._hosts = {} self._hostname_status = {} self._hostname_to_cb = {} self._cb_to_hostname = {} self._cache = lru_cache.LRUCache(timeout=300) self._sock = None if server_list is None: self._servers = None self._parse_resolv() else: self._servers = server_list self._parse_hosts() # TODO monitor hosts change and reload hosts # TODO parse /etc/gai.conf and follow its rules def _parse_resolv(self): self._servers = [] try: with open('/etc/resolv.conf', 'rb') as f: content = f.readlines() for line in content: line = line.strip() if line: if line.startswith(b'nameserver'): parts = line.split() if len(parts) >= 2: server = parts[1] if common.is_ip(server) == socket.AF_INET: if type(server) != str: server = server.decode('utf8') self._servers.append(server) except IOError: pass if not self._servers: self._servers = ['8.8.4.4', '8.8.8.8'] def _parse_hosts(self): etc_path = '/etc/hosts' if 'WINDIR' in os.environ: etc_path = os.environ['WINDIR'] + '/system32/drivers/etc/hosts' try: with open(etc_path, 'rb') as f: for line in f.readlines(): line = line.strip() parts = line.split() if len(parts) >= 2: ip = parts[0] if common.is_ip(ip): for i in range(1, len(parts)): hostname = parts[i] if hostname: self._hosts[hostname] = ip except IOError: self._hosts['localhost'] = '127.0.0.1' def add_to_loop(self, loop): if self._loop: raise Exception('already add to loop') self._loop = loop # TODO when dns server is IPv6 self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.SOL_UDP) self._sock.setblocking(False) loop.add(self._sock, eventloop.POLL_IN, self) loop.add_periodic(self.handle_periodic) def _call_callback(self, hostname, ip, error=None): callbacks = self._hostname_to_cb.get(hostname, []) for callback in callbacks: if callback in self._cb_to_hostname: del self._cb_to_hostname[callback] if ip or error: callback((hostname, ip), error) else: callback((hostname, None), Exception('unknown hostname %s' % hostname)) if hostname in self._hostname_to_cb: del self._hostname_to_cb[hostname] if hostname in self._hostname_status: del self._hostname_status[hostname] def _handle_data(self, data): response = parse_response(data) if response and response.hostname: hostname = response.hostname ip = None for answer in response.answers: if answer[1] in (QTYPE_A, QTYPE_AAAA) and \ answer[2] == QCLASS_IN: ip = answer[0] break if not ip and self._hostname_status.get(hostname, STATUS_IPV6) \ == STATUS_IPV4: self._hostname_status[hostname] = STATUS_IPV6 self._send_req(hostname, QTYPE_AAAA) else: if ip: self._cache[hostname] = ip self._call_callback(hostname, ip) elif self._hostname_status.get(hostname, None) == STATUS_IPV6: for question in response.questions: if question[1] == QTYPE_AAAA: self._call_callback(hostname, None) break def handle_event(self, sock, fd, event): if sock != self._sock: return if event & eventloop.POLL_ERR: logging.error('dns socket err') self._loop.remove(self._sock) self._sock.close() # TODO when dns server is IPv6 self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.SOL_UDP) self._sock.setblocking(False) self._loop.add(self._sock, eventloop.POLL_IN, self) else: data, addr = sock.recvfrom(1024) if addr[0] not in self._servers: logging.warn('received a packet other than our dns') return self._handle_data(data) def handle_periodic(self): self._cache.sweep() def remove_callback(self, callback): hostname = self._cb_to_hostname.get(callback) if hostname: del self._cb_to_hostname[callback] arr = self._hostname_to_cb.get(hostname, None) if arr: arr.remove(callback) if not arr: del self._hostname_to_cb[hostname] if hostname in self._hostname_status: del self._hostname_status[hostname] def _send_req(self, hostname, qtype): req = build_request(hostname, qtype) for server in self._servers: logging.debug('resolving %s with type %d using server %s', hostname, qtype, server) self._sock.sendto(req, (server, 53)) def resolve(self, hostname, callback): if type(hostname) != bytes: hostname = hostname.encode('utf8') if not hostname: callback(None, Exception('empty hostname')) elif common.is_ip(hostname): callback((hostname, hostname), None) elif hostname in self._hosts: logging.debug('hit hosts: %s', hostname) ip = self._hosts[hostname] callback((hostname, ip), None) elif hostname in self._cache: logging.debug('hit cache: %s', hostname) ip = self._cache[hostname] callback((hostname, ip), None) else: if not is_valid_hostname(hostname): callback(None, Exception('invalid hostname: %s' % hostname)) return arr = self._hostname_to_cb.get(hostname, None) if not arr: self._hostname_status[hostname] = STATUS_IPV4 self._send_req(hostname, QTYPE_A) self._hostname_to_cb[hostname] = [callback] self._cb_to_hostname[callback] = hostname else: arr.append(callback) # TODO send again only if waited too long self._send_req(hostname, QTYPE_A) def close(self): if self._sock: if self._loop: self._loop.remove_periodic(self.handle_periodic) self._loop.remove(self._sock) self._sock.close() self._sock = None def test(): dns_resolver = DNSResolver() loop = eventloop.EventLoop() dns_resolver.add_to_loop(loop) global counter counter = 0 def make_callback(): global counter def callback(result, error): global counter # TODO: what can we assert? print(result, error) counter += 1 if counter == 9: dns_resolver.close() loop.stop() a_callback = callback return a_callback assert(make_callback() != make_callback()) dns_resolver.resolve(b'google.com', make_callback()) dns_resolver.resolve('google.com', make_callback()) dns_resolver.resolve('example.com', make_callback()) dns_resolver.resolve('ipv6.google.com', make_callback()) dns_resolver.resolve('www.facebook.com', make_callback()) dns_resolver.resolve('ns2.google.com', make_callback()) dns_resolver.resolve('invalid.@!#$%^&$@.hostname', make_callback()) dns_resolver.resolve('toooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'long.hostname', make_callback()) dns_resolver.resolve('toooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'long.hostname', make_callback()) loop.run() if __name__ == '__main__': test()
j-dasilva/COMP4350
refs/heads/master
apartment/calendarPage/apps.py
1
from django.apps import AppConfig class CalendarpageConfig(AppConfig): name = 'calendarPage'
realzzt/BitCoin2013
refs/heads/master
contrib/devtools/fix-copyright-headers.py
1
#!/usr/bin/env python3 """ Run this script to update all the copyright headers of files that were changed this year. For example: // Copyright (c) 2009-2012 The Bitcoin Core developers it will change it to // Copyright (c) 2009-2015 The Bitcoin Core developers """ import subprocess import time import re CMD_GIT_LIST_FILES = ['git', 'ls-files'] CMD_GIT_DATE = ['git', 'log', '--format=%ad', '--date=short', '-1'] CMD_PERL_REGEX = ['perl', '-pi', '-e'] REGEX_TEMPLATE = 's/(20\\d\\d)(?:-20\\d\\d)? The Bitcoin/$1-%s The Bitcoin/' FOLDERS = ["qa/", "src/"] EXTENSIONS = [".cpp",".h", ".py"] def get_git_date(file_path): d = subprocess.run(CMD_GIT_DATE + [file_path], stdout=subprocess.PIPE, check=True, universal_newlines=True).stdout # yyyy-mm-dd return d.split('-')[0] def skip_file(file_path): for ext in EXTENSIONS: if file_path.endswith(ext): return False else: return True if __name__ == "__main__": year = str(time.gmtime()[0]) regex_current = re.compile("%s The Bitcoin" % year) n = 1 for folder in FOLDERS: for file_path in subprocess.run( CMD_GIT_LIST_FILES + [folder], stdout=subprocess.PIPE, check=True, universal_newlines=True ).stdout.split("\n"): if skip_file(file_path): # print(file_path, "(skip)") continue git_date = get_git_date(file_path) if not year == git_date: # print(file_path, year, "(skip)") continue if regex_current.search(open(file_path, "r").read()) is not None: # already up to date # print(file_path, year, "(skip)") continue print(n, file_path, "(update to %s)" % year) subprocess.run(CMD_PERL_REGEX + [REGEX_TEMPLATE % year, file_path], check=True) n = n + 1
maheshcn/memory-usage-from-ldfile
refs/heads/master
openpyxl/charts/tests/test_graph.py
2
from datetime import date class TestGraphChart: def test_ctor(self, GraphChart, Axis): c = GraphChart() assert isinstance(c.x_axis, Axis) assert isinstance(c.y_axis, Axis) def test_get_x_unit(self, GraphChart, series): c = GraphChart() c.append(series) assert c.get_x_units() == 10 def test_get_y_unit(self, GraphChart, series): c = GraphChart() c.append(series) c.y_axis.max = 10 assert c.get_y_units() == 190500 def test_get_y_char(self, GraphChart, series): c = GraphChart() c.append(series) assert c.get_y_chars() == 1 def test_compute_series_extremes(self, GraphChart, series): c = GraphChart() c.append(series) mini, maxi = c._get_extremes() assert mini == 0 assert maxi == 9 def test_compute_series_max_dates(self, ws, Reference, Series, GraphChart): for i in range(1, 10): ws.append([date(2013, i, 1)]) c = GraphChart() ref = Reference(ws, (1, 1), (10, 1)) series = Series(ref) c.append(series) mini, maxi = c._get_extremes() assert mini == 0 assert maxi == 41518.0 def test_override_axis(self, GraphChart, series): c = GraphChart() c.add_serie(series) c.compute_axes() assert c.y_axis.min == 0 assert c.y_axis.max == 10 c.y_axis.min = -1 c.y_axis.max = 5 assert c.y_axis.min == -2 assert c.y_axis.max == 6
iSoir/gnuGame
refs/heads/master
gnuGame/settings.py
1
""" Django settings for gnuGame project. Generated by 'django-admin startproject' using Django 1.9.5. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = 'staticfiles' STATIC_DIR = os.path.join(BASE_DIR, 'static') TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'kpk($zhqdwx4aadmoi-ci4212=m#&$+h!0vt3-zl4nzu7urw1)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'server', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'gnuGame.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'gnuGame.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = {} if os.getenv('SQLITE', False): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } else: DATABASE_URL = 'postgres://alumnodb:alumnodb@localhost:5432/gnuGame' DATABASES = { 'default': dj_database_url.config(default=DATABASE_URL) } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', ) # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR, ] LOGIN_URL = '/server/nologged/'
supergentle/migueltutorial
refs/heads/master
flask/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/mbcharsetprober.py
2923
######################## 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 # Proofpoint, Inc. # # 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 class MultiByteCharSetProber(CharSetProber): def __init__(self): CharSetProber.__init__(self) self._mDistributionAnalyzer = None self._mCodingSM = None self._mLastChar = [0, 0] def reset(self): CharSetProber.reset(self) if self._mCodingSM: self._mCodingSM.reset() if self._mDistributionAnalyzer: self._mDistributionAnalyzer.reset() self._mLastChar = [0, 0] def get_charset_name(self): pass def feed(self, aBuf): aLen = len(aBuf) for i in range(0, aLen): codingState = self._mCodingSM.next_state(aBuf[i]) if codingState == constants.eError: if constants._debug: sys.stderr.write(self.get_charset_name() + ' prober hit error at byte ' + str(i) + '\n') self._mState = constants.eNotMe break elif codingState == constants.eItsMe: self._mState = constants.eFoundIt break elif codingState == constants.eStart: charLen = self._mCodingSM.get_current_charlen() if i == 0: self._mLastChar[1] = aBuf[0] self._mDistributionAnalyzer.feed(self._mLastChar, charLen) else: self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mLastChar[0] = aBuf[aLen - 1] if self.get_state() == constants.eDetecting: if (self._mDistributionAnalyzer.got_enough_data() and (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): self._mState = constants.eFoundIt return self.get_state() def get_confidence(self): return self._mDistributionAnalyzer.get_confidence()
mscuthbert/abjad
refs/heads/master
abjad/tools/stringtools/to_accent_free_snake_case.py
2
# -*- encoding: utf-8 -*- import six from abjad.tools.stringtools.strip_diacritics import strip_diacritics def to_accent_free_snake_case(string): '''Changes `string` to accent-free snake case. .. container:: example :: >>> stringtools.to_accent_free_snake_case('Déja vu') 'deja_vu' Strips accents from accented characters. Changes all punctuation (including spaces) to underscore. Sets to lowercase. Returns string. ''' assert isinstance(string, six.string_types) result = strip_diacritics(string) result = result.replace(' ', '_') result = result.replace("'", '_') result = result.lower() return result