text
stringlengths
3
1.05M
const Path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const Webpack = require('webpack'); const Merge = require("webpack-merge"); const Common = require('./webpack.common.js'); const devDir = Path.resolve(Common.rootDir, 'dev-static'); const ScalaJs = Merge(Common.ScalaJs, { output: { publicPath: '/' } }); const Web = Merge(Common.Web, { output: { publicPath: '/' }, entry: { app: Path.resolve(Common.resourcesDir, './dev.js'), embedded: Path.resolve(Common.resourcesDir, './dev-embed.js') }, module: { rules: [ { test: /\.scss$/, use: [ "style-loader", "css-loader", "resolve-url-loader", "sass-loader?sourceMap" ] } ] }, devServer: { hot: true, contentBase: [ devDir, __dirname, Common.rootDir ], proxy: { "/***": { target: "http://localhost:9000", bypass: function(req, res, proxyOptions) { // regex matching snippet ids var homepage = /(\/[A-Za-z0-9]{22}|\/[A-Za-z0-9]{22}\/([A-Za-z0-9])*[/(0-9)*])/; var backendUrls = /(\/api\/|\/login|\/logout)/; if(!backendUrls.test(req.url)) { if (homepage.test(req.url)) { console.log("index: " + req.url); return "/"; } else { console.log("other: " + req.url); return req.url; } } else { console.log("proxied: " + req.url); } } } } }, plugins: [ new Webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ filename: "embed.html", chunks: ["embedded"], template: Path.resolve(Common.resourcesDir, './embed.html'), favicon: Path.resolve(Common.resourcesDir, './images/favicon.ico') }), new HtmlWebpackPlugin({ filename: "index.html", chunks: ["app"], template: Path.resolve(Common.resourcesDir, './index.html'), favicon: Path.resolve(Common.resourcesDir, './images/favicon.ico') }) ] }); module.exports = Merge( ScalaJs, Web );
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _connectField = require('uniforms/connectField'); var _connectField2 = _interopRequireDefault(_connectField); var _filterDOMProps = require('uniforms/filterDOMProps'); var _filterDOMProps2 = _interopRequireDefault(_filterDOMProps); var _injectName = require('uniforms/injectName'); var _injectName2 = _interopRequireDefault(_injectName); var _joinName = require('uniforms/joinName'); var _joinName2 = _interopRequireDefault(_joinName); var _AutoField = require('./AutoField'); var _AutoField2 = _interopRequireDefault(_AutoField); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var Nest = function Nest(_ref) { var children = _ref.children, fields = _ref.fields, itemProps = _ref.itemProps, label = _ref.label, name = _ref.name, props = _objectWithoutProperties(_ref, ['children', 'fields', 'itemProps', 'label', 'name']); return _react2.default.createElement( 'div', (0, _filterDOMProps2.default)(props), label && _react2.default.createElement( 'label', null, label ), children ? (0, _injectName2.default)(name, children) : fields.map(function (key) { return _react2.default.createElement(_AutoField2.default, _extends({ key: key, name: (0, _joinName2.default)(name, key) }, itemProps)); }) ); }; exports.default = (0, _connectField2.default)(Nest, { ensureValue: false, includeInChain: false });
#!/usr/bin/python # # linearize-data.py: Construct a linear, no-fork version of the chain. # # Copyright (c) 2013 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json import struct import re import os import base64 import httplib import sys import hashlib import datetime import time import ltc_scrypt settings = {} def uint32(x): return x & 0xffffffffL def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) def bufreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): word = struct.unpack('@I', in_buf[i:i+4])[0] out_words.append(struct.pack('@I', bytereverse(word))) return ''.join(out_words) def wordreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): out_words.append(in_buf[i:i+4]) out_words.reverse() return ''.join(out_words) def calc_hdr_hash(blk_hdr): hash1 = hashlib.sha256() hash1.update(blk_hdr) hash1_o = hash1.digest() hash2 = hashlib.sha256() hash2.update(hash1_o) hash2_o = hash2.digest() return hash2_o def calc_hash_str(blk_hdr): hash = calc_hdr_hash(blk_hdr) hash = bufreverse(hash) hash = wordreverse(hash) hash_str = hash.encode('hex') return hash_str def calc_scrypt_hash_str(blk_hdr): hash = ltc_scrypt.getPoWHash(blk_hdr) hash = bufreverse(hash) hash = wordreverse(hash) hash_str = hash.encode('hex') return hash_str def get_blk_dt(blk_hdr): mCreedTokens = struct.unpack("<I", blk_hdr[68:68+4]) nTime = mCreedTokens[0] dt = datetime.datetime.fromtimestamp(nTime) dt_ym = datetime.datetime(dt.year, dt.month, 1) return (dt_ym, nTime) def get_block_hashes(settings): blkindex = [] f = open(settings['hashlist'], "r") for line in f: line = line.rstrip() blkindex.append(line) print("Read " + str(len(blkindex)) + " hashes") return blkindex def mkblockset(blkindex): blkmap = {} for hash in blkindex: blkmap[hash] = True return blkmap def copydata(settings, blkindex, blkset): inFn = 1 inF = None outFn = 0 outsz = 0 outF = None outFname = None blkCount = 0 lastDate = datetime.datetime(2000, 1, 1) highTS = 1408893517 - 315360000 timestampSplit = False fileOutput = True setFileTime = False maxOutSz = settings['max_out_sz'] if 'output' in settings: fileOutput = False if settings['file_timestamp'] != 0: setFileTime = True if settings['split_timestamp'] != 0: timestampSplit = True while True: if not inF: fname = "%s/blk%04d.dat" % (settings['input'], inFn) print("Input file" + fname) try: inF = open(fname, "rb") except IOError: print "Done" return inhdr = inF.read(8) if (not inhdr or (inhdr[0] == "\0")): inF.close() inF = None inFn = inFn + 1 continue inMagic = inhdr[:4] if (inMagic != settings['netmagic']): print("Invalid magic:" + inMagic) return inLenLE = inhdr[4:] su = struct.unpack("<I", inLenLE) inLen = su[0] rawblock = inF.read(inLen) blk_hdr = rawblock[:80] hash_str = 0 if blkCount > 319000: hash_str = calc_hash_str(blk_hdr) else: hash_str = calc_scrypt_hash_str(blk_hdr) if not hash_str in blkset: print("Skipping unknown block " + hash_str) continue if blkindex[blkCount] != hash_str: print("Out of order block.") print("Expected " + blkindex[blkCount]) print("Got " + hash_str) sys.exit(1) if not fileOutput and ((outsz + inLen) > maxOutSz): outF.close() if setFileTime: os.utime(outFname, (int(time.time()), highTS)) outF = None outFname = None outFn = outFn + 1 outsz = 0 (blkDate, blkTS) = get_blk_dt(blk_hdr) if timestampSplit and (blkDate > lastDate): print("New month " + blkDate.strftime("%Y-%m") + " @ " + hash_str) lastDate = blkDate if outF: outF.close() if setFileTime: os.utime(outFname, (int(time.time()), highTS)) outF = None outFname = None outFn = outFn + 1 outsz = 0 if not outF: if fileOutput: outFname = settings['output_file'] else: outFname = "%s/blk%05d.dat" % (settings['output'], outFn) print("Output file" + outFname) outF = open(outFname, "wb") outF.write(inhdr) outF.write(rawblock) outsz = outsz + inLen + 8 blkCount = blkCount + 1 if blkTS > highTS: highTS = blkTS if (blkCount % 1000) == 0: print("Wrote " + str(blkCount) + " blocks") if __name__ == '__main__': if len(sys.argv) != 2: print "Usage: linearize-data.py CONFIG-FILE" sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() if 'netmagic' not in settings: settings['netmagic'] = '70352205' if 'input' not in settings: settings['input'] = 'input' if 'hashlist' not in settings: settings['hashlist'] = 'hashlist.txt' if 'file_timestamp' not in settings: settings['file_timestamp'] = 0 if 'split_timestamp' not in settings: settings['split_timestamp'] = 0 if 'max_out_sz' not in settings: settings['max_out_sz'] = 1000L * 1000 * 1000 settings['max_out_sz'] = long(settings['max_out_sz']) settings['split_timestamp'] = int(settings['split_timestamp']) settings['file_timestamp'] = int(settings['file_timestamp']) settings['netmagic'] = settings['netmagic'].decode('hex') if 'output_file' not in settings and 'output' not in settings: print("Missing output file / directory") sys.exit(1) blkindex = get_block_hashes(settings) blkset = mkblockset(blkindex) if not "000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563" in blkset: print("not found") else: copydata(settings, blkindex, blkset)
$(function() { $(".pesometros").keyup(function (event) { var total = 0; $(".pesometros").each(function () { var gtotal = 0; $(this).find(".pesometro").each(function () { var qty = parseInt($(this).find(".cantidad4").val()); var rate = parseInt($(this).find(".v_unitario4").val()); var subtotal = qty * rate; $(this).find(".subtotal4").val(subtotal); if (!isNaN(subtotal)) gtotal += subtotal; }); $(this).find(".totalpe").val(gtotal); total += gtotal }); }); });
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_NOTIFICATOR_H #define BITCOIN_QT_NOTIFICATOR_H #if defined(HAVE_CONFIG_H) #include "config/fss-config.h" #endif #include <QIcon> #include <QObject> QT_BEGIN_NAMESPACE class QSystemTrayIcon; #ifdef USE_DBUS class QDBusInterface; #endif QT_END_NAMESPACE /** Cross-platform desktop notification client. */ class Notificator : public QObject { Q_OBJECT public: /** Create a new notificator. @note Ownership of trayIcon is not transferred to this object. */ Notificator(const QString& programName, QSystemTrayIcon* trayIcon, QWidget* parent); ~Notificator(); // Message class enum Class { Information, /**< Informational message */ Warning, /**< Notify user of potential problem */ Critical /**< An error occurred */ }; public slots: /** Show notification message. @param[in] cls general message class @param[in] title title shown with message @param[in] text message content @param[in] icon optional icon to show with message @param[in] millisTimeout notification timeout in milliseconds (defaults to 10 seconds) @note Platform implementations are free to ignore any of the provided fields except for \a text. */ void notify(Class cls, const QString& title, const QString& text, const QIcon& icon = QIcon(), int millisTimeout = 10000); private: QWidget* parent; enum Mode { None, /**< Ignore informational notifications, and show a modal pop-up dialog for Critical notifications. */ Freedesktop, /**< Use DBus org.freedesktop.Notifications */ QSystemTray, /**< Use QSystemTray::showMessage */ Growl12, /**< Use the Growl 1.2 notification system (Mac only) */ Growl13, /**< Use the Growl 1.3 notification system (Mac only) */ UserNotificationCenter /**< Use the 10.8+ User Notification Center (Mac only) */ }; QString programName; Mode mode; QSystemTrayIcon* trayIcon; #ifdef USE_DBUS QDBusInterface* interface; void notifyDBus(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout); #endif void notifySystray(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout); #ifdef Q_OS_MAC void notifyGrowl(Class cls, const QString& title, const QString& text, const QIcon& icon); void notifyMacUserNotificationCenter(Class cls, const QString& title, const QString& text, const QIcon& icon); #endif }; #endif // BITCOIN_QT_NOTIFICATOR_H
#!/usr/bin/env python import os import json def compile_contests_table(): """ supposed to run from /py directory """ os.chdir('../contests') compiled_contests_table = "" for file in filter(lambda _: os.path.splitext(_)[1] == '.json', os.listdir()): contest = json.loads(open(file, 'r', encoding='utf-8').read()) assert contest['type'] == 'contest' compiled_contests_table += f''' <tr contest-id="{contest['id']}"> <td class="contest-number-column"><a href="/MathForces/contests/{contest['id']}_t.html">{contest['id']}</a></td> <td class="contest-name-column"><a href="/MathForces/contests/{contest['id']}_t.html">{contest['name']}</a></td> <td class="contest-start-time-column">{contest['start_time'].replace(', ', '<br>')}</td> <td class="contest-duration-column">{contest['duration'].zfill(5)}</td> </tr> ''' # update index: index_lines = open('index.html', 'r', encoding='utf-8').readlines() table_body_start = index_lines.index(' <tbody id="contests-table-body">\n') table_body_end = index_lines.index(' </tbody>\n') index_lines = index_lines[:table_body_start + 1] + [compiled_contests_table, ] + index_lines[table_body_end:] open('index.html', 'w', encoding='utf-8').writelines(index_lines) os.chdir('../py') if __name__ == '__main__': compile_contests_table() # autoupdate on GitHub Pages: os.system('git add . && git commit -m "Recompiled contests table" && git push')
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The audio part of VoxCeleb dataset.""" import collections import os import tensorflow as tf import tensorflow_datasets.public_api as tfds _CITATION = """ @InProceedings{Nagrani17, author = "Nagrani, A. and Chung, J.~S. and Zisserman, A.", title = "VoxCeleb: a large-scale speaker identification dataset", booktitle = "INTERSPEECH", year = "2017", } """ _DESCRIPTION = """ An large scale dataset for speaker identification. This data is collected from over 1,251 speakers, with over 150k samples in total. This release contains the audio part of the voxceleb1.1 dataset. """ _HOMEPAGE = 'http://www.robots.ox.ac.uk/~vgg/data/voxceleb/vox1.html' IDEN_SPLITS_URL = 'http://www.robots.ox.ac.uk/~vgg/data/voxceleb/meta/iden_split.txt' NUM_CLASSES = 1252 class Voxceleb(tfds.core.GeneratorBasedBuilder): """The VoxCeleb dataset for speaker identification.""" VERSION = tfds.core.Version('1.2.1') RELEASE_NOTES = {'1.2.1': 'Add youtube_id field'} MANUAL_DOWNLOAD_INSTRUCTIONS = """ manual_dir should contain the file vox_dev_wav.zip. The instructions for downloading this file are found in {}. This dataset requires registration. """.format(_HOMEPAGE) def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ 'audio': tfds.features.Audio(file_format='wav', sample_rate=16000), 'label': tfds.features.ClassLabel(num_classes=NUM_CLASSES), 'youtube_id': tfds.features.Text(), }), supervised_keys=('audio', 'label'), homepage=_HOMEPAGE, citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" zip_path = os.path.join(dl_manager.manual_dir, 'vox_dev_wav.zip') if not tf.io.gfile.exists(zip_path): raise AssertionError( 'VoxCeleb requires manual download of the data. Please download ' 'the audio data and place it into: {}'.format(zip_path)) # Need to extract instead of reading directly from archive since reading # audio files from zip archive is not supported. extract_path = dl_manager.extract(zip_path) # Download the file defining the train/validation/test split on speakers. iden_splits_path = dl_manager.download({'iden_split': IDEN_SPLITS_URL}) iden_splits = self._calculate_splits(iden_splits_path['iden_split']) return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, gen_kwargs={ 'extract_path': extract_path, 'file_names': iden_splits['train'] }, ), tfds.core.SplitGenerator( name=tfds.Split.VALIDATION, gen_kwargs={ 'extract_path': extract_path, 'file_names': iden_splits['validation'] }, ), tfds.core.SplitGenerator( name=tfds.Split.TEST, gen_kwargs={ 'extract_path': extract_path, 'file_names': iden_splits['test'] }, ), ] def _generate_examples(self, extract_path, file_names): """Yields examples.""" for file_name in file_names: full_name = os.path.join(extract_path, 'wav', file_name) if not tf.io.gfile.exists(full_name): continue speaker, ytid, _ = file_name[:-len('.wav')].split('/') speaker_id = int(speaker[3:]) example = {'audio': full_name, 'label': speaker_id, 'youtube_id': ytid} yield file_name, example def _calculate_splits(self, iden_splits_path): """Read the train/dev/test splits from VoxCeleb's iden_split.txt file.""" data_splits = collections.defaultdict(set) with tf.io.gfile.GFile(iden_splits_path) as f: for line in f: group, path = line.strip().split() split_name = {1: 'train', 2: 'validation', 3: 'test'}[int(group)] data_splits[split_name].add(path.strip()) return data_splits
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.location_list, name='api_location_list'), url( r'^(?P<pk>[0-9]+)/$', views.location_details, name='api_location_details'), # geojson url( r'^geojson/$', views.geojson_location_list, name='api_geojson_location_list'), url( r'^geojson/(?P<pk>[0-9]+)/$', views.geojson_location_details, name='api_geojson_location_details'), url( r'^geojson_hidden/(?P<pk>[0-9]+)/$', views.geojson_location_details_hidden, name='api_geojson_location_details_hidden'), url( r'^geojson_none/(?P<pk>[0-9]+)/$', views.geojson_location_details_none, name='api_geojson_location_details_none'), url( r'^geojson/(?P<slug>[-\w]+)/$', views.geojson_location_slug_details, name='api_geojson_location_slug_details'), url( r'^geojson-falseid/(?P<pk>[0-9]+)/$', views.geojson_location_falseid_details, name='api_geojson_location_falseid_details'), url( r'^geojson-noid/(?P<pk>[0-9]+)/$', views.geojson_location_noid_details, name='api_geojson_location_noid_details'), # file url( r'^geojson-file/(?P<pk>[0-9]+)/$', views.geojson_located_file_details, name='api_geojson_located_file_details'), # geojson with bbox with its own geometry field url( r'^geojson-with-bbox/$', views.geojson_boxedlocation_list, name='api_geojson_boxedlocation_list'), url( r'^geojson-with-bbox/(?P<pk>[0-9]+)/$', views.geojson_boxedlocation_details, name='api_geojson_boxedlocation_details'), # geojson with bbox with autogenerated bbox url( r'^geojson-with-auto-bbox/$', views.geojson_location_bbox_list, name='api_geojson_location_bbox_list'), # Filters url( r'^filters/contained_in_bbox$', views.geojson_location_contained_in_bbox_list, name='api_geojson_location_list_contained_in_bbox_filter'), url( r'^filters/overlaps_bbox$', views.geojson_location_overlaps_bbox_list, name='api_geojson_location_list_overlaps_bbox_filter'), url( r'^filters/contained_in_geometry$', views.geojson_contained_in_geometry, name='api_geojson_contained_in_geometry'), url( r'^filters/contained_in_tile$', views.geojson_location_contained_in_tile_list, name='api_geojson_location_list_contained_in_tile_filter'), url( r'^filters/overlaps_tile$', views.geojson_location_overlaps_tile_list, name='api_geojson_location_list_overlaps_tile_filter'), url( r'^filters/within_distance_of_point$', views.geojson_location_within_distance_of_point_list, name='api_geojson_location_list_within_distance_of_point_filter'), url( r'^filters/within_degrees_of_point$', views.geojson_location_within_degrees_of_point_list, name='api_geojson_location_list_within_degrees_of_point_filter'), ]
import { createStore, applyMiddleware, combineReducers } from 'redux'; import { appReducer, leaderBoardReducer } from './reducers'; import { composeWithDevTools } from 'redux-devtools-extension'; import thunk from 'redux-thunk'; const rootReducer = combineReducers({ appReducer, leaderBoardReducer }); const middlewares = [thunk]; const enhancer = composeWithDevTools(applyMiddleware(...middlewares)); export const store = createStore(rootReducer, enhancer);
import React, {Component} from "react"; import {Link} from "react-router"; import PropTypes from 'prop-types'; import {connect} from "react-redux"; import { Tabs} from 'antd-mobile'; import Commodity from "./Commodity"; import {changeNavbarTitle} from '../../actions/home' import './index.less' class Product extends Component { static propTypes = {}; static defaultProps = {}; static contextTypes = { router: React.PropTypes.object.isRequired }; constructor(props) { super(props); this.state = {} } componentWillMount() { this.props.dispatch(changeNavbarTitle("商品详情")) } render() { const {id} = this.props.location.query; return ( <div className="vb-product"> <Commodity id={id}/> </div> ) } } function mapStateToProps(state) { return { tempProduct: state.tempProduct, productDetails: state.productDetails, productspec: state.productspec } } export default connect(mapStateToProps)(Product)
/** * skylark-langx-async - The skylark JavaScript language extension library. * @author Hudaokeji Co.,Ltd * @version v0.9.0 * @link www.skylarkjs.org * @license MIT */ define(["skylark-langx-objects","./async","./deferred"],function(e,n,r){return n.waterful=function(n,t,u){var a=new r,c=a.promise;return u=u||null,t=t||[],a.resolveWith(u,t),e.each(n,function(e,n){c=c.then(n)}),c}}); //# sourceMappingURL=sourcemaps/waterful.js.map
/* $Id: groestl.c 260 2011-07-21 01:02:38Z tp $ */ /* * Groestl implementation. * * ==========================(LICENSE BEGIN)============================ * * Copyright (c) 2007-2010 Projet RNRT SAPHIR * * 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. * * ===========================(LICENSE END)============================= * * @author Thomas Pornin <thomas.pornin@cryptolog.com> */ #include <stddef.h> #include <string.h> #include "sph_groestl.h" #ifdef __cplusplus extern "C"{ #endif #if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_GROESTL #define SPH_SMALL_FOOTPRINT_GROESTL 1 #endif /* * Apparently, the 32-bit-only version is not faster than the 64-bit * version unless using the "small footprint" code on a 32-bit machine. */ #if !defined SPH_GROESTL_64 #if SPH_SMALL_FOOTPRINT_GROESTL && !SPH_64_TRUE #define SPH_GROESTL_64 0 #else #define SPH_GROESTL_64 1 #endif #endif #if !SPH_64 #undef SPH_GROESTL_64 #endif #ifdef _MSC_VER #pragma warning (disable: 4146) #endif /* * The internal representation may use either big-endian or * little-endian. Using the platform default representation speeds up * encoding and decoding between bytes and the matrix coluleno. */ #undef USE_LE #if SPH_GROESTL_LITTLE_ENDIAN #define USE_LE 1 #elif SPH_GROESTL_BIG_ENDIAN #define USE_LE 0 #elif SPH_LITTLE_ENDIAN #define USE_LE 1 #endif #if USE_LE #define C32e(x) ((SPH_C32(x) >> 24) \ | ((SPH_C32(x) >> 8) & SPH_C32(0x0000FF00)) \ | ((SPH_C32(x) << 8) & SPH_C32(0x00FF0000)) \ | ((SPH_C32(x) << 24) & SPH_C32(0xFF000000))) #define dec32e_aligned sph_dec32le_aligned #define enc32e sph_enc32le #define B32_0(x) ((x) & 0xFF) #define B32_1(x) (((x) >> 8) & 0xFF) #define B32_2(x) (((x) >> 16) & 0xFF) #define B32_3(x) ((x) >> 24) #define R32u(u, d) SPH_T32(((u) << 16) | ((d) >> 16)) #define R32d(u, d) SPH_T32(((u) >> 16) | ((d) << 16)) #define PC32up(j, r) ((sph_u32)((j) + (r))) #define PC32dn(j, r) 0 #define QC32up(j, r) SPH_C32(0xFFFFFFFF) #define QC32dn(j, r) (((sph_u32)(r) << 24) ^ SPH_T32(~((sph_u32)(j) << 24))) #if SPH_64 #define C64e(x) ((SPH_C64(x) >> 56) \ | ((SPH_C64(x) >> 40) & SPH_C64(0x000000000000FF00)) \ | ((SPH_C64(x) >> 24) & SPH_C64(0x0000000000FF0000)) \ | ((SPH_C64(x) >> 8) & SPH_C64(0x00000000FF000000)) \ | ((SPH_C64(x) << 8) & SPH_C64(0x000000FF00000000)) \ | ((SPH_C64(x) << 24) & SPH_C64(0x0000FF0000000000)) \ | ((SPH_C64(x) << 40) & SPH_C64(0x00FF000000000000)) \ | ((SPH_C64(x) << 56) & SPH_C64(0xFF00000000000000))) #define dec64e_aligned sph_dec64le_aligned #define enc64e sph_enc64le #define B64_0(x) ((x) & 0xFF) #define B64_1(x) (((x) >> 8) & 0xFF) #define B64_2(x) (((x) >> 16) & 0xFF) #define B64_3(x) (((x) >> 24) & 0xFF) #define B64_4(x) (((x) >> 32) & 0xFF) #define B64_5(x) (((x) >> 40) & 0xFF) #define B64_6(x) (((x) >> 48) & 0xFF) #define B64_7(x) ((x) >> 56) #define R64 SPH_ROTL64 #define PC64(j, r) ((sph_u64)((j) + (r))) #define QC64(j, r) (((sph_u64)(r) << 56) ^ SPH_T64(~((sph_u64)(j) << 56))) #endif #else #define C32e(x) SPH_C32(x) #define dec32e_aligned sph_dec32be_aligned #define enc32e sph_enc32be #define B32_0(x) ((x) >> 24) #define B32_1(x) (((x) >> 16) & 0xFF) #define B32_2(x) (((x) >> 8) & 0xFF) #define B32_3(x) ((x) & 0xFF) #define R32u(u, d) SPH_T32(((u) >> 16) | ((d) << 16)) #define R32d(u, d) SPH_T32(((u) << 16) | ((d) >> 16)) #define PC32up(j, r) ((sph_u32)((j) + (r)) << 24) #define PC32dn(j, r) 0 #define QC32up(j, r) SPH_C32(0xFFFFFFFF) #define QC32dn(j, r) ((sph_u32)(r) ^ SPH_T32(~(sph_u32)(j))) #if SPH_64 #define C64e(x) SPH_C64(x) #define dec64e_aligned sph_dec64be_aligned #define enc64e sph_enc64be #define B64_0(x) ((x) >> 56) #define B64_1(x) (((x) >> 48) & 0xFF) #define B64_2(x) (((x) >> 40) & 0xFF) #define B64_3(x) (((x) >> 32) & 0xFF) #define B64_4(x) (((x) >> 24) & 0xFF) #define B64_5(x) (((x) >> 16) & 0xFF) #define B64_6(x) (((x) >> 8) & 0xFF) #define B64_7(x) ((x) & 0xFF) #define R64 SPH_ROTR64 #define PC64(j, r) ((sph_u64)((j) + (r)) << 56) #define QC64(j, r) ((sph_u64)(r) ^ SPH_T64(~(sph_u64)(j))) #endif #endif #if SPH_GROESTL_64 static const sph_u64 T0[] = { C64e(0xc632f4a5f497a5c6), C64e(0xf86f978497eb84f8), C64e(0xee5eb099b0c799ee), C64e(0xf67a8c8d8cf78df6), C64e(0xffe8170d17e50dff), C64e(0xd60adcbddcb7bdd6), C64e(0xde16c8b1c8a7b1de), C64e(0x916dfc54fc395491), C64e(0x6090f050f0c05060), C64e(0x0207050305040302), C64e(0xce2ee0a9e087a9ce), C64e(0x56d1877d87ac7d56), C64e(0xe7cc2b192bd519e7), C64e(0xb513a662a67162b5), C64e(0x4d7c31e6319ae64d), C64e(0xec59b59ab5c39aec), C64e(0x8f40cf45cf05458f), C64e(0x1fa3bc9dbc3e9d1f), C64e(0x8949c040c0094089), C64e(0xfa68928792ef87fa), C64e(0xefd03f153fc515ef), C64e(0xb29426eb267febb2), C64e(0x8ece40c94007c98e), C64e(0xfbe61d0b1ded0bfb), C64e(0x416e2fec2f82ec41), C64e(0xb31aa967a97d67b3), C64e(0x5f431cfd1cbefd5f), C64e(0x456025ea258aea45), C64e(0x23f9dabfda46bf23), C64e(0x535102f702a6f753), C64e(0xe445a196a1d396e4), C64e(0x9b76ed5bed2d5b9b), C64e(0x75285dc25deac275), C64e(0xe1c5241c24d91ce1), C64e(0x3dd4e9aee97aae3d), C64e(0x4cf2be6abe986a4c), C64e(0x6c82ee5aeed85a6c), C64e(0x7ebdc341c3fc417e), C64e(0xf5f3060206f102f5), C64e(0x8352d14fd11d4f83), C64e(0x688ce45ce4d05c68), C64e(0x515607f407a2f451), C64e(0xd18d5c345cb934d1), C64e(0xf9e1180818e908f9), C64e(0xe24cae93aedf93e2), C64e(0xab3e9573954d73ab), C64e(0x6297f553f5c45362), C64e(0x2a6b413f41543f2a), C64e(0x081c140c14100c08), C64e(0x9563f652f6315295), C64e(0x46e9af65af8c6546), C64e(0x9d7fe25ee2215e9d), C64e(0x3048782878602830), C64e(0x37cff8a1f86ea137), C64e(0x0a1b110f11140f0a), C64e(0x2febc4b5c45eb52f), C64e(0x0e151b091b1c090e), C64e(0x247e5a365a483624), C64e(0x1badb69bb6369b1b), C64e(0xdf98473d47a53ddf), C64e(0xcda76a266a8126cd), C64e(0x4ef5bb69bb9c694e), C64e(0x7f334ccd4cfecd7f), C64e(0xea50ba9fbacf9fea), C64e(0x123f2d1b2d241b12), C64e(0x1da4b99eb93a9e1d), C64e(0x58c49c749cb07458), C64e(0x3446722e72682e34), C64e(0x3641772d776c2d36), C64e(0xdc11cdb2cda3b2dc), C64e(0xb49d29ee2973eeb4), C64e(0x5b4d16fb16b6fb5b), C64e(0xa4a501f60153f6a4), C64e(0x76a1d74dd7ec4d76), C64e(0xb714a361a37561b7), C64e(0x7d3449ce49face7d), C64e(0x52df8d7b8da47b52), C64e(0xdd9f423e42a13edd), C64e(0x5ecd937193bc715e), C64e(0x13b1a297a2269713), C64e(0xa6a204f50457f5a6), C64e(0xb901b868b86968b9), C64e(0x0000000000000000), C64e(0xc1b5742c74992cc1), C64e(0x40e0a060a0806040), C64e(0xe3c2211f21dd1fe3), C64e(0x793a43c843f2c879), C64e(0xb69a2ced2c77edb6), C64e(0xd40dd9bed9b3bed4), C64e(0x8d47ca46ca01468d), C64e(0x671770d970ced967), C64e(0x72afdd4bdde44b72), C64e(0x94ed79de7933de94), C64e(0x98ff67d4672bd498), C64e(0xb09323e8237be8b0), C64e(0x855bde4ade114a85), C64e(0xbb06bd6bbd6d6bbb), C64e(0xc5bb7e2a7e912ac5), C64e(0x4f7b34e5349ee54f), C64e(0xedd73a163ac116ed), C64e(0x86d254c55417c586), C64e(0x9af862d7622fd79a), C64e(0x6699ff55ffcc5566), C64e(0x11b6a794a7229411), C64e(0x8ac04acf4a0fcf8a), C64e(0xe9d9301030c910e9), C64e(0x040e0a060a080604), C64e(0xfe66988198e781fe), C64e(0xa0ab0bf00b5bf0a0), C64e(0x78b4cc44ccf04478), C64e(0x25f0d5bad54aba25), C64e(0x4b753ee33e96e34b), C64e(0xa2ac0ef30e5ff3a2), C64e(0x5d4419fe19bafe5d), C64e(0x80db5bc05b1bc080), C64e(0x0580858a850a8a05), C64e(0x3fd3ecadec7ead3f), C64e(0x21fedfbcdf42bc21), C64e(0x70a8d848d8e04870), C64e(0xf1fd0c040cf904f1), C64e(0x63197adf7ac6df63), C64e(0x772f58c158eec177), C64e(0xaf309f759f4575af), C64e(0x42e7a563a5846342), C64e(0x2070503050403020), C64e(0xe5cb2e1a2ed11ae5), C64e(0xfdef120e12e10efd), C64e(0xbf08b76db7656dbf), C64e(0x8155d44cd4194c81), C64e(0x18243c143c301418), C64e(0x26795f355f4c3526), C64e(0xc3b2712f719d2fc3), C64e(0xbe8638e13867e1be), C64e(0x35c8fda2fd6aa235), C64e(0x88c74fcc4f0bcc88), C64e(0x2e654b394b5c392e), C64e(0x936af957f93d5793), C64e(0x55580df20daaf255), C64e(0xfc619d829de382fc), C64e(0x7ab3c947c9f4477a), C64e(0xc827efacef8bacc8), C64e(0xba8832e7326fe7ba), C64e(0x324f7d2b7d642b32), C64e(0xe642a495a4d795e6), C64e(0xc03bfba0fb9ba0c0), C64e(0x19aab398b3329819), C64e(0x9ef668d16827d19e), C64e(0xa322817f815d7fa3), C64e(0x44eeaa66aa886644), C64e(0x54d6827e82a87e54), C64e(0x3bdde6abe676ab3b), C64e(0x0b959e839e16830b), C64e(0x8cc945ca4503ca8c), C64e(0xc7bc7b297b9529c7), C64e(0x6b056ed36ed6d36b), C64e(0x286c443c44503c28), C64e(0xa72c8b798b5579a7), C64e(0xbc813de23d63e2bc), C64e(0x1631271d272c1d16), C64e(0xad379a769a4176ad), C64e(0xdb964d3b4dad3bdb), C64e(0x649efa56fac85664), C64e(0x74a6d24ed2e84e74), C64e(0x1436221e22281e14), C64e(0x92e476db763fdb92), C64e(0x0c121e0a1e180a0c), C64e(0x48fcb46cb4906c48), C64e(0xb88f37e4376be4b8), C64e(0x9f78e75de7255d9f), C64e(0xbd0fb26eb2616ebd), C64e(0x43692aef2a86ef43), C64e(0xc435f1a6f193a6c4), C64e(0x39dae3a8e372a839), C64e(0x31c6f7a4f762a431), C64e(0xd38a593759bd37d3), C64e(0xf274868b86ff8bf2), C64e(0xd583563256b132d5), C64e(0x8b4ec543c50d438b), C64e(0x6e85eb59ebdc596e), C64e(0xda18c2b7c2afb7da), C64e(0x018e8f8c8f028c01), C64e(0xb11dac64ac7964b1), C64e(0x9cf16dd26d23d29c), C64e(0x49723be03b92e049), C64e(0xd81fc7b4c7abb4d8), C64e(0xacb915fa1543faac), C64e(0xf3fa090709fd07f3), C64e(0xcfa06f256f8525cf), C64e(0xca20eaafea8fafca), C64e(0xf47d898e89f38ef4), C64e(0x476720e9208ee947), C64e(0x1038281828201810), C64e(0x6f0b64d564ded56f), C64e(0xf073838883fb88f0), C64e(0x4afbb16fb1946f4a), C64e(0x5cca967296b8725c), C64e(0x38546c246c702438), C64e(0x575f08f108aef157), C64e(0x732152c752e6c773), C64e(0x9764f351f3355197), C64e(0xcbae6523658d23cb), C64e(0xa125847c84597ca1), C64e(0xe857bf9cbfcb9ce8), C64e(0x3e5d6321637c213e), C64e(0x96ea7cdd7c37dd96), C64e(0x611e7fdc7fc2dc61), C64e(0x0d9c9186911a860d), C64e(0x0f9b9485941e850f), C64e(0xe04bab90abdb90e0), C64e(0x7cbac642c6f8427c), C64e(0x712657c457e2c471), C64e(0xcc29e5aae583aacc), C64e(0x90e373d8733bd890), C64e(0x06090f050f0c0506), C64e(0xf7f4030103f501f7), C64e(0x1c2a36123638121c), C64e(0xc23cfea3fe9fa3c2), C64e(0x6a8be15fe1d45f6a), C64e(0xaebe10f91047f9ae), C64e(0x69026bd06bd2d069), C64e(0x17bfa891a82e9117), C64e(0x9971e858e8295899), C64e(0x3a5369276974273a), C64e(0x27f7d0b9d04eb927), C64e(0xd991483848a938d9), C64e(0xebde351335cd13eb), C64e(0x2be5ceb3ce56b32b), C64e(0x2277553355443322), C64e(0xd204d6bbd6bfbbd2), C64e(0xa9399070904970a9), C64e(0x07878089800e8907), C64e(0x33c1f2a7f266a733), C64e(0x2decc1b6c15ab62d), C64e(0x3c5a66226678223c), C64e(0x15b8ad92ad2a9215), C64e(0xc9a96020608920c9), C64e(0x875cdb49db154987), C64e(0xaab01aff1a4fffaa), C64e(0x50d8887888a07850), C64e(0xa52b8e7a8e517aa5), C64e(0x03898a8f8a068f03), C64e(0x594a13f813b2f859), C64e(0x09929b809b128009), C64e(0x1a2339173934171a), C64e(0x651075da75cada65), C64e(0xd784533153b531d7), C64e(0x84d551c65113c684), C64e(0xd003d3b8d3bbb8d0), C64e(0x82dc5ec35e1fc382), C64e(0x29e2cbb0cb52b029), C64e(0x5ac3997799b4775a), C64e(0x1e2d3311333c111e), C64e(0x7b3d46cb46f6cb7b), C64e(0xa8b71ffc1f4bfca8), C64e(0x6d0c61d661dad66d), C64e(0x2c624e3a4e583a2c) }; #if !SPH_SMALL_FOOTPRINT_GROESTL static const sph_u64 T1[] = { C64e(0xc6c632f4a5f497a5), C64e(0xf8f86f978497eb84), C64e(0xeeee5eb099b0c799), C64e(0xf6f67a8c8d8cf78d), C64e(0xffffe8170d17e50d), C64e(0xd6d60adcbddcb7bd), C64e(0xdede16c8b1c8a7b1), C64e(0x91916dfc54fc3954), C64e(0x606090f050f0c050), C64e(0x0202070503050403), C64e(0xcece2ee0a9e087a9), C64e(0x5656d1877d87ac7d), C64e(0xe7e7cc2b192bd519), C64e(0xb5b513a662a67162), C64e(0x4d4d7c31e6319ae6), C64e(0xecec59b59ab5c39a), C64e(0x8f8f40cf45cf0545), C64e(0x1f1fa3bc9dbc3e9d), C64e(0x898949c040c00940), C64e(0xfafa68928792ef87), C64e(0xefefd03f153fc515), C64e(0xb2b29426eb267feb), C64e(0x8e8ece40c94007c9), C64e(0xfbfbe61d0b1ded0b), C64e(0x41416e2fec2f82ec), C64e(0xb3b31aa967a97d67), C64e(0x5f5f431cfd1cbefd), C64e(0x45456025ea258aea), C64e(0x2323f9dabfda46bf), C64e(0x53535102f702a6f7), C64e(0xe4e445a196a1d396), C64e(0x9b9b76ed5bed2d5b), C64e(0x7575285dc25deac2), C64e(0xe1e1c5241c24d91c), C64e(0x3d3dd4e9aee97aae), C64e(0x4c4cf2be6abe986a), C64e(0x6c6c82ee5aeed85a), C64e(0x7e7ebdc341c3fc41), C64e(0xf5f5f3060206f102), C64e(0x838352d14fd11d4f), C64e(0x68688ce45ce4d05c), C64e(0x51515607f407a2f4), C64e(0xd1d18d5c345cb934), C64e(0xf9f9e1180818e908), C64e(0xe2e24cae93aedf93), C64e(0xabab3e9573954d73), C64e(0x626297f553f5c453), C64e(0x2a2a6b413f41543f), C64e(0x08081c140c14100c), C64e(0x959563f652f63152), C64e(0x4646e9af65af8c65), C64e(0x9d9d7fe25ee2215e), C64e(0x3030487828786028), C64e(0x3737cff8a1f86ea1), C64e(0x0a0a1b110f11140f), C64e(0x2f2febc4b5c45eb5), C64e(0x0e0e151b091b1c09), C64e(0x24247e5a365a4836), C64e(0x1b1badb69bb6369b), C64e(0xdfdf98473d47a53d), C64e(0xcdcda76a266a8126), C64e(0x4e4ef5bb69bb9c69), C64e(0x7f7f334ccd4cfecd), C64e(0xeaea50ba9fbacf9f), C64e(0x12123f2d1b2d241b), C64e(0x1d1da4b99eb93a9e), C64e(0x5858c49c749cb074), C64e(0x343446722e72682e), C64e(0x363641772d776c2d), C64e(0xdcdc11cdb2cda3b2), C64e(0xb4b49d29ee2973ee), C64e(0x5b5b4d16fb16b6fb), C64e(0xa4a4a501f60153f6), C64e(0x7676a1d74dd7ec4d), C64e(0xb7b714a361a37561), C64e(0x7d7d3449ce49face), C64e(0x5252df8d7b8da47b), C64e(0xdddd9f423e42a13e), C64e(0x5e5ecd937193bc71), C64e(0x1313b1a297a22697), C64e(0xa6a6a204f50457f5), C64e(0xb9b901b868b86968), C64e(0x0000000000000000), C64e(0xc1c1b5742c74992c), C64e(0x4040e0a060a08060), C64e(0xe3e3c2211f21dd1f), C64e(0x79793a43c843f2c8), C64e(0xb6b69a2ced2c77ed), C64e(0xd4d40dd9bed9b3be), C64e(0x8d8d47ca46ca0146), C64e(0x67671770d970ced9), C64e(0x7272afdd4bdde44b), C64e(0x9494ed79de7933de), C64e(0x9898ff67d4672bd4), C64e(0xb0b09323e8237be8), C64e(0x85855bde4ade114a), C64e(0xbbbb06bd6bbd6d6b), C64e(0xc5c5bb7e2a7e912a), C64e(0x4f4f7b34e5349ee5), C64e(0xededd73a163ac116), C64e(0x8686d254c55417c5), C64e(0x9a9af862d7622fd7), C64e(0x666699ff55ffcc55), C64e(0x1111b6a794a72294), C64e(0x8a8ac04acf4a0fcf), C64e(0xe9e9d9301030c910), C64e(0x04040e0a060a0806), C64e(0xfefe66988198e781), C64e(0xa0a0ab0bf00b5bf0), C64e(0x7878b4cc44ccf044), C64e(0x2525f0d5bad54aba), C64e(0x4b4b753ee33e96e3), C64e(0xa2a2ac0ef30e5ff3), C64e(0x5d5d4419fe19bafe), C64e(0x8080db5bc05b1bc0), C64e(0x050580858a850a8a), C64e(0x3f3fd3ecadec7ead), C64e(0x2121fedfbcdf42bc), C64e(0x7070a8d848d8e048), C64e(0xf1f1fd0c040cf904), C64e(0x6363197adf7ac6df), C64e(0x77772f58c158eec1), C64e(0xafaf309f759f4575), C64e(0x4242e7a563a58463), C64e(0x2020705030504030), C64e(0xe5e5cb2e1a2ed11a), C64e(0xfdfdef120e12e10e), C64e(0xbfbf08b76db7656d), C64e(0x818155d44cd4194c), C64e(0x1818243c143c3014), C64e(0x2626795f355f4c35), C64e(0xc3c3b2712f719d2f), C64e(0xbebe8638e13867e1), C64e(0x3535c8fda2fd6aa2), C64e(0x8888c74fcc4f0bcc), C64e(0x2e2e654b394b5c39), C64e(0x93936af957f93d57), C64e(0x5555580df20daaf2), C64e(0xfcfc619d829de382), C64e(0x7a7ab3c947c9f447), C64e(0xc8c827efacef8bac), C64e(0xbaba8832e7326fe7), C64e(0x32324f7d2b7d642b), C64e(0xe6e642a495a4d795), C64e(0xc0c03bfba0fb9ba0), C64e(0x1919aab398b33298), C64e(0x9e9ef668d16827d1), C64e(0xa3a322817f815d7f), C64e(0x4444eeaa66aa8866), C64e(0x5454d6827e82a87e), C64e(0x3b3bdde6abe676ab), C64e(0x0b0b959e839e1683), C64e(0x8c8cc945ca4503ca), C64e(0xc7c7bc7b297b9529), C64e(0x6b6b056ed36ed6d3), C64e(0x28286c443c44503c), C64e(0xa7a72c8b798b5579), C64e(0xbcbc813de23d63e2), C64e(0x161631271d272c1d), C64e(0xadad379a769a4176), C64e(0xdbdb964d3b4dad3b), C64e(0x64649efa56fac856), C64e(0x7474a6d24ed2e84e), C64e(0x141436221e22281e), C64e(0x9292e476db763fdb), C64e(0x0c0c121e0a1e180a), C64e(0x4848fcb46cb4906c), C64e(0xb8b88f37e4376be4), C64e(0x9f9f78e75de7255d), C64e(0xbdbd0fb26eb2616e), C64e(0x4343692aef2a86ef), C64e(0xc4c435f1a6f193a6), C64e(0x3939dae3a8e372a8), C64e(0x3131c6f7a4f762a4), C64e(0xd3d38a593759bd37), C64e(0xf2f274868b86ff8b), C64e(0xd5d583563256b132), C64e(0x8b8b4ec543c50d43), C64e(0x6e6e85eb59ebdc59), C64e(0xdada18c2b7c2afb7), C64e(0x01018e8f8c8f028c), C64e(0xb1b11dac64ac7964), C64e(0x9c9cf16dd26d23d2), C64e(0x4949723be03b92e0), C64e(0xd8d81fc7b4c7abb4), C64e(0xacacb915fa1543fa), C64e(0xf3f3fa090709fd07), C64e(0xcfcfa06f256f8525), C64e(0xcaca20eaafea8faf), C64e(0xf4f47d898e89f38e), C64e(0x47476720e9208ee9), C64e(0x1010382818282018), C64e(0x6f6f0b64d564ded5), C64e(0xf0f073838883fb88), C64e(0x4a4afbb16fb1946f), C64e(0x5c5cca967296b872), C64e(0x3838546c246c7024), C64e(0x57575f08f108aef1), C64e(0x73732152c752e6c7), C64e(0x979764f351f33551), C64e(0xcbcbae6523658d23), C64e(0xa1a125847c84597c), C64e(0xe8e857bf9cbfcb9c), C64e(0x3e3e5d6321637c21), C64e(0x9696ea7cdd7c37dd), C64e(0x61611e7fdc7fc2dc), C64e(0x0d0d9c9186911a86), C64e(0x0f0f9b9485941e85), C64e(0xe0e04bab90abdb90), C64e(0x7c7cbac642c6f842), C64e(0x71712657c457e2c4), C64e(0xcccc29e5aae583aa), C64e(0x9090e373d8733bd8), C64e(0x0606090f050f0c05), C64e(0xf7f7f4030103f501), C64e(0x1c1c2a3612363812), C64e(0xc2c23cfea3fe9fa3), C64e(0x6a6a8be15fe1d45f), C64e(0xaeaebe10f91047f9), C64e(0x6969026bd06bd2d0), C64e(0x1717bfa891a82e91), C64e(0x999971e858e82958), C64e(0x3a3a536927697427), C64e(0x2727f7d0b9d04eb9), C64e(0xd9d991483848a938), C64e(0xebebde351335cd13), C64e(0x2b2be5ceb3ce56b3), C64e(0x2222775533554433), C64e(0xd2d204d6bbd6bfbb), C64e(0xa9a9399070904970), C64e(0x0707878089800e89), C64e(0x3333c1f2a7f266a7), C64e(0x2d2decc1b6c15ab6), C64e(0x3c3c5a6622667822), C64e(0x1515b8ad92ad2a92), C64e(0xc9c9a96020608920), C64e(0x87875cdb49db1549), C64e(0xaaaab01aff1a4fff), C64e(0x5050d8887888a078), C64e(0xa5a52b8e7a8e517a), C64e(0x0303898a8f8a068f), C64e(0x59594a13f813b2f8), C64e(0x0909929b809b1280), C64e(0x1a1a233917393417), C64e(0x65651075da75cada), C64e(0xd7d784533153b531), C64e(0x8484d551c65113c6), C64e(0xd0d003d3b8d3bbb8), C64e(0x8282dc5ec35e1fc3), C64e(0x2929e2cbb0cb52b0), C64e(0x5a5ac3997799b477), C64e(0x1e1e2d3311333c11), C64e(0x7b7b3d46cb46f6cb), C64e(0xa8a8b71ffc1f4bfc), C64e(0x6d6d0c61d661dad6), C64e(0x2c2c624e3a4e583a) }; static const sph_u64 T2[] = { C64e(0xa5c6c632f4a5f497), C64e(0x84f8f86f978497eb), C64e(0x99eeee5eb099b0c7), C64e(0x8df6f67a8c8d8cf7), C64e(0x0dffffe8170d17e5), C64e(0xbdd6d60adcbddcb7), C64e(0xb1dede16c8b1c8a7), C64e(0x5491916dfc54fc39), C64e(0x50606090f050f0c0), C64e(0x0302020705030504), C64e(0xa9cece2ee0a9e087), C64e(0x7d5656d1877d87ac), C64e(0x19e7e7cc2b192bd5), C64e(0x62b5b513a662a671), C64e(0xe64d4d7c31e6319a), C64e(0x9aecec59b59ab5c3), C64e(0x458f8f40cf45cf05), C64e(0x9d1f1fa3bc9dbc3e), C64e(0x40898949c040c009), C64e(0x87fafa68928792ef), C64e(0x15efefd03f153fc5), C64e(0xebb2b29426eb267f), C64e(0xc98e8ece40c94007), C64e(0x0bfbfbe61d0b1ded), C64e(0xec41416e2fec2f82), C64e(0x67b3b31aa967a97d), C64e(0xfd5f5f431cfd1cbe), C64e(0xea45456025ea258a), C64e(0xbf2323f9dabfda46), C64e(0xf753535102f702a6), C64e(0x96e4e445a196a1d3), C64e(0x5b9b9b76ed5bed2d), C64e(0xc27575285dc25dea), C64e(0x1ce1e1c5241c24d9), C64e(0xae3d3dd4e9aee97a), C64e(0x6a4c4cf2be6abe98), C64e(0x5a6c6c82ee5aeed8), C64e(0x417e7ebdc341c3fc), C64e(0x02f5f5f3060206f1), C64e(0x4f838352d14fd11d), C64e(0x5c68688ce45ce4d0), C64e(0xf451515607f407a2), C64e(0x34d1d18d5c345cb9), C64e(0x08f9f9e1180818e9), C64e(0x93e2e24cae93aedf), C64e(0x73abab3e9573954d), C64e(0x53626297f553f5c4), C64e(0x3f2a2a6b413f4154), C64e(0x0c08081c140c1410), C64e(0x52959563f652f631), C64e(0x654646e9af65af8c), C64e(0x5e9d9d7fe25ee221), C64e(0x2830304878287860), C64e(0xa13737cff8a1f86e), C64e(0x0f0a0a1b110f1114), C64e(0xb52f2febc4b5c45e), C64e(0x090e0e151b091b1c), C64e(0x3624247e5a365a48), C64e(0x9b1b1badb69bb636), C64e(0x3ddfdf98473d47a5), C64e(0x26cdcda76a266a81), C64e(0x694e4ef5bb69bb9c), C64e(0xcd7f7f334ccd4cfe), C64e(0x9feaea50ba9fbacf), C64e(0x1b12123f2d1b2d24), C64e(0x9e1d1da4b99eb93a), C64e(0x745858c49c749cb0), C64e(0x2e343446722e7268), C64e(0x2d363641772d776c), C64e(0xb2dcdc11cdb2cda3), C64e(0xeeb4b49d29ee2973), C64e(0xfb5b5b4d16fb16b6), C64e(0xf6a4a4a501f60153), C64e(0x4d7676a1d74dd7ec), C64e(0x61b7b714a361a375), C64e(0xce7d7d3449ce49fa), C64e(0x7b5252df8d7b8da4), C64e(0x3edddd9f423e42a1), C64e(0x715e5ecd937193bc), C64e(0x971313b1a297a226), C64e(0xf5a6a6a204f50457), C64e(0x68b9b901b868b869), C64e(0x0000000000000000), C64e(0x2cc1c1b5742c7499), C64e(0x604040e0a060a080), C64e(0x1fe3e3c2211f21dd), C64e(0xc879793a43c843f2), C64e(0xedb6b69a2ced2c77), C64e(0xbed4d40dd9bed9b3), C64e(0x468d8d47ca46ca01), C64e(0xd967671770d970ce), C64e(0x4b7272afdd4bdde4), C64e(0xde9494ed79de7933), C64e(0xd49898ff67d4672b), C64e(0xe8b0b09323e8237b), C64e(0x4a85855bde4ade11), C64e(0x6bbbbb06bd6bbd6d), C64e(0x2ac5c5bb7e2a7e91), C64e(0xe54f4f7b34e5349e), C64e(0x16ededd73a163ac1), C64e(0xc58686d254c55417), C64e(0xd79a9af862d7622f), C64e(0x55666699ff55ffcc), C64e(0x941111b6a794a722), C64e(0xcf8a8ac04acf4a0f), C64e(0x10e9e9d9301030c9), C64e(0x0604040e0a060a08), C64e(0x81fefe66988198e7), C64e(0xf0a0a0ab0bf00b5b), C64e(0x447878b4cc44ccf0), C64e(0xba2525f0d5bad54a), C64e(0xe34b4b753ee33e96), C64e(0xf3a2a2ac0ef30e5f), C64e(0xfe5d5d4419fe19ba), C64e(0xc08080db5bc05b1b), C64e(0x8a050580858a850a), C64e(0xad3f3fd3ecadec7e), C64e(0xbc2121fedfbcdf42), C64e(0x487070a8d848d8e0), C64e(0x04f1f1fd0c040cf9), C64e(0xdf6363197adf7ac6), C64e(0xc177772f58c158ee), C64e(0x75afaf309f759f45), C64e(0x634242e7a563a584), C64e(0x3020207050305040), C64e(0x1ae5e5cb2e1a2ed1), C64e(0x0efdfdef120e12e1), C64e(0x6dbfbf08b76db765), C64e(0x4c818155d44cd419), C64e(0x141818243c143c30), C64e(0x352626795f355f4c), C64e(0x2fc3c3b2712f719d), C64e(0xe1bebe8638e13867), C64e(0xa23535c8fda2fd6a), C64e(0xcc8888c74fcc4f0b), C64e(0x392e2e654b394b5c), C64e(0x5793936af957f93d), C64e(0xf25555580df20daa), C64e(0x82fcfc619d829de3), C64e(0x477a7ab3c947c9f4), C64e(0xacc8c827efacef8b), C64e(0xe7baba8832e7326f), C64e(0x2b32324f7d2b7d64), C64e(0x95e6e642a495a4d7), C64e(0xa0c0c03bfba0fb9b), C64e(0x981919aab398b332), C64e(0xd19e9ef668d16827), C64e(0x7fa3a322817f815d), C64e(0x664444eeaa66aa88), C64e(0x7e5454d6827e82a8), C64e(0xab3b3bdde6abe676), C64e(0x830b0b959e839e16), C64e(0xca8c8cc945ca4503), C64e(0x29c7c7bc7b297b95), C64e(0xd36b6b056ed36ed6), C64e(0x3c28286c443c4450), C64e(0x79a7a72c8b798b55), C64e(0xe2bcbc813de23d63), C64e(0x1d161631271d272c), C64e(0x76adad379a769a41), C64e(0x3bdbdb964d3b4dad), C64e(0x5664649efa56fac8), C64e(0x4e7474a6d24ed2e8), C64e(0x1e141436221e2228), C64e(0xdb9292e476db763f), C64e(0x0a0c0c121e0a1e18), C64e(0x6c4848fcb46cb490), C64e(0xe4b8b88f37e4376b), C64e(0x5d9f9f78e75de725), C64e(0x6ebdbd0fb26eb261), C64e(0xef4343692aef2a86), C64e(0xa6c4c435f1a6f193), C64e(0xa83939dae3a8e372), C64e(0xa43131c6f7a4f762), C64e(0x37d3d38a593759bd), C64e(0x8bf2f274868b86ff), C64e(0x32d5d583563256b1), C64e(0x438b8b4ec543c50d), C64e(0x596e6e85eb59ebdc), C64e(0xb7dada18c2b7c2af), C64e(0x8c01018e8f8c8f02), C64e(0x64b1b11dac64ac79), C64e(0xd29c9cf16dd26d23), C64e(0xe04949723be03b92), C64e(0xb4d8d81fc7b4c7ab), C64e(0xfaacacb915fa1543), C64e(0x07f3f3fa090709fd), C64e(0x25cfcfa06f256f85), C64e(0xafcaca20eaafea8f), C64e(0x8ef4f47d898e89f3), C64e(0xe947476720e9208e), C64e(0x1810103828182820), C64e(0xd56f6f0b64d564de), C64e(0x88f0f073838883fb), C64e(0x6f4a4afbb16fb194), C64e(0x725c5cca967296b8), C64e(0x243838546c246c70), C64e(0xf157575f08f108ae), C64e(0xc773732152c752e6), C64e(0x51979764f351f335), C64e(0x23cbcbae6523658d), C64e(0x7ca1a125847c8459), C64e(0x9ce8e857bf9cbfcb), C64e(0x213e3e5d6321637c), C64e(0xdd9696ea7cdd7c37), C64e(0xdc61611e7fdc7fc2), C64e(0x860d0d9c9186911a), C64e(0x850f0f9b9485941e), C64e(0x90e0e04bab90abdb), C64e(0x427c7cbac642c6f8), C64e(0xc471712657c457e2), C64e(0xaacccc29e5aae583), C64e(0xd89090e373d8733b), C64e(0x050606090f050f0c), C64e(0x01f7f7f4030103f5), C64e(0x121c1c2a36123638), C64e(0xa3c2c23cfea3fe9f), C64e(0x5f6a6a8be15fe1d4), C64e(0xf9aeaebe10f91047), C64e(0xd06969026bd06bd2), C64e(0x911717bfa891a82e), C64e(0x58999971e858e829), C64e(0x273a3a5369276974), C64e(0xb92727f7d0b9d04e), C64e(0x38d9d991483848a9), C64e(0x13ebebde351335cd), C64e(0xb32b2be5ceb3ce56), C64e(0x3322227755335544), C64e(0xbbd2d204d6bbd6bf), C64e(0x70a9a93990709049), C64e(0x890707878089800e), C64e(0xa73333c1f2a7f266), C64e(0xb62d2decc1b6c15a), C64e(0x223c3c5a66226678), C64e(0x921515b8ad92ad2a), C64e(0x20c9c9a960206089), C64e(0x4987875cdb49db15), C64e(0xffaaaab01aff1a4f), C64e(0x785050d8887888a0), C64e(0x7aa5a52b8e7a8e51), C64e(0x8f0303898a8f8a06), C64e(0xf859594a13f813b2), C64e(0x800909929b809b12), C64e(0x171a1a2339173934), C64e(0xda65651075da75ca), C64e(0x31d7d784533153b5), C64e(0xc68484d551c65113), C64e(0xb8d0d003d3b8d3bb), C64e(0xc38282dc5ec35e1f), C64e(0xb02929e2cbb0cb52), C64e(0x775a5ac3997799b4), C64e(0x111e1e2d3311333c), C64e(0xcb7b7b3d46cb46f6), C64e(0xfca8a8b71ffc1f4b), C64e(0xd66d6d0c61d661da), C64e(0x3a2c2c624e3a4e58) }; static const sph_u64 T3[] = { C64e(0x97a5c6c632f4a5f4), C64e(0xeb84f8f86f978497), C64e(0xc799eeee5eb099b0), C64e(0xf78df6f67a8c8d8c), C64e(0xe50dffffe8170d17), C64e(0xb7bdd6d60adcbddc), C64e(0xa7b1dede16c8b1c8), C64e(0x395491916dfc54fc), C64e(0xc050606090f050f0), C64e(0x0403020207050305), C64e(0x87a9cece2ee0a9e0), C64e(0xac7d5656d1877d87), C64e(0xd519e7e7cc2b192b), C64e(0x7162b5b513a662a6), C64e(0x9ae64d4d7c31e631), C64e(0xc39aecec59b59ab5), C64e(0x05458f8f40cf45cf), C64e(0x3e9d1f1fa3bc9dbc), C64e(0x0940898949c040c0), C64e(0xef87fafa68928792), C64e(0xc515efefd03f153f), C64e(0x7febb2b29426eb26), C64e(0x07c98e8ece40c940), C64e(0xed0bfbfbe61d0b1d), C64e(0x82ec41416e2fec2f), C64e(0x7d67b3b31aa967a9), C64e(0xbefd5f5f431cfd1c), C64e(0x8aea45456025ea25), C64e(0x46bf2323f9dabfda), C64e(0xa6f753535102f702), C64e(0xd396e4e445a196a1), C64e(0x2d5b9b9b76ed5bed), C64e(0xeac27575285dc25d), C64e(0xd91ce1e1c5241c24), C64e(0x7aae3d3dd4e9aee9), C64e(0x986a4c4cf2be6abe), C64e(0xd85a6c6c82ee5aee), C64e(0xfc417e7ebdc341c3), C64e(0xf102f5f5f3060206), C64e(0x1d4f838352d14fd1), C64e(0xd05c68688ce45ce4), C64e(0xa2f451515607f407), C64e(0xb934d1d18d5c345c), C64e(0xe908f9f9e1180818), C64e(0xdf93e2e24cae93ae), C64e(0x4d73abab3e957395), C64e(0xc453626297f553f5), C64e(0x543f2a2a6b413f41), C64e(0x100c08081c140c14), C64e(0x3152959563f652f6), C64e(0x8c654646e9af65af), C64e(0x215e9d9d7fe25ee2), C64e(0x6028303048782878), C64e(0x6ea13737cff8a1f8), C64e(0x140f0a0a1b110f11), C64e(0x5eb52f2febc4b5c4), C64e(0x1c090e0e151b091b), C64e(0x483624247e5a365a), C64e(0x369b1b1badb69bb6), C64e(0xa53ddfdf98473d47), C64e(0x8126cdcda76a266a), C64e(0x9c694e4ef5bb69bb), C64e(0xfecd7f7f334ccd4c), C64e(0xcf9feaea50ba9fba), C64e(0x241b12123f2d1b2d), C64e(0x3a9e1d1da4b99eb9), C64e(0xb0745858c49c749c), C64e(0x682e343446722e72), C64e(0x6c2d363641772d77), C64e(0xa3b2dcdc11cdb2cd), C64e(0x73eeb4b49d29ee29), C64e(0xb6fb5b5b4d16fb16), C64e(0x53f6a4a4a501f601), C64e(0xec4d7676a1d74dd7), C64e(0x7561b7b714a361a3), C64e(0xface7d7d3449ce49), C64e(0xa47b5252df8d7b8d), C64e(0xa13edddd9f423e42), C64e(0xbc715e5ecd937193), C64e(0x26971313b1a297a2), C64e(0x57f5a6a6a204f504), C64e(0x6968b9b901b868b8), C64e(0x0000000000000000), C64e(0x992cc1c1b5742c74), C64e(0x80604040e0a060a0), C64e(0xdd1fe3e3c2211f21), C64e(0xf2c879793a43c843), C64e(0x77edb6b69a2ced2c), C64e(0xb3bed4d40dd9bed9), C64e(0x01468d8d47ca46ca), C64e(0xced967671770d970), C64e(0xe44b7272afdd4bdd), C64e(0x33de9494ed79de79), C64e(0x2bd49898ff67d467), C64e(0x7be8b0b09323e823), C64e(0x114a85855bde4ade), C64e(0x6d6bbbbb06bd6bbd), C64e(0x912ac5c5bb7e2a7e), C64e(0x9ee54f4f7b34e534), C64e(0xc116ededd73a163a), C64e(0x17c58686d254c554), C64e(0x2fd79a9af862d762), C64e(0xcc55666699ff55ff), C64e(0x22941111b6a794a7), C64e(0x0fcf8a8ac04acf4a), C64e(0xc910e9e9d9301030), C64e(0x080604040e0a060a), C64e(0xe781fefe66988198), C64e(0x5bf0a0a0ab0bf00b), C64e(0xf0447878b4cc44cc), C64e(0x4aba2525f0d5bad5), C64e(0x96e34b4b753ee33e), C64e(0x5ff3a2a2ac0ef30e), C64e(0xbafe5d5d4419fe19), C64e(0x1bc08080db5bc05b), C64e(0x0a8a050580858a85), C64e(0x7ead3f3fd3ecadec), C64e(0x42bc2121fedfbcdf), C64e(0xe0487070a8d848d8), C64e(0xf904f1f1fd0c040c), C64e(0xc6df6363197adf7a), C64e(0xeec177772f58c158), C64e(0x4575afaf309f759f), C64e(0x84634242e7a563a5), C64e(0x4030202070503050), C64e(0xd11ae5e5cb2e1a2e), C64e(0xe10efdfdef120e12), C64e(0x656dbfbf08b76db7), C64e(0x194c818155d44cd4), C64e(0x30141818243c143c), C64e(0x4c352626795f355f), C64e(0x9d2fc3c3b2712f71), C64e(0x67e1bebe8638e138), C64e(0x6aa23535c8fda2fd), C64e(0x0bcc8888c74fcc4f), C64e(0x5c392e2e654b394b), C64e(0x3d5793936af957f9), C64e(0xaaf25555580df20d), C64e(0xe382fcfc619d829d), C64e(0xf4477a7ab3c947c9), C64e(0x8bacc8c827efacef), C64e(0x6fe7baba8832e732), C64e(0x642b32324f7d2b7d), C64e(0xd795e6e642a495a4), C64e(0x9ba0c0c03bfba0fb), C64e(0x32981919aab398b3), C64e(0x27d19e9ef668d168), C64e(0x5d7fa3a322817f81), C64e(0x88664444eeaa66aa), C64e(0xa87e5454d6827e82), C64e(0x76ab3b3bdde6abe6), C64e(0x16830b0b959e839e), C64e(0x03ca8c8cc945ca45), C64e(0x9529c7c7bc7b297b), C64e(0xd6d36b6b056ed36e), C64e(0x503c28286c443c44), C64e(0x5579a7a72c8b798b), C64e(0x63e2bcbc813de23d), C64e(0x2c1d161631271d27), C64e(0x4176adad379a769a), C64e(0xad3bdbdb964d3b4d), C64e(0xc85664649efa56fa), C64e(0xe84e7474a6d24ed2), C64e(0x281e141436221e22), C64e(0x3fdb9292e476db76), C64e(0x180a0c0c121e0a1e), C64e(0x906c4848fcb46cb4), C64e(0x6be4b8b88f37e437), C64e(0x255d9f9f78e75de7), C64e(0x616ebdbd0fb26eb2), C64e(0x86ef4343692aef2a), C64e(0x93a6c4c435f1a6f1), C64e(0x72a83939dae3a8e3), C64e(0x62a43131c6f7a4f7), C64e(0xbd37d3d38a593759), C64e(0xff8bf2f274868b86), C64e(0xb132d5d583563256), C64e(0x0d438b8b4ec543c5), C64e(0xdc596e6e85eb59eb), C64e(0xafb7dada18c2b7c2), C64e(0x028c01018e8f8c8f), C64e(0x7964b1b11dac64ac), C64e(0x23d29c9cf16dd26d), C64e(0x92e04949723be03b), C64e(0xabb4d8d81fc7b4c7), C64e(0x43faacacb915fa15), C64e(0xfd07f3f3fa090709), C64e(0x8525cfcfa06f256f), C64e(0x8fafcaca20eaafea), C64e(0xf38ef4f47d898e89), C64e(0x8ee947476720e920), C64e(0x2018101038281828), C64e(0xded56f6f0b64d564), C64e(0xfb88f0f073838883), C64e(0x946f4a4afbb16fb1), C64e(0xb8725c5cca967296), C64e(0x70243838546c246c), C64e(0xaef157575f08f108), C64e(0xe6c773732152c752), C64e(0x3551979764f351f3), C64e(0x8d23cbcbae652365), C64e(0x597ca1a125847c84), C64e(0xcb9ce8e857bf9cbf), C64e(0x7c213e3e5d632163), C64e(0x37dd9696ea7cdd7c), C64e(0xc2dc61611e7fdc7f), C64e(0x1a860d0d9c918691), C64e(0x1e850f0f9b948594), C64e(0xdb90e0e04bab90ab), C64e(0xf8427c7cbac642c6), C64e(0xe2c471712657c457), C64e(0x83aacccc29e5aae5), C64e(0x3bd89090e373d873), C64e(0x0c050606090f050f), C64e(0xf501f7f7f4030103), C64e(0x38121c1c2a361236), C64e(0x9fa3c2c23cfea3fe), C64e(0xd45f6a6a8be15fe1), C64e(0x47f9aeaebe10f910), C64e(0xd2d06969026bd06b), C64e(0x2e911717bfa891a8), C64e(0x2958999971e858e8), C64e(0x74273a3a53692769), C64e(0x4eb92727f7d0b9d0), C64e(0xa938d9d991483848), C64e(0xcd13ebebde351335), C64e(0x56b32b2be5ceb3ce), C64e(0x4433222277553355), C64e(0xbfbbd2d204d6bbd6), C64e(0x4970a9a939907090), C64e(0x0e89070787808980), C64e(0x66a73333c1f2a7f2), C64e(0x5ab62d2decc1b6c1), C64e(0x78223c3c5a662266), C64e(0x2a921515b8ad92ad), C64e(0x8920c9c9a9602060), C64e(0x154987875cdb49db), C64e(0x4fffaaaab01aff1a), C64e(0xa0785050d8887888), C64e(0x517aa5a52b8e7a8e), C64e(0x068f0303898a8f8a), C64e(0xb2f859594a13f813), C64e(0x12800909929b809b), C64e(0x34171a1a23391739), C64e(0xcada65651075da75), C64e(0xb531d7d784533153), C64e(0x13c68484d551c651), C64e(0xbbb8d0d003d3b8d3), C64e(0x1fc38282dc5ec35e), C64e(0x52b02929e2cbb0cb), C64e(0xb4775a5ac3997799), C64e(0x3c111e1e2d331133), C64e(0xf6cb7b7b3d46cb46), C64e(0x4bfca8a8b71ffc1f), C64e(0xdad66d6d0c61d661), C64e(0x583a2c2c624e3a4e) }; #endif static const sph_u64 T4[] = { C64e(0xf497a5c6c632f4a5), C64e(0x97eb84f8f86f9784), C64e(0xb0c799eeee5eb099), C64e(0x8cf78df6f67a8c8d), C64e(0x17e50dffffe8170d), C64e(0xdcb7bdd6d60adcbd), C64e(0xc8a7b1dede16c8b1), C64e(0xfc395491916dfc54), C64e(0xf0c050606090f050), C64e(0x0504030202070503), C64e(0xe087a9cece2ee0a9), C64e(0x87ac7d5656d1877d), C64e(0x2bd519e7e7cc2b19), C64e(0xa67162b5b513a662), C64e(0x319ae64d4d7c31e6), C64e(0xb5c39aecec59b59a), C64e(0xcf05458f8f40cf45), C64e(0xbc3e9d1f1fa3bc9d), C64e(0xc00940898949c040), C64e(0x92ef87fafa689287), C64e(0x3fc515efefd03f15), C64e(0x267febb2b29426eb), C64e(0x4007c98e8ece40c9), C64e(0x1ded0bfbfbe61d0b), C64e(0x2f82ec41416e2fec), C64e(0xa97d67b3b31aa967), C64e(0x1cbefd5f5f431cfd), C64e(0x258aea45456025ea), C64e(0xda46bf2323f9dabf), C64e(0x02a6f753535102f7), C64e(0xa1d396e4e445a196), C64e(0xed2d5b9b9b76ed5b), C64e(0x5deac27575285dc2), C64e(0x24d91ce1e1c5241c), C64e(0xe97aae3d3dd4e9ae), C64e(0xbe986a4c4cf2be6a), C64e(0xeed85a6c6c82ee5a), C64e(0xc3fc417e7ebdc341), C64e(0x06f102f5f5f30602), C64e(0xd11d4f838352d14f), C64e(0xe4d05c68688ce45c), C64e(0x07a2f451515607f4), C64e(0x5cb934d1d18d5c34), C64e(0x18e908f9f9e11808), C64e(0xaedf93e2e24cae93), C64e(0x954d73abab3e9573), C64e(0xf5c453626297f553), C64e(0x41543f2a2a6b413f), C64e(0x14100c08081c140c), C64e(0xf63152959563f652), C64e(0xaf8c654646e9af65), C64e(0xe2215e9d9d7fe25e), C64e(0x7860283030487828), C64e(0xf86ea13737cff8a1), C64e(0x11140f0a0a1b110f), C64e(0xc45eb52f2febc4b5), C64e(0x1b1c090e0e151b09), C64e(0x5a483624247e5a36), C64e(0xb6369b1b1badb69b), C64e(0x47a53ddfdf98473d), C64e(0x6a8126cdcda76a26), C64e(0xbb9c694e4ef5bb69), C64e(0x4cfecd7f7f334ccd), C64e(0xbacf9feaea50ba9f), C64e(0x2d241b12123f2d1b), C64e(0xb93a9e1d1da4b99e), C64e(0x9cb0745858c49c74), C64e(0x72682e343446722e), C64e(0x776c2d363641772d), C64e(0xcda3b2dcdc11cdb2), C64e(0x2973eeb4b49d29ee), C64e(0x16b6fb5b5b4d16fb), C64e(0x0153f6a4a4a501f6), C64e(0xd7ec4d7676a1d74d), C64e(0xa37561b7b714a361), C64e(0x49face7d7d3449ce), C64e(0x8da47b5252df8d7b), C64e(0x42a13edddd9f423e), C64e(0x93bc715e5ecd9371), C64e(0xa226971313b1a297), C64e(0x0457f5a6a6a204f5), C64e(0xb86968b9b901b868), C64e(0x0000000000000000), C64e(0x74992cc1c1b5742c), C64e(0xa080604040e0a060), C64e(0x21dd1fe3e3c2211f), C64e(0x43f2c879793a43c8), C64e(0x2c77edb6b69a2ced), C64e(0xd9b3bed4d40dd9be), C64e(0xca01468d8d47ca46), C64e(0x70ced967671770d9), C64e(0xdde44b7272afdd4b), C64e(0x7933de9494ed79de), C64e(0x672bd49898ff67d4), C64e(0x237be8b0b09323e8), C64e(0xde114a85855bde4a), C64e(0xbd6d6bbbbb06bd6b), C64e(0x7e912ac5c5bb7e2a), C64e(0x349ee54f4f7b34e5), C64e(0x3ac116ededd73a16), C64e(0x5417c58686d254c5), C64e(0x622fd79a9af862d7), C64e(0xffcc55666699ff55), C64e(0xa722941111b6a794), C64e(0x4a0fcf8a8ac04acf), C64e(0x30c910e9e9d93010), C64e(0x0a080604040e0a06), C64e(0x98e781fefe669881), C64e(0x0b5bf0a0a0ab0bf0), C64e(0xccf0447878b4cc44), C64e(0xd54aba2525f0d5ba), C64e(0x3e96e34b4b753ee3), C64e(0x0e5ff3a2a2ac0ef3), C64e(0x19bafe5d5d4419fe), C64e(0x5b1bc08080db5bc0), C64e(0x850a8a050580858a), C64e(0xec7ead3f3fd3ecad), C64e(0xdf42bc2121fedfbc), C64e(0xd8e0487070a8d848), C64e(0x0cf904f1f1fd0c04), C64e(0x7ac6df6363197adf), C64e(0x58eec177772f58c1), C64e(0x9f4575afaf309f75), C64e(0xa584634242e7a563), C64e(0x5040302020705030), C64e(0x2ed11ae5e5cb2e1a), C64e(0x12e10efdfdef120e), C64e(0xb7656dbfbf08b76d), C64e(0xd4194c818155d44c), C64e(0x3c30141818243c14), C64e(0x5f4c352626795f35), C64e(0x719d2fc3c3b2712f), C64e(0x3867e1bebe8638e1), C64e(0xfd6aa23535c8fda2), C64e(0x4f0bcc8888c74fcc), C64e(0x4b5c392e2e654b39), C64e(0xf93d5793936af957), C64e(0x0daaf25555580df2), C64e(0x9de382fcfc619d82), C64e(0xc9f4477a7ab3c947), C64e(0xef8bacc8c827efac), C64e(0x326fe7baba8832e7), C64e(0x7d642b32324f7d2b), C64e(0xa4d795e6e642a495), C64e(0xfb9ba0c0c03bfba0), C64e(0xb332981919aab398), C64e(0x6827d19e9ef668d1), C64e(0x815d7fa3a322817f), C64e(0xaa88664444eeaa66), C64e(0x82a87e5454d6827e), C64e(0xe676ab3b3bdde6ab), C64e(0x9e16830b0b959e83), C64e(0x4503ca8c8cc945ca), C64e(0x7b9529c7c7bc7b29), C64e(0x6ed6d36b6b056ed3), C64e(0x44503c28286c443c), C64e(0x8b5579a7a72c8b79), C64e(0x3d63e2bcbc813de2), C64e(0x272c1d161631271d), C64e(0x9a4176adad379a76), C64e(0x4dad3bdbdb964d3b), C64e(0xfac85664649efa56), C64e(0xd2e84e7474a6d24e), C64e(0x22281e141436221e), C64e(0x763fdb9292e476db), C64e(0x1e180a0c0c121e0a), C64e(0xb4906c4848fcb46c), C64e(0x376be4b8b88f37e4), C64e(0xe7255d9f9f78e75d), C64e(0xb2616ebdbd0fb26e), C64e(0x2a86ef4343692aef), C64e(0xf193a6c4c435f1a6), C64e(0xe372a83939dae3a8), C64e(0xf762a43131c6f7a4), C64e(0x59bd37d3d38a5937), C64e(0x86ff8bf2f274868b), C64e(0x56b132d5d5835632), C64e(0xc50d438b8b4ec543), C64e(0xebdc596e6e85eb59), C64e(0xc2afb7dada18c2b7), C64e(0x8f028c01018e8f8c), C64e(0xac7964b1b11dac64), C64e(0x6d23d29c9cf16dd2), C64e(0x3b92e04949723be0), C64e(0xc7abb4d8d81fc7b4), C64e(0x1543faacacb915fa), C64e(0x09fd07f3f3fa0907), C64e(0x6f8525cfcfa06f25), C64e(0xea8fafcaca20eaaf), C64e(0x89f38ef4f47d898e), C64e(0x208ee947476720e9), C64e(0x2820181010382818), C64e(0x64ded56f6f0b64d5), C64e(0x83fb88f0f0738388), C64e(0xb1946f4a4afbb16f), C64e(0x96b8725c5cca9672), C64e(0x6c70243838546c24), C64e(0x08aef157575f08f1), C64e(0x52e6c773732152c7), C64e(0xf33551979764f351), C64e(0x658d23cbcbae6523), C64e(0x84597ca1a125847c), C64e(0xbfcb9ce8e857bf9c), C64e(0x637c213e3e5d6321), C64e(0x7c37dd9696ea7cdd), C64e(0x7fc2dc61611e7fdc), C64e(0x911a860d0d9c9186), C64e(0x941e850f0f9b9485), C64e(0xabdb90e0e04bab90), C64e(0xc6f8427c7cbac642), C64e(0x57e2c471712657c4), C64e(0xe583aacccc29e5aa), C64e(0x733bd89090e373d8), C64e(0x0f0c050606090f05), C64e(0x03f501f7f7f40301), C64e(0x3638121c1c2a3612), C64e(0xfe9fa3c2c23cfea3), C64e(0xe1d45f6a6a8be15f), C64e(0x1047f9aeaebe10f9), C64e(0x6bd2d06969026bd0), C64e(0xa82e911717bfa891), C64e(0xe82958999971e858), C64e(0x6974273a3a536927), C64e(0xd04eb92727f7d0b9), C64e(0x48a938d9d9914838), C64e(0x35cd13ebebde3513), C64e(0xce56b32b2be5ceb3), C64e(0x5544332222775533), C64e(0xd6bfbbd2d204d6bb), C64e(0x904970a9a9399070), C64e(0x800e890707878089), C64e(0xf266a73333c1f2a7), C64e(0xc15ab62d2decc1b6), C64e(0x6678223c3c5a6622), C64e(0xad2a921515b8ad92), C64e(0x608920c9c9a96020), C64e(0xdb154987875cdb49), C64e(0x1a4fffaaaab01aff), C64e(0x88a0785050d88878), C64e(0x8e517aa5a52b8e7a), C64e(0x8a068f0303898a8f), C64e(0x13b2f859594a13f8), C64e(0x9b12800909929b80), C64e(0x3934171a1a233917), C64e(0x75cada65651075da), C64e(0x53b531d7d7845331), C64e(0x5113c68484d551c6), C64e(0xd3bbb8d0d003d3b8), C64e(0x5e1fc38282dc5ec3), C64e(0xcb52b02929e2cbb0), C64e(0x99b4775a5ac39977), C64e(0x333c111e1e2d3311), C64e(0x46f6cb7b7b3d46cb), C64e(0x1f4bfca8a8b71ffc), C64e(0x61dad66d6d0c61d6), C64e(0x4e583a2c2c624e3a) }; #if !SPH_SMALL_FOOTPRINT_GROESTL static const sph_u64 T5[] = { C64e(0xa5f497a5c6c632f4), C64e(0x8497eb84f8f86f97), C64e(0x99b0c799eeee5eb0), C64e(0x8d8cf78df6f67a8c), C64e(0x0d17e50dffffe817), C64e(0xbddcb7bdd6d60adc), C64e(0xb1c8a7b1dede16c8), C64e(0x54fc395491916dfc), C64e(0x50f0c050606090f0), C64e(0x0305040302020705), C64e(0xa9e087a9cece2ee0), C64e(0x7d87ac7d5656d187), C64e(0x192bd519e7e7cc2b), C64e(0x62a67162b5b513a6), C64e(0xe6319ae64d4d7c31), C64e(0x9ab5c39aecec59b5), C64e(0x45cf05458f8f40cf), C64e(0x9dbc3e9d1f1fa3bc), C64e(0x40c00940898949c0), C64e(0x8792ef87fafa6892), C64e(0x153fc515efefd03f), C64e(0xeb267febb2b29426), C64e(0xc94007c98e8ece40), C64e(0x0b1ded0bfbfbe61d), C64e(0xec2f82ec41416e2f), C64e(0x67a97d67b3b31aa9), C64e(0xfd1cbefd5f5f431c), C64e(0xea258aea45456025), C64e(0xbfda46bf2323f9da), C64e(0xf702a6f753535102), C64e(0x96a1d396e4e445a1), C64e(0x5bed2d5b9b9b76ed), C64e(0xc25deac27575285d), C64e(0x1c24d91ce1e1c524), C64e(0xaee97aae3d3dd4e9), C64e(0x6abe986a4c4cf2be), C64e(0x5aeed85a6c6c82ee), C64e(0x41c3fc417e7ebdc3), C64e(0x0206f102f5f5f306), C64e(0x4fd11d4f838352d1), C64e(0x5ce4d05c68688ce4), C64e(0xf407a2f451515607), C64e(0x345cb934d1d18d5c), C64e(0x0818e908f9f9e118), C64e(0x93aedf93e2e24cae), C64e(0x73954d73abab3e95), C64e(0x53f5c453626297f5), C64e(0x3f41543f2a2a6b41), C64e(0x0c14100c08081c14), C64e(0x52f63152959563f6), C64e(0x65af8c654646e9af), C64e(0x5ee2215e9d9d7fe2), C64e(0x2878602830304878), C64e(0xa1f86ea13737cff8), C64e(0x0f11140f0a0a1b11), C64e(0xb5c45eb52f2febc4), C64e(0x091b1c090e0e151b), C64e(0x365a483624247e5a), C64e(0x9bb6369b1b1badb6), C64e(0x3d47a53ddfdf9847), C64e(0x266a8126cdcda76a), C64e(0x69bb9c694e4ef5bb), C64e(0xcd4cfecd7f7f334c), C64e(0x9fbacf9feaea50ba), C64e(0x1b2d241b12123f2d), C64e(0x9eb93a9e1d1da4b9), C64e(0x749cb0745858c49c), C64e(0x2e72682e34344672), C64e(0x2d776c2d36364177), C64e(0xb2cda3b2dcdc11cd), C64e(0xee2973eeb4b49d29), C64e(0xfb16b6fb5b5b4d16), C64e(0xf60153f6a4a4a501), C64e(0x4dd7ec4d7676a1d7), C64e(0x61a37561b7b714a3), C64e(0xce49face7d7d3449), C64e(0x7b8da47b5252df8d), C64e(0x3e42a13edddd9f42), C64e(0x7193bc715e5ecd93), C64e(0x97a226971313b1a2), C64e(0xf50457f5a6a6a204), C64e(0x68b86968b9b901b8), C64e(0x0000000000000000), C64e(0x2c74992cc1c1b574), C64e(0x60a080604040e0a0), C64e(0x1f21dd1fe3e3c221), C64e(0xc843f2c879793a43), C64e(0xed2c77edb6b69a2c), C64e(0xbed9b3bed4d40dd9), C64e(0x46ca01468d8d47ca), C64e(0xd970ced967671770), C64e(0x4bdde44b7272afdd), C64e(0xde7933de9494ed79), C64e(0xd4672bd49898ff67), C64e(0xe8237be8b0b09323), C64e(0x4ade114a85855bde), C64e(0x6bbd6d6bbbbb06bd), C64e(0x2a7e912ac5c5bb7e), C64e(0xe5349ee54f4f7b34), C64e(0x163ac116ededd73a), C64e(0xc55417c58686d254), C64e(0xd7622fd79a9af862), C64e(0x55ffcc55666699ff), C64e(0x94a722941111b6a7), C64e(0xcf4a0fcf8a8ac04a), C64e(0x1030c910e9e9d930), C64e(0x060a080604040e0a), C64e(0x8198e781fefe6698), C64e(0xf00b5bf0a0a0ab0b), C64e(0x44ccf0447878b4cc), C64e(0xbad54aba2525f0d5), C64e(0xe33e96e34b4b753e), C64e(0xf30e5ff3a2a2ac0e), C64e(0xfe19bafe5d5d4419), C64e(0xc05b1bc08080db5b), C64e(0x8a850a8a05058085), C64e(0xadec7ead3f3fd3ec), C64e(0xbcdf42bc2121fedf), C64e(0x48d8e0487070a8d8), C64e(0x040cf904f1f1fd0c), C64e(0xdf7ac6df6363197a), C64e(0xc158eec177772f58), C64e(0x759f4575afaf309f), C64e(0x63a584634242e7a5), C64e(0x3050403020207050), C64e(0x1a2ed11ae5e5cb2e), C64e(0x0e12e10efdfdef12), C64e(0x6db7656dbfbf08b7), C64e(0x4cd4194c818155d4), C64e(0x143c30141818243c), C64e(0x355f4c352626795f), C64e(0x2f719d2fc3c3b271), C64e(0xe13867e1bebe8638), C64e(0xa2fd6aa23535c8fd), C64e(0xcc4f0bcc8888c74f), C64e(0x394b5c392e2e654b), C64e(0x57f93d5793936af9), C64e(0xf20daaf25555580d), C64e(0x829de382fcfc619d), C64e(0x47c9f4477a7ab3c9), C64e(0xacef8bacc8c827ef), C64e(0xe7326fe7baba8832), C64e(0x2b7d642b32324f7d), C64e(0x95a4d795e6e642a4), C64e(0xa0fb9ba0c0c03bfb), C64e(0x98b332981919aab3), C64e(0xd16827d19e9ef668), C64e(0x7f815d7fa3a32281), C64e(0x66aa88664444eeaa), C64e(0x7e82a87e5454d682), C64e(0xabe676ab3b3bdde6), C64e(0x839e16830b0b959e), C64e(0xca4503ca8c8cc945), C64e(0x297b9529c7c7bc7b), C64e(0xd36ed6d36b6b056e), C64e(0x3c44503c28286c44), C64e(0x798b5579a7a72c8b), C64e(0xe23d63e2bcbc813d), C64e(0x1d272c1d16163127), C64e(0x769a4176adad379a), C64e(0x3b4dad3bdbdb964d), C64e(0x56fac85664649efa), C64e(0x4ed2e84e7474a6d2), C64e(0x1e22281e14143622), C64e(0xdb763fdb9292e476), C64e(0x0a1e180a0c0c121e), C64e(0x6cb4906c4848fcb4), C64e(0xe4376be4b8b88f37), C64e(0x5de7255d9f9f78e7), C64e(0x6eb2616ebdbd0fb2), C64e(0xef2a86ef4343692a), C64e(0xa6f193a6c4c435f1), C64e(0xa8e372a83939dae3), C64e(0xa4f762a43131c6f7), C64e(0x3759bd37d3d38a59), C64e(0x8b86ff8bf2f27486), C64e(0x3256b132d5d58356), C64e(0x43c50d438b8b4ec5), C64e(0x59ebdc596e6e85eb), C64e(0xb7c2afb7dada18c2), C64e(0x8c8f028c01018e8f), C64e(0x64ac7964b1b11dac), C64e(0xd26d23d29c9cf16d), C64e(0xe03b92e04949723b), C64e(0xb4c7abb4d8d81fc7), C64e(0xfa1543faacacb915), C64e(0x0709fd07f3f3fa09), C64e(0x256f8525cfcfa06f), C64e(0xafea8fafcaca20ea), C64e(0x8e89f38ef4f47d89), C64e(0xe9208ee947476720), C64e(0x1828201810103828), C64e(0xd564ded56f6f0b64), C64e(0x8883fb88f0f07383), C64e(0x6fb1946f4a4afbb1), C64e(0x7296b8725c5cca96), C64e(0x246c70243838546c), C64e(0xf108aef157575f08), C64e(0xc752e6c773732152), C64e(0x51f33551979764f3), C64e(0x23658d23cbcbae65), C64e(0x7c84597ca1a12584), C64e(0x9cbfcb9ce8e857bf), C64e(0x21637c213e3e5d63), C64e(0xdd7c37dd9696ea7c), C64e(0xdc7fc2dc61611e7f), C64e(0x86911a860d0d9c91), C64e(0x85941e850f0f9b94), C64e(0x90abdb90e0e04bab), C64e(0x42c6f8427c7cbac6), C64e(0xc457e2c471712657), C64e(0xaae583aacccc29e5), C64e(0xd8733bd89090e373), C64e(0x050f0c050606090f), C64e(0x0103f501f7f7f403), C64e(0x123638121c1c2a36), C64e(0xa3fe9fa3c2c23cfe), C64e(0x5fe1d45f6a6a8be1), C64e(0xf91047f9aeaebe10), C64e(0xd06bd2d06969026b), C64e(0x91a82e911717bfa8), C64e(0x58e82958999971e8), C64e(0x276974273a3a5369), C64e(0xb9d04eb92727f7d0), C64e(0x3848a938d9d99148), C64e(0x1335cd13ebebde35), C64e(0xb3ce56b32b2be5ce), C64e(0x3355443322227755), C64e(0xbbd6bfbbd2d204d6), C64e(0x70904970a9a93990), C64e(0x89800e8907078780), C64e(0xa7f266a73333c1f2), C64e(0xb6c15ab62d2decc1), C64e(0x226678223c3c5a66), C64e(0x92ad2a921515b8ad), C64e(0x20608920c9c9a960), C64e(0x49db154987875cdb), C64e(0xff1a4fffaaaab01a), C64e(0x7888a0785050d888), C64e(0x7a8e517aa5a52b8e), C64e(0x8f8a068f0303898a), C64e(0xf813b2f859594a13), C64e(0x809b12800909929b), C64e(0x173934171a1a2339), C64e(0xda75cada65651075), C64e(0x3153b531d7d78453), C64e(0xc65113c68484d551), C64e(0xb8d3bbb8d0d003d3), C64e(0xc35e1fc38282dc5e), C64e(0xb0cb52b02929e2cb), C64e(0x7799b4775a5ac399), C64e(0x11333c111e1e2d33), C64e(0xcb46f6cb7b7b3d46), C64e(0xfc1f4bfca8a8b71f), C64e(0xd661dad66d6d0c61), C64e(0x3a4e583a2c2c624e) }; static const sph_u64 T6[] = { C64e(0xf4a5f497a5c6c632), C64e(0x978497eb84f8f86f), C64e(0xb099b0c799eeee5e), C64e(0x8c8d8cf78df6f67a), C64e(0x170d17e50dffffe8), C64e(0xdcbddcb7bdd6d60a), C64e(0xc8b1c8a7b1dede16), C64e(0xfc54fc395491916d), C64e(0xf050f0c050606090), C64e(0x0503050403020207), C64e(0xe0a9e087a9cece2e), C64e(0x877d87ac7d5656d1), C64e(0x2b192bd519e7e7cc), C64e(0xa662a67162b5b513), C64e(0x31e6319ae64d4d7c), C64e(0xb59ab5c39aecec59), C64e(0xcf45cf05458f8f40), C64e(0xbc9dbc3e9d1f1fa3), C64e(0xc040c00940898949), C64e(0x928792ef87fafa68), C64e(0x3f153fc515efefd0), C64e(0x26eb267febb2b294), C64e(0x40c94007c98e8ece), C64e(0x1d0b1ded0bfbfbe6), C64e(0x2fec2f82ec41416e), C64e(0xa967a97d67b3b31a), C64e(0x1cfd1cbefd5f5f43), C64e(0x25ea258aea454560), C64e(0xdabfda46bf2323f9), C64e(0x02f702a6f7535351), C64e(0xa196a1d396e4e445), C64e(0xed5bed2d5b9b9b76), C64e(0x5dc25deac2757528), C64e(0x241c24d91ce1e1c5), C64e(0xe9aee97aae3d3dd4), C64e(0xbe6abe986a4c4cf2), C64e(0xee5aeed85a6c6c82), C64e(0xc341c3fc417e7ebd), C64e(0x060206f102f5f5f3), C64e(0xd14fd11d4f838352), C64e(0xe45ce4d05c68688c), C64e(0x07f407a2f4515156), C64e(0x5c345cb934d1d18d), C64e(0x180818e908f9f9e1), C64e(0xae93aedf93e2e24c), C64e(0x9573954d73abab3e), C64e(0xf553f5c453626297), C64e(0x413f41543f2a2a6b), C64e(0x140c14100c08081c), C64e(0xf652f63152959563), C64e(0xaf65af8c654646e9), C64e(0xe25ee2215e9d9d7f), C64e(0x7828786028303048), C64e(0xf8a1f86ea13737cf), C64e(0x110f11140f0a0a1b), C64e(0xc4b5c45eb52f2feb), C64e(0x1b091b1c090e0e15), C64e(0x5a365a483624247e), C64e(0xb69bb6369b1b1bad), C64e(0x473d47a53ddfdf98), C64e(0x6a266a8126cdcda7), C64e(0xbb69bb9c694e4ef5), C64e(0x4ccd4cfecd7f7f33), C64e(0xba9fbacf9feaea50), C64e(0x2d1b2d241b12123f), C64e(0xb99eb93a9e1d1da4), C64e(0x9c749cb0745858c4), C64e(0x722e72682e343446), C64e(0x772d776c2d363641), C64e(0xcdb2cda3b2dcdc11), C64e(0x29ee2973eeb4b49d), C64e(0x16fb16b6fb5b5b4d), C64e(0x01f60153f6a4a4a5), C64e(0xd74dd7ec4d7676a1), C64e(0xa361a37561b7b714), C64e(0x49ce49face7d7d34), C64e(0x8d7b8da47b5252df), C64e(0x423e42a13edddd9f), C64e(0x937193bc715e5ecd), C64e(0xa297a226971313b1), C64e(0x04f50457f5a6a6a2), C64e(0xb868b86968b9b901), C64e(0x0000000000000000), C64e(0x742c74992cc1c1b5), C64e(0xa060a080604040e0), C64e(0x211f21dd1fe3e3c2), C64e(0x43c843f2c879793a), C64e(0x2ced2c77edb6b69a), C64e(0xd9bed9b3bed4d40d), C64e(0xca46ca01468d8d47), C64e(0x70d970ced9676717), C64e(0xdd4bdde44b7272af), C64e(0x79de7933de9494ed), C64e(0x67d4672bd49898ff), C64e(0x23e8237be8b0b093), C64e(0xde4ade114a85855b), C64e(0xbd6bbd6d6bbbbb06), C64e(0x7e2a7e912ac5c5bb), C64e(0x34e5349ee54f4f7b), C64e(0x3a163ac116ededd7), C64e(0x54c55417c58686d2), C64e(0x62d7622fd79a9af8), C64e(0xff55ffcc55666699), C64e(0xa794a722941111b6), C64e(0x4acf4a0fcf8a8ac0), C64e(0x301030c910e9e9d9), C64e(0x0a060a080604040e), C64e(0x988198e781fefe66), C64e(0x0bf00b5bf0a0a0ab), C64e(0xcc44ccf0447878b4), C64e(0xd5bad54aba2525f0), C64e(0x3ee33e96e34b4b75), C64e(0x0ef30e5ff3a2a2ac), C64e(0x19fe19bafe5d5d44), C64e(0x5bc05b1bc08080db), C64e(0x858a850a8a050580), C64e(0xecadec7ead3f3fd3), C64e(0xdfbcdf42bc2121fe), C64e(0xd848d8e0487070a8), C64e(0x0c040cf904f1f1fd), C64e(0x7adf7ac6df636319), C64e(0x58c158eec177772f), C64e(0x9f759f4575afaf30), C64e(0xa563a584634242e7), C64e(0x5030504030202070), C64e(0x2e1a2ed11ae5e5cb), C64e(0x120e12e10efdfdef), C64e(0xb76db7656dbfbf08), C64e(0xd44cd4194c818155), C64e(0x3c143c3014181824), C64e(0x5f355f4c35262679), C64e(0x712f719d2fc3c3b2), C64e(0x38e13867e1bebe86), C64e(0xfda2fd6aa23535c8), C64e(0x4fcc4f0bcc8888c7), C64e(0x4b394b5c392e2e65), C64e(0xf957f93d5793936a), C64e(0x0df20daaf2555558), C64e(0x9d829de382fcfc61), C64e(0xc947c9f4477a7ab3), C64e(0xefacef8bacc8c827), C64e(0x32e7326fe7baba88), C64e(0x7d2b7d642b32324f), C64e(0xa495a4d795e6e642), C64e(0xfba0fb9ba0c0c03b), C64e(0xb398b332981919aa), C64e(0x68d16827d19e9ef6), C64e(0x817f815d7fa3a322), C64e(0xaa66aa88664444ee), C64e(0x827e82a87e5454d6), C64e(0xe6abe676ab3b3bdd), C64e(0x9e839e16830b0b95), C64e(0x45ca4503ca8c8cc9), C64e(0x7b297b9529c7c7bc), C64e(0x6ed36ed6d36b6b05), C64e(0x443c44503c28286c), C64e(0x8b798b5579a7a72c), C64e(0x3de23d63e2bcbc81), C64e(0x271d272c1d161631), C64e(0x9a769a4176adad37), C64e(0x4d3b4dad3bdbdb96), C64e(0xfa56fac85664649e), C64e(0xd24ed2e84e7474a6), C64e(0x221e22281e141436), C64e(0x76db763fdb9292e4), C64e(0x1e0a1e180a0c0c12), C64e(0xb46cb4906c4848fc), C64e(0x37e4376be4b8b88f), C64e(0xe75de7255d9f9f78), C64e(0xb26eb2616ebdbd0f), C64e(0x2aef2a86ef434369), C64e(0xf1a6f193a6c4c435), C64e(0xe3a8e372a83939da), C64e(0xf7a4f762a43131c6), C64e(0x593759bd37d3d38a), C64e(0x868b86ff8bf2f274), C64e(0x563256b132d5d583), C64e(0xc543c50d438b8b4e), C64e(0xeb59ebdc596e6e85), C64e(0xc2b7c2afb7dada18), C64e(0x8f8c8f028c01018e), C64e(0xac64ac7964b1b11d), C64e(0x6dd26d23d29c9cf1), C64e(0x3be03b92e0494972), C64e(0xc7b4c7abb4d8d81f), C64e(0x15fa1543faacacb9), C64e(0x090709fd07f3f3fa), C64e(0x6f256f8525cfcfa0), C64e(0xeaafea8fafcaca20), C64e(0x898e89f38ef4f47d), C64e(0x20e9208ee9474767), C64e(0x2818282018101038), C64e(0x64d564ded56f6f0b), C64e(0x838883fb88f0f073), C64e(0xb16fb1946f4a4afb), C64e(0x967296b8725c5cca), C64e(0x6c246c7024383854), C64e(0x08f108aef157575f), C64e(0x52c752e6c7737321), C64e(0xf351f33551979764), C64e(0x6523658d23cbcbae), C64e(0x847c84597ca1a125), C64e(0xbf9cbfcb9ce8e857), C64e(0x6321637c213e3e5d), C64e(0x7cdd7c37dd9696ea), C64e(0x7fdc7fc2dc61611e), C64e(0x9186911a860d0d9c), C64e(0x9485941e850f0f9b), C64e(0xab90abdb90e0e04b), C64e(0xc642c6f8427c7cba), C64e(0x57c457e2c4717126), C64e(0xe5aae583aacccc29), C64e(0x73d8733bd89090e3), C64e(0x0f050f0c05060609), C64e(0x030103f501f7f7f4), C64e(0x36123638121c1c2a), C64e(0xfea3fe9fa3c2c23c), C64e(0xe15fe1d45f6a6a8b), C64e(0x10f91047f9aeaebe), C64e(0x6bd06bd2d0696902), C64e(0xa891a82e911717bf), C64e(0xe858e82958999971), C64e(0x69276974273a3a53), C64e(0xd0b9d04eb92727f7), C64e(0x483848a938d9d991), C64e(0x351335cd13ebebde), C64e(0xceb3ce56b32b2be5), C64e(0x5533554433222277), C64e(0xd6bbd6bfbbd2d204), C64e(0x9070904970a9a939), C64e(0x8089800e89070787), C64e(0xf2a7f266a73333c1), C64e(0xc1b6c15ab62d2dec), C64e(0x66226678223c3c5a), C64e(0xad92ad2a921515b8), C64e(0x6020608920c9c9a9), C64e(0xdb49db154987875c), C64e(0x1aff1a4fffaaaab0), C64e(0x887888a0785050d8), C64e(0x8e7a8e517aa5a52b), C64e(0x8a8f8a068f030389), C64e(0x13f813b2f859594a), C64e(0x9b809b1280090992), C64e(0x39173934171a1a23), C64e(0x75da75cada656510), C64e(0x533153b531d7d784), C64e(0x51c65113c68484d5), C64e(0xd3b8d3bbb8d0d003), C64e(0x5ec35e1fc38282dc), C64e(0xcbb0cb52b02929e2), C64e(0x997799b4775a5ac3), C64e(0x3311333c111e1e2d), C64e(0x46cb46f6cb7b7b3d), C64e(0x1ffc1f4bfca8a8b7), C64e(0x61d661dad66d6d0c), C64e(0x4e3a4e583a2c2c62) }; static const sph_u64 T7[] = { C64e(0x32f4a5f497a5c6c6), C64e(0x6f978497eb84f8f8), C64e(0x5eb099b0c799eeee), C64e(0x7a8c8d8cf78df6f6), C64e(0xe8170d17e50dffff), C64e(0x0adcbddcb7bdd6d6), C64e(0x16c8b1c8a7b1dede), C64e(0x6dfc54fc39549191), C64e(0x90f050f0c0506060), C64e(0x0705030504030202), C64e(0x2ee0a9e087a9cece), C64e(0xd1877d87ac7d5656), C64e(0xcc2b192bd519e7e7), C64e(0x13a662a67162b5b5), C64e(0x7c31e6319ae64d4d), C64e(0x59b59ab5c39aecec), C64e(0x40cf45cf05458f8f), C64e(0xa3bc9dbc3e9d1f1f), C64e(0x49c040c009408989), C64e(0x68928792ef87fafa), C64e(0xd03f153fc515efef), C64e(0x9426eb267febb2b2), C64e(0xce40c94007c98e8e), C64e(0xe61d0b1ded0bfbfb), C64e(0x6e2fec2f82ec4141), C64e(0x1aa967a97d67b3b3), C64e(0x431cfd1cbefd5f5f), C64e(0x6025ea258aea4545), C64e(0xf9dabfda46bf2323), C64e(0x5102f702a6f75353), C64e(0x45a196a1d396e4e4), C64e(0x76ed5bed2d5b9b9b), C64e(0x285dc25deac27575), C64e(0xc5241c24d91ce1e1), C64e(0xd4e9aee97aae3d3d), C64e(0xf2be6abe986a4c4c), C64e(0x82ee5aeed85a6c6c), C64e(0xbdc341c3fc417e7e), C64e(0xf3060206f102f5f5), C64e(0x52d14fd11d4f8383), C64e(0x8ce45ce4d05c6868), C64e(0x5607f407a2f45151), C64e(0x8d5c345cb934d1d1), C64e(0xe1180818e908f9f9), C64e(0x4cae93aedf93e2e2), C64e(0x3e9573954d73abab), C64e(0x97f553f5c4536262), C64e(0x6b413f41543f2a2a), C64e(0x1c140c14100c0808), C64e(0x63f652f631529595), C64e(0xe9af65af8c654646), C64e(0x7fe25ee2215e9d9d), C64e(0x4878287860283030), C64e(0xcff8a1f86ea13737), C64e(0x1b110f11140f0a0a), C64e(0xebc4b5c45eb52f2f), C64e(0x151b091b1c090e0e), C64e(0x7e5a365a48362424), C64e(0xadb69bb6369b1b1b), C64e(0x98473d47a53ddfdf), C64e(0xa76a266a8126cdcd), C64e(0xf5bb69bb9c694e4e), C64e(0x334ccd4cfecd7f7f), C64e(0x50ba9fbacf9feaea), C64e(0x3f2d1b2d241b1212), C64e(0xa4b99eb93a9e1d1d), C64e(0xc49c749cb0745858), C64e(0x46722e72682e3434), C64e(0x41772d776c2d3636), C64e(0x11cdb2cda3b2dcdc), C64e(0x9d29ee2973eeb4b4), C64e(0x4d16fb16b6fb5b5b), C64e(0xa501f60153f6a4a4), C64e(0xa1d74dd7ec4d7676), C64e(0x14a361a37561b7b7), C64e(0x3449ce49face7d7d), C64e(0xdf8d7b8da47b5252), C64e(0x9f423e42a13edddd), C64e(0xcd937193bc715e5e), C64e(0xb1a297a226971313), C64e(0xa204f50457f5a6a6), C64e(0x01b868b86968b9b9), C64e(0x0000000000000000), C64e(0xb5742c74992cc1c1), C64e(0xe0a060a080604040), C64e(0xc2211f21dd1fe3e3), C64e(0x3a43c843f2c87979), C64e(0x9a2ced2c77edb6b6), C64e(0x0dd9bed9b3bed4d4), C64e(0x47ca46ca01468d8d), C64e(0x1770d970ced96767), C64e(0xafdd4bdde44b7272), C64e(0xed79de7933de9494), C64e(0xff67d4672bd49898), C64e(0x9323e8237be8b0b0), C64e(0x5bde4ade114a8585), C64e(0x06bd6bbd6d6bbbbb), C64e(0xbb7e2a7e912ac5c5), C64e(0x7b34e5349ee54f4f), C64e(0xd73a163ac116eded), C64e(0xd254c55417c58686), C64e(0xf862d7622fd79a9a), C64e(0x99ff55ffcc556666), C64e(0xb6a794a722941111), C64e(0xc04acf4a0fcf8a8a), C64e(0xd9301030c910e9e9), C64e(0x0e0a060a08060404), C64e(0x66988198e781fefe), C64e(0xab0bf00b5bf0a0a0), C64e(0xb4cc44ccf0447878), C64e(0xf0d5bad54aba2525), C64e(0x753ee33e96e34b4b), C64e(0xac0ef30e5ff3a2a2), C64e(0x4419fe19bafe5d5d), C64e(0xdb5bc05b1bc08080), C64e(0x80858a850a8a0505), C64e(0xd3ecadec7ead3f3f), C64e(0xfedfbcdf42bc2121), C64e(0xa8d848d8e0487070), C64e(0xfd0c040cf904f1f1), C64e(0x197adf7ac6df6363), C64e(0x2f58c158eec17777), C64e(0x309f759f4575afaf), C64e(0xe7a563a584634242), C64e(0x7050305040302020), C64e(0xcb2e1a2ed11ae5e5), C64e(0xef120e12e10efdfd), C64e(0x08b76db7656dbfbf), C64e(0x55d44cd4194c8181), C64e(0x243c143c30141818), C64e(0x795f355f4c352626), C64e(0xb2712f719d2fc3c3), C64e(0x8638e13867e1bebe), C64e(0xc8fda2fd6aa23535), C64e(0xc74fcc4f0bcc8888), C64e(0x654b394b5c392e2e), C64e(0x6af957f93d579393), C64e(0x580df20daaf25555), C64e(0x619d829de382fcfc), C64e(0xb3c947c9f4477a7a), C64e(0x27efacef8bacc8c8), C64e(0x8832e7326fe7baba), C64e(0x4f7d2b7d642b3232), C64e(0x42a495a4d795e6e6), C64e(0x3bfba0fb9ba0c0c0), C64e(0xaab398b332981919), C64e(0xf668d16827d19e9e), C64e(0x22817f815d7fa3a3), C64e(0xeeaa66aa88664444), C64e(0xd6827e82a87e5454), C64e(0xdde6abe676ab3b3b), C64e(0x959e839e16830b0b), C64e(0xc945ca4503ca8c8c), C64e(0xbc7b297b9529c7c7), C64e(0x056ed36ed6d36b6b), C64e(0x6c443c44503c2828), C64e(0x2c8b798b5579a7a7), C64e(0x813de23d63e2bcbc), C64e(0x31271d272c1d1616), C64e(0x379a769a4176adad), C64e(0x964d3b4dad3bdbdb), C64e(0x9efa56fac8566464), C64e(0xa6d24ed2e84e7474), C64e(0x36221e22281e1414), C64e(0xe476db763fdb9292), C64e(0x121e0a1e180a0c0c), C64e(0xfcb46cb4906c4848), C64e(0x8f37e4376be4b8b8), C64e(0x78e75de7255d9f9f), C64e(0x0fb26eb2616ebdbd), C64e(0x692aef2a86ef4343), C64e(0x35f1a6f193a6c4c4), C64e(0xdae3a8e372a83939), C64e(0xc6f7a4f762a43131), C64e(0x8a593759bd37d3d3), C64e(0x74868b86ff8bf2f2), C64e(0x83563256b132d5d5), C64e(0x4ec543c50d438b8b), C64e(0x85eb59ebdc596e6e), C64e(0x18c2b7c2afb7dada), C64e(0x8e8f8c8f028c0101), C64e(0x1dac64ac7964b1b1), C64e(0xf16dd26d23d29c9c), C64e(0x723be03b92e04949), C64e(0x1fc7b4c7abb4d8d8), C64e(0xb915fa1543faacac), C64e(0xfa090709fd07f3f3), C64e(0xa06f256f8525cfcf), C64e(0x20eaafea8fafcaca), C64e(0x7d898e89f38ef4f4), C64e(0x6720e9208ee94747), C64e(0x3828182820181010), C64e(0x0b64d564ded56f6f), C64e(0x73838883fb88f0f0), C64e(0xfbb16fb1946f4a4a), C64e(0xca967296b8725c5c), C64e(0x546c246c70243838), C64e(0x5f08f108aef15757), C64e(0x2152c752e6c77373), C64e(0x64f351f335519797), C64e(0xae6523658d23cbcb), C64e(0x25847c84597ca1a1), C64e(0x57bf9cbfcb9ce8e8), C64e(0x5d6321637c213e3e), C64e(0xea7cdd7c37dd9696), C64e(0x1e7fdc7fc2dc6161), C64e(0x9c9186911a860d0d), C64e(0x9b9485941e850f0f), C64e(0x4bab90abdb90e0e0), C64e(0xbac642c6f8427c7c), C64e(0x2657c457e2c47171), C64e(0x29e5aae583aacccc), C64e(0xe373d8733bd89090), C64e(0x090f050f0c050606), C64e(0xf4030103f501f7f7), C64e(0x2a36123638121c1c), C64e(0x3cfea3fe9fa3c2c2), C64e(0x8be15fe1d45f6a6a), C64e(0xbe10f91047f9aeae), C64e(0x026bd06bd2d06969), C64e(0xbfa891a82e911717), C64e(0x71e858e829589999), C64e(0x5369276974273a3a), C64e(0xf7d0b9d04eb92727), C64e(0x91483848a938d9d9), C64e(0xde351335cd13ebeb), C64e(0xe5ceb3ce56b32b2b), C64e(0x7755335544332222), C64e(0x04d6bbd6bfbbd2d2), C64e(0x399070904970a9a9), C64e(0x878089800e890707), C64e(0xc1f2a7f266a73333), C64e(0xecc1b6c15ab62d2d), C64e(0x5a66226678223c3c), C64e(0xb8ad92ad2a921515), C64e(0xa96020608920c9c9), C64e(0x5cdb49db15498787), C64e(0xb01aff1a4fffaaaa), C64e(0xd8887888a0785050), C64e(0x2b8e7a8e517aa5a5), C64e(0x898a8f8a068f0303), C64e(0x4a13f813b2f85959), C64e(0x929b809b12800909), C64e(0x2339173934171a1a), C64e(0x1075da75cada6565), C64e(0x84533153b531d7d7), C64e(0xd551c65113c68484), C64e(0x03d3b8d3bbb8d0d0), C64e(0xdc5ec35e1fc38282), C64e(0xe2cbb0cb52b02929), C64e(0xc3997799b4775a5a), C64e(0x2d3311333c111e1e), C64e(0x3d46cb46f6cb7b7b), C64e(0xb71ffc1f4bfca8a8), C64e(0x0c61d661dad66d6d), C64e(0x624e3a4e583a2c2c) }; #endif #define DECL_STATE_SMALL \ sph_u64 H[8]; #define READ_STATE_SMALL(sc) do { \ memcpy(H, (sc)->state.wide, sizeof H); \ } while (0) #define WRITE_STATE_SMALL(sc) do { \ memcpy((sc)->state.wide, H, sizeof H); \ } while (0) #if SPH_SMALL_FOOTPRINT_GROESTL #define RSTT(d, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ t[d] = T0[B64_0(a[b0])] \ ^ R64(T0[B64_1(a[b1])], 8) \ ^ R64(T0[B64_2(a[b2])], 16) \ ^ R64(T0[B64_3(a[b3])], 24) \ ^ T4[B64_4(a[b4])] \ ^ R64(T4[B64_5(a[b5])], 8) \ ^ R64(T4[B64_6(a[b6])], 16) \ ^ R64(T4[B64_7(a[b7])], 24); \ } while (0) #else #define RSTT(d, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ t[d] = T0[B64_0(a[b0])] \ ^ T1[B64_1(a[b1])] \ ^ T2[B64_2(a[b2])] \ ^ T3[B64_3(a[b3])] \ ^ T4[B64_4(a[b4])] \ ^ T5[B64_5(a[b5])] \ ^ T6[B64_6(a[b6])] \ ^ T7[B64_7(a[b7])]; \ } while (0) #endif #define ROUND_SMALL_P(a, r) do { \ sph_u64 t[8]; \ a[0] ^= PC64(0x00, r); \ a[1] ^= PC64(0x10, r); \ a[2] ^= PC64(0x20, r); \ a[3] ^= PC64(0x30, r); \ a[4] ^= PC64(0x40, r); \ a[5] ^= PC64(0x50, r); \ a[6] ^= PC64(0x60, r); \ a[7] ^= PC64(0x70, r); \ RSTT(0, a, 0, 1, 2, 3, 4, 5, 6, 7); \ RSTT(1, a, 1, 2, 3, 4, 5, 6, 7, 0); \ RSTT(2, a, 2, 3, 4, 5, 6, 7, 0, 1); \ RSTT(3, a, 3, 4, 5, 6, 7, 0, 1, 2); \ RSTT(4, a, 4, 5, 6, 7, 0, 1, 2, 3); \ RSTT(5, a, 5, 6, 7, 0, 1, 2, 3, 4); \ RSTT(6, a, 6, 7, 0, 1, 2, 3, 4, 5); \ RSTT(7, a, 7, 0, 1, 2, 3, 4, 5, 6); \ a[0] = t[0]; \ a[1] = t[1]; \ a[2] = t[2]; \ a[3] = t[3]; \ a[4] = t[4]; \ a[5] = t[5]; \ a[6] = t[6]; \ a[7] = t[7]; \ } while (0) #define ROUND_SMALL_Q(a, r) do { \ sph_u64 t[8]; \ a[0] ^= QC64(0x00, r); \ a[1] ^= QC64(0x10, r); \ a[2] ^= QC64(0x20, r); \ a[3] ^= QC64(0x30, r); \ a[4] ^= QC64(0x40, r); \ a[5] ^= QC64(0x50, r); \ a[6] ^= QC64(0x60, r); \ a[7] ^= QC64(0x70, r); \ RSTT(0, a, 1, 3, 5, 7, 0, 2, 4, 6); \ RSTT(1, a, 2, 4, 6, 0, 1, 3, 5, 7); \ RSTT(2, a, 3, 5, 7, 1, 2, 4, 6, 0); \ RSTT(3, a, 4, 6, 0, 2, 3, 5, 7, 1); \ RSTT(4, a, 5, 7, 1, 3, 4, 6, 0, 2); \ RSTT(5, a, 6, 0, 2, 4, 5, 7, 1, 3); \ RSTT(6, a, 7, 1, 3, 5, 6, 0, 2, 4); \ RSTT(7, a, 0, 2, 4, 6, 7, 1, 3, 5); \ a[0] = t[0]; \ a[1] = t[1]; \ a[2] = t[2]; \ a[3] = t[3]; \ a[4] = t[4]; \ a[5] = t[5]; \ a[6] = t[6]; \ a[7] = t[7]; \ } while (0) #if SPH_SMALL_FOOTPRINT_GROESTL #define PERM_SMALL_P(a) do { \ int r; \ for (r = 0; r < 10; r ++) \ ROUND_SMALL_P(a, r); \ } while (0) #define PERM_SMALL_Q(a) do { \ int r; \ for (r = 0; r < 10; r ++) \ ROUND_SMALL_Q(a, r); \ } while (0) #else /* * Apparently, unrolling more than that confuses GCC, resulting in * lower performance, even though L1 cache would be no problem. */ #define PERM_SMALL_P(a) do { \ int r; \ for (r = 0; r < 10; r += 2) { \ ROUND_SMALL_P(a, r + 0); \ ROUND_SMALL_P(a, r + 1); \ } \ } while (0) #define PERM_SMALL_Q(a) do { \ int r; \ for (r = 0; r < 10; r += 2) { \ ROUND_SMALL_Q(a, r + 0); \ ROUND_SMALL_Q(a, r + 1); \ } \ } while (0) #endif #define COMPRESS_SMALL do { \ sph_u64 g[8], m[8]; \ size_t u; \ for (u = 0; u < 8; u ++) { \ m[u] = dec64e_aligned(buf + (u << 3)); \ g[u] = m[u] ^ H[u]; \ } \ PERM_SMALL_P(g); \ PERM_SMALL_Q(m); \ for (u = 0; u < 8; u ++) \ H[u] ^= g[u] ^ m[u]; \ } while (0) #define FINAL_SMALL do { \ sph_u64 x[8]; \ size_t u; \ memcpy(x, H, sizeof x); \ PERM_SMALL_P(x); \ for (u = 0; u < 8; u ++) \ H[u] ^= x[u]; \ } while (0) #define DECL_STATE_BIG \ sph_u64 H[16]; #define READ_STATE_BIG(sc) do { \ memcpy(H, (sc)->state.wide, sizeof H); \ } while (0) #define WRITE_STATE_BIG(sc) do { \ memcpy((sc)->state.wide, H, sizeof H); \ } while (0) #if SPH_SMALL_FOOTPRINT_GROESTL #define RBTT(d, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ t[d] = T0[B64_0(a[b0])] \ ^ R64(T0[B64_1(a[b1])], 8) \ ^ R64(T0[B64_2(a[b2])], 16) \ ^ R64(T0[B64_3(a[b3])], 24) \ ^ T4[B64_4(a[b4])] \ ^ R64(T4[B64_5(a[b5])], 8) \ ^ R64(T4[B64_6(a[b6])], 16) \ ^ R64(T4[B64_7(a[b7])], 24); \ } while (0) #else #define RBTT(d, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ t[d] = T0[B64_0(a[b0])] \ ^ T1[B64_1(a[b1])] \ ^ T2[B64_2(a[b2])] \ ^ T3[B64_3(a[b3])] \ ^ T4[B64_4(a[b4])] \ ^ T5[B64_5(a[b5])] \ ^ T6[B64_6(a[b6])] \ ^ T7[B64_7(a[b7])]; \ } while (0) #endif #if SPH_SMALL_FOOTPRINT_GROESTL #define ROUND_BIG_P(a, r) do { \ sph_u64 t[16]; \ size_t u; \ a[0x0] ^= PC64(0x00, r); \ a[0x1] ^= PC64(0x10, r); \ a[0x2] ^= PC64(0x20, r); \ a[0x3] ^= PC64(0x30, r); \ a[0x4] ^= PC64(0x40, r); \ a[0x5] ^= PC64(0x50, r); \ a[0x6] ^= PC64(0x60, r); \ a[0x7] ^= PC64(0x70, r); \ a[0x8] ^= PC64(0x80, r); \ a[0x9] ^= PC64(0x90, r); \ a[0xA] ^= PC64(0xA0, r); \ a[0xB] ^= PC64(0xB0, r); \ a[0xC] ^= PC64(0xC0, r); \ a[0xD] ^= PC64(0xD0, r); \ a[0xE] ^= PC64(0xE0, r); \ a[0xF] ^= PC64(0xF0, r); \ for (u = 0; u < 16; u += 4) { \ RBTT(u + 0, a, u + 0, (u + 1) & 0xF, \ (u + 2) & 0xF, (u + 3) & 0xF, (u + 4) & 0xF, \ (u + 5) & 0xF, (u + 6) & 0xF, (u + 11) & 0xF); \ RBTT(u + 1, a, u + 1, (u + 2) & 0xF, \ (u + 3) & 0xF, (u + 4) & 0xF, (u + 5) & 0xF, \ (u + 6) & 0xF, (u + 7) & 0xF, (u + 12) & 0xF); \ RBTT(u + 2, a, u + 2, (u + 3) & 0xF, \ (u + 4) & 0xF, (u + 5) & 0xF, (u + 6) & 0xF, \ (u + 7) & 0xF, (u + 8) & 0xF, (u + 13) & 0xF); \ RBTT(u + 3, a, u + 3, (u + 4) & 0xF, \ (u + 5) & 0xF, (u + 6) & 0xF, (u + 7) & 0xF, \ (u + 8) & 0xF, (u + 9) & 0xF, (u + 14) & 0xF); \ } \ memcpy(a, t, sizeof t); \ } while (0) #define ROUND_BIG_Q(a, r) do { \ sph_u64 t[16]; \ size_t u; \ a[0x0] ^= QC64(0x00, r); \ a[0x1] ^= QC64(0x10, r); \ a[0x2] ^= QC64(0x20, r); \ a[0x3] ^= QC64(0x30, r); \ a[0x4] ^= QC64(0x40, r); \ a[0x5] ^= QC64(0x50, r); \ a[0x6] ^= QC64(0x60, r); \ a[0x7] ^= QC64(0x70, r); \ a[0x8] ^= QC64(0x80, r); \ a[0x9] ^= QC64(0x90, r); \ a[0xA] ^= QC64(0xA0, r); \ a[0xB] ^= QC64(0xB0, r); \ a[0xC] ^= QC64(0xC0, r); \ a[0xD] ^= QC64(0xD0, r); \ a[0xE] ^= QC64(0xE0, r); \ a[0xF] ^= QC64(0xF0, r); \ for (u = 0; u < 16; u += 4) { \ RBTT(u + 0, a, (u + 1) & 0xF, (u + 3) & 0xF, \ (u + 5) & 0xF, (u + 11) & 0xF, (u + 0) & 0xF, \ (u + 2) & 0xF, (u + 4) & 0xF, (u + 6) & 0xF); \ RBTT(u + 1, a, (u + 2) & 0xF, (u + 4) & 0xF, \ (u + 6) & 0xF, (u + 12) & 0xF, (u + 1) & 0xF, \ (u + 3) & 0xF, (u + 5) & 0xF, (u + 7) & 0xF); \ RBTT(u + 2, a, (u + 3) & 0xF, (u + 5) & 0xF, \ (u + 7) & 0xF, (u + 13) & 0xF, (u + 2) & 0xF, \ (u + 4) & 0xF, (u + 6) & 0xF, (u + 8) & 0xF); \ RBTT(u + 3, a, (u + 4) & 0xF, (u + 6) & 0xF, \ (u + 8) & 0xF, (u + 14) & 0xF, (u + 3) & 0xF, \ (u + 5) & 0xF, (u + 7) & 0xF, (u + 9) & 0xF); \ } \ memcpy(a, t, sizeof t); \ } while (0) #else #define ROUND_BIG_P(a, r) do { \ sph_u64 t[16]; \ a[0x0] ^= PC64(0x00, r); \ a[0x1] ^= PC64(0x10, r); \ a[0x2] ^= PC64(0x20, r); \ a[0x3] ^= PC64(0x30, r); \ a[0x4] ^= PC64(0x40, r); \ a[0x5] ^= PC64(0x50, r); \ a[0x6] ^= PC64(0x60, r); \ a[0x7] ^= PC64(0x70, r); \ a[0x8] ^= PC64(0x80, r); \ a[0x9] ^= PC64(0x90, r); \ a[0xA] ^= PC64(0xA0, r); \ a[0xB] ^= PC64(0xB0, r); \ a[0xC] ^= PC64(0xC0, r); \ a[0xD] ^= PC64(0xD0, r); \ a[0xE] ^= PC64(0xE0, r); \ a[0xF] ^= PC64(0xF0, r); \ RBTT(0x0, a, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xB); \ RBTT(0x1, a, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0xC); \ RBTT(0x2, a, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0xD); \ RBTT(0x3, a, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xE); \ RBTT(0x4, a, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xF); \ RBTT(0x5, a, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0x0); \ RBTT(0x6, a, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0x1); \ RBTT(0x7, a, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0x2); \ RBTT(0x8, a, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x3); \ RBTT(0x9, a, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x4); \ RBTT(0xA, a, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x0, 0x5); \ RBTT(0xB, a, 0xB, 0xC, 0xD, 0xE, 0xF, 0x0, 0x1, 0x6); \ RBTT(0xC, a, 0xC, 0xD, 0xE, 0xF, 0x0, 0x1, 0x2, 0x7); \ RBTT(0xD, a, 0xD, 0xE, 0xF, 0x0, 0x1, 0x2, 0x3, 0x8); \ RBTT(0xE, a, 0xE, 0xF, 0x0, 0x1, 0x2, 0x3, 0x4, 0x9); \ RBTT(0xF, a, 0xF, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0xA); \ a[0x0] = t[0x0]; \ a[0x1] = t[0x1]; \ a[0x2] = t[0x2]; \ a[0x3] = t[0x3]; \ a[0x4] = t[0x4]; \ a[0x5] = t[0x5]; \ a[0x6] = t[0x6]; \ a[0x7] = t[0x7]; \ a[0x8] = t[0x8]; \ a[0x9] = t[0x9]; \ a[0xA] = t[0xA]; \ a[0xB] = t[0xB]; \ a[0xC] = t[0xC]; \ a[0xD] = t[0xD]; \ a[0xE] = t[0xE]; \ a[0xF] = t[0xF]; \ } while (0) #define ROUND_BIG_Q(a, r) do { \ sph_u64 t[16]; \ a[0x0] ^= QC64(0x00, r); \ a[0x1] ^= QC64(0x10, r); \ a[0x2] ^= QC64(0x20, r); \ a[0x3] ^= QC64(0x30, r); \ a[0x4] ^= QC64(0x40, r); \ a[0x5] ^= QC64(0x50, r); \ a[0x6] ^= QC64(0x60, r); \ a[0x7] ^= QC64(0x70, r); \ a[0x8] ^= QC64(0x80, r); \ a[0x9] ^= QC64(0x90, r); \ a[0xA] ^= QC64(0xA0, r); \ a[0xB] ^= QC64(0xB0, r); \ a[0xC] ^= QC64(0xC0, r); \ a[0xD] ^= QC64(0xD0, r); \ a[0xE] ^= QC64(0xE0, r); \ a[0xF] ^= QC64(0xF0, r); \ RBTT(0x0, a, 0x1, 0x3, 0x5, 0xB, 0x0, 0x2, 0x4, 0x6); \ RBTT(0x1, a, 0x2, 0x4, 0x6, 0xC, 0x1, 0x3, 0x5, 0x7); \ RBTT(0x2, a, 0x3, 0x5, 0x7, 0xD, 0x2, 0x4, 0x6, 0x8); \ RBTT(0x3, a, 0x4, 0x6, 0x8, 0xE, 0x3, 0x5, 0x7, 0x9); \ RBTT(0x4, a, 0x5, 0x7, 0x9, 0xF, 0x4, 0x6, 0x8, 0xA); \ RBTT(0x5, a, 0x6, 0x8, 0xA, 0x0, 0x5, 0x7, 0x9, 0xB); \ RBTT(0x6, a, 0x7, 0x9, 0xB, 0x1, 0x6, 0x8, 0xA, 0xC); \ RBTT(0x7, a, 0x8, 0xA, 0xC, 0x2, 0x7, 0x9, 0xB, 0xD); \ RBTT(0x8, a, 0x9, 0xB, 0xD, 0x3, 0x8, 0xA, 0xC, 0xE); \ RBTT(0x9, a, 0xA, 0xC, 0xE, 0x4, 0x9, 0xB, 0xD, 0xF); \ RBTT(0xA, a, 0xB, 0xD, 0xF, 0x5, 0xA, 0xC, 0xE, 0x0); \ RBTT(0xB, a, 0xC, 0xE, 0x0, 0x6, 0xB, 0xD, 0xF, 0x1); \ RBTT(0xC, a, 0xD, 0xF, 0x1, 0x7, 0xC, 0xE, 0x0, 0x2); \ RBTT(0xD, a, 0xE, 0x0, 0x2, 0x8, 0xD, 0xF, 0x1, 0x3); \ RBTT(0xE, a, 0xF, 0x1, 0x3, 0x9, 0xE, 0x0, 0x2, 0x4); \ RBTT(0xF, a, 0x0, 0x2, 0x4, 0xA, 0xF, 0x1, 0x3, 0x5); \ a[0x0] = t[0x0]; \ a[0x1] = t[0x1]; \ a[0x2] = t[0x2]; \ a[0x3] = t[0x3]; \ a[0x4] = t[0x4]; \ a[0x5] = t[0x5]; \ a[0x6] = t[0x6]; \ a[0x7] = t[0x7]; \ a[0x8] = t[0x8]; \ a[0x9] = t[0x9]; \ a[0xA] = t[0xA]; \ a[0xB] = t[0xB]; \ a[0xC] = t[0xC]; \ a[0xD] = t[0xD]; \ a[0xE] = t[0xE]; \ a[0xF] = t[0xF]; \ } while (0) #endif #define PERM_BIG_P(a) do { \ int r; \ for (r = 0; r < 14; r += 2) { \ ROUND_BIG_P(a, r + 0); \ ROUND_BIG_P(a, r + 1); \ } \ } while (0) #define PERM_BIG_Q(a) do { \ int r; \ for (r = 0; r < 14; r += 2) { \ ROUND_BIG_Q(a, r + 0); \ ROUND_BIG_Q(a, r + 1); \ } \ } while (0) /* obsolete #if SPH_SMALL_FOOTPRINT_GROESTL #define COMPRESS_BIG do { \ sph_u64 g[16], m[16], *ya; \ const sph_u64 *yc; \ size_t u; \ int i; \ for (u = 0; u < 16; u ++) { \ m[u] = dec64e_aligned(buf + (u << 3)); \ g[u] = m[u] ^ H[u]; \ } \ ya = g; \ yc = CP; \ for (i = 0; i < 2; i ++) { \ PERM_BIG(ya, yc); \ ya = m; \ yc = CQ; \ } \ for (u = 0; u < 16; u ++) { \ H[u] ^= g[u] ^ m[u]; \ } \ } while (0) #else */ #define COMPRESS_BIG do { \ sph_u64 g[16], m[16]; \ size_t u; \ for (u = 0; u < 16; u ++) { \ m[u] = dec64e_aligned(buf + (u << 3)); \ g[u] = m[u] ^ H[u]; \ } \ PERM_BIG_P(g); \ PERM_BIG_Q(m); \ for (u = 0; u < 16; u ++) { \ H[u] ^= g[u] ^ m[u]; \ } \ } while (0) /* obsolete #endif */ #define FINAL_BIG do { \ sph_u64 x[16]; \ size_t u; \ memcpy(x, H, sizeof x); \ PERM_BIG_P(x); \ for (u = 0; u < 16; u ++) \ H[u] ^= x[u]; \ } while (0) #else static const sph_u32 T0up[] = { C32e(0xc632f4a5), C32e(0xf86f9784), C32e(0xee5eb099), C32e(0xf67a8c8d), C32e(0xffe8170d), C32e(0xd60adcbd), C32e(0xde16c8b1), C32e(0x916dfc54), C32e(0x6090f050), C32e(0x02070503), C32e(0xce2ee0a9), C32e(0x56d1877d), C32e(0xe7cc2b19), C32e(0xb513a662), C32e(0x4d7c31e6), C32e(0xec59b59a), C32e(0x8f40cf45), C32e(0x1fa3bc9d), C32e(0x8949c040), C32e(0xfa689287), C32e(0xefd03f15), C32e(0xb29426eb), C32e(0x8ece40c9), C32e(0xfbe61d0b), C32e(0x416e2fec), C32e(0xb31aa967), C32e(0x5f431cfd), C32e(0x456025ea), C32e(0x23f9dabf), C32e(0x535102f7), C32e(0xe445a196), C32e(0x9b76ed5b), C32e(0x75285dc2), C32e(0xe1c5241c), C32e(0x3dd4e9ae), C32e(0x4cf2be6a), C32e(0x6c82ee5a), C32e(0x7ebdc341), C32e(0xf5f30602), C32e(0x8352d14f), C32e(0x688ce45c), C32e(0x515607f4), C32e(0xd18d5c34), C32e(0xf9e11808), C32e(0xe24cae93), C32e(0xab3e9573), C32e(0x6297f553), C32e(0x2a6b413f), C32e(0x081c140c), C32e(0x9563f652), C32e(0x46e9af65), C32e(0x9d7fe25e), C32e(0x30487828), C32e(0x37cff8a1), C32e(0x0a1b110f), C32e(0x2febc4b5), C32e(0x0e151b09), C32e(0x247e5a36), C32e(0x1badb69b), C32e(0xdf98473d), C32e(0xcda76a26), C32e(0x4ef5bb69), C32e(0x7f334ccd), C32e(0xea50ba9f), C32e(0x123f2d1b), C32e(0x1da4b99e), C32e(0x58c49c74), C32e(0x3446722e), C32e(0x3641772d), C32e(0xdc11cdb2), C32e(0xb49d29ee), C32e(0x5b4d16fb), C32e(0xa4a501f6), C32e(0x76a1d74d), C32e(0xb714a361), C32e(0x7d3449ce), C32e(0x52df8d7b), C32e(0xdd9f423e), C32e(0x5ecd9371), C32e(0x13b1a297), C32e(0xa6a204f5), C32e(0xb901b868), C32e(0x00000000), C32e(0xc1b5742c), C32e(0x40e0a060), C32e(0xe3c2211f), C32e(0x793a43c8), C32e(0xb69a2ced), C32e(0xd40dd9be), C32e(0x8d47ca46), C32e(0x671770d9), C32e(0x72afdd4b), C32e(0x94ed79de), C32e(0x98ff67d4), C32e(0xb09323e8), C32e(0x855bde4a), C32e(0xbb06bd6b), C32e(0xc5bb7e2a), C32e(0x4f7b34e5), C32e(0xedd73a16), C32e(0x86d254c5), C32e(0x9af862d7), C32e(0x6699ff55), C32e(0x11b6a794), C32e(0x8ac04acf), C32e(0xe9d93010), C32e(0x040e0a06), C32e(0xfe669881), C32e(0xa0ab0bf0), C32e(0x78b4cc44), C32e(0x25f0d5ba), C32e(0x4b753ee3), C32e(0xa2ac0ef3), C32e(0x5d4419fe), C32e(0x80db5bc0), C32e(0x0580858a), C32e(0x3fd3ecad), C32e(0x21fedfbc), C32e(0x70a8d848), C32e(0xf1fd0c04), C32e(0x63197adf), C32e(0x772f58c1), C32e(0xaf309f75), C32e(0x42e7a563), C32e(0x20705030), C32e(0xe5cb2e1a), C32e(0xfdef120e), C32e(0xbf08b76d), C32e(0x8155d44c), C32e(0x18243c14), C32e(0x26795f35), C32e(0xc3b2712f), C32e(0xbe8638e1), C32e(0x35c8fda2), C32e(0x88c74fcc), C32e(0x2e654b39), C32e(0x936af957), C32e(0x55580df2), C32e(0xfc619d82), C32e(0x7ab3c947), C32e(0xc827efac), C32e(0xba8832e7), C32e(0x324f7d2b), C32e(0xe642a495), C32e(0xc03bfba0), C32e(0x19aab398), C32e(0x9ef668d1), C32e(0xa322817f), C32e(0x44eeaa66), C32e(0x54d6827e), C32e(0x3bdde6ab), C32e(0x0b959e83), C32e(0x8cc945ca), C32e(0xc7bc7b29), C32e(0x6b056ed3), C32e(0x286c443c), C32e(0xa72c8b79), C32e(0xbc813de2), C32e(0x1631271d), C32e(0xad379a76), C32e(0xdb964d3b), C32e(0x649efa56), C32e(0x74a6d24e), C32e(0x1436221e), C32e(0x92e476db), C32e(0x0c121e0a), C32e(0x48fcb46c), C32e(0xb88f37e4), C32e(0x9f78e75d), C32e(0xbd0fb26e), C32e(0x43692aef), C32e(0xc435f1a6), C32e(0x39dae3a8), C32e(0x31c6f7a4), C32e(0xd38a5937), C32e(0xf274868b), C32e(0xd5835632), C32e(0x8b4ec543), C32e(0x6e85eb59), C32e(0xda18c2b7), C32e(0x018e8f8c), C32e(0xb11dac64), C32e(0x9cf16dd2), C32e(0x49723be0), C32e(0xd81fc7b4), C32e(0xacb915fa), C32e(0xf3fa0907), C32e(0xcfa06f25), C32e(0xca20eaaf), C32e(0xf47d898e), C32e(0x476720e9), C32e(0x10382818), C32e(0x6f0b64d5), C32e(0xf0738388), C32e(0x4afbb16f), C32e(0x5cca9672), C32e(0x38546c24), C32e(0x575f08f1), C32e(0x732152c7), C32e(0x9764f351), C32e(0xcbae6523), C32e(0xa125847c), C32e(0xe857bf9c), C32e(0x3e5d6321), C32e(0x96ea7cdd), C32e(0x611e7fdc), C32e(0x0d9c9186), C32e(0x0f9b9485), C32e(0xe04bab90), C32e(0x7cbac642), C32e(0x712657c4), C32e(0xcc29e5aa), C32e(0x90e373d8), C32e(0x06090f05), C32e(0xf7f40301), C32e(0x1c2a3612), C32e(0xc23cfea3), C32e(0x6a8be15f), C32e(0xaebe10f9), C32e(0x69026bd0), C32e(0x17bfa891), C32e(0x9971e858), C32e(0x3a536927), C32e(0x27f7d0b9), C32e(0xd9914838), C32e(0xebde3513), C32e(0x2be5ceb3), C32e(0x22775533), C32e(0xd204d6bb), C32e(0xa9399070), C32e(0x07878089), C32e(0x33c1f2a7), C32e(0x2decc1b6), C32e(0x3c5a6622), C32e(0x15b8ad92), C32e(0xc9a96020), C32e(0x875cdb49), C32e(0xaab01aff), C32e(0x50d88878), C32e(0xa52b8e7a), C32e(0x03898a8f), C32e(0x594a13f8), C32e(0x09929b80), C32e(0x1a233917), C32e(0x651075da), C32e(0xd7845331), C32e(0x84d551c6), C32e(0xd003d3b8), C32e(0x82dc5ec3), C32e(0x29e2cbb0), C32e(0x5ac39977), C32e(0x1e2d3311), C32e(0x7b3d46cb), C32e(0xa8b71ffc), C32e(0x6d0c61d6), C32e(0x2c624e3a) }; static const sph_u32 T0dn[] = { C32e(0xf497a5c6), C32e(0x97eb84f8), C32e(0xb0c799ee), C32e(0x8cf78df6), C32e(0x17e50dff), C32e(0xdcb7bdd6), C32e(0xc8a7b1de), C32e(0xfc395491), C32e(0xf0c05060), C32e(0x05040302), C32e(0xe087a9ce), C32e(0x87ac7d56), C32e(0x2bd519e7), C32e(0xa67162b5), C32e(0x319ae64d), C32e(0xb5c39aec), C32e(0xcf05458f), C32e(0xbc3e9d1f), C32e(0xc0094089), C32e(0x92ef87fa), C32e(0x3fc515ef), C32e(0x267febb2), C32e(0x4007c98e), C32e(0x1ded0bfb), C32e(0x2f82ec41), C32e(0xa97d67b3), C32e(0x1cbefd5f), C32e(0x258aea45), C32e(0xda46bf23), C32e(0x02a6f753), C32e(0xa1d396e4), C32e(0xed2d5b9b), C32e(0x5deac275), C32e(0x24d91ce1), C32e(0xe97aae3d), C32e(0xbe986a4c), C32e(0xeed85a6c), C32e(0xc3fc417e), C32e(0x06f102f5), C32e(0xd11d4f83), C32e(0xe4d05c68), C32e(0x07a2f451), C32e(0x5cb934d1), C32e(0x18e908f9), C32e(0xaedf93e2), C32e(0x954d73ab), C32e(0xf5c45362), C32e(0x41543f2a), C32e(0x14100c08), C32e(0xf6315295), C32e(0xaf8c6546), C32e(0xe2215e9d), C32e(0x78602830), C32e(0xf86ea137), C32e(0x11140f0a), C32e(0xc45eb52f), C32e(0x1b1c090e), C32e(0x5a483624), C32e(0xb6369b1b), C32e(0x47a53ddf), C32e(0x6a8126cd), C32e(0xbb9c694e), C32e(0x4cfecd7f), C32e(0xbacf9fea), C32e(0x2d241b12), C32e(0xb93a9e1d), C32e(0x9cb07458), C32e(0x72682e34), C32e(0x776c2d36), C32e(0xcda3b2dc), C32e(0x2973eeb4), C32e(0x16b6fb5b), C32e(0x0153f6a4), C32e(0xd7ec4d76), C32e(0xa37561b7), C32e(0x49face7d), C32e(0x8da47b52), C32e(0x42a13edd), C32e(0x93bc715e), C32e(0xa2269713), C32e(0x0457f5a6), C32e(0xb86968b9), C32e(0x00000000), C32e(0x74992cc1), C32e(0xa0806040), C32e(0x21dd1fe3), C32e(0x43f2c879), C32e(0x2c77edb6), C32e(0xd9b3bed4), C32e(0xca01468d), C32e(0x70ced967), C32e(0xdde44b72), C32e(0x7933de94), C32e(0x672bd498), C32e(0x237be8b0), C32e(0xde114a85), C32e(0xbd6d6bbb), C32e(0x7e912ac5), C32e(0x349ee54f), C32e(0x3ac116ed), C32e(0x5417c586), C32e(0x622fd79a), C32e(0xffcc5566), C32e(0xa7229411), C32e(0x4a0fcf8a), C32e(0x30c910e9), C32e(0x0a080604), C32e(0x98e781fe), C32e(0x0b5bf0a0), C32e(0xccf04478), C32e(0xd54aba25), C32e(0x3e96e34b), C32e(0x0e5ff3a2), C32e(0x19bafe5d), C32e(0x5b1bc080), C32e(0x850a8a05), C32e(0xec7ead3f), C32e(0xdf42bc21), C32e(0xd8e04870), C32e(0x0cf904f1), C32e(0x7ac6df63), C32e(0x58eec177), C32e(0x9f4575af), C32e(0xa5846342), C32e(0x50403020), C32e(0x2ed11ae5), C32e(0x12e10efd), C32e(0xb7656dbf), C32e(0xd4194c81), C32e(0x3c301418), C32e(0x5f4c3526), C32e(0x719d2fc3), C32e(0x3867e1be), C32e(0xfd6aa235), C32e(0x4f0bcc88), C32e(0x4b5c392e), C32e(0xf93d5793), C32e(0x0daaf255), C32e(0x9de382fc), C32e(0xc9f4477a), C32e(0xef8bacc8), C32e(0x326fe7ba), C32e(0x7d642b32), C32e(0xa4d795e6), C32e(0xfb9ba0c0), C32e(0xb3329819), C32e(0x6827d19e), C32e(0x815d7fa3), C32e(0xaa886644), C32e(0x82a87e54), C32e(0xe676ab3b), C32e(0x9e16830b), C32e(0x4503ca8c), C32e(0x7b9529c7), C32e(0x6ed6d36b), C32e(0x44503c28), C32e(0x8b5579a7), C32e(0x3d63e2bc), C32e(0x272c1d16), C32e(0x9a4176ad), C32e(0x4dad3bdb), C32e(0xfac85664), C32e(0xd2e84e74), C32e(0x22281e14), C32e(0x763fdb92), C32e(0x1e180a0c), C32e(0xb4906c48), C32e(0x376be4b8), C32e(0xe7255d9f), C32e(0xb2616ebd), C32e(0x2a86ef43), C32e(0xf193a6c4), C32e(0xe372a839), C32e(0xf762a431), C32e(0x59bd37d3), C32e(0x86ff8bf2), C32e(0x56b132d5), C32e(0xc50d438b), C32e(0xebdc596e), C32e(0xc2afb7da), C32e(0x8f028c01), C32e(0xac7964b1), C32e(0x6d23d29c), C32e(0x3b92e049), C32e(0xc7abb4d8), C32e(0x1543faac), C32e(0x09fd07f3), C32e(0x6f8525cf), C32e(0xea8fafca), C32e(0x89f38ef4), C32e(0x208ee947), C32e(0x28201810), C32e(0x64ded56f), C32e(0x83fb88f0), C32e(0xb1946f4a), C32e(0x96b8725c), C32e(0x6c702438), C32e(0x08aef157), C32e(0x52e6c773), C32e(0xf3355197), C32e(0x658d23cb), C32e(0x84597ca1), C32e(0xbfcb9ce8), C32e(0x637c213e), C32e(0x7c37dd96), C32e(0x7fc2dc61), C32e(0x911a860d), C32e(0x941e850f), C32e(0xabdb90e0), C32e(0xc6f8427c), C32e(0x57e2c471), C32e(0xe583aacc), C32e(0x733bd890), C32e(0x0f0c0506), C32e(0x03f501f7), C32e(0x3638121c), C32e(0xfe9fa3c2), C32e(0xe1d45f6a), C32e(0x1047f9ae), C32e(0x6bd2d069), C32e(0xa82e9117), C32e(0xe8295899), C32e(0x6974273a), C32e(0xd04eb927), C32e(0x48a938d9), C32e(0x35cd13eb), C32e(0xce56b32b), C32e(0x55443322), C32e(0xd6bfbbd2), C32e(0x904970a9), C32e(0x800e8907), C32e(0xf266a733), C32e(0xc15ab62d), C32e(0x6678223c), C32e(0xad2a9215), C32e(0x608920c9), C32e(0xdb154987), C32e(0x1a4fffaa), C32e(0x88a07850), C32e(0x8e517aa5), C32e(0x8a068f03), C32e(0x13b2f859), C32e(0x9b128009), C32e(0x3934171a), C32e(0x75cada65), C32e(0x53b531d7), C32e(0x5113c684), C32e(0xd3bbb8d0), C32e(0x5e1fc382), C32e(0xcb52b029), C32e(0x99b4775a), C32e(0x333c111e), C32e(0x46f6cb7b), C32e(0x1f4bfca8), C32e(0x61dad66d), C32e(0x4e583a2c) }; static const sph_u32 T1up[] = { C32e(0xc6c632f4), C32e(0xf8f86f97), C32e(0xeeee5eb0), C32e(0xf6f67a8c), C32e(0xffffe817), C32e(0xd6d60adc), C32e(0xdede16c8), C32e(0x91916dfc), C32e(0x606090f0), C32e(0x02020705), C32e(0xcece2ee0), C32e(0x5656d187), C32e(0xe7e7cc2b), C32e(0xb5b513a6), C32e(0x4d4d7c31), C32e(0xecec59b5), C32e(0x8f8f40cf), C32e(0x1f1fa3bc), C32e(0x898949c0), C32e(0xfafa6892), C32e(0xefefd03f), C32e(0xb2b29426), C32e(0x8e8ece40), C32e(0xfbfbe61d), C32e(0x41416e2f), C32e(0xb3b31aa9), C32e(0x5f5f431c), C32e(0x45456025), C32e(0x2323f9da), C32e(0x53535102), C32e(0xe4e445a1), C32e(0x9b9b76ed), C32e(0x7575285d), C32e(0xe1e1c524), C32e(0x3d3dd4e9), C32e(0x4c4cf2be), C32e(0x6c6c82ee), C32e(0x7e7ebdc3), C32e(0xf5f5f306), C32e(0x838352d1), C32e(0x68688ce4), C32e(0x51515607), C32e(0xd1d18d5c), C32e(0xf9f9e118), C32e(0xe2e24cae), C32e(0xabab3e95), C32e(0x626297f5), C32e(0x2a2a6b41), C32e(0x08081c14), C32e(0x959563f6), C32e(0x4646e9af), C32e(0x9d9d7fe2), C32e(0x30304878), C32e(0x3737cff8), C32e(0x0a0a1b11), C32e(0x2f2febc4), C32e(0x0e0e151b), C32e(0x24247e5a), C32e(0x1b1badb6), C32e(0xdfdf9847), C32e(0xcdcda76a), C32e(0x4e4ef5bb), C32e(0x7f7f334c), C32e(0xeaea50ba), C32e(0x12123f2d), C32e(0x1d1da4b9), C32e(0x5858c49c), C32e(0x34344672), C32e(0x36364177), C32e(0xdcdc11cd), C32e(0xb4b49d29), C32e(0x5b5b4d16), C32e(0xa4a4a501), C32e(0x7676a1d7), C32e(0xb7b714a3), C32e(0x7d7d3449), C32e(0x5252df8d), C32e(0xdddd9f42), C32e(0x5e5ecd93), C32e(0x1313b1a2), C32e(0xa6a6a204), C32e(0xb9b901b8), C32e(0x00000000), C32e(0xc1c1b574), C32e(0x4040e0a0), C32e(0xe3e3c221), C32e(0x79793a43), C32e(0xb6b69a2c), C32e(0xd4d40dd9), C32e(0x8d8d47ca), C32e(0x67671770), C32e(0x7272afdd), C32e(0x9494ed79), C32e(0x9898ff67), C32e(0xb0b09323), C32e(0x85855bde), C32e(0xbbbb06bd), C32e(0xc5c5bb7e), C32e(0x4f4f7b34), C32e(0xededd73a), C32e(0x8686d254), C32e(0x9a9af862), C32e(0x666699ff), C32e(0x1111b6a7), C32e(0x8a8ac04a), C32e(0xe9e9d930), C32e(0x04040e0a), C32e(0xfefe6698), C32e(0xa0a0ab0b), C32e(0x7878b4cc), C32e(0x2525f0d5), C32e(0x4b4b753e), C32e(0xa2a2ac0e), C32e(0x5d5d4419), C32e(0x8080db5b), C32e(0x05058085), C32e(0x3f3fd3ec), C32e(0x2121fedf), C32e(0x7070a8d8), C32e(0xf1f1fd0c), C32e(0x6363197a), C32e(0x77772f58), C32e(0xafaf309f), C32e(0x4242e7a5), C32e(0x20207050), C32e(0xe5e5cb2e), C32e(0xfdfdef12), C32e(0xbfbf08b7), C32e(0x818155d4), C32e(0x1818243c), C32e(0x2626795f), C32e(0xc3c3b271), C32e(0xbebe8638), C32e(0x3535c8fd), C32e(0x8888c74f), C32e(0x2e2e654b), C32e(0x93936af9), C32e(0x5555580d), C32e(0xfcfc619d), C32e(0x7a7ab3c9), C32e(0xc8c827ef), C32e(0xbaba8832), C32e(0x32324f7d), C32e(0xe6e642a4), C32e(0xc0c03bfb), C32e(0x1919aab3), C32e(0x9e9ef668), C32e(0xa3a32281), C32e(0x4444eeaa), C32e(0x5454d682), C32e(0x3b3bdde6), C32e(0x0b0b959e), C32e(0x8c8cc945), C32e(0xc7c7bc7b), C32e(0x6b6b056e), C32e(0x28286c44), C32e(0xa7a72c8b), C32e(0xbcbc813d), C32e(0x16163127), C32e(0xadad379a), C32e(0xdbdb964d), C32e(0x64649efa), C32e(0x7474a6d2), C32e(0x14143622), C32e(0x9292e476), C32e(0x0c0c121e), C32e(0x4848fcb4), C32e(0xb8b88f37), C32e(0x9f9f78e7), C32e(0xbdbd0fb2), C32e(0x4343692a), C32e(0xc4c435f1), C32e(0x3939dae3), C32e(0x3131c6f7), C32e(0xd3d38a59), C32e(0xf2f27486), C32e(0xd5d58356), C32e(0x8b8b4ec5), C32e(0x6e6e85eb), C32e(0xdada18c2), C32e(0x01018e8f), C32e(0xb1b11dac), C32e(0x9c9cf16d), C32e(0x4949723b), C32e(0xd8d81fc7), C32e(0xacacb915), C32e(0xf3f3fa09), C32e(0xcfcfa06f), C32e(0xcaca20ea), C32e(0xf4f47d89), C32e(0x47476720), C32e(0x10103828), C32e(0x6f6f0b64), C32e(0xf0f07383), C32e(0x4a4afbb1), C32e(0x5c5cca96), C32e(0x3838546c), C32e(0x57575f08), C32e(0x73732152), C32e(0x979764f3), C32e(0xcbcbae65), C32e(0xa1a12584), C32e(0xe8e857bf), C32e(0x3e3e5d63), C32e(0x9696ea7c), C32e(0x61611e7f), C32e(0x0d0d9c91), C32e(0x0f0f9b94), C32e(0xe0e04bab), C32e(0x7c7cbac6), C32e(0x71712657), C32e(0xcccc29e5), C32e(0x9090e373), C32e(0x0606090f), C32e(0xf7f7f403), C32e(0x1c1c2a36), C32e(0xc2c23cfe), C32e(0x6a6a8be1), C32e(0xaeaebe10), C32e(0x6969026b), C32e(0x1717bfa8), C32e(0x999971e8), C32e(0x3a3a5369), C32e(0x2727f7d0), C32e(0xd9d99148), C32e(0xebebde35), C32e(0x2b2be5ce), C32e(0x22227755), C32e(0xd2d204d6), C32e(0xa9a93990), C32e(0x07078780), C32e(0x3333c1f2), C32e(0x2d2decc1), C32e(0x3c3c5a66), C32e(0x1515b8ad), C32e(0xc9c9a960), C32e(0x87875cdb), C32e(0xaaaab01a), C32e(0x5050d888), C32e(0xa5a52b8e), C32e(0x0303898a), C32e(0x59594a13), C32e(0x0909929b), C32e(0x1a1a2339), C32e(0x65651075), C32e(0xd7d78453), C32e(0x8484d551), C32e(0xd0d003d3), C32e(0x8282dc5e), C32e(0x2929e2cb), C32e(0x5a5ac399), C32e(0x1e1e2d33), C32e(0x7b7b3d46), C32e(0xa8a8b71f), C32e(0x6d6d0c61), C32e(0x2c2c624e) }; static const sph_u32 T1dn[] = { C32e(0xa5f497a5), C32e(0x8497eb84), C32e(0x99b0c799), C32e(0x8d8cf78d), C32e(0x0d17e50d), C32e(0xbddcb7bd), C32e(0xb1c8a7b1), C32e(0x54fc3954), C32e(0x50f0c050), C32e(0x03050403), C32e(0xa9e087a9), C32e(0x7d87ac7d), C32e(0x192bd519), C32e(0x62a67162), C32e(0xe6319ae6), C32e(0x9ab5c39a), C32e(0x45cf0545), C32e(0x9dbc3e9d), C32e(0x40c00940), C32e(0x8792ef87), C32e(0x153fc515), C32e(0xeb267feb), C32e(0xc94007c9), C32e(0x0b1ded0b), C32e(0xec2f82ec), C32e(0x67a97d67), C32e(0xfd1cbefd), C32e(0xea258aea), C32e(0xbfda46bf), C32e(0xf702a6f7), C32e(0x96a1d396), C32e(0x5bed2d5b), C32e(0xc25deac2), C32e(0x1c24d91c), C32e(0xaee97aae), C32e(0x6abe986a), C32e(0x5aeed85a), C32e(0x41c3fc41), C32e(0x0206f102), C32e(0x4fd11d4f), C32e(0x5ce4d05c), C32e(0xf407a2f4), C32e(0x345cb934), C32e(0x0818e908), C32e(0x93aedf93), C32e(0x73954d73), C32e(0x53f5c453), C32e(0x3f41543f), C32e(0x0c14100c), C32e(0x52f63152), C32e(0x65af8c65), C32e(0x5ee2215e), C32e(0x28786028), C32e(0xa1f86ea1), C32e(0x0f11140f), C32e(0xb5c45eb5), C32e(0x091b1c09), C32e(0x365a4836), C32e(0x9bb6369b), C32e(0x3d47a53d), C32e(0x266a8126), C32e(0x69bb9c69), C32e(0xcd4cfecd), C32e(0x9fbacf9f), C32e(0x1b2d241b), C32e(0x9eb93a9e), C32e(0x749cb074), C32e(0x2e72682e), C32e(0x2d776c2d), C32e(0xb2cda3b2), C32e(0xee2973ee), C32e(0xfb16b6fb), C32e(0xf60153f6), C32e(0x4dd7ec4d), C32e(0x61a37561), C32e(0xce49face), C32e(0x7b8da47b), C32e(0x3e42a13e), C32e(0x7193bc71), C32e(0x97a22697), C32e(0xf50457f5), C32e(0x68b86968), C32e(0x00000000), C32e(0x2c74992c), C32e(0x60a08060), C32e(0x1f21dd1f), C32e(0xc843f2c8), C32e(0xed2c77ed), C32e(0xbed9b3be), C32e(0x46ca0146), C32e(0xd970ced9), C32e(0x4bdde44b), C32e(0xde7933de), C32e(0xd4672bd4), C32e(0xe8237be8), C32e(0x4ade114a), C32e(0x6bbd6d6b), C32e(0x2a7e912a), C32e(0xe5349ee5), C32e(0x163ac116), C32e(0xc55417c5), C32e(0xd7622fd7), C32e(0x55ffcc55), C32e(0x94a72294), C32e(0xcf4a0fcf), C32e(0x1030c910), C32e(0x060a0806), C32e(0x8198e781), C32e(0xf00b5bf0), C32e(0x44ccf044), C32e(0xbad54aba), C32e(0xe33e96e3), C32e(0xf30e5ff3), C32e(0xfe19bafe), C32e(0xc05b1bc0), C32e(0x8a850a8a), C32e(0xadec7ead), C32e(0xbcdf42bc), C32e(0x48d8e048), C32e(0x040cf904), C32e(0xdf7ac6df), C32e(0xc158eec1), C32e(0x759f4575), C32e(0x63a58463), C32e(0x30504030), C32e(0x1a2ed11a), C32e(0x0e12e10e), C32e(0x6db7656d), C32e(0x4cd4194c), C32e(0x143c3014), C32e(0x355f4c35), C32e(0x2f719d2f), C32e(0xe13867e1), C32e(0xa2fd6aa2), C32e(0xcc4f0bcc), C32e(0x394b5c39), C32e(0x57f93d57), C32e(0xf20daaf2), C32e(0x829de382), C32e(0x47c9f447), C32e(0xacef8bac), C32e(0xe7326fe7), C32e(0x2b7d642b), C32e(0x95a4d795), C32e(0xa0fb9ba0), C32e(0x98b33298), C32e(0xd16827d1), C32e(0x7f815d7f), C32e(0x66aa8866), C32e(0x7e82a87e), C32e(0xabe676ab), C32e(0x839e1683), C32e(0xca4503ca), C32e(0x297b9529), C32e(0xd36ed6d3), C32e(0x3c44503c), C32e(0x798b5579), C32e(0xe23d63e2), C32e(0x1d272c1d), C32e(0x769a4176), C32e(0x3b4dad3b), C32e(0x56fac856), C32e(0x4ed2e84e), C32e(0x1e22281e), C32e(0xdb763fdb), C32e(0x0a1e180a), C32e(0x6cb4906c), C32e(0xe4376be4), C32e(0x5de7255d), C32e(0x6eb2616e), C32e(0xef2a86ef), C32e(0xa6f193a6), C32e(0xa8e372a8), C32e(0xa4f762a4), C32e(0x3759bd37), C32e(0x8b86ff8b), C32e(0x3256b132), C32e(0x43c50d43), C32e(0x59ebdc59), C32e(0xb7c2afb7), C32e(0x8c8f028c), C32e(0x64ac7964), C32e(0xd26d23d2), C32e(0xe03b92e0), C32e(0xb4c7abb4), C32e(0xfa1543fa), C32e(0x0709fd07), C32e(0x256f8525), C32e(0xafea8faf), C32e(0x8e89f38e), C32e(0xe9208ee9), C32e(0x18282018), C32e(0xd564ded5), C32e(0x8883fb88), C32e(0x6fb1946f), C32e(0x7296b872), C32e(0x246c7024), C32e(0xf108aef1), C32e(0xc752e6c7), C32e(0x51f33551), C32e(0x23658d23), C32e(0x7c84597c), C32e(0x9cbfcb9c), C32e(0x21637c21), C32e(0xdd7c37dd), C32e(0xdc7fc2dc), C32e(0x86911a86), C32e(0x85941e85), C32e(0x90abdb90), C32e(0x42c6f842), C32e(0xc457e2c4), C32e(0xaae583aa), C32e(0xd8733bd8), C32e(0x050f0c05), C32e(0x0103f501), C32e(0x12363812), C32e(0xa3fe9fa3), C32e(0x5fe1d45f), C32e(0xf91047f9), C32e(0xd06bd2d0), C32e(0x91a82e91), C32e(0x58e82958), C32e(0x27697427), C32e(0xb9d04eb9), C32e(0x3848a938), C32e(0x1335cd13), C32e(0xb3ce56b3), C32e(0x33554433), C32e(0xbbd6bfbb), C32e(0x70904970), C32e(0x89800e89), C32e(0xa7f266a7), C32e(0xb6c15ab6), C32e(0x22667822), C32e(0x92ad2a92), C32e(0x20608920), C32e(0x49db1549), C32e(0xff1a4fff), C32e(0x7888a078), C32e(0x7a8e517a), C32e(0x8f8a068f), C32e(0xf813b2f8), C32e(0x809b1280), C32e(0x17393417), C32e(0xda75cada), C32e(0x3153b531), C32e(0xc65113c6), C32e(0xb8d3bbb8), C32e(0xc35e1fc3), C32e(0xb0cb52b0), C32e(0x7799b477), C32e(0x11333c11), C32e(0xcb46f6cb), C32e(0xfc1f4bfc), C32e(0xd661dad6), C32e(0x3a4e583a) }; static const sph_u32 T2up[] = { C32e(0xa5c6c632), C32e(0x84f8f86f), C32e(0x99eeee5e), C32e(0x8df6f67a), C32e(0x0dffffe8), C32e(0xbdd6d60a), C32e(0xb1dede16), C32e(0x5491916d), C32e(0x50606090), C32e(0x03020207), C32e(0xa9cece2e), C32e(0x7d5656d1), C32e(0x19e7e7cc), C32e(0x62b5b513), C32e(0xe64d4d7c), C32e(0x9aecec59), C32e(0x458f8f40), C32e(0x9d1f1fa3), C32e(0x40898949), C32e(0x87fafa68), C32e(0x15efefd0), C32e(0xebb2b294), C32e(0xc98e8ece), C32e(0x0bfbfbe6), C32e(0xec41416e), C32e(0x67b3b31a), C32e(0xfd5f5f43), C32e(0xea454560), C32e(0xbf2323f9), C32e(0xf7535351), C32e(0x96e4e445), C32e(0x5b9b9b76), C32e(0xc2757528), C32e(0x1ce1e1c5), C32e(0xae3d3dd4), C32e(0x6a4c4cf2), C32e(0x5a6c6c82), C32e(0x417e7ebd), C32e(0x02f5f5f3), C32e(0x4f838352), C32e(0x5c68688c), C32e(0xf4515156), C32e(0x34d1d18d), C32e(0x08f9f9e1), C32e(0x93e2e24c), C32e(0x73abab3e), C32e(0x53626297), C32e(0x3f2a2a6b), C32e(0x0c08081c), C32e(0x52959563), C32e(0x654646e9), C32e(0x5e9d9d7f), C32e(0x28303048), C32e(0xa13737cf), C32e(0x0f0a0a1b), C32e(0xb52f2feb), C32e(0x090e0e15), C32e(0x3624247e), C32e(0x9b1b1bad), C32e(0x3ddfdf98), C32e(0x26cdcda7), C32e(0x694e4ef5), C32e(0xcd7f7f33), C32e(0x9feaea50), C32e(0x1b12123f), C32e(0x9e1d1da4), C32e(0x745858c4), C32e(0x2e343446), C32e(0x2d363641), C32e(0xb2dcdc11), C32e(0xeeb4b49d), C32e(0xfb5b5b4d), C32e(0xf6a4a4a5), C32e(0x4d7676a1), C32e(0x61b7b714), C32e(0xce7d7d34), C32e(0x7b5252df), C32e(0x3edddd9f), C32e(0x715e5ecd), C32e(0x971313b1), C32e(0xf5a6a6a2), C32e(0x68b9b901), C32e(0x00000000), C32e(0x2cc1c1b5), C32e(0x604040e0), C32e(0x1fe3e3c2), C32e(0xc879793a), C32e(0xedb6b69a), C32e(0xbed4d40d), C32e(0x468d8d47), C32e(0xd9676717), C32e(0x4b7272af), C32e(0xde9494ed), C32e(0xd49898ff), C32e(0xe8b0b093), C32e(0x4a85855b), C32e(0x6bbbbb06), C32e(0x2ac5c5bb), C32e(0xe54f4f7b), C32e(0x16ededd7), C32e(0xc58686d2), C32e(0xd79a9af8), C32e(0x55666699), C32e(0x941111b6), C32e(0xcf8a8ac0), C32e(0x10e9e9d9), C32e(0x0604040e), C32e(0x81fefe66), C32e(0xf0a0a0ab), C32e(0x447878b4), C32e(0xba2525f0), C32e(0xe34b4b75), C32e(0xf3a2a2ac), C32e(0xfe5d5d44), C32e(0xc08080db), C32e(0x8a050580), C32e(0xad3f3fd3), C32e(0xbc2121fe), C32e(0x487070a8), C32e(0x04f1f1fd), C32e(0xdf636319), C32e(0xc177772f), C32e(0x75afaf30), C32e(0x634242e7), C32e(0x30202070), C32e(0x1ae5e5cb), C32e(0x0efdfdef), C32e(0x6dbfbf08), C32e(0x4c818155), C32e(0x14181824), C32e(0x35262679), C32e(0x2fc3c3b2), C32e(0xe1bebe86), C32e(0xa23535c8), C32e(0xcc8888c7), C32e(0x392e2e65), C32e(0x5793936a), C32e(0xf2555558), C32e(0x82fcfc61), C32e(0x477a7ab3), C32e(0xacc8c827), C32e(0xe7baba88), C32e(0x2b32324f), C32e(0x95e6e642), C32e(0xa0c0c03b), C32e(0x981919aa), C32e(0xd19e9ef6), C32e(0x7fa3a322), C32e(0x664444ee), C32e(0x7e5454d6), C32e(0xab3b3bdd), C32e(0x830b0b95), C32e(0xca8c8cc9), C32e(0x29c7c7bc), C32e(0xd36b6b05), C32e(0x3c28286c), C32e(0x79a7a72c), C32e(0xe2bcbc81), C32e(0x1d161631), C32e(0x76adad37), C32e(0x3bdbdb96), C32e(0x5664649e), C32e(0x4e7474a6), C32e(0x1e141436), C32e(0xdb9292e4), C32e(0x0a0c0c12), C32e(0x6c4848fc), C32e(0xe4b8b88f), C32e(0x5d9f9f78), C32e(0x6ebdbd0f), C32e(0xef434369), C32e(0xa6c4c435), C32e(0xa83939da), C32e(0xa43131c6), C32e(0x37d3d38a), C32e(0x8bf2f274), C32e(0x32d5d583), C32e(0x438b8b4e), C32e(0x596e6e85), C32e(0xb7dada18), C32e(0x8c01018e), C32e(0x64b1b11d), C32e(0xd29c9cf1), C32e(0xe0494972), C32e(0xb4d8d81f), C32e(0xfaacacb9), C32e(0x07f3f3fa), C32e(0x25cfcfa0), C32e(0xafcaca20), C32e(0x8ef4f47d), C32e(0xe9474767), C32e(0x18101038), C32e(0xd56f6f0b), C32e(0x88f0f073), C32e(0x6f4a4afb), C32e(0x725c5cca), C32e(0x24383854), C32e(0xf157575f), C32e(0xc7737321), C32e(0x51979764), C32e(0x23cbcbae), C32e(0x7ca1a125), C32e(0x9ce8e857), C32e(0x213e3e5d), C32e(0xdd9696ea), C32e(0xdc61611e), C32e(0x860d0d9c), C32e(0x850f0f9b), C32e(0x90e0e04b), C32e(0x427c7cba), C32e(0xc4717126), C32e(0xaacccc29), C32e(0xd89090e3), C32e(0x05060609), C32e(0x01f7f7f4), C32e(0x121c1c2a), C32e(0xa3c2c23c), C32e(0x5f6a6a8b), C32e(0xf9aeaebe), C32e(0xd0696902), C32e(0x911717bf), C32e(0x58999971), C32e(0x273a3a53), C32e(0xb92727f7), C32e(0x38d9d991), C32e(0x13ebebde), C32e(0xb32b2be5), C32e(0x33222277), C32e(0xbbd2d204), C32e(0x70a9a939), C32e(0x89070787), C32e(0xa73333c1), C32e(0xb62d2dec), C32e(0x223c3c5a), C32e(0x921515b8), C32e(0x20c9c9a9), C32e(0x4987875c), C32e(0xffaaaab0), C32e(0x785050d8), C32e(0x7aa5a52b), C32e(0x8f030389), C32e(0xf859594a), C32e(0x80090992), C32e(0x171a1a23), C32e(0xda656510), C32e(0x31d7d784), C32e(0xc68484d5), C32e(0xb8d0d003), C32e(0xc38282dc), C32e(0xb02929e2), C32e(0x775a5ac3), C32e(0x111e1e2d), C32e(0xcb7b7b3d), C32e(0xfca8a8b7), C32e(0xd66d6d0c), C32e(0x3a2c2c62) }; static const sph_u32 T2dn[] = { C32e(0xf4a5f497), C32e(0x978497eb), C32e(0xb099b0c7), C32e(0x8c8d8cf7), C32e(0x170d17e5), C32e(0xdcbddcb7), C32e(0xc8b1c8a7), C32e(0xfc54fc39), C32e(0xf050f0c0), C32e(0x05030504), C32e(0xe0a9e087), C32e(0x877d87ac), C32e(0x2b192bd5), C32e(0xa662a671), C32e(0x31e6319a), C32e(0xb59ab5c3), C32e(0xcf45cf05), C32e(0xbc9dbc3e), C32e(0xc040c009), C32e(0x928792ef), C32e(0x3f153fc5), C32e(0x26eb267f), C32e(0x40c94007), C32e(0x1d0b1ded), C32e(0x2fec2f82), C32e(0xa967a97d), C32e(0x1cfd1cbe), C32e(0x25ea258a), C32e(0xdabfda46), C32e(0x02f702a6), C32e(0xa196a1d3), C32e(0xed5bed2d), C32e(0x5dc25dea), C32e(0x241c24d9), C32e(0xe9aee97a), C32e(0xbe6abe98), C32e(0xee5aeed8), C32e(0xc341c3fc), C32e(0x060206f1), C32e(0xd14fd11d), C32e(0xe45ce4d0), C32e(0x07f407a2), C32e(0x5c345cb9), C32e(0x180818e9), C32e(0xae93aedf), C32e(0x9573954d), C32e(0xf553f5c4), C32e(0x413f4154), C32e(0x140c1410), C32e(0xf652f631), C32e(0xaf65af8c), C32e(0xe25ee221), C32e(0x78287860), C32e(0xf8a1f86e), C32e(0x110f1114), C32e(0xc4b5c45e), C32e(0x1b091b1c), C32e(0x5a365a48), C32e(0xb69bb636), C32e(0x473d47a5), C32e(0x6a266a81), C32e(0xbb69bb9c), C32e(0x4ccd4cfe), C32e(0xba9fbacf), C32e(0x2d1b2d24), C32e(0xb99eb93a), C32e(0x9c749cb0), C32e(0x722e7268), C32e(0x772d776c), C32e(0xcdb2cda3), C32e(0x29ee2973), C32e(0x16fb16b6), C32e(0x01f60153), C32e(0xd74dd7ec), C32e(0xa361a375), C32e(0x49ce49fa), C32e(0x8d7b8da4), C32e(0x423e42a1), C32e(0x937193bc), C32e(0xa297a226), C32e(0x04f50457), C32e(0xb868b869), C32e(0x00000000), C32e(0x742c7499), C32e(0xa060a080), C32e(0x211f21dd), C32e(0x43c843f2), C32e(0x2ced2c77), C32e(0xd9bed9b3), C32e(0xca46ca01), C32e(0x70d970ce), C32e(0xdd4bdde4), C32e(0x79de7933), C32e(0x67d4672b), C32e(0x23e8237b), C32e(0xde4ade11), C32e(0xbd6bbd6d), C32e(0x7e2a7e91), C32e(0x34e5349e), C32e(0x3a163ac1), C32e(0x54c55417), C32e(0x62d7622f), C32e(0xff55ffcc), C32e(0xa794a722), C32e(0x4acf4a0f), C32e(0x301030c9), C32e(0x0a060a08), C32e(0x988198e7), C32e(0x0bf00b5b), C32e(0xcc44ccf0), C32e(0xd5bad54a), C32e(0x3ee33e96), C32e(0x0ef30e5f), C32e(0x19fe19ba), C32e(0x5bc05b1b), C32e(0x858a850a), C32e(0xecadec7e), C32e(0xdfbcdf42), C32e(0xd848d8e0), C32e(0x0c040cf9), C32e(0x7adf7ac6), C32e(0x58c158ee), C32e(0x9f759f45), C32e(0xa563a584), C32e(0x50305040), C32e(0x2e1a2ed1), C32e(0x120e12e1), C32e(0xb76db765), C32e(0xd44cd419), C32e(0x3c143c30), C32e(0x5f355f4c), C32e(0x712f719d), C32e(0x38e13867), C32e(0xfda2fd6a), C32e(0x4fcc4f0b), C32e(0x4b394b5c), C32e(0xf957f93d), C32e(0x0df20daa), C32e(0x9d829de3), C32e(0xc947c9f4), C32e(0xefacef8b), C32e(0x32e7326f), C32e(0x7d2b7d64), C32e(0xa495a4d7), C32e(0xfba0fb9b), C32e(0xb398b332), C32e(0x68d16827), C32e(0x817f815d), C32e(0xaa66aa88), C32e(0x827e82a8), C32e(0xe6abe676), C32e(0x9e839e16), C32e(0x45ca4503), C32e(0x7b297b95), C32e(0x6ed36ed6), C32e(0x443c4450), C32e(0x8b798b55), C32e(0x3de23d63), C32e(0x271d272c), C32e(0x9a769a41), C32e(0x4d3b4dad), C32e(0xfa56fac8), C32e(0xd24ed2e8), C32e(0x221e2228), C32e(0x76db763f), C32e(0x1e0a1e18), C32e(0xb46cb490), C32e(0x37e4376b), C32e(0xe75de725), C32e(0xb26eb261), C32e(0x2aef2a86), C32e(0xf1a6f193), C32e(0xe3a8e372), C32e(0xf7a4f762), C32e(0x593759bd), C32e(0x868b86ff), C32e(0x563256b1), C32e(0xc543c50d), C32e(0xeb59ebdc), C32e(0xc2b7c2af), C32e(0x8f8c8f02), C32e(0xac64ac79), C32e(0x6dd26d23), C32e(0x3be03b92), C32e(0xc7b4c7ab), C32e(0x15fa1543), C32e(0x090709fd), C32e(0x6f256f85), C32e(0xeaafea8f), C32e(0x898e89f3), C32e(0x20e9208e), C32e(0x28182820), C32e(0x64d564de), C32e(0x838883fb), C32e(0xb16fb194), C32e(0x967296b8), C32e(0x6c246c70), C32e(0x08f108ae), C32e(0x52c752e6), C32e(0xf351f335), C32e(0x6523658d), C32e(0x847c8459), C32e(0xbf9cbfcb), C32e(0x6321637c), C32e(0x7cdd7c37), C32e(0x7fdc7fc2), C32e(0x9186911a), C32e(0x9485941e), C32e(0xab90abdb), C32e(0xc642c6f8), C32e(0x57c457e2), C32e(0xe5aae583), C32e(0x73d8733b), C32e(0x0f050f0c), C32e(0x030103f5), C32e(0x36123638), C32e(0xfea3fe9f), C32e(0xe15fe1d4), C32e(0x10f91047), C32e(0x6bd06bd2), C32e(0xa891a82e), C32e(0xe858e829), C32e(0x69276974), C32e(0xd0b9d04e), C32e(0x483848a9), C32e(0x351335cd), C32e(0xceb3ce56), C32e(0x55335544), C32e(0xd6bbd6bf), C32e(0x90709049), C32e(0x8089800e), C32e(0xf2a7f266), C32e(0xc1b6c15a), C32e(0x66226678), C32e(0xad92ad2a), C32e(0x60206089), C32e(0xdb49db15), C32e(0x1aff1a4f), C32e(0x887888a0), C32e(0x8e7a8e51), C32e(0x8a8f8a06), C32e(0x13f813b2), C32e(0x9b809b12), C32e(0x39173934), C32e(0x75da75ca), C32e(0x533153b5), C32e(0x51c65113), C32e(0xd3b8d3bb), C32e(0x5ec35e1f), C32e(0xcbb0cb52), C32e(0x997799b4), C32e(0x3311333c), C32e(0x46cb46f6), C32e(0x1ffc1f4b), C32e(0x61d661da), C32e(0x4e3a4e58) }; static const sph_u32 T3up[] = { C32e(0x97a5c6c6), C32e(0xeb84f8f8), C32e(0xc799eeee), C32e(0xf78df6f6), C32e(0xe50dffff), C32e(0xb7bdd6d6), C32e(0xa7b1dede), C32e(0x39549191), C32e(0xc0506060), C32e(0x04030202), C32e(0x87a9cece), C32e(0xac7d5656), C32e(0xd519e7e7), C32e(0x7162b5b5), C32e(0x9ae64d4d), C32e(0xc39aecec), C32e(0x05458f8f), C32e(0x3e9d1f1f), C32e(0x09408989), C32e(0xef87fafa), C32e(0xc515efef), C32e(0x7febb2b2), C32e(0x07c98e8e), C32e(0xed0bfbfb), C32e(0x82ec4141), C32e(0x7d67b3b3), C32e(0xbefd5f5f), C32e(0x8aea4545), C32e(0x46bf2323), C32e(0xa6f75353), C32e(0xd396e4e4), C32e(0x2d5b9b9b), C32e(0xeac27575), C32e(0xd91ce1e1), C32e(0x7aae3d3d), C32e(0x986a4c4c), C32e(0xd85a6c6c), C32e(0xfc417e7e), C32e(0xf102f5f5), C32e(0x1d4f8383), C32e(0xd05c6868), C32e(0xa2f45151), C32e(0xb934d1d1), C32e(0xe908f9f9), C32e(0xdf93e2e2), C32e(0x4d73abab), C32e(0xc4536262), C32e(0x543f2a2a), C32e(0x100c0808), C32e(0x31529595), C32e(0x8c654646), C32e(0x215e9d9d), C32e(0x60283030), C32e(0x6ea13737), C32e(0x140f0a0a), C32e(0x5eb52f2f), C32e(0x1c090e0e), C32e(0x48362424), C32e(0x369b1b1b), C32e(0xa53ddfdf), C32e(0x8126cdcd), C32e(0x9c694e4e), C32e(0xfecd7f7f), C32e(0xcf9feaea), C32e(0x241b1212), C32e(0x3a9e1d1d), C32e(0xb0745858), C32e(0x682e3434), C32e(0x6c2d3636), C32e(0xa3b2dcdc), C32e(0x73eeb4b4), C32e(0xb6fb5b5b), C32e(0x53f6a4a4), C32e(0xec4d7676), C32e(0x7561b7b7), C32e(0xface7d7d), C32e(0xa47b5252), C32e(0xa13edddd), C32e(0xbc715e5e), C32e(0x26971313), C32e(0x57f5a6a6), C32e(0x6968b9b9), C32e(0x00000000), C32e(0x992cc1c1), C32e(0x80604040), C32e(0xdd1fe3e3), C32e(0xf2c87979), C32e(0x77edb6b6), C32e(0xb3bed4d4), C32e(0x01468d8d), C32e(0xced96767), C32e(0xe44b7272), C32e(0x33de9494), C32e(0x2bd49898), C32e(0x7be8b0b0), C32e(0x114a8585), C32e(0x6d6bbbbb), C32e(0x912ac5c5), C32e(0x9ee54f4f), C32e(0xc116eded), C32e(0x17c58686), C32e(0x2fd79a9a), C32e(0xcc556666), C32e(0x22941111), C32e(0x0fcf8a8a), C32e(0xc910e9e9), C32e(0x08060404), C32e(0xe781fefe), C32e(0x5bf0a0a0), C32e(0xf0447878), C32e(0x4aba2525), C32e(0x96e34b4b), C32e(0x5ff3a2a2), C32e(0xbafe5d5d), C32e(0x1bc08080), C32e(0x0a8a0505), C32e(0x7ead3f3f), C32e(0x42bc2121), C32e(0xe0487070), C32e(0xf904f1f1), C32e(0xc6df6363), C32e(0xeec17777), C32e(0x4575afaf), C32e(0x84634242), C32e(0x40302020), C32e(0xd11ae5e5), C32e(0xe10efdfd), C32e(0x656dbfbf), C32e(0x194c8181), C32e(0x30141818), C32e(0x4c352626), C32e(0x9d2fc3c3), C32e(0x67e1bebe), C32e(0x6aa23535), C32e(0x0bcc8888), C32e(0x5c392e2e), C32e(0x3d579393), C32e(0xaaf25555), C32e(0xe382fcfc), C32e(0xf4477a7a), C32e(0x8bacc8c8), C32e(0x6fe7baba), C32e(0x642b3232), C32e(0xd795e6e6), C32e(0x9ba0c0c0), C32e(0x32981919), C32e(0x27d19e9e), C32e(0x5d7fa3a3), C32e(0x88664444), C32e(0xa87e5454), C32e(0x76ab3b3b), C32e(0x16830b0b), C32e(0x03ca8c8c), C32e(0x9529c7c7), C32e(0xd6d36b6b), C32e(0x503c2828), C32e(0x5579a7a7), C32e(0x63e2bcbc), C32e(0x2c1d1616), C32e(0x4176adad), C32e(0xad3bdbdb), C32e(0xc8566464), C32e(0xe84e7474), C32e(0x281e1414), C32e(0x3fdb9292), C32e(0x180a0c0c), C32e(0x906c4848), C32e(0x6be4b8b8), C32e(0x255d9f9f), C32e(0x616ebdbd), C32e(0x86ef4343), C32e(0x93a6c4c4), C32e(0x72a83939), C32e(0x62a43131), C32e(0xbd37d3d3), C32e(0xff8bf2f2), C32e(0xb132d5d5), C32e(0x0d438b8b), C32e(0xdc596e6e), C32e(0xafb7dada), C32e(0x028c0101), C32e(0x7964b1b1), C32e(0x23d29c9c), C32e(0x92e04949), C32e(0xabb4d8d8), C32e(0x43faacac), C32e(0xfd07f3f3), C32e(0x8525cfcf), C32e(0x8fafcaca), C32e(0xf38ef4f4), C32e(0x8ee94747), C32e(0x20181010), C32e(0xded56f6f), C32e(0xfb88f0f0), C32e(0x946f4a4a), C32e(0xb8725c5c), C32e(0x70243838), C32e(0xaef15757), C32e(0xe6c77373), C32e(0x35519797), C32e(0x8d23cbcb), C32e(0x597ca1a1), C32e(0xcb9ce8e8), C32e(0x7c213e3e), C32e(0x37dd9696), C32e(0xc2dc6161), C32e(0x1a860d0d), C32e(0x1e850f0f), C32e(0xdb90e0e0), C32e(0xf8427c7c), C32e(0xe2c47171), C32e(0x83aacccc), C32e(0x3bd89090), C32e(0x0c050606), C32e(0xf501f7f7), C32e(0x38121c1c), C32e(0x9fa3c2c2), C32e(0xd45f6a6a), C32e(0x47f9aeae), C32e(0xd2d06969), C32e(0x2e911717), C32e(0x29589999), C32e(0x74273a3a), C32e(0x4eb92727), C32e(0xa938d9d9), C32e(0xcd13ebeb), C32e(0x56b32b2b), C32e(0x44332222), C32e(0xbfbbd2d2), C32e(0x4970a9a9), C32e(0x0e890707), C32e(0x66a73333), C32e(0x5ab62d2d), C32e(0x78223c3c), C32e(0x2a921515), C32e(0x8920c9c9), C32e(0x15498787), C32e(0x4fffaaaa), C32e(0xa0785050), C32e(0x517aa5a5), C32e(0x068f0303), C32e(0xb2f85959), C32e(0x12800909), C32e(0x34171a1a), C32e(0xcada6565), C32e(0xb531d7d7), C32e(0x13c68484), C32e(0xbbb8d0d0), C32e(0x1fc38282), C32e(0x52b02929), C32e(0xb4775a5a), C32e(0x3c111e1e), C32e(0xf6cb7b7b), C32e(0x4bfca8a8), C32e(0xdad66d6d), C32e(0x583a2c2c) }; static const sph_u32 T3dn[] = { C32e(0x32f4a5f4), C32e(0x6f978497), C32e(0x5eb099b0), C32e(0x7a8c8d8c), C32e(0xe8170d17), C32e(0x0adcbddc), C32e(0x16c8b1c8), C32e(0x6dfc54fc), C32e(0x90f050f0), C32e(0x07050305), C32e(0x2ee0a9e0), C32e(0xd1877d87), C32e(0xcc2b192b), C32e(0x13a662a6), C32e(0x7c31e631), C32e(0x59b59ab5), C32e(0x40cf45cf), C32e(0xa3bc9dbc), C32e(0x49c040c0), C32e(0x68928792), C32e(0xd03f153f), C32e(0x9426eb26), C32e(0xce40c940), C32e(0xe61d0b1d), C32e(0x6e2fec2f), C32e(0x1aa967a9), C32e(0x431cfd1c), C32e(0x6025ea25), C32e(0xf9dabfda), C32e(0x5102f702), C32e(0x45a196a1), C32e(0x76ed5bed), C32e(0x285dc25d), C32e(0xc5241c24), C32e(0xd4e9aee9), C32e(0xf2be6abe), C32e(0x82ee5aee), C32e(0xbdc341c3), C32e(0xf3060206), C32e(0x52d14fd1), C32e(0x8ce45ce4), C32e(0x5607f407), C32e(0x8d5c345c), C32e(0xe1180818), C32e(0x4cae93ae), C32e(0x3e957395), C32e(0x97f553f5), C32e(0x6b413f41), C32e(0x1c140c14), C32e(0x63f652f6), C32e(0xe9af65af), C32e(0x7fe25ee2), C32e(0x48782878), C32e(0xcff8a1f8), C32e(0x1b110f11), C32e(0xebc4b5c4), C32e(0x151b091b), C32e(0x7e5a365a), C32e(0xadb69bb6), C32e(0x98473d47), C32e(0xa76a266a), C32e(0xf5bb69bb), C32e(0x334ccd4c), C32e(0x50ba9fba), C32e(0x3f2d1b2d), C32e(0xa4b99eb9), C32e(0xc49c749c), C32e(0x46722e72), C32e(0x41772d77), C32e(0x11cdb2cd), C32e(0x9d29ee29), C32e(0x4d16fb16), C32e(0xa501f601), C32e(0xa1d74dd7), C32e(0x14a361a3), C32e(0x3449ce49), C32e(0xdf8d7b8d), C32e(0x9f423e42), C32e(0xcd937193), C32e(0xb1a297a2), C32e(0xa204f504), C32e(0x01b868b8), C32e(0x00000000), C32e(0xb5742c74), C32e(0xe0a060a0), C32e(0xc2211f21), C32e(0x3a43c843), C32e(0x9a2ced2c), C32e(0x0dd9bed9), C32e(0x47ca46ca), C32e(0x1770d970), C32e(0xafdd4bdd), C32e(0xed79de79), C32e(0xff67d467), C32e(0x9323e823), C32e(0x5bde4ade), C32e(0x06bd6bbd), C32e(0xbb7e2a7e), C32e(0x7b34e534), C32e(0xd73a163a), C32e(0xd254c554), C32e(0xf862d762), C32e(0x99ff55ff), C32e(0xb6a794a7), C32e(0xc04acf4a), C32e(0xd9301030), C32e(0x0e0a060a), C32e(0x66988198), C32e(0xab0bf00b), C32e(0xb4cc44cc), C32e(0xf0d5bad5), C32e(0x753ee33e), C32e(0xac0ef30e), C32e(0x4419fe19), C32e(0xdb5bc05b), C32e(0x80858a85), C32e(0xd3ecadec), C32e(0xfedfbcdf), C32e(0xa8d848d8), C32e(0xfd0c040c), C32e(0x197adf7a), C32e(0x2f58c158), C32e(0x309f759f), C32e(0xe7a563a5), C32e(0x70503050), C32e(0xcb2e1a2e), C32e(0xef120e12), C32e(0x08b76db7), C32e(0x55d44cd4), C32e(0x243c143c), C32e(0x795f355f), C32e(0xb2712f71), C32e(0x8638e138), C32e(0xc8fda2fd), C32e(0xc74fcc4f), C32e(0x654b394b), C32e(0x6af957f9), C32e(0x580df20d), C32e(0x619d829d), C32e(0xb3c947c9), C32e(0x27efacef), C32e(0x8832e732), C32e(0x4f7d2b7d), C32e(0x42a495a4), C32e(0x3bfba0fb), C32e(0xaab398b3), C32e(0xf668d168), C32e(0x22817f81), C32e(0xeeaa66aa), C32e(0xd6827e82), C32e(0xdde6abe6), C32e(0x959e839e), C32e(0xc945ca45), C32e(0xbc7b297b), C32e(0x056ed36e), C32e(0x6c443c44), C32e(0x2c8b798b), C32e(0x813de23d), C32e(0x31271d27), C32e(0x379a769a), C32e(0x964d3b4d), C32e(0x9efa56fa), C32e(0xa6d24ed2), C32e(0x36221e22), C32e(0xe476db76), C32e(0x121e0a1e), C32e(0xfcb46cb4), C32e(0x8f37e437), C32e(0x78e75de7), C32e(0x0fb26eb2), C32e(0x692aef2a), C32e(0x35f1a6f1), C32e(0xdae3a8e3), C32e(0xc6f7a4f7), C32e(0x8a593759), C32e(0x74868b86), C32e(0x83563256), C32e(0x4ec543c5), C32e(0x85eb59eb), C32e(0x18c2b7c2), C32e(0x8e8f8c8f), C32e(0x1dac64ac), C32e(0xf16dd26d), C32e(0x723be03b), C32e(0x1fc7b4c7), C32e(0xb915fa15), C32e(0xfa090709), C32e(0xa06f256f), C32e(0x20eaafea), C32e(0x7d898e89), C32e(0x6720e920), C32e(0x38281828), C32e(0x0b64d564), C32e(0x73838883), C32e(0xfbb16fb1), C32e(0xca967296), C32e(0x546c246c), C32e(0x5f08f108), C32e(0x2152c752), C32e(0x64f351f3), C32e(0xae652365), C32e(0x25847c84), C32e(0x57bf9cbf), C32e(0x5d632163), C32e(0xea7cdd7c), C32e(0x1e7fdc7f), C32e(0x9c918691), C32e(0x9b948594), C32e(0x4bab90ab), C32e(0xbac642c6), C32e(0x2657c457), C32e(0x29e5aae5), C32e(0xe373d873), C32e(0x090f050f), C32e(0xf4030103), C32e(0x2a361236), C32e(0x3cfea3fe), C32e(0x8be15fe1), C32e(0xbe10f910), C32e(0x026bd06b), C32e(0xbfa891a8), C32e(0x71e858e8), C32e(0x53692769), C32e(0xf7d0b9d0), C32e(0x91483848), C32e(0xde351335), C32e(0xe5ceb3ce), C32e(0x77553355), C32e(0x04d6bbd6), C32e(0x39907090), C32e(0x87808980), C32e(0xc1f2a7f2), C32e(0xecc1b6c1), C32e(0x5a662266), C32e(0xb8ad92ad), C32e(0xa9602060), C32e(0x5cdb49db), C32e(0xb01aff1a), C32e(0xd8887888), C32e(0x2b8e7a8e), C32e(0x898a8f8a), C32e(0x4a13f813), C32e(0x929b809b), C32e(0x23391739), C32e(0x1075da75), C32e(0x84533153), C32e(0xd551c651), C32e(0x03d3b8d3), C32e(0xdc5ec35e), C32e(0xe2cbb0cb), C32e(0xc3997799), C32e(0x2d331133), C32e(0x3d46cb46), C32e(0xb71ffc1f), C32e(0x0c61d661), C32e(0x624e3a4e) }; #define DECL_STATE_SMALL \ sph_u32 H[16]; #define READ_STATE_SMALL(sc) do { \ memcpy(H, (sc)->state.narrow, sizeof H); \ } while (0) #define WRITE_STATE_SMALL(sc) do { \ memcpy((sc)->state.narrow, H, sizeof H); \ } while (0) #define XCAT(x, y) XCAT_(x, y) #define XCAT_(x, y) x ## y #define RSTT(d0, d1, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ t[d0] = T0up[B32_0(a[b0])] \ ^ T1up[B32_1(a[b1])] \ ^ T2up[B32_2(a[b2])] \ ^ T3up[B32_3(a[b3])] \ ^ T0dn[B32_0(a[b4])] \ ^ T1dn[B32_1(a[b5])] \ ^ T2dn[B32_2(a[b6])] \ ^ T3dn[B32_3(a[b7])]; \ t[d1] = T0dn[B32_0(a[b0])] \ ^ T1dn[B32_1(a[b1])] \ ^ T2dn[B32_2(a[b2])] \ ^ T3dn[B32_3(a[b3])] \ ^ T0up[B32_0(a[b4])] \ ^ T1up[B32_1(a[b5])] \ ^ T2up[B32_2(a[b6])] \ ^ T3up[B32_3(a[b7])]; \ } while (0) #define ROUND_SMALL_P(a, r) do { \ sph_u32 t[16]; \ a[0x0] ^= PC32up(0x00, r); \ a[0x1] ^= PC32dn(0x00, r); \ a[0x2] ^= PC32up(0x10, r); \ a[0x3] ^= PC32dn(0x10, r); \ a[0x4] ^= PC32up(0x20, r); \ a[0x5] ^= PC32dn(0x20, r); \ a[0x6] ^= PC32up(0x30, r); \ a[0x7] ^= PC32dn(0x30, r); \ a[0x8] ^= PC32up(0x40, r); \ a[0x9] ^= PC32dn(0x40, r); \ a[0xA] ^= PC32up(0x50, r); \ a[0xB] ^= PC32dn(0x50, r); \ a[0xC] ^= PC32up(0x60, r); \ a[0xD] ^= PC32dn(0x60, r); \ a[0xE] ^= PC32up(0x70, r); \ a[0xF] ^= PC32dn(0x70, r); \ RSTT(0x0, 0x1, a, 0x0, 0x2, 0x4, 0x6, 0x9, 0xB, 0xD, 0xF); \ RSTT(0x2, 0x3, a, 0x2, 0x4, 0x6, 0x8, 0xB, 0xD, 0xF, 0x1); \ RSTT(0x4, 0x5, a, 0x4, 0x6, 0x8, 0xA, 0xD, 0xF, 0x1, 0x3); \ RSTT(0x6, 0x7, a, 0x6, 0x8, 0xA, 0xC, 0xF, 0x1, 0x3, 0x5); \ RSTT(0x8, 0x9, a, 0x8, 0xA, 0xC, 0xE, 0x1, 0x3, 0x5, 0x7); \ RSTT(0xA, 0xB, a, 0xA, 0xC, 0xE, 0x0, 0x3, 0x5, 0x7, 0x9); \ RSTT(0xC, 0xD, a, 0xC, 0xE, 0x0, 0x2, 0x5, 0x7, 0x9, 0xB); \ RSTT(0xE, 0xF, a, 0xE, 0x0, 0x2, 0x4, 0x7, 0x9, 0xB, 0xD); \ memcpy(a, t, sizeof t); \ } while (0) #define ROUND_SMALL_Q(a, r) do { \ sph_u32 t[16]; \ a[0x0] ^= QC32up(0x00, r); \ a[0x1] ^= QC32dn(0x00, r); \ a[0x2] ^= QC32up(0x10, r); \ a[0x3] ^= QC32dn(0x10, r); \ a[0x4] ^= QC32up(0x20, r); \ a[0x5] ^= QC32dn(0x20, r); \ a[0x6] ^= QC32up(0x30, r); \ a[0x7] ^= QC32dn(0x30, r); \ a[0x8] ^= QC32up(0x40, r); \ a[0x9] ^= QC32dn(0x40, r); \ a[0xA] ^= QC32up(0x50, r); \ a[0xB] ^= QC32dn(0x50, r); \ a[0xC] ^= QC32up(0x60, r); \ a[0xD] ^= QC32dn(0x60, r); \ a[0xE] ^= QC32up(0x70, r); \ a[0xF] ^= QC32dn(0x70, r); \ RSTT(0x0, 0x1, a, 0x2, 0x6, 0xA, 0xE, 0x1, 0x5, 0x9, 0xD); \ RSTT(0x2, 0x3, a, 0x4, 0x8, 0xC, 0x0, 0x3, 0x7, 0xB, 0xF); \ RSTT(0x4, 0x5, a, 0x6, 0xA, 0xE, 0x2, 0x5, 0x9, 0xD, 0x1); \ RSTT(0x6, 0x7, a, 0x8, 0xC, 0x0, 0x4, 0x7, 0xB, 0xF, 0x3); \ RSTT(0x8, 0x9, a, 0xA, 0xE, 0x2, 0x6, 0x9, 0xD, 0x1, 0x5); \ RSTT(0xA, 0xB, a, 0xC, 0x0, 0x4, 0x8, 0xB, 0xF, 0x3, 0x7); \ RSTT(0xC, 0xD, a, 0xE, 0x2, 0x6, 0xA, 0xD, 0x1, 0x5, 0x9); \ RSTT(0xE, 0xF, a, 0x0, 0x4, 0x8, 0xC, 0xF, 0x3, 0x7, 0xB); \ memcpy(a, t, sizeof t); \ } while (0) #if SPH_SMALL_FOOTPRINT_GROESTL #define PERM_SMALL_P(a) do { \ int r; \ for (r = 0; r < 10; r ++) \ ROUND_SMALL_P(a, r); \ } while (0) #define PERM_SMALL_Q(a) do { \ int r; \ for (r = 0; r < 10; r ++) \ ROUND_SMALL_Q(a, r); \ } while (0) #else #define PERM_SMALL_P(a) do { \ int r; \ for (r = 0; r < 10; r += 2) { \ ROUND_SMALL_P(a, r + 0); \ ROUND_SMALL_P(a, r + 1); \ } \ } while (0) #define PERM_SMALL_Q(a) do { \ int r; \ for (r = 0; r < 10; r += 2) { \ ROUND_SMALL_Q(a, r + 0); \ ROUND_SMALL_Q(a, r + 1); \ } \ } while (0) #endif #define COMPRESS_SMALL do { \ sph_u32 g[16], m[16]; \ size_t u; \ for (u = 0; u < 16; u ++) { \ m[u] = dec32e_aligned(buf + (u << 2)); \ g[u] = m[u] ^ H[u]; \ } \ PERM_SMALL_P(g); \ PERM_SMALL_Q(m); \ for (u = 0; u < 16; u ++) \ H[u] ^= g[u] ^ m[u]; \ } while (0) #define FINAL_SMALL do { \ sph_u32 x[16]; \ size_t u; \ memcpy(x, H, sizeof x); \ PERM_SMALL_P(x); \ for (u = 0; u < 16; u ++) \ H[u] ^= x[u]; \ } while (0) #define DECL_STATE_BIG \ sph_u32 H[32]; #define READ_STATE_BIG(sc) do { \ memcpy(H, (sc)->state.narrow, sizeof H); \ } while (0) #define WRITE_STATE_BIG(sc) do { \ memcpy((sc)->state.narrow, H, sizeof H); \ } while (0) #if SPH_SMALL_FOOTPRINT_GROESTL #define RBTT(d0, d1, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ sph_u32 fu2 = T0up[B32_2(a[b2])]; \ sph_u32 fd2 = T0dn[B32_2(a[b2])]; \ sph_u32 fu3 = T1up[B32_3(a[b3])]; \ sph_u32 fd3 = T1dn[B32_3(a[b3])]; \ sph_u32 fu6 = T0up[B32_2(a[b6])]; \ sph_u32 fd6 = T0dn[B32_2(a[b6])]; \ sph_u32 fu7 = T1up[B32_3(a[b7])]; \ sph_u32 fd7 = T1dn[B32_3(a[b7])]; \ t[d0] = T0up[B32_0(a[b0])] \ ^ T1up[B32_1(a[b1])] \ ^ R32u(fu2, fd2) \ ^ R32u(fu3, fd3) \ ^ T0dn[B32_0(a[b4])] \ ^ T1dn[B32_1(a[b5])] \ ^ R32d(fu6, fd6) \ ^ R32d(fu7, fd7); \ t[d1] = T0dn[B32_0(a[b0])] \ ^ T1dn[B32_1(a[b1])] \ ^ R32d(fu2, fd2) \ ^ R32d(fu3, fd3) \ ^ T0up[B32_0(a[b4])] \ ^ T1up[B32_1(a[b5])] \ ^ R32u(fu6, fd6) \ ^ R32u(fu7, fd7); \ } while (0) #else #define RBTT(d0, d1, a, b0, b1, b2, b3, b4, b5, b6, b7) do { \ t[d0] = T0up[B32_0(a[b0])] \ ^ T1up[B32_1(a[b1])] \ ^ T2up[B32_2(a[b2])] \ ^ T3up[B32_3(a[b3])] \ ^ T0dn[B32_0(a[b4])] \ ^ T1dn[B32_1(a[b5])] \ ^ T2dn[B32_2(a[b6])] \ ^ T3dn[B32_3(a[b7])]; \ t[d1] = T0dn[B32_0(a[b0])] \ ^ T1dn[B32_1(a[b1])] \ ^ T2dn[B32_2(a[b2])] \ ^ T3dn[B32_3(a[b3])] \ ^ T0up[B32_0(a[b4])] \ ^ T1up[B32_1(a[b5])] \ ^ T2up[B32_2(a[b6])] \ ^ T3up[B32_3(a[b7])]; \ } while (0) #endif #if SPH_SMALL_FOOTPRINT_GROESTL #define ROUND_BIG_P(a, r) do { \ sph_u32 t[32]; \ size_t u; \ a[0x00] ^= PC32up(0x00, r); \ a[0x01] ^= PC32dn(0x00, r); \ a[0x02] ^= PC32up(0x10, r); \ a[0x03] ^= PC32dn(0x10, r); \ a[0x04] ^= PC32up(0x20, r); \ a[0x05] ^= PC32dn(0x20, r); \ a[0x06] ^= PC32up(0x30, r); \ a[0x07] ^= PC32dn(0x30, r); \ a[0x08] ^= PC32up(0x40, r); \ a[0x09] ^= PC32dn(0x40, r); \ a[0x0A] ^= PC32up(0x50, r); \ a[0x0B] ^= PC32dn(0x50, r); \ a[0x0C] ^= PC32up(0x60, r); \ a[0x0D] ^= PC32dn(0x60, r); \ a[0x0E] ^= PC32up(0x70, r); \ a[0x0F] ^= PC32dn(0x70, r); \ a[0x10] ^= PC32up(0x80, r); \ a[0x11] ^= PC32dn(0x80, r); \ a[0x12] ^= PC32up(0x90, r); \ a[0x13] ^= PC32dn(0x90, r); \ a[0x14] ^= PC32up(0xA0, r); \ a[0x15] ^= PC32dn(0xA0, r); \ a[0x16] ^= PC32up(0xB0, r); \ a[0x17] ^= PC32dn(0xB0, r); \ a[0x18] ^= PC32up(0xC0, r); \ a[0x19] ^= PC32dn(0xC0, r); \ a[0x1A] ^= PC32up(0xD0, r); \ a[0x1B] ^= PC32dn(0xD0, r); \ a[0x1C] ^= PC32up(0xE0, r); \ a[0x1D] ^= PC32dn(0xE0, r); \ a[0x1E] ^= PC32up(0xF0, r); \ a[0x1F] ^= PC32dn(0xF0, r); \ for (u = 0; u < 32; u += 8) { \ RBTT(u + 0x00, (u + 0x01) & 0x1F, a, \ u + 0x00, (u + 0x02) & 0x1F, \ (u + 0x04) & 0x1F, (u + 0x06) & 0x1F, \ (u + 0x09) & 0x1F, (u + 0x0B) & 0x1F, \ (u + 0x0D) & 0x1F, (u + 0x17) & 0x1F); \ RBTT(u + 0x02, (u + 0x03) & 0x1F, a, \ u + 0x02, (u + 0x04) & 0x1F, \ (u + 0x06) & 0x1F, (u + 0x08) & 0x1F, \ (u + 0x0B) & 0x1F, (u + 0x0D) & 0x1F, \ (u + 0x0F) & 0x1F, (u + 0x19) & 0x1F); \ RBTT(u + 0x04, (u + 0x05) & 0x1F, a, \ u + 0x04, (u + 0x06) & 0x1F, \ (u + 0x08) & 0x1F, (u + 0x0A) & 0x1F, \ (u + 0x0D) & 0x1F, (u + 0x0F) & 0x1F, \ (u + 0x11) & 0x1F, (u + 0x1B) & 0x1F); \ RBTT(u + 0x06, (u + 0x07) & 0x1F, a, \ u + 0x06, (u + 0x08) & 0x1F, \ (u + 0x0A) & 0x1F, (u + 0x0C) & 0x1F, \ (u + 0x0F) & 0x1F, (u + 0x11) & 0x1F, \ (u + 0x13) & 0x1F, (u + 0x1D) & 0x1F); \ } \ memcpy(a, t, sizeof t); \ } while (0) #define ROUND_BIG_Q(a, r) do { \ sph_u32 t[32]; \ size_t u; \ a[0x00] ^= QC32up(0x00, r); \ a[0x01] ^= QC32dn(0x00, r); \ a[0x02] ^= QC32up(0x10, r); \ a[0x03] ^= QC32dn(0x10, r); \ a[0x04] ^= QC32up(0x20, r); \ a[0x05] ^= QC32dn(0x20, r); \ a[0x06] ^= QC32up(0x30, r); \ a[0x07] ^= QC32dn(0x30, r); \ a[0x08] ^= QC32up(0x40, r); \ a[0x09] ^= QC32dn(0x40, r); \ a[0x0A] ^= QC32up(0x50, r); \ a[0x0B] ^= QC32dn(0x50, r); \ a[0x0C] ^= QC32up(0x60, r); \ a[0x0D] ^= QC32dn(0x60, r); \ a[0x0E] ^= QC32up(0x70, r); \ a[0x0F] ^= QC32dn(0x70, r); \ a[0x10] ^= QC32up(0x80, r); \ a[0x11] ^= QC32dn(0x80, r); \ a[0x12] ^= QC32up(0x90, r); \ a[0x13] ^= QC32dn(0x90, r); \ a[0x14] ^= QC32up(0xA0, r); \ a[0x15] ^= QC32dn(0xA0, r); \ a[0x16] ^= QC32up(0xB0, r); \ a[0x17] ^= QC32dn(0xB0, r); \ a[0x18] ^= QC32up(0xC0, r); \ a[0x19] ^= QC32dn(0xC0, r); \ a[0x1A] ^= QC32up(0xD0, r); \ a[0x1B] ^= QC32dn(0xD0, r); \ a[0x1C] ^= QC32up(0xE0, r); \ a[0x1D] ^= QC32dn(0xE0, r); \ a[0x1E] ^= QC32up(0xF0, r); \ a[0x1F] ^= QC32dn(0xF0, r); \ for (u = 0; u < 32; u += 8) { \ RBTT(u + 0x00, (u + 0x01) & 0x1F, a, \ (u + 0x02) & 0x1F, (u + 0x06) & 0x1F, \ (u + 0x0A) & 0x1F, (u + 0x16) & 0x1F, \ (u + 0x01) & 0x1F, (u + 0x05) & 0x1F, \ (u + 0x09) & 0x1F, (u + 0x0D) & 0x1F); \ RBTT(u + 0x02, (u + 0x03) & 0x1F, a, \ (u + 0x04) & 0x1F, (u + 0x08) & 0x1F, \ (u + 0x0C) & 0x1F, (u + 0x18) & 0x1F, \ (u + 0x03) & 0x1F, (u + 0x07) & 0x1F, \ (u + 0x0B) & 0x1F, (u + 0x0F) & 0x1F); \ RBTT(u + 0x04, (u + 0x05) & 0x1F, a, \ (u + 0x06) & 0x1F, (u + 0x0A) & 0x1F, \ (u + 0x0E) & 0x1F, (u + 0x1A) & 0x1F, \ (u + 0x05) & 0x1F, (u + 0x09) & 0x1F, \ (u + 0x0D) & 0x1F, (u + 0x11) & 0x1F); \ RBTT(u + 0x06, (u + 0x07) & 0x1F, a, \ (u + 0x08) & 0x1F, (u + 0x0C) & 0x1F, \ (u + 0x10) & 0x1F, (u + 0x1C) & 0x1F, \ (u + 0x07) & 0x1F, (u + 0x0B) & 0x1F, \ (u + 0x0F) & 0x1F, (u + 0x13) & 0x1F); \ } \ memcpy(a, t, sizeof t); \ } while (0) #else #define ROUND_BIG_P(a, r) do { \ sph_u32 t[32]; \ a[0x00] ^= PC32up(0x00, r); \ a[0x01] ^= PC32dn(0x00, r); \ a[0x02] ^= PC32up(0x10, r); \ a[0x03] ^= PC32dn(0x10, r); \ a[0x04] ^= PC32up(0x20, r); \ a[0x05] ^= PC32dn(0x20, r); \ a[0x06] ^= PC32up(0x30, r); \ a[0x07] ^= PC32dn(0x30, r); \ a[0x08] ^= PC32up(0x40, r); \ a[0x09] ^= PC32dn(0x40, r); \ a[0x0A] ^= PC32up(0x50, r); \ a[0x0B] ^= PC32dn(0x50, r); \ a[0x0C] ^= PC32up(0x60, r); \ a[0x0D] ^= PC32dn(0x60, r); \ a[0x0E] ^= PC32up(0x70, r); \ a[0x0F] ^= PC32dn(0x70, r); \ a[0x10] ^= PC32up(0x80, r); \ a[0x11] ^= PC32dn(0x80, r); \ a[0x12] ^= PC32up(0x90, r); \ a[0x13] ^= PC32dn(0x90, r); \ a[0x14] ^= PC32up(0xA0, r); \ a[0x15] ^= PC32dn(0xA0, r); \ a[0x16] ^= PC32up(0xB0, r); \ a[0x17] ^= PC32dn(0xB0, r); \ a[0x18] ^= PC32up(0xC0, r); \ a[0x19] ^= PC32dn(0xC0, r); \ a[0x1A] ^= PC32up(0xD0, r); \ a[0x1B] ^= PC32dn(0xD0, r); \ a[0x1C] ^= PC32up(0xE0, r); \ a[0x1D] ^= PC32dn(0xE0, r); \ a[0x1E] ^= PC32up(0xF0, r); \ a[0x1F] ^= PC32dn(0xF0, r); \ RBTT(0x00, 0x01, a, \ 0x00, 0x02, 0x04, 0x06, 0x09, 0x0B, 0x0D, 0x17); \ RBTT(0x02, 0x03, a, \ 0x02, 0x04, 0x06, 0x08, 0x0B, 0x0D, 0x0F, 0x19); \ RBTT(0x04, 0x05, a, \ 0x04, 0x06, 0x08, 0x0A, 0x0D, 0x0F, 0x11, 0x1B); \ RBTT(0x06, 0x07, a, \ 0x06, 0x08, 0x0A, 0x0C, 0x0F, 0x11, 0x13, 0x1D); \ RBTT(0x08, 0x09, a, \ 0x08, 0x0A, 0x0C, 0x0E, 0x11, 0x13, 0x15, 0x1F); \ RBTT(0x0A, 0x0B, a, \ 0x0A, 0x0C, 0x0E, 0x10, 0x13, 0x15, 0x17, 0x01); \ RBTT(0x0C, 0x0D, a, \ 0x0C, 0x0E, 0x10, 0x12, 0x15, 0x17, 0x19, 0x03); \ RBTT(0x0E, 0x0F, a, \ 0x0E, 0x10, 0x12, 0x14, 0x17, 0x19, 0x1B, 0x05); \ RBTT(0x10, 0x11, a, \ 0x10, 0x12, 0x14, 0x16, 0x19, 0x1B, 0x1D, 0x07); \ RBTT(0x12, 0x13, a, \ 0x12, 0x14, 0x16, 0x18, 0x1B, 0x1D, 0x1F, 0x09); \ RBTT(0x14, 0x15, a, \ 0x14, 0x16, 0x18, 0x1A, 0x1D, 0x1F, 0x01, 0x0B); \ RBTT(0x16, 0x17, a, \ 0x16, 0x18, 0x1A, 0x1C, 0x1F, 0x01, 0x03, 0x0D); \ RBTT(0x18, 0x19, a, \ 0x18, 0x1A, 0x1C, 0x1E, 0x01, 0x03, 0x05, 0x0F); \ RBTT(0x1A, 0x1B, a, \ 0x1A, 0x1C, 0x1E, 0x00, 0x03, 0x05, 0x07, 0x11); \ RBTT(0x1C, 0x1D, a, \ 0x1C, 0x1E, 0x00, 0x02, 0x05, 0x07, 0x09, 0x13); \ RBTT(0x1E, 0x1F, a, \ 0x1E, 0x00, 0x02, 0x04, 0x07, 0x09, 0x0B, 0x15); \ memcpy(a, t, sizeof t); \ } while (0) #define ROUND_BIG_Q(a, r) do { \ sph_u32 t[32]; \ a[0x00] ^= QC32up(0x00, r); \ a[0x01] ^= QC32dn(0x00, r); \ a[0x02] ^= QC32up(0x10, r); \ a[0x03] ^= QC32dn(0x10, r); \ a[0x04] ^= QC32up(0x20, r); \ a[0x05] ^= QC32dn(0x20, r); \ a[0x06] ^= QC32up(0x30, r); \ a[0x07] ^= QC32dn(0x30, r); \ a[0x08] ^= QC32up(0x40, r); \ a[0x09] ^= QC32dn(0x40, r); \ a[0x0A] ^= QC32up(0x50, r); \ a[0x0B] ^= QC32dn(0x50, r); \ a[0x0C] ^= QC32up(0x60, r); \ a[0x0D] ^= QC32dn(0x60, r); \ a[0x0E] ^= QC32up(0x70, r); \ a[0x0F] ^= QC32dn(0x70, r); \ a[0x10] ^= QC32up(0x80, r); \ a[0x11] ^= QC32dn(0x80, r); \ a[0x12] ^= QC32up(0x90, r); \ a[0x13] ^= QC32dn(0x90, r); \ a[0x14] ^= QC32up(0xA0, r); \ a[0x15] ^= QC32dn(0xA0, r); \ a[0x16] ^= QC32up(0xB0, r); \ a[0x17] ^= QC32dn(0xB0, r); \ a[0x18] ^= QC32up(0xC0, r); \ a[0x19] ^= QC32dn(0xC0, r); \ a[0x1A] ^= QC32up(0xD0, r); \ a[0x1B] ^= QC32dn(0xD0, r); \ a[0x1C] ^= QC32up(0xE0, r); \ a[0x1D] ^= QC32dn(0xE0, r); \ a[0x1E] ^= QC32up(0xF0, r); \ a[0x1F] ^= QC32dn(0xF0, r); \ RBTT(0x00, 0x01, a, \ 0x02, 0x06, 0x0A, 0x16, 0x01, 0x05, 0x09, 0x0D); \ RBTT(0x02, 0x03, a, \ 0x04, 0x08, 0x0C, 0x18, 0x03, 0x07, 0x0B, 0x0F); \ RBTT(0x04, 0x05, a, \ 0x06, 0x0A, 0x0E, 0x1A, 0x05, 0x09, 0x0D, 0x11); \ RBTT(0x06, 0x07, a, \ 0x08, 0x0C, 0x10, 0x1C, 0x07, 0x0B, 0x0F, 0x13); \ RBTT(0x08, 0x09, a, \ 0x0A, 0x0E, 0x12, 0x1E, 0x09, 0x0D, 0x11, 0x15); \ RBTT(0x0A, 0x0B, a, \ 0x0C, 0x10, 0x14, 0x00, 0x0B, 0x0F, 0x13, 0x17); \ RBTT(0x0C, 0x0D, a, \ 0x0E, 0x12, 0x16, 0x02, 0x0D, 0x11, 0x15, 0x19); \ RBTT(0x0E, 0x0F, a, \ 0x10, 0x14, 0x18, 0x04, 0x0F, 0x13, 0x17, 0x1B); \ RBTT(0x10, 0x11, a, \ 0x12, 0x16, 0x1A, 0x06, 0x11, 0x15, 0x19, 0x1D); \ RBTT(0x12, 0x13, a, \ 0x14, 0x18, 0x1C, 0x08, 0x13, 0x17, 0x1B, 0x1F); \ RBTT(0x14, 0x15, a, \ 0x16, 0x1A, 0x1E, 0x0A, 0x15, 0x19, 0x1D, 0x01); \ RBTT(0x16, 0x17, a, \ 0x18, 0x1C, 0x00, 0x0C, 0x17, 0x1B, 0x1F, 0x03); \ RBTT(0x18, 0x19, a, \ 0x1A, 0x1E, 0x02, 0x0E, 0x19, 0x1D, 0x01, 0x05); \ RBTT(0x1A, 0x1B, a, \ 0x1C, 0x00, 0x04, 0x10, 0x1B, 0x1F, 0x03, 0x07); \ RBTT(0x1C, 0x1D, a, \ 0x1E, 0x02, 0x06, 0x12, 0x1D, 0x01, 0x05, 0x09); \ RBTT(0x1E, 0x1F, a, \ 0x00, 0x04, 0x08, 0x14, 0x1F, 0x03, 0x07, 0x0B); \ memcpy(a, t, sizeof t); \ } while (0) #endif #if SPH_SMALL_FOOTPRINT_GROESTL #define PERM_BIG_P(a) do { \ int r; \ for (r = 0; r < 14; r ++) \ ROUND_BIG_P(a, r); \ } while (0) #define PERM_BIG_Q(a) do { \ int r; \ for (r = 0; r < 14; r ++) \ ROUND_BIG_Q(a, r); \ } while (0) #else #define PERM_BIG_P(a) do { \ int r; \ for (r = 0; r < 14; r += 2) { \ ROUND_BIG_P(a, r + 0); \ ROUND_BIG_P(a, r + 1); \ } \ } while (0) #define PERM_BIG_Q(a) do { \ int r; \ for (r = 0; r < 14; r += 2) { \ ROUND_BIG_Q(a, r + 0); \ ROUND_BIG_Q(a, r + 1); \ } \ } while (0) #endif #define COMPRESS_BIG do { \ sph_u32 g[32], m[32]; \ size_t u; \ for (u = 0; u < 32; u ++) { \ m[u] = dec32e_aligned(buf + (u << 2)); \ g[u] = m[u] ^ H[u]; \ } \ PERM_BIG_P(g); \ PERM_BIG_Q(m); \ for (u = 0; u < 32; u ++) \ H[u] ^= g[u] ^ m[u]; \ } while (0) #define FINAL_BIG do { \ sph_u32 x[32]; \ size_t u; \ memcpy(x, H, sizeof x); \ PERM_BIG_P(x); \ for (u = 0; u < 32; u ++) \ H[u] ^= x[u]; \ } while (0) #endif static void groestl_small_init(sph_groestl_small_context *sc, unsigned out_size) { size_t u; for (u = 0; u < 64; u ++) sc->buf[u] = 0; sc->ptr = 0; #if SPH_GROESTL_64 for (u = 0; u < 7; u ++) sc->state.wide[u] = 0; #if USE_LE sc->state.wide[7] = ((sph_u64)(out_size & 0xFF) << 56) | ((sph_u64)(out_size & 0xFF00) << 40); #else sc->state.wide[7] = (sph_u64)out_size; #endif #else for (u = 0; u < 15; u ++) sc->state.narrow[u] = 0; #if USE_LE sc->state.narrow[15] = ((sph_u32)(out_size & 0xFF) << 24) | ((sph_u32)(out_size & 0xFF00) << 8); #else sc->state.narrow[15] = (sph_u32)out_size; #endif #endif #if SPH_64 sc->count = 0; #else sc->count_high = 0; sc->count_low = 0; #endif } static void groestl_small_core(sph_groestl_small_context *sc, const void *data, size_t len) { unsigned char *buf; size_t ptr; DECL_STATE_SMALL buf = sc->buf; ptr = sc->ptr; if (len < (sizeof sc->buf) - ptr) { memcpy(buf + ptr, data, len); ptr += len; sc->ptr = ptr; return; } READ_STATE_SMALL(sc); while (len > 0) { size_t clen; clen = (sizeof sc->buf) - ptr; if (clen > len) clen = len; memcpy(buf + ptr, data, clen); ptr += clen; data = (const unsigned char *)data + clen; len -= clen; if (ptr == sizeof sc->buf) { COMPRESS_SMALL; #if SPH_64 sc->count ++; #else if ((sc->count_low = SPH_T32(sc->count_low + 1)) == 0) sc->count_high = SPH_T32(sc->count_high + 1); #endif ptr = 0; } } WRITE_STATE_SMALL(sc); sc->ptr = ptr; } static void groestl_small_close(sph_groestl_small_context *sc, unsigned ub, unsigned n, void *dst, size_t out_len) { unsigned char *buf; unsigned char pad[72]; size_t u=0, ptr=0, pad_len=0; #if SPH_64 sph_u64 count=0; #else sph_u32 count_high=0, count_low=0; #endif unsigned z=0; DECL_STATE_SMALL buf = sc->buf; ptr = sc->ptr; z = 0x80 >> n; pad[0] = ((ub & -z) | z) & 0xFF; if (ptr < 56) { pad_len = 64 - ptr; #if SPH_64 count = SPH_T64(sc->count + 1); #else count_low = SPH_T32(sc->count_low + 1); count_high = SPH_T32(sc->count_high); if (count_low == 0) count_high = SPH_T32(count_high + 1); #endif } else { pad_len = 128 - ptr; #if SPH_64 count = SPH_T64(sc->count + 2); #else count_low = SPH_T32(sc->count_low + 2); count_high = SPH_T32(sc->count_high); if (count_low <= 1) count_high = SPH_T32(count_high + 1); #endif } memset(pad + 1, 0, pad_len - 9); #if SPH_64 sph_enc64be(pad + pad_len - 8, count); #else sph_enc64be(pad + pad_len - 8, count_high); sph_enc64be(pad + pad_len - 4, count_low); #endif groestl_small_core(sc, pad, pad_len); READ_STATE_SMALL(sc); FINAL_SMALL; #if SPH_GROESTL_64 for (u = 0; u < 4; u ++) enc64e(pad + (u << 3), H[u + 4]); #else for (u = 0; u < 8; u ++) enc32e(pad + (u << 2), H[u + 8]); #endif memcpy(dst, pad + 32 - out_len, out_len); groestl_small_init(sc, (unsigned)out_len << 3); } static void groestl_big_init(sph_groestl_big_context *sc, unsigned out_size) { size_t u; for (u = 0; u < 128; u ++) sc->buf[u] = 0; sc->ptr = 0; #if SPH_GROESTL_64 for (u = 0; u < 15; u ++) sc->state.wide[u] = 0; #if USE_LE sc->state.wide[15] = ((sph_u64)(out_size & 0xFF) << 56) | ((sph_u64)(out_size & 0xFF00) << 40); #else sc->state.wide[15] = (sph_u64)out_size; #endif #else for (u = 0; u < 31; u ++) sc->state.narrow[u] = 0; #if USE_LE sc->state.narrow[31] = ((sph_u32)(out_size & 0xFF) << 24) | ((sph_u32)(out_size & 0xFF00) << 8); #else sc->state.narrow[31] = (sph_u32)out_size; #endif #endif #if SPH_64 sc->count = 0; #else sc->count_high = 0; sc->count_low = 0; #endif } static void groestl_big_core(sph_groestl_big_context *sc, const void *data, size_t len) { unsigned char *buf; size_t ptr; DECL_STATE_BIG buf = sc->buf; ptr = sc->ptr; if (len < (sizeof sc->buf) - ptr) { memcpy(buf + ptr, data, len); ptr += len; sc->ptr = ptr; return; } READ_STATE_BIG(sc); while (len > 0) { size_t clen; clen = (sizeof sc->buf) - ptr; if (clen > len) clen = len; memcpy(buf + ptr, data, clen); ptr += clen; data = (const unsigned char *)data + clen; len -= clen; if (ptr == sizeof sc->buf) { COMPRESS_BIG; #if SPH_64 sc->count ++; #else if ((sc->count_low = SPH_T32(sc->count_low + 1)) == 0) sc->count_high = SPH_T32(sc->count_high + 1); #endif ptr = 0; } } WRITE_STATE_BIG(sc); sc->ptr = ptr; } static void groestl_big_close(sph_groestl_big_context *sc, unsigned ub, unsigned n, void *dst, size_t out_len) { unsigned char *buf; unsigned char pad[136]; size_t ptr=0, pad_len=0, u=0; #if SPH_64 sph_u64 count=0; #else sph_u32 count_high=0, count_low=0; #endif unsigned z=0; DECL_STATE_BIG buf = sc->buf; ptr = sc->ptr; z = 0x80 >> n; pad[0] = ((ub & -z) | z) & 0xFF; if (ptr < 120) { pad_len = 128 - ptr; #if SPH_64 count = SPH_T64(sc->count + 1); #else count_low = SPH_T32(sc->count_low + 1); count_high = SPH_T32(sc->count_high); if (count_low == 0) count_high = SPH_T32(count_high + 1); #endif } else { pad_len = 256 - ptr; #if SPH_64 count = SPH_T64(sc->count + 2); #else count_low = SPH_T32(sc->count_low + 2); count_high = SPH_T32(sc->count_high); if (count_low <= 1) count_high = SPH_T32(count_high + 1); #endif } memset(pad + 1, 0, pad_len - 9); #if SPH_64 sph_enc64be(pad + pad_len - 8, count); #else sph_enc64be(pad + pad_len - 8, count_high); sph_enc64be(pad + pad_len - 4, count_low); #endif groestl_big_core(sc, pad, pad_len); READ_STATE_BIG(sc); FINAL_BIG; #if SPH_GROESTL_64 for (u = 0; u < 8; u ++) enc64e(pad + (u << 3), H[u + 8]); #else for (u = 0; u < 16; u ++) enc32e(pad + (u << 2), H[u + 16]); #endif memcpy(dst, pad + 64 - out_len, out_len); groestl_big_init(sc, (unsigned)out_len << 3); } /* see sph_groestl.h */ void sph_groestl224_init(void *cc) { groestl_small_init(cc, 224); } /* see sph_groestl.h */ void sph_groestl224(void *cc, const void *data, size_t len) { groestl_small_core(cc, data, len); } /* see sph_groestl.h */ void sph_groestl224_close(void *cc, void *dst) { groestl_small_close(cc, 0, 0, dst, 28); } /* see sph_groestl.h */ void sph_groestl224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) { groestl_small_close(cc, ub, n, dst, 28); } /* see sph_groestl.h */ void sph_groestl256_init(void *cc) { groestl_small_init(cc, 256); } /* see sph_groestl.h */ void sph_groestl256(void *cc, const void *data, size_t len) { groestl_small_core(cc, data, len); } /* see sph_groestl.h */ void sph_groestl256_close(void *cc, void *dst) { groestl_small_close(cc, 0, 0, dst, 32); } /* see sph_groestl.h */ void sph_groestl256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) { groestl_small_close(cc, ub, n, dst, 32); } /* see sph_groestl.h */ void sph_groestl384_init(void *cc) { groestl_big_init(cc, 384); } /* see sph_groestl.h */ void sph_groestl384(void *cc, const void *data, size_t len) { groestl_big_core(cc, data, len); } /* see sph_groestl.h */ void sph_groestl384_close(void *cc, void *dst) { groestl_big_close(cc, 0, 0, dst, 48); } /* see sph_groestl.h */ void sph_groestl384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) { groestl_big_close(cc, ub, n, dst, 48); } /* see sph_groestl.h */ void sph_groestl512_init(void *cc) { groestl_big_init(cc, 512); } /* see sph_groestl.h */ void sph_groestl512(void *cc, const void *data, size_t len) { groestl_big_core(cc, data, len); } /* see sph_groestl.h */ void sph_groestl512_close(void *cc, void *dst) { groestl_big_close(cc, 0, 0, dst, 64); } /* see sph_groestl.h */ void sph_groestl512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst) { groestl_big_close(cc, ub, n, dst, 64); } #ifdef __cplusplus } #endif
import React from "react"; import { Button, Row, Col, Form, FormGroup, InputGroup, InputGroupText, InputGroupAddon, Input, } from "reactstrap"; // core components import ExamplesNavbar from "components/Navbars/ExamplesNavbar.js"; import Footer from "components/Footer/Footer.js"; import axios from "../../axios"; import { Link } from "react-router-dom"; import classnames from "classnames"; import { ChatBubble, BubbleGroup, Message } from "react-chat-ui"; export default function LandingPage(props) { React.useEffect(() => { document.body.classList.toggle("landing-page"); return function cleanup() { document.body.classList.toggle("landing-page"); }; }, []); const [data, setData] = React.useState({ messages: [] }); const [sendMessage, setSendMessage] = React.useState(""); const getData = () => { axios.get(`messages/${props.match.params.offer}`).then((res) => { setData(res.data); }); }; React.useEffect(() => { getData(); }, []); const handleSend = (e) => { e.preventDefault(); axios .post(`messages/${props.match.params.offer}`, { message: sendMessage }) .then(() => { setSendMessage(""); getData(); }); }; const [formModal, setFormModal] = React.useState(false); const [textFocus, setTextFocus] = React.useState(false); return ( <> <ExamplesNavbar /> <div className="wrapper"> <div className="page-header"> <img alt="..." className="path" src={require("assets/img/blob.png").default} /> <img alt="..." className="path2" src={require("assets/img/path2.png").default} /> <img alt="..." className="shapes triangle" src={require("assets/img/triunghiuri.png").default} /> <img alt="..." className="shapes wave" src={require("assets/img/waves.png").default} /> <img alt="..." className="shapes squares" src={require("assets/img/patrat.png").default} /> <img alt="..." className="shapes circle" src={require("assets/img/cercuri.png").default} /> <div className="content-center"> <Row> <Col className="col-md-6 offset-3"> <div className="container"> KÖFTE Sohbet Ekranı <br /> <br /> {data.messages.map((message, index) => ( <ChatBubble key={"adasd-" + index} message={ new Message({ id: data.me === message.user ? 0 : 1, message: message.message, }) } /> ))} </div> <Form autoComplete="off" onSubmit={handleSend} role="form"> <FormGroup> <InputGroup className={classnames("input-group-alternative", { "input-group-focus": textFocus, })} > <InputGroupAddon addonType="prepend"> <InputGroupText> <i className="tim-icons icon-double-right" /> </InputGroupText> </InputGroupAddon> <Input placeholder="Mesajınız" type="text" onFocus={(e) => setTextFocus(true)} onBlur={(e) => setTextFocus(false)} value={sendMessage} onChange={(e) => setSendMessage(e.target.value)} /> </InputGroup> <div className="text-center"> <Button color="success" type="submit"> Gönder </Button> </div> </FormGroup> </Form> </Col> </Row> </div> </div> <Footer /> </div> </> ); }
from ...exceptions import BadRequestException from ...utils import get_temp_dir from biosimulators_utils.combine.data_model import CombineArchiveContent from biosimulators_utils.combine.io import CombineArchiveReader, CombineArchiveWriter import connexion import flask import os import requests import requests.exceptions import src.s3 def handler(body, files=None): ''' Add one or more files to a COMBINE/OMEX archive Args: body (:obj:`dict`): dictionary with schema ``CombineArchiveAndAdditionalContent`` with the specifications of the desired additions to the COMBINE/OMEX archive files (:obj:`list` of :obj:`werkzeug.datastructures.FileStorage`, optional): files (e.g., SBML file) Returns: :obj:`werkzeug.wrappers.response.Response` or :obj:`str`: response with COMBINE/OMEX archive or a URL to a COMBINE/OMEX archive ''' archive = body.get('archive') new_content = body.get('newContent') files = connexion.request.files.getlist('files') filename_map = {file.filename: file for file in files} overwrite_locations = body.get('overwriteLocations', True) download = body.get('download', False) # create temporary working directory temp_dirname = get_temp_dir() archive_filename = os.path.join(temp_dirname, 'archive.omex') # get COMBINE/OMEX archive archive_url = archive.get('url', None) if archive_url: try: response = requests.get(archive_url) response.raise_for_status() except requests.exceptions.RequestException as exception: title = 'COMBINE/OMEX archive could not be loaded from `{}`'.format( archive_url) raise BadRequestException( title=title, instance=exception, ) # save archive to local temporary file with open(archive_filename, 'wb') as file: file.write(response.content) else: archive_file = filename_map.get(archive['filename'], None) if archive_file is None: raise BadRequestException( title='Archive file with name `{}` was not uploaded'.format( archive['filename']), instance=ValueError(), ) archive_file.save(archive_filename) # read archive archive_dirname = os.path.join(temp_dirname, 'archive') try: archive = CombineArchiveReader().run(archive_filename, archive_dirname) except Exception as exception: # return exception raise BadRequestException( title='COMBINE/OMEX archive is not valid.', instance=exception, ) location_content_map = {os.path.relpath(content.location, '.'): content for content in archive.contents} new_location = os.path.relpath(new_content['location'], '.') content = location_content_map.get(new_location, None) if content is None: content = CombineArchiveContent(location=new_location) archive.contents.append(content) else: if not overwrite_locations: new_location_parts = os.path.splitext(new_location) i_file = 0 while True: i_file += 1 temp_new_location = new_location_parts[0] + '_' + str(i_file) + new_location_parts[1] if temp_new_location not in location_content_map: new_location = temp_new_location break content = CombineArchiveContent(location=new_location) archive.contents.append(content) content_filename = new_content['filename'] file = filename_map.get(content_filename, None) if file: file.save(os.path.join(archive_dirname, new_location)) else: raise BadRequestException( title='File with name `{}` was not uploaded'.format(content_filename), instance=ValueError(), ) content.format = new_content['format'] content.master = new_content['master'] # package COMBINE/OMEX archive CombineArchiveWriter().run(archive, archive_dirname, archive_filename) if download: return flask.send_file(archive_filename, mimetype='application/zip', as_attachment=True, attachment_filename='archive.omex') else: # save COMBINE/OMEX archive to S3 bucket archive_url = src.s3.save_temporary_combine_archive_to_s3_bucket(archive_filename, public=True) # return URL for archive in S3 bucket return archive_url
#pragma once #include <stdint.h> #define PROFILE_MODE #define GAME_MAX_INSTANCE_COUNT 3000000 typedef struct { uint8_t spriteIndices[GAME_MAX_INSTANCE_COUNT]; uint16_t scales[GAME_MAX_INSTANCE_COUNT]; uint16_t positionX[GAME_MAX_INSTANCE_COUNT]; uint16_t positionY[GAME_MAX_INSTANCE_COUNT]; } Game_InstanceBuffer; void game_init(Game_InstanceBuffer* buffer); void game_tick(float delta); void game_kill(void); uint32_t game_gen_instance_buffer(Game_InstanceBuffer* buffer);
///////////////////////////////////////////////////////////////////////////// // Name: wx/osx/cocoa/dataview.h // Purpose: wxDataViewCtrl native implementation header for carbon // Author: // Copyright: (c) 2009 // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_DATAVIEWCTRL_COCOOA_H_ #define _WX_DATAVIEWCTRL_COCOOA_H_ #include "wx/defs.h" #import <Cocoa/Cocoa.h> #include "wx/osx/core/dataview.h" #include "wx/osx/private.h" // Forward declaration class wxCocoaDataViewControl; /* Dramatis personae: [vertical arrows indicate inheritance, horizontal -- aggregation] wxWindow ---> wxWidgetCocoaImpl wxDataViewWidgetImpl NSOutlineView | \ / | | \ / | | \ / | v \/ \/ v wxDataViewCtrl -------> wxCocoaDataViewControl <-------> wxCocoaOutlineView The right most classes are Objective-C only and can't be used from (pure) C++ code. */ // ============================================================================ // wxPointerObject: simply stores a pointer, without taking its ownership // ============================================================================ // Two pointer objects are equal if the containing pointers are equal. This // means also that the hash value of a pointer object depends only on the // stored pointer. @interface wxPointerObject : NSObject { void* pointer; } -(id) initWithPointer:(void*)initPointer; -(void*) pointer; -(void) setPointer:(void*)newPointer; @end // ============================================================================ // wxSortDescriptorObject: helper class to use native sorting facilities // ============================================================================ @interface wxSortDescriptorObject : NSSortDescriptor<NSCopying> { wxDataViewColumn* columnPtr; // pointer to the sorting column wxDataViewModel* modelPtr; // pointer to model } -(id) initWithModelPtr:(wxDataViewModel*)initModelPtr sortingColumnPtr:(wxDataViewColumn*)initColumnPtr ascending:(BOOL)sortAscending; -(wxDataViewColumn*) columnPtr; -(wxDataViewModel*) modelPtr; -(void) setColumnPtr:(wxDataViewColumn*)newColumnPtr; -(void) setModelPtr:(wxDataViewModel*)newModelPtr; @end // ============================================================================ // wxDataViewColumnNativeData: extra data for wxDataViewColumn // ============================================================================ class wxDataViewColumnNativeData { public: wxDataViewColumnNativeData() : m_NativeColumnPtr(NULL) { } wxDataViewColumnNativeData(NSTableColumn* initNativeColumnPtr) : m_NativeColumnPtr(initNativeColumnPtr) { } NSTableColumn* GetNativeColumnPtr() const { return m_NativeColumnPtr; } void SetNativeColumnPtr(NSTableColumn* newNativeColumnPtr) { m_NativeColumnPtr = newNativeColumnPtr; } private: // not owned by us NSTableColumn* m_NativeColumnPtr; }; // ============================================================================ // wxDataViewRendererNativeData: extra data for wxDataViewRenderer // ============================================================================ class wxDataViewRendererNativeData { public: wxDataViewRendererNativeData() : m_Object(NULL), m_ColumnCell(NULL) { Init(); } wxDataViewRendererNativeData(NSCell* initColumnCell) : m_Object(NULL), m_ColumnCell([initColumnCell retain]) { Init(); } wxDataViewRendererNativeData(NSCell* initColumnCell, id initObject) : m_Object([initObject retain]), m_ColumnCell([initColumnCell retain]) { Init(); } ~wxDataViewRendererNativeData() { [m_ColumnCell release]; [m_Object release]; [m_origFont release]; [m_origTextColour release]; } NSCell* GetColumnCell() const { return m_ColumnCell; } NSTableColumn* GetColumnPtr() const { return m_TableColumnPtr; } id GetItem() const { return m_Item; } NSCell* GetItemCell() const { return m_ItemCell; } id GetObject() const { return m_Object; } void SetColumnCell(NSCell* newCell) { [newCell retain]; [m_ColumnCell release]; m_ColumnCell = newCell; } void SetColumnPtr(NSTableColumn* newColumnPtr) { m_TableColumnPtr = newColumnPtr; } void SetItem(id newItem) { m_Item = newItem; } void SetItemCell(NSCell* newCell) { m_ItemCell = newCell; } void SetObject(id newObject) { [newObject retain]; [m_Object release]; m_Object = newObject; } // The original cell font and text colour stored here are NULL by default // and are only initialized to the values retrieved from the cell when we // change them from wxCocoaOutlineView:willDisplayCell:forTableColumn:item: // which calls our SaveOriginalXXX() methods before changing the cell // attributes. // // This allows us to avoid doing anything for the columns without any // attributes but still be able to restore the correct attributes for the // ones that do. NSFont *GetOriginalFont() const { return m_origFont; } NSColor *GetOriginalTextColour() const { return m_origTextColour; } void SaveOriginalFont(NSFont *font) { m_origFont = [font retain]; } void SaveOriginalTextColour(NSColor *textColour) { m_origTextColour = [textColour retain]; } // The ellipsization mode which we need to set for each cell being rendered. void SetEllipsizeMode(wxEllipsizeMode mode) { m_ellipsizeMode = mode; } wxEllipsizeMode GetEllipsizeMode() const { return m_ellipsizeMode; } // Set the line break mode for the given cell using our m_ellipsizeMode void ApplyLineBreakMode(NSCell *cell); private: // common part of all ctors void Init(); id m_Item; // item NOT owned by renderer // object that can be used by renderer for storing special data (owned by // renderer) id m_Object; NSCell* m_ColumnCell; // column's cell is owned by renderer NSCell* m_ItemCell; // item's cell is NOT owned by renderer NSTableColumn* m_TableColumnPtr; // column NOT owned by renderer // we own those if they're non-NULL NSFont *m_origFont; NSColor *m_origTextColour; wxEllipsizeMode m_ellipsizeMode; }; // ============================================================================ // wxCocoaOutlineDataSource // ============================================================================ // This class implements the data source delegate for the outline view. // As only an informal protocol exists this class inherits from NSObject only. // // As mentioned in the documentation for NSOutlineView the native control does // not own any data. Therefore, it has to be done by the data source. // Unfortunately, wxWidget's data source is a C++ data source but // NSOutlineDataSource requires objects as data. Therefore, the data (or better // the native item objects) have to be stored additionally in the native data // source. // NSOutlineView requires quick access to the item objects and quick linear // access to an item's children. This requires normally a hash type of storage // for the item object itself and an array structure for each item's children. // This means that basically two times the whole structure of wxWidget's model // class has to be stored. // This implementation is using a compromise: all items that are in use by the // control are stored in a set (from there they can be easily retrieved) and // owned by the set. Furthermore, children of the last parent are stored // in a linear list. // @interface wxCocoaOutlineDataSource : NSObject <NSOutlineViewDataSource> { // descriptors specifying the sorting (currently the array only holds one // object only) NSArray* sortDescriptors; NSMutableArray* children; // buffered children NSMutableSet* items; // stores all items that are in use by the control wxCocoaDataViewControl* implementation; wxDataViewModel* model; // parent of the buffered children; the object is owned wxPointerObject* currentParentItem; } // methods of informal protocol: -(BOOL) outlineView:(NSOutlineView*)outlineView acceptDrop:(id<NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index; -(id) outlineView:(NSOutlineView*)outlineView child:(NSInteger)index ofItem:(id)item; -(id) outlineView:(NSOutlineView*)outlineView objectValueForTableColumn:(NSTableColumn*)tableColumn byItem:(id)item; -(BOOL) outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item; -(NSInteger) outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item; -(NSDragOperation) outlineView:(NSOutlineView*)outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index; -(BOOL) outlineView:(NSOutlineView*)outlineView writeItems:(NSArray*)items toPasteboard:(NSPasteboard*)pasteboard; // buffer for items handling -(void) addToBuffer:(wxPointerObject*)item; -(void) clearBuffer; // returns the item in the buffer that has got the same pointer as "item", // if such an item does not exist nil is returned -(wxPointerObject*) getDataViewItemFromBuffer:(const wxDataViewItem&)item; -(wxPointerObject*) getItemFromBuffer:(wxPointerObject*)item; -(BOOL) isInBuffer:(wxPointerObject*)item; -(void) removeFromBuffer:(wxPointerObject*)item; // buffered children handling -(void) clearChildren; -(wxPointerObject*) getChild:(NSUInteger)index; -(NSUInteger) getChildCount; // buffer handling -(void) clearBuffers; // sorting -(NSArray*) sortDescriptors; -(void) setSortDescriptors:(NSArray*)newSortDescriptors; // access to wxWidgets variables -(wxPointerObject*) currentParentItem; -(wxCocoaDataViewControl*) implementation; -(wxDataViewModel*) model; -(void) setCurrentParentItem:(wxPointerObject*)newCurrentParentItem; -(void) setImplementation:(wxCocoaDataViewControl*)newImplementation; -(void) setModel:(wxDataViewModel*)newModel; // other methods -(void) bufferItem:(wxPointerObject*)parentItem withChildren:(wxDataViewItemArray*)dataViewChildrenPtr; @end // ============================================================================ // wxCustomCell: used for custom renderers // ============================================================================ @interface wxCustomCell : NSTextFieldCell { } -(NSSize) cellSize; @end // ============================================================================ // wxImageTextCell // ============================================================================ // // As the native cocoa environment does not have a cell displaying an icon/ // image and text at the same time, it has to be implemented by the user. // This implementation follows the implementation of Chuck Pisula in Apple's // DragNDropOutline sample application. // Although in wxDataViewCtrl icons are used on OSX icons do not exist for // display. Therefore, the cell is also called wxImageTextCell. // Instead of displaying images of any size (which is possible) this cell uses // a fixed size for displaying the image. Larger images are scaled to fit // into their reserved space. Smaller or not existing images use the fixed // reserved size and are scaled if necessary. // @interface wxImageTextCell : NSTextFieldCell { @private CGFloat xImageShift; // shift for the image in x-direction from border CGFloat spaceImageText; // space between image and text NSImage* image; // the image itself NSSize imageSize; // largest size of the image; default size is (16, 16) // the text alignment is used to align the whole cell (image and text) NSTextAlignment cellAlignment; } -(NSTextAlignment) alignment; -(void) setAlignment:(NSTextAlignment)newAlignment; -(NSImage*) image; -(void) setImage:(NSImage*)newImage; -(NSSize) imageSize; -(void) setImageSize:(NSSize) newImageSize; -(NSSize) cellSize; @end // ============================================================================ // wxCocoaOutlineView // ============================================================================ @interface wxCocoaOutlineView : NSOutlineView <NSOutlineViewDelegate> { @private // column and row of the cell being edited or -1 if none int currentlyEditedColumn, currentlyEditedRow; wxCocoaDataViewControl* implementation; } -(wxCocoaDataViewControl*) implementation; -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation; @end // ============================================================================ // wxCocoaDataViewControl // ============================================================================ // This is the internal interface class between wxDataViewCtrl (wxWidget) and // the native source view (Mac OS X cocoa). class wxCocoaDataViewControl : public wxWidgetCocoaImpl, public wxDataViewWidgetImpl { public: // constructors / destructor wxCocoaDataViewControl(wxWindow* peer, const wxPoint& pos, const wxSize& size, long style); virtual ~wxCocoaDataViewControl(); wxDataViewCtrl* GetDataViewCtrl() const { return static_cast<wxDataViewCtrl*>(GetWXPeer()); } // column related methods (inherited from wxDataViewWidgetImpl) virtual bool ClearColumns(); virtual bool DeleteColumn(wxDataViewColumn* columnPtr); virtual void DoSetExpanderColumn(wxDataViewColumn const* columnPtr); virtual wxDataViewColumn* GetColumn(unsigned int pos) const; virtual int GetColumnPosition(wxDataViewColumn const* columnPtr) const; virtual bool InsertColumn(unsigned int pos, wxDataViewColumn* columnPtr); virtual void FitColumnWidthToContent(unsigned int pos); // item related methods (inherited from wxDataViewWidgetImpl) virtual bool Add(const wxDataViewItem& parent, const wxDataViewItem& item); virtual bool Add(const wxDataViewItem& parent, const wxDataViewItemArray& items); virtual void Collapse(const wxDataViewItem& item); virtual void EnsureVisible(const wxDataViewItem& item, wxDataViewColumn const* columnPtr); virtual void Expand(const wxDataViewItem& item); virtual unsigned int GetCount() const; virtual wxRect GetRectangle(const wxDataViewItem& item, wxDataViewColumn const* columnPtr); virtual bool IsExpanded(const wxDataViewItem& item) const; virtual bool Reload(); virtual bool Remove(const wxDataViewItem& parent, const wxDataViewItem& item); virtual bool Remove(const wxDataViewItem& parent, const wxDataViewItemArray& item); virtual bool Update(const wxDataViewColumn* columnPtr); virtual bool Update(const wxDataViewItem& parent, const wxDataViewItem& item); virtual bool Update(const wxDataViewItem& parent, const wxDataViewItemArray& items); // model related methods virtual bool AssociateModel(wxDataViewModel* model); // // selection related methods (inherited from wxDataViewWidgetImpl) // virtual wxDataViewItem GetCurrentItem() const; virtual void SetCurrentItem(const wxDataViewItem& item); virtual wxDataViewColumn *GetCurrentColumn() const; virtual int GetSelectedItemsCount() const; virtual int GetSelections(wxDataViewItemArray& sel) const; virtual bool IsSelected(const wxDataViewItem& item) const; virtual void Select(const wxDataViewItem& item); virtual void SelectAll(); virtual void Unselect(const wxDataViewItem& item); virtual void UnselectAll(); // // sorting related methods // virtual wxDataViewColumn* GetSortingColumn () const; virtual void Resort(); // // other methods (inherited from wxDataViewWidgetImpl) // virtual void DoSetIndent(int indent); virtual void HitTest(const wxPoint& point, wxDataViewItem& item, wxDataViewColumn*& columnPtr) const; virtual void SetRowHeight(const wxDataViewItem& item, unsigned int height); virtual void OnSize(); virtual void StartEditor( const wxDataViewItem & item, unsigned int column ); // drag & drop helper methods wxDataFormat GetDnDDataFormat(wxDataObjectComposite* dataObjects); wxDataObjectComposite* GetDnDDataObjects(NSData* dataObject) const; // Cocoa-specific helpers id GetItemAtRow(int row) const; private: void InitOutlineView(long style); wxCocoaOutlineDataSource* m_DataSource; wxCocoaOutlineView* m_OutlineView; }; #endif // _WX_DATAVIEWCTRL_COCOOA_H_
const CryptoJS = require('crypto-js'); const settingsRouter = require('express').Router(); const adminSettingsFormData = require('./../../shared/formData/adminSettingsFormData'); const userSettingsFormData = require('./../../shared/formData/userSettingsFormData'); const logger = require('./../utils/logger'); const AdminSetting = require('./../models/adminSetting'); const UserSetting = require('./../models/userSetting'); const { createNewEditedArray } = require('./../utils/helpers'); const { getAndValidateForm } = require('./forms/formEngine'); const { getPublicSettings, getEnabledSettingsData, getFilteredSettings, checkIfAdminSettingEnabled, } = require('../utils/settingsService'); // Get all user settings values settingsRouter.get('/', async (request, response) => { const formId = userSettingsFormData.formId; const error = await getAndValidateForm(formId, 'GET', request); if (error) { return response.status(error.code).json(error.obj); } const result = await UserSetting.find({ userId: request.session._id }); const enabledSettings = await getEnabledSettingsData(request); const filteredResult = getFilteredSettings(result, enabledSettings); response.json(filteredResult); }); // Edit user settings settingsRouter.put('/', async (request, response) => { const body = request.body; const error = await getAndValidateForm(body.id, 'PUT', request); if (error) { return response.status(error.code).json(error.obj); } const setting = await UserSetting.findById(body.mongoId); const enabledSettings = await getEnabledSettingsData(request); if (!setting) { logger.error( 'Could not find user setting. Setting was not found (id: ' + body.mongoId + '). (+ body)', body ); return response.status(404).json({ msg: 'Setting was not found.', settingNotFoundError: true, }); } else if (body[setting.settingId] === null || body[setting.settingId] === undefined) { logger.error( "Could not find value with key '" + setting.settingId + "' in the payload for editing a user setting. (+ body)", body ); return response.status(400).json({ msg: 'Bad request.', settingValueNotFoundError: true, }); } else if (!checkIfAdminSettingEnabled(enabledSettings[setting.enabledId], setting.id)) { logger.error( `Could not update user setting. Setting is either disabled, always enabled (${ enabledSettings[setting.enabledId] }), or email or verification is not enabled. (+ body)`, body ); return response.status(401).json({ msg: 'Unauthorised', unauthorised: true, }); } const updatedUserSetting = { value: body[setting.settingId], }; const savedSetting = await UserSetting.findByIdAndUpdate(body.mongoId, updatedUserSetting, { new: true, }); if (!savedSetting) { logger.error( 'Could not find user setting after save. Setting was not found (id: ' + body.mongoId + '). (+ body)', body ); return response.status(404).json({ msg: 'Setting was not found.', settingNotFoundError: true, }); } logger.log(`Setting '${savedSetting.settingId}' was changed (user setting).`); const publicSettings = await getPublicSettings(request); response.json(publicSettings); }); // Get all admin settings values settingsRouter.get('/admin', async (request, response) => { const formId = adminSettingsFormData.formId; const error = await getAndValidateForm(formId, 'GET', request); if (error) { return response.status(error.code).json(error.obj); } const result = await AdminSetting.find({}); // Decrypt passwords for (let i = 0; i < result.length; i++) { const setting = result[i]; if (setting.password) { const bytes = CryptoJS.AES.decrypt(setting.value, process.env.SECRET); const originalText = bytes.toString(CryptoJS.enc.Utf8); result[i].value = originalText; } } response.json(result); }); // Edit admin settings settingsRouter.put('/admin', async (request, response) => { const body = request.body; const error = await getAndValidateForm(body.id, 'PUT', request); if (error) { return response.status(error.code).json(error.obj); } const setting = await AdminSetting.findById(body.mongoId); if (!setting) { logger.error( 'Could not find admin setting. Setting was not found (id: ' + body.mongoId + '). (+ body)', body ); return response.status(404).json({ msg: 'Setting was not found.', settingNotFoundError: true, }); } else if (body[setting.settingId] === null || body[setting.settingId] === undefined) { logger.error( "Could not find value with key '" + setting.settingId + "' in the payload for editing an admin setting. (+ body)", body ); return response.status(400).json({ msg: 'Bad request.', settingValueNotFoundError: true, }); } const edited = await createNewEditedArray(setting.edited, request.session._id); let value = body[setting.settingId]; if (setting.password && value !== '') { value = CryptoJS.AES.encrypt(value, process.env.SECRET).toString(); } const updatedAdminSetting = { value, edited, }; const savedSetting = await AdminSetting.findByIdAndUpdate(body.mongoId, updatedAdminSetting, { new: true, }); if (!savedSetting) { logger.error( 'Could not find admin setting after save. Setting was not found (id: ' + body.mongoId + '). (+ body)', body ); return response.status(404).json({ msg: 'Setting was not found.', settingNotFoundError: true, }); } logger.log(`Setting '${savedSetting.settingId}' was changed (admin setting).`); const publicSettings = await getPublicSettings(request); response.json(publicSettings); }); module.exports = settingsRouter;
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from os.path import join import ubelt as ub import torch # NOQA from torch.utils import data as torch_data # NOQA import numpy as np import netharn as nh import kwimage import scriptconfig as scfg from torch.nn import functional as F try: import imgaug.augmenters as iaa import imgaug except Exception: iaa = None imgaug = None class SegmentationConfig(scfg.Config): """ Default configuration for setting up a training session """ default = { 'name': scfg.Value('untitled', help='A human readable tag that is "nice" for humans'), 'workdir': scfg.Path('~/work/sseg', help='Dump all results in your workdir'), 'workers': scfg.Value(0, help='number of parallel dataloading jobs'), 'xpu': scfg.Value('argv', help='See netharn.XPU for details. can be cpu/gpu/cuda0/0,1,2,3)'), 'augmenter': scfg.Value('simple', help='type of training dataset augmentation'), 'class_weights': scfg.Value('log-median-idf', help='how to weight inbalanced classes'), # 'class_weights': scfg.Value(None, help='how to weight inbalanced classes'), 'datasets': scfg.Value('special:shapes256', help='Either a special key or a coco file'), 'train_dataset': scfg.Value(None), 'vali_dataset': scfg.Value(None), 'test_dataset': scfg.Value(None), 'arch': scfg.Value('psp', help='Network architecture code'), 'optim': scfg.Value('adam', help='Weight optimizer. Can be SGD, ADAM, ADAMW, etc..'), 'backend': scfg.Value('npy', help='fast lookup backnd. may be npy or cog'), 'input_dims': scfg.Value((224, 224), help='Window size to input to the network'), 'input_overlap': scfg.Value(0.25, help='amount of overlap when creating a sliding window dataset'), 'normalize_inputs': scfg.Value(True, help='if True, precompute training mean and std for data whitening'), 'channels': scfg.Value(None), 'batch_size': scfg.Value(4, help='number of items per batch'), 'bstep': scfg.Value(4, help='number of batches before a gradient descent step'), 'max_epoch': scfg.Value(140, help='Maximum number of epochs'), 'patience': scfg.Value(140, help='Maximum "bad" validation epochs before early stopping'), 'lr': scfg.Value(1e-4, help='Base learning rate'), 'decay': scfg.Value(1e-5, help='Base weight decay'), 'focus': scfg.Value(0.0, help='focus for focal loss'), 'schedule': scfg.Value('step90', help=('Special coercable netharn code. Eg: onecycle50, step50, gamma')), 'init': scfg.Value('kaiming_normal', help='How to initialized weights. (can be a path to a pretrained model)'), 'pretrained': scfg.Path(help=('alternative way to specify a path to a pretrained model')), } def normalize(self): if self['pretrained'] in ['null', 'None']: self['pretrained'] = None if self['pretrained'] is not None: self['init'] = 'pretrained' class SegmentationDataset(torch.utils.data.Dataset): """ Efficient loader for training on a sementic segmentation dataset Example: >>> # DISABLE_DOCTEST >>> #input_dims = (224, 224) >>> # xdoctest: +REQUIRES(module:ndsampler) >>> from netharn.examples.segmentation import * # NOQA >>> import ndsampler >>> sampler = ndsampler.CocoSampler.demo('shapes') >>> input_dims = (512, 512) >>> self = dset = SegmentationDataset(sampler, input_dims) >>> output = self[1] >>> # xdoctest: +REQUIRES(--show) >>> import kwplot >>> plt = kwplot.autoplt() >>> cidxs = output['class_idxs'] >>> colored_labels = self._colorized_labels(cidxs) >>> kwplot.figure(doclf=True) >>> kwplot.imshow(output['im']) >>> kwplot.imshow(colored_labels, alpha=.4) Example: >>> # xdoctest: +REQUIRES(--interact) >>> import xdev >>> import kwplot >>> plt = kwplot.autoplt() >>> indices = list(range(len(self))) >>> for index in xdev.InteractiveIter(indices): >>> output = self[index] >>> cidxs = output['class_idxs'] >>> colored_labels = self._colorized_labels(cidxs) >>> kwplot.figure(doclf=True) >>> kwplot.imshow(output['im']) >>> kwplot.imshow(colored_labels, alpha=.4) >>> xdev.InteractiveIter.draw() """ def __init__(self, sampler, input_dims=(224, 224), input_overlap=0.5, augmenter=False, channels=None): self.input_dims = None self.input_id = None self.cid_to_cidx = None self.classes = None self.sampler = None self.subindex = None self.gid_to_slider = None self._gids = None self._sliders = None if channels is not None: from kwcoco.channel_spec import FusedChannelSpec channels = FusedChannelSpec.coerce(channels) self.channels = channels self.sampler = sampler self.input_id = self.sampler.dset.hashid self.cid_to_cidx = sampler.catgraph.id_to_idx self.classes = sampler.catgraph # Create a slider for every image self._build_sliders(input_dims=input_dims, input_overlap=input_overlap) self.augmenter = self._rectify_augmenter(augmenter) def _rectify_augmenter(self, augmenter): import netharn as nh if augmenter is True: augmenter = 'simple' if not augmenter: augmenter = None else: if iaa is None: raise NotImplementedError( 'Augmentation requires imgaug, which is deprecated. ' 'Need to repackage part of it. ' 'Its the only good aug library') if augmenter == 'simple': augmenter = iaa.Sequential([ iaa.Crop(percent=(0, .2)), iaa.Fliplr(p=.5) ]) elif augmenter == 'complex': augmenter = iaa.Sequential([ iaa.Sometimes(0.2, nh.data.transforms.HSVShift(hue=0.1, sat=1.5, val=1.5)), iaa.Crop(percent=(0, .2)), iaa.Fliplr(p=.5) ]) else: raise KeyError('Unknown augmentation {!r}'.format(self.augment)) return augmenter def _build_sliders(self, input_dims=(224, 224), input_overlap=0.5): """ Use the ndsampler.Sampler and sliders to build a flat index that can reach every subregion of every image in the training set. """ import netharn as nh gid_to_slider = {} for img in self.sampler.dset.imgs.values(): full_dims = [img['height'], img['width']] slider = nh.util.SlidingWindow(full_dims, input_dims, overlap=input_overlap, allow_overshoot=True) gid_to_slider[img['id']] = slider self.input_dims = input_dims self.gid_to_slider = gid_to_slider self._gids = list(gid_to_slider.keys()) self._sliders = list(gid_to_slider.values()) self.subindex = nh.util.FlatIndexer.fromlist(self._sliders) return gid_to_slider def __len__(self): return len(self.subindex) def __getitem__(self, index): """ Example: >>> # DISABLE_DOCTEST >>> self = SegmentationDataset.demo(augmenter=True) >>> output = self[10] >>> # xdoctest: +REQUIRES(--show) >>> import kwplot >>> plt = kwplot.autoplt() >>> colored_labels = self._colorized_labels(output['class_idxs']) >>> kwplot.figure(doclf=True) >>> kwplot.imshow(output['im']) >>> kwplot.imshow(colored_labels, alpha=.4) """ outer, inner = self.subindex.unravel(index) gid = self._gids[outer] slider = self._sliders[outer] slices = slider[inner] tr = {'gid': gid, 'slices': slices} if self.channels is not None: tr['channels'] = self.channels sample = self.sampler.load_sample(tr, with_annots=['segmentation']) imdata = sample['im'] heatmap = self._sample_to_sseg_heatmap(sample) heatmap = heatmap.numpy() heatmap.data['class_idx'] = heatmap.data['class_idx'].astype(np.int32) cidx_segmap = heatmap.data['class_idx'] if self.augmenter: if imgaug is None: raise AssertionError('imgaug is not installed') augdet = self.augmenter.to_deterministic() imdata = augdet.augment_image(imdata) if hasattr(imgaug, 'SegmentationMapsOnImage'): # Oh imgaug, stop breaking. cidx_segmap_oi = imgaug.SegmentationMapsOnImage(cidx_segmap, cidx_segmap.shape) cidx_segmap_oi = augdet.augment_segmentation_maps(cidx_segmap_oi) assert cidx_segmap_oi.arr.shape[2] == 1 cidx_segmap = cidx_segmap_oi.arr[..., 0] cidx_segmap = np.ascontiguousarray(cidx_segmap) else: cidx_segmap_oi = imgaug.SegmentationMapOnImage(cidx_segmap, cidx_segmap.shape, nb_classes=len(self.classes)) cidx_segmap_oi = augdet.augment_segmentation_maps([cidx_segmap_oi])[0] cidx_segmap = cidx_segmap_oi.arr.argmax(axis=2) im_chw = torch.FloatTensor( imdata.transpose(2, 0, 1).astype(np.float32) / 255.) cidxs = torch.LongTensor(cidx_segmap) weight = (1 - (cidxs == 0).float()) output = { 'im': im_chw, 'class_idxs': cidxs, 'weight': weight, } return output def _sample_to_sseg_heatmap(self, sample): imdata = sample['im'] annots = sample['annots'] aids = annots['aids'] cids = annots['cids'] boxes = annots['rel_boxes'] # Clip boxes to the image boundary input_dims = imdata.shape[0:2] boxes = boxes.clip(0, 0, input_dims[1], input_dims[0]) class_idxs = np.array([self.cid_to_cidx[cid] for cid in cids]) segmentations = annots['rel_ssegs'] raw_dets = kwimage.Detections( aids=aids, boxes=boxes, class_idxs=class_idxs, segmentations=segmentations, classes=self.classes, datakeys=['aids'], ) keep = [] for i, s in enumerate(raw_dets.data['segmentations']): # TODO: clip polygons m = s.to_mask(input_dims) if m.area > 0: keep.append(i) dets = raw_dets.take(keep) heatmap = dets.rasterize( bg_size=(1, 1), input_dims=input_dims, soften=0, exclude=['diameter', 'class_probs', 'offset'] ) try: # TODO: THIS MAY NOT BE THE CORRECT TRANSFORM input_shape = (1, 3,) + input_dims output_dims = getattr(self, '_output_dims', None) if output_dims is None: output_shape = self.raw_model.output_shape_for(input_shape) output_dims = self.output_dims = output_shape[2:] sf = np.array(output_dims) / np.array(input_dims) heatmap = heatmap.scale(sf, output_dims=output_dims, interpolation='nearest') except Exception: pass return heatmap def _colorized_labels(self, cidxs): dset = self.sampler.dset cx_to_color = [ dset.name_to_cat.get(self.classes[cx], {}).get('color', None) for cx in range(len(self.cid_to_cidx)) ] if any(color is None for color in cx_to_color): defaults = kwimage.Color.distinct(len(cx_to_color)) for cx, color in enumerate(cx_to_color): if color is None: cx_to_color[cx] = defaults[cx] self.cx_to_color = np.array(cx_to_color) colorized = self.cx_to_color[cidxs] return colorized @classmethod def demo(cls, **kwargs): # from grab_camvid import grab_coco_camvid # dset = grab_coco_camvid() import ndsampler sampler = ndsampler.CocoSampler.demo( 'shapes', workdir=None, backend=None) self = cls(sampler, **kwargs) return self class SegmentationHarn(nh.FitHarn): """ Custom harness to address a basic semantic segmentation problem """ def after_initialize(harn, **kw): harn.draw_timer = ub.Timer().tic() # hack: for k, v in harn.datasets.items(): v.raw_model = harn.xpu.raw(harn.model) def prepare_batch(harn, raw_batch): """ Move a batch onto the XPU """ batch = harn.xpu.move(raw_batch) return batch def run_batch(harn, batch): """ How to compute a forward pass through the network and compute loss Example: >>> # xdoctest: +REQUIRES(--slow) >>> kw = {'workers': 0, 'xpu': 'cpu', 'batch_size': 2} >>> harn = setup_harn(cmdline=False, **kw).initialize() >>> batch = harn._demo_batch(tag='train') >>> outputs, loss_parts = harn.run_batch(batch) """ im = batch['im'] class_idxs = batch['class_idxs'] # You'll almost always have to do something custom to get the batch # into the network. Define that here. outputs = harn.model(im) if not isinstance(outputs, dict): outputs = { 'class_energy': outputs, } class_energy = outputs['class_energy'] class_probs = F.softmax(class_energy, dim=1) # Heirarchical softmax seems to have a memory leak # class_probs = harn.classes.hierarchical_softmax(class_energy, dim=1) outputs['class_probs'] = class_probs outputs['class_idxs'] = class_idxs # You'll almost always have to do something custom to compute loss. # Define that here. harn.criterion.reduction = 'none' pixel_loss = harn.criterion(class_energy, class_idxs) pixel_weight = batch['weight'] clf_loss = (pixel_weight * pixel_loss).sum() / pixel_weight.sum() # Return info for netharn to track loss_parts = {} loss_parts['clf'] = clf_loss return outputs, loss_parts def on_batch(harn, batch, outputs, loss): batch_metrics = {} with torch.no_grad(): # Track accuracy of each batch clf_true = outputs['class_idxs'].data.cpu().numpy().astype(np.uint8) clf_prob = outputs['class_probs'].data.cpu().numpy().astype(np.float32) clf_pred = clf_prob.argmax(axis=1) batch_metrics['clf_accuracy'] = (clf_pred == clf_true)[clf_true != 0].mean() # Draw first X batches or once every Y minutes do_draw = (harn.batch_index <= 8) do_draw |= (harn.draw_timer.toc() > 60 * 3) if do_draw: harn.draw_timer.tic() toshow = harn._draw_batch_preds(batch, outputs) dpath = ub.ensuredir((harn.train_dpath, 'monitor', harn.current_tag, 'batch')) fpath = join(dpath, 'batch{}_epoch{}.jpg'.format(harn.batch_index, harn.epoch)) kwimage.imwrite(fpath, toshow) return batch_metrics def _draw_batch_preds(harn, batch, outputs, lim=16): """ Example: >>> # xdoctest: +REQUIRES(--slow) >>> kw = {'workers': 0, 'xpu': 'cpu', 'batch_size': 8} >>> harn = setup_harn(cmdline=False, **kw).initialize() >>> batch = harn._demo_batch(tag='train') >>> outputs, loss_parts = harn.run_batch(batch) >>> toshow = harn._draw_batch_preds(batch, outputs) >>> # xdoctest: +REQUIRES(--show) >>> import kwplot >>> kwplot.autompl() >>> kwplot.imshow(toshow) """ import cv2 im = batch['im'].data.cpu().numpy() class_true = batch['class_idxs'].data.cpu().numpy() class_pred = outputs['class_probs'].data.cpu().numpy().argmax(axis=1) batch_imgs = [] for bx in range(min(len(class_true), lim)): orig_img = im[bx].transpose(1, 2, 0)[..., 0:3] out_size = class_pred[bx].shape[::-1] orig_img = cv2.resize(orig_img, tuple(map(int, out_size))) orig_img = kwimage.ensure_alpha_channel(orig_img) if orig_img.max() > 1: orig_img = kwimage.normalize_intensity(orig_img) pred_heatmap = kwimage.Heatmap( class_idx=class_pred[bx], classes=harn.classes ) true_heatmap = kwimage.Heatmap( class_idx=class_true[bx], classes=harn.classes ) # TODO: scale up to original image size pred_img = pred_heatmap.draw_on(orig_img, channel='idx', with_alpha=.5) true_img = true_heatmap.draw_on(orig_img, channel='idx', with_alpha=.5) true_img = kwimage.ensure_uint255(true_img) pred_img = kwimage.ensure_uint255(pred_img) true_img = kwimage.draw_text_on_image( true_img, 'true', org=(0, 0), valign='top', color='blue') pred_img = kwimage.draw_text_on_image( pred_img, 'pred', org=(0, 0), valign='top', color='blue') item_img = kwimage.stack_images([pred_img, true_img], axis=1) batch_imgs.append(item_img) toshow = kwimage.stack_images_grid(batch_imgs, chunksize=2, overlap=-32) return toshow def on_complete(harn): """ Ignore: >>> kw = {'workers': 0, 'xpu': 'auto', 'batch_size': 8} >>> harn = setup_harn(cmdline=False, **kw).initialize() >>> harn.datasets['test'] """ deployed = harn.raw_model out_dpath = ub.ensuredir((harn.train_dpath, 'monitor/test/')) # test_dset = harn.datasets['test'] # sampler = test_dset.sampler eval_config = { 'deployed': deployed, 'xpu': harn.xpu, 'out_dpath': out_dpath, 'do_draw': True, } print('todo: evalute eval_config = {!r}'.format(eval_config)) class SegmentationModel(nh.layers.Sequential): """ Dummy wrapper around the real model but with input norm """ def __init__(self, arch, classes, in_channels=3, input_stats=None): super(SegmentationModel, self).__init__() import ndsampler if input_stats is None: input_stats = {} input_norm = nh.layers.InputNorm(**input_stats) classes = ndsampler.CategoryTree.coerce(classes) self.classes = classes if arch == 'unet': # Note: UNet can get through 256x256 images at a rate of ~17Hz with # batch_size=8. This is pretty slow and can likely be improved by fixing # some of the weird padding / mirror stuff I have to do in unet to get # output_dims = input_dims. from netharn.models.unet import UNet model_ = (UNet, { 'classes': classes, 'in_channels': in_channels, }) elif arch == 'segnet': from netharn.models.segnet import Segnet model_ = (Segnet, { 'in_channels': in_channels, }) elif arch == 'psp': from netharn.models.psp import PSPNet_Resnet50_8s model_ = (PSPNet_Resnet50_8s, { 'classes': classes, 'in_channels': in_channels, }) elif arch == 'deeplab_v3': from netharn.models.deeplab_v3 import DeepLabV3 model_ = (DeepLabV3, { 'classes': classes, 'in_channels': in_channels, }) else: raise KeyError(arch) self.add_module('input_norm', input_norm) self.add_module('model', model_[0](**model_[1])) def _cached_class_frequency(dset, workers=0): import ubelt as ub import copy # Copy the dataset so we can muck with it dset_copy = copy.copy(dset) dset_copy._build_sliders(input_overlap=0) dset_copy.augmenter = None cfgstr = '_'.join([dset_copy.sampler.dset.hashid, 'v1']) cacher = ub.Cacher('class_freq', cfgstr=cfgstr) total_freq = cacher.tryload() if total_freq is None: total_freq = np.zeros(len(dset_copy.classes), dtype=np.int64) if True: loader = torch_data.DataLoader(dset_copy, batch_size=16, num_workers=workers, shuffle=False, pin_memory=True) prog = ub.ProgIter(loader, desc='computing (par) class freq') for batch in prog: class_idxs = batch['class_idxs'].data.numpy() item_freq = np.histogram(class_idxs, bins=len(dset_copy.classes))[0] total_freq += item_freq else: prog = ub.ProgIter(range(len(dset_copy)), desc='computing (ser) class freq') for index in prog: item = dset_copy[index] class_idxs = item['class_idxs'].data.numpy() item_freq = np.histogram(class_idxs, bins=len(dset_copy.classes))[0] total_freq += item_freq cacher.save(total_freq) return total_freq def _precompute_class_weights(dset, workers=0, mode='median-idf'): """ Example: >>> # xdoctest: +REQUIRES(--slow) >>> harn = setup_harn(0, workers=0, xpu='cpu').initialize() >>> dset = harn.datasets['train'] """ assert mode in ['median-idf', 'log-median-idf'] total_freq = _cached_class_frequency(dset, workers=workers) def logb(arr, base): if base == 'e': return np.log(arr) elif base == 2: return np.log2(arr) elif base == 10: return np.log10(arr) else: out = np.log(arr) out /= np.log(base) return out _min, _max = np.percentile(total_freq, [5, 95]) is_valid = (_min <= total_freq) & (total_freq <= _max) if np.any(is_valid): middle_value = np.median(total_freq[is_valid]) else: middle_value = np.median(total_freq) # variant of median-inverse-frequency nonzero_freq = total_freq[total_freq != 0] if len(nonzero_freq): total_freq[total_freq == 0] = nonzero_freq.min() / 2 if mode == 'median-idf': weights = (middle_value / total_freq) weights[~np.isfinite(weights)] = 1.0 elif mode == 'log-median-idf': weights = (middle_value / total_freq) weights[~np.isfinite(weights)] = 1.0 base = 2 base = np.exp(1) weights = logb(weights + (base - 1), base) weights = np.maximum(weights, .1) weights = np.minimum(weights, 10) else: raise KeyError('mode = {!r}'.format(mode)) weights = np.round(weights, 2) cname_to_weight = ub.dzip(dset.classes, weights) print('weights: ' + ub.repr2(cname_to_weight)) return weights def setup_harn(cmdline=True, **kw): """ CommandLine: xdoctest -m netharn.examples.segmentation setup_harn Example: >>> # xdoctest: +REQUIRES(--slow) >>> kw = {'workers': 0, 'xpu': 'cpu', 'batch_size': 2} >>> cmdline = False >>> # Just sets up the harness, does not do any heavy lifting >>> harn = setup_harn(cmdline=cmdline, **kw) >>> # >>> harn.initialize() >>> # >>> batch = harn._demo_batch(tag='train') >>> epoch_metrics = harn._demo_epoch(tag='vali', max_iter=2) """ import sys import ndsampler import kwarray # kwarray.seed_global(2108744082) config = SegmentationConfig(default=kw) config.load(cmdline=cmdline) nh.configure_hacks(config) # fix opencv bugs coco_datasets = nh.api.Datasets.coerce(config) print('coco_datasets = {}'.format(ub.repr2(coco_datasets))) for tag, dset in coco_datasets.items(): dset._build_hashid(hash_pixels=False) workdir = ub.ensuredir(ub.expandpath(config['workdir'])) samplers = { tag: ndsampler.CocoSampler(dset, workdir=workdir, backend=config['backend']) for tag, dset in coco_datasets.items() } for tag, sampler in ub.ProgIter(list(samplers.items()), desc='prepare frames'): try: sampler.frames.prepare(workers=config['workers']) except AttributeError: pass from kwcoco.channel_spec import FusedChannelSpec channels = FusedChannelSpec.coerce(config['channels']).normalize() torch_datasets = { tag: SegmentationDataset( sampler, config['input_dims'], channels=channels, input_overlap=((tag == 'train') and config['input_overlap']), augmenter=((tag == 'train') and config['augmenter']), ) for tag, sampler in samplers.items() } torch_loaders = { tag: torch_data.DataLoader(dset, batch_size=config['batch_size'], num_workers=config['workers'], shuffle=(tag == 'train'), drop_last=True, pin_memory=True) for tag, dset in torch_datasets.items() } if config['class_weights']: mode = config['class_weights'] dset = torch_datasets['train'] class_weights = _precompute_class_weights(dset, mode=mode, workers=config['workers']) class_weights = torch.FloatTensor(class_weights) # try: # class_weights[dset.classes.index('background')] = 0 # except Exception: # pass else: class_weights = None print('class_weights = {!r}'.format(class_weights)) if config['normalize_inputs']: stats_dset = torch_datasets['train'] stats_idxs = kwarray.shuffle(np.arange(len(stats_dset)), rng=0)[0:min(1000, len(stats_dset))] stats_subset = torch.utils.data.Subset(stats_dset, stats_idxs) cacher = ub.Cacher('dset_mean', cfgstr=stats_dset.input_id + 'v3') input_stats = cacher.tryload() if input_stats is None: loader = torch.utils.data.DataLoader( stats_subset, num_workers=config['workers'], shuffle=True, batch_size=config['batch_size']) running = nh.util.RunningStats() for batch in ub.ProgIter(loader, desc='estimate mean/std'): try: running.update(batch['im'].numpy()) except ValueError: # final batch broadcast error pass input_stats = { 'std': running.simple(axis=None)['mean'].round(3), 'mean': running.simple(axis=None)['std'].round(3), } cacher.save(input_stats) else: input_stats = {} print('input_stats = {!r}'.format(input_stats)) # TODO: infer numbr of channels model_ = (SegmentationModel, { 'arch': config['arch'], 'input_stats': input_stats, 'classes': torch_datasets['train'].classes.__json__(), 'in_channels': channels.numel(), }) initializer_ = nh.Initializer.coerce(config) # if config['init'] == 'cls': # initializer_ = model_[0]._initializer_cls() # Create hyperparameters hyper = nh.HyperParams( nice=config['name'], workdir=config['workdir'], xpu=nh.XPU.coerce(config['xpu']), datasets=torch_datasets, loaders=torch_loaders, model=model_, initializer=initializer_, scheduler=nh.Scheduler.coerce(config), optimizer=nh.Optimizer.coerce(config), dynamics=nh.Dynamics.coerce(config), criterion=(nh.criterions.FocalLoss, { 'focus': config['focus'], 'weight': class_weights, # 'reduction': 'none', }), monitor=(nh.Monitor, { 'minimize': ['loss'], 'patience': config['patience'], 'max_epoch': config['max_epoch'], 'smoothing': .6, }), other={ 'batch_size': config['batch_size'], }, extra={ 'argv': sys.argv, 'config': ub.repr2(config.asdict()), } ) # Create harness harn = SegmentationHarn(hyper=hyper) harn.classes = torch_datasets['train'].classes harn.preferences.update({ 'num_keep': 2, 'keyboard_debug': True, # 'export_modules': ['netharn'], }) harn.intervals.update({ 'vali': 1, 'test': 10, }) harn.script_config = config return harn def main(): harn = setup_harn() harn.run() if __name__ == '__main__': r""" CommandLine: conda install gdal # Use the kwcoco-coercable toydata dataset names python -m netharn.examples.segmentation \ --name=shapes_demo --datasets=shapes32 \ --workers=0 --xpu=cpu # Or write the toy data explicitly using the kwcoco CLI kwcoco toydata --key shapes1024 --dst toy_train.kwcoco.json kwcoco toydata --key shapes8 --dst toy_vali.kwcoco.json # Run on the explicit kwcoco files python -m netharn.examples.segmentation \ --name=shapes_segmentation_demo \ --train_dataset=./toy_train.kwcoco.json \ --vali_dataset=./toy_vali.kwcoco.json \ --input_overlap=0.9 \ --input_dims=256,256 \ --batch_size=8 \ --arch=deeplab_v3 \ --optim=RAdam \ --workers=14 --xpu=0 # Run on the explicit kwcoco files python -m netharn.examples.segmentation \ --name=shapes_segmentation_demo \ --train_dataset=./toy_train.kwcoco.json \ --vali_dataset=./toy_vali.kwcoco.json \ --workers=0 --xpu=cpu # You can use MS-COCO files to learn to segment your own data To # demonstrate grab the CamVid dataset (the following script also # transforms camvid into the MS-COCO format) python -m kwcoco.data.grab_camvid # Download MS-COCO files python -m netharn.examples.segmentation --workers=4 --xpu=cpu --name=camvid_deeplab \ --train_dataset=$HOME/.cache/kwcoco/camvid/camvid-master/camvid-train.mscoco.json \ --vali_dataset=$HOME/.cache/kwcoco/camvid/camvid-master/camvid-train.mscoco.json \ --schedule=step-90-120 --arch=deeplab_v3 --batch_size=8 --lr=1e-5 --input_dims=224,224 --optim=sgd --bstep=8 python -m netharn.examples.segmentation --workers=4 --xpu=0 --name=camvid_deeplab \ --train_dataset=$HOME/.cache/kwcoco/camvid/camvid-master/camvid-train.mscoco.json \ --vali_dataset=$HOME/.cache/kwcoco/camvid/camvid-master/camvid-train.mscoco.json \ --schedule=step-90-120 --arch=deeplab_v3 --batch_size=8 --lr=1e-5 --input_dims=224,224 --optim=sgd --bstep=8 python -m netharn.examples.segmentation --workers=4 --xpu=auto --name=camvid_psp_wip \ --train_dataset=$HOME/.cache/kwcoco/camvid/camvid-master/camvid-train.mscoco.json \ --vali_dataset=$HOME/.cache/kwcoco/camvid/camvid-master/camvid-train.mscoco.json \ --schedule=step-90-120 --arch=psp --batch_size=6 --lr=1e-3 --input_dims=512,512 --optim=sgd --bstep=1 # Note you would need to change the path to a pretrained network python -m netharn.examples.segmentation --workers=4 --xpu=auto --name=camvid_psp_wip_fine \ --train_dataset=$HOME/.cache/kwcoco/camvid/camvid-master/camvid-train.mscoco.json \ --vali_dataset=$HOME/.cache/kwcoco/camvid/camvid-master/camvid-train.mscoco.json \ --pretrained=$HOME/work/sseg/fit/runs/camvid_psp_wip/fowjplca/deploy_SegmentationModel_fowjplca_134_CZARGB.zip \ --schedule=step-90-120 --arch=psp --batch_size=6 --lr=1e-2 --input_dims=512,512 --optim=sgd --bstep=8 """ main()
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models class Canteen(models.Model): canteen_id = models.AutoField(primary_key=True, verbose_name='食堂编号') canteen_name = models.CharField(max_length=10, verbose_name='食堂名称') canteen_photo = models.ImageField(upload_to='images/canteen', null=True, blank=True, verbose_name='食堂照片') sanitation_level = models.CharField(max_length=1, choices=[("A", 'A'), ("B", 'B'), ("C", 'C')], verbose_name='卫生等级') canteen_active = models.CharField(max_length=10, choices=[("营业中", '营业中'), ("歇业中", '歇业中')], verbose_name='食堂状态') class Meta: ordering = ['canteen_id'] db_table = 'canteen' verbose_name = "食堂信息" verbose_name_plural = verbose_name def __str__(self): return self.canteen_name class Shop(models.Model): shop_id = models.AutoField(primary_key=True, verbose_name='窗口编号') canteen = models.ForeignKey(Canteen, models.CASCADE, verbose_name='食堂') manager = models.ForeignKey('ShopManager', models.SET_NULL, null=True, verbose_name='窗口经营者') shop_name = models.CharField(max_length=20, verbose_name='窗口名称') shop_detail = models.CharField(max_length=200, blank=True, null=True, verbose_name='窗口描述') shop_photo = models.ImageField(upload_to='images/shop', null=True, blank=True, verbose_name='窗口照片') shop_active = models.IntegerField(choices=[(1, '营业中'), (0, '歇业中')], verbose_name='窗口状态') class Meta: ordering = ['shop_id'] db_table = 'shop' verbose_name = "窗口信息" verbose_name_plural = verbose_name def __str__(self): return self.shop_name class ShopManager(models.Model): manager_id = models.AutoField(primary_key=True, verbose_name='经营者编号') manager_name = models.CharField(max_length=20, verbose_name='经营者昵称') manager_password = models.CharField(max_length=20, verbose_name='经营者密码') manager_tel = models.CharField(max_length=11, verbose_name="经营者电话") manager_status = models.IntegerField(choices=[(0, '离线'), (1, '在线')], default=0, verbose_name="经营者状态") manage_shop_num = models.IntegerField(verbose_name='经营窗口数') class Meta: ordering = ['manager_id'] db_table = 'shop_manager' verbose_name = "窗口经营者信息" verbose_name_plural = verbose_name def __str__(self): return self.manager_name
var path = require("path"); module.exports = { entry: "./src/index.js", output: { filename: "bundle.js", path: path.resolve(__dirname, "js") }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ } ] }, watch: true };
import { Subject } from "rxjs"; import { startWith, switchMap } from "rxjs/operators"; export function resettable(factory, ...args) { const resetter = new Subject(); const source = new Subject(); let destination = factory(...args); let subscription = source.subscribe(destination); return { reset(...args) { subscription.unsubscribe(); destination = factory(...args); subscription = source.subscribe(destination); resetter.next(); }, unsubscribe() { subscription.unsubscribe(); source.unsubscribe(); }, get closed() { return subscription.closed; }, get observable() { return resetter.asObservable().pipe(startWith(null), switchMap(() => destination)); }, get subject() { return source; }, }; } //# sourceMappingURL=resettable.js.map
#ifndef _PM_GENPROC_H_ #define _PM_GENPROC_H_ #define IS_Q_EMPTY(q) (q.head == q.tail) #define IS_SET(z) ( \ (bw==MAXITER_SHADE) ? ((z)==maxiter) : \ (bw==EVEN_SHADE) ? ((z)==maxiter || !((z)%2)) : (z)) #define ITER2COLOR( iter ) ( \ (bw) ? ((iter)==maxiter || !((iter)%2)) : \ ((iter)==maxiter) ? (MPE_BLACK) : ((iter) % (numColors-1) + 1) ) #define RECT_ASSIGN( rect, w, x, y, z ) { \ (rect).l = (w); (rect).r = (x); (rect).t = (y); (rect).b = (z); } #ifdef __STDC__ typedef int Fract_FN(NUM,NUM); #else typedef int Fract_FN(); #endif #endif /* _PM_GENPROC_H_ */
# -*- coding: utf-8 -*- """ This module provides methods for calling objective functions """ # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # Standard Library from inspect import getargspec # First Party from metaopt.core.call.util.exception import CallNotPossibleError from metaopt.core.returnspec.util.wrap_return_values import wrap_return_values def call(f, fargs, param_spec, return_spec=None): """Call a function using a list of args""" if fargs is None: fargs = [] extra_kwargs = param_spec.extra_kwargs or {} args, vargs, kwargs, _ = getargspec(f) if vargs is not None: raise CallNotPossibleError( "Functions with variable arguments are not supported.") if kwargs is not None: fkwargs = dict() for farg in fargs: fkwargs[farg.param.name] = farg.value fkwargs.update(extra_kwargs) return wrap_return_values(f(**fkwargs), return_spec) if vargs is None and kwargs is None: if len(args) == len(fargs) + len(extra_kwargs): return wrap_return_values( f(*[farg.value for farg in fargs], **extra_kwargs), return_spec ) else: raise CallNotPossibleError( "Function expects %s arguments but %s were given." % (len(args), len(fargs)))
export { default as Event } from './Event' export { default as EventBody } from './EventBody' export { default as EventEntry } from './EventEntry' export { default as EventTab } from './EventTab' export { default as EventImage } from './EventImage'
/* * ngene-cards.c: nGene PCIe bridge driver - card specific info * * Copyright (C) 2005-2007 Micronas * * Copyright (C) 2008-2009 Ralph Metzler <rjkm@metzlerbros.de> * Modifications for new nGene firmware, * support for EEPROM-copying, * support for new dual DVB-S2 card prototype * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 only, as published by the Free Software Foundation. * * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * To obtain the license, point your browser to * http://www.gnu.org/copyleft/gpl.html */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/init.h> #include <linux/pci.h> #include <linux/pci_ids.h> #include "ngene.h" /* demods/tuners */ #include "stv6110x.h" #include "stv090x.h" #include "lnbh24.h" #include "lgdt330x.h" #include "mt2131.h" #include "tda18271c2dd.h" #include "drxk.h" #include "drxd.h" #include "dvb-pll.h" #include "stv0367.h" #include "stv0367_priv.h" #include "tda18212.h" #include "cxd2841er.h" #include "stv0910.h" #include "stv6111.h" #include "lnbh25.h" /****************************************************************************/ /* I2C transfer functions used for demod/tuner probing***********************/ /****************************************************************************/ static int i2c_io(struct i2c_adapter *adapter, u8 adr, u8 *wbuf, u32 wlen, u8 *rbuf, u32 rlen) { struct i2c_msg msgs[2] = {{.addr = adr, .flags = 0, .buf = wbuf, .len = wlen }, {.addr = adr, .flags = I2C_M_RD, .buf = rbuf, .len = rlen } }; return (i2c_transfer(adapter, msgs, 2) == 2) ? 0 : -1; } static int i2c_write(struct i2c_adapter *adap, u8 adr, u8 *data, int len) { struct i2c_msg msg = {.addr = adr, .flags = 0, .buf = data, .len = len}; return (i2c_transfer(adap, &msg, 1) == 1) ? 0 : -1; } static int i2c_write_reg(struct i2c_adapter *adap, u8 adr, u8 reg, u8 val) { u8 msg[2] = {reg, val}; return i2c_write(adap, adr, msg, 2); } static int i2c_read(struct i2c_adapter *adapter, u8 adr, u8 *val) { struct i2c_msg msgs[1] = {{.addr = adr, .flags = I2C_M_RD, .buf = val, .len = 1 } }; return (i2c_transfer(adapter, msgs, 1) == 1) ? 0 : -1; } static int i2c_read_reg16(struct i2c_adapter *adapter, u8 adr, u16 reg, u8 *val) { u8 msg[2] = {reg >> 8, reg & 0xff}; struct i2c_msg msgs[2] = {{.addr = adr, .flags = 0, .buf = msg, .len = 2}, {.addr = adr, .flags = I2C_M_RD, .buf = val, .len = 1} }; return (i2c_transfer(adapter, msgs, 2) == 2) ? 0 : -1; } static int i2c_read_regs(struct i2c_adapter *adapter, u8 adr, u8 reg, u8 *val, u8 len) { struct i2c_msg msgs[2] = {{.addr = adr, .flags = 0, .buf = &reg, .len = 1}, {.addr = adr, .flags = I2C_M_RD, .buf = val, .len = len} }; return (i2c_transfer(adapter, msgs, 2) == 2) ? 0 : -1; } static int i2c_read_reg(struct i2c_adapter *adapter, u8 adr, u8 reg, u8 *val) { return i2c_read_regs(adapter, adr, reg, val, 1); } /****************************************************************************/ /* Demod/tuner attachment ***************************************************/ /****************************************************************************/ static struct i2c_adapter *i2c_adapter_from_chan(struct ngene_channel *chan) { /* tuner 1+2: i2c adapter #0, tuner 3+4: i2c adapter #1 */ if (chan->number < 2) return &chan->dev->channel[0].i2c_adapter; return &chan->dev->channel[1].i2c_adapter; } static int tuner_attach_stv6110(struct ngene_channel *chan) { struct device *pdev = &chan->dev->pci_dev->dev; struct i2c_adapter *i2c = i2c_adapter_from_chan(chan); struct stv090x_config *feconf = (struct stv090x_config *) chan->dev->card_info->fe_config[chan->number]; struct stv6110x_config *tunerconf = (struct stv6110x_config *) chan->dev->card_info->tuner_config[chan->number]; const struct stv6110x_devctl *ctl; if (chan->number < 2) i2c = &chan->dev->channel[0].i2c_adapter; else i2c = &chan->dev->channel[1].i2c_adapter; ctl = dvb_attach(stv6110x_attach, chan->fe, tunerconf, i2c); if (ctl == NULL) { dev_err(pdev, "No STV6110X found!\n"); return -ENODEV; } feconf->tuner_init = ctl->tuner_init; feconf->tuner_sleep = ctl->tuner_sleep; feconf->tuner_set_mode = ctl->tuner_set_mode; feconf->tuner_set_frequency = ctl->tuner_set_frequency; feconf->tuner_get_frequency = ctl->tuner_get_frequency; feconf->tuner_set_bandwidth = ctl->tuner_set_bandwidth; feconf->tuner_get_bandwidth = ctl->tuner_get_bandwidth; feconf->tuner_set_bbgain = ctl->tuner_set_bbgain; feconf->tuner_get_bbgain = ctl->tuner_get_bbgain; feconf->tuner_set_refclk = ctl->tuner_set_refclk; feconf->tuner_get_status = ctl->tuner_get_status; return 0; } static int tuner_attach_stv6111(struct ngene_channel *chan) { struct device *pdev = &chan->dev->pci_dev->dev; struct i2c_adapter *i2c = i2c_adapter_from_chan(chan); struct dvb_frontend *fe; u8 adr = 4 + ((chan->number & 1) ? 0x63 : 0x60); fe = dvb_attach(stv6111_attach, chan->fe, i2c, adr); if (!fe) { fe = dvb_attach(stv6111_attach, chan->fe, i2c, adr & ~4); if (!fe) { dev_err(pdev, "stv6111_attach() failed!\n"); return -ENODEV; } } return 0; } static int drxk_gate_ctrl(struct dvb_frontend *fe, int enable) { struct ngene_channel *chan = fe->sec_priv; int status; if (enable) { down(&chan->dev->pll_mutex); status = chan->gate_ctrl(fe, 1); } else { status = chan->gate_ctrl(fe, 0); up(&chan->dev->pll_mutex); } return status; } static int tuner_attach_tda18271(struct ngene_channel *chan) { struct device *pdev = &chan->dev->pci_dev->dev; struct i2c_adapter *i2c = i2c_adapter_from_chan(chan); struct dvb_frontend *fe; if (chan->fe->ops.i2c_gate_ctrl) chan->fe->ops.i2c_gate_ctrl(chan->fe, 1); fe = dvb_attach(tda18271c2dd_attach, chan->fe, i2c, 0x60); if (chan->fe->ops.i2c_gate_ctrl) chan->fe->ops.i2c_gate_ctrl(chan->fe, 0); if (!fe) { dev_err(pdev, "No TDA18271 found!\n"); return -ENODEV; } return 0; } static int tuner_tda18212_ping(struct ngene_channel *chan, struct i2c_adapter *i2c, unsigned short adr) { struct device *pdev = &chan->dev->pci_dev->dev; u8 tda_id[2]; u8 subaddr = 0x00; dev_dbg(pdev, "stv0367-tda18212 tuner ping\n"); if (chan->fe->ops.i2c_gate_ctrl) chan->fe->ops.i2c_gate_ctrl(chan->fe, 1); if (i2c_read_regs(i2c, adr, subaddr, tda_id, sizeof(tda_id)) < 0) dev_dbg(pdev, "tda18212 ping 1 fail\n"); if (i2c_read_regs(i2c, adr, subaddr, tda_id, sizeof(tda_id)) < 0) dev_warn(pdev, "tda18212 ping failed, expect problems\n"); if (chan->fe->ops.i2c_gate_ctrl) chan->fe->ops.i2c_gate_ctrl(chan->fe, 0); return 0; } static int tuner_attach_tda18212(struct ngene_channel *chan, u32 dmdtype) { struct device *pdev = &chan->dev->pci_dev->dev; struct i2c_adapter *i2c = i2c_adapter_from_chan(chan); struct i2c_client *client; struct tda18212_config config = { .fe = chan->fe, .if_dvbt_6 = 3550, .if_dvbt_7 = 3700, .if_dvbt_8 = 4150, .if_dvbt2_6 = 3250, .if_dvbt2_7 = 4000, .if_dvbt2_8 = 4000, .if_dvbc = 5000, }; u8 addr = (chan->number & 1) ? 0x63 : 0x60; /* * due to a hardware quirk with the I2C gate on the stv0367+tda18212 * combo, the tda18212 must be probed by reading it's id _twice_ when * cold started, or it very likely will fail. */ if (dmdtype == DEMOD_TYPE_STV0367) tuner_tda18212_ping(chan, i2c, addr); /* perform tuner probe/init/attach */ client = dvb_module_probe("tda18212", NULL, i2c, addr, &config); if (!client) goto err; chan->i2c_client[0] = client; chan->i2c_client_fe = 1; return 0; err: dev_err(pdev, "TDA18212 tuner not found. Device is not fully operational.\n"); return -ENODEV; } static int tuner_attach_probe(struct ngene_channel *chan) { switch (chan->demod_type) { case DEMOD_TYPE_STV090X: return tuner_attach_stv6110(chan); case DEMOD_TYPE_DRXK: return tuner_attach_tda18271(chan); case DEMOD_TYPE_STV0367: case DEMOD_TYPE_SONY_CT2: case DEMOD_TYPE_SONY_ISDBT: case DEMOD_TYPE_SONY_C2T2: case DEMOD_TYPE_SONY_C2T2I: return tuner_attach_tda18212(chan, chan->demod_type); case DEMOD_TYPE_STV0910: return tuner_attach_stv6111(chan); } return -EINVAL; } static int demod_attach_stv0900(struct ngene_channel *chan) { struct device *pdev = &chan->dev->pci_dev->dev; struct i2c_adapter *i2c = i2c_adapter_from_chan(chan); struct stv090x_config *feconf = (struct stv090x_config *) chan->dev->card_info->fe_config[chan->number]; /* tuner 1+2: i2c adapter #0, tuner 3+4: i2c adapter #1 */ /* Note: Both adapters share the same i2c bus, but the demod */ /* driver requires that each demod has its own i2c adapter */ if (chan->number < 2) i2c = &chan->dev->channel[0].i2c_adapter; else i2c = &chan->dev->channel[1].i2c_adapter; chan->fe = dvb_attach(stv090x_attach, feconf, i2c, (chan->number & 1) == 0 ? STV090x_DEMODULATOR_0 : STV090x_DEMODULATOR_1); if (chan->fe == NULL) { dev_err(pdev, "No STV0900 found!\n"); return -ENODEV; } /* store channel info */ if (feconf->tuner_i2c_lock) chan->fe->analog_demod_priv = chan; if (!dvb_attach(lnbh24_attach, chan->fe, i2c, 0, 0, chan->dev->card_info->lnb[chan->number])) { dev_err(pdev, "No LNBH24 found!\n"); dvb_frontend_detach(chan->fe); chan->fe = NULL; return -ENODEV; } return 0; } static struct stv0910_cfg stv0910_p = { .adr = 0x68, .parallel = 1, .rptlvl = 4, .clk = 30000000, }; static struct lnbh25_config lnbh25_cfg = { .i2c_address = 0x0c << 1, .data2_config = LNBH25_TEN }; static int demod_attach_stv0910(struct ngene_channel *chan, struct i2c_adapter *i2c) { struct device *pdev = &chan->dev->pci_dev->dev; struct stv0910_cfg cfg = stv0910_p; struct lnbh25_config lnbcfg = lnbh25_cfg; chan->fe = dvb_attach(stv0910_attach, i2c, &cfg, (chan->number & 1)); if (!chan->fe) { cfg.adr = 0x6c; chan->fe = dvb_attach(stv0910_attach, i2c, &cfg, (chan->number & 1)); } if (!chan->fe) { dev_err(pdev, "stv0910_attach() failed!\n"); return -ENODEV; } /* * attach lnbh25 - leftshift by one as the lnbh25 driver expects 8bit * i2c addresses */ lnbcfg.i2c_address = (((chan->number & 1) ? 0x0d : 0x0c) << 1); if (!dvb_attach(lnbh25_attach, chan->fe, &lnbcfg, i2c)) { lnbcfg.i2c_address = (((chan->number & 1) ? 0x09 : 0x08) << 1); if (!dvb_attach(lnbh25_attach, chan->fe, &lnbcfg, i2c)) { dev_err(pdev, "lnbh25_attach() failed!\n"); dvb_frontend_detach(chan->fe); chan->fe = NULL; return -ENODEV; } } return 0; } static struct stv0367_config ddb_stv0367_config[] = { { .demod_address = 0x1f, .xtal = 27000000, .if_khz = 0, .if_iq_mode = FE_TER_NORMAL_IF_TUNER, .ts_mode = STV0367_SERIAL_PUNCT_CLOCK, .clk_pol = STV0367_CLOCKPOLARITY_DEFAULT, }, { .demod_address = 0x1e, .xtal = 27000000, .if_khz = 0, .if_iq_mode = FE_TER_NORMAL_IF_TUNER, .ts_mode = STV0367_SERIAL_PUNCT_CLOCK, .clk_pol = STV0367_CLOCKPOLARITY_DEFAULT, }, }; static int demod_attach_stv0367(struct ngene_channel *chan, struct i2c_adapter *i2c) { struct device *pdev = &chan->dev->pci_dev->dev; chan->fe = dvb_attach(stv0367ddb_attach, &ddb_stv0367_config[(chan->number & 1)], i2c); if (!chan->fe) { dev_err(pdev, "stv0367ddb_attach() failed!\n"); return -ENODEV; } chan->fe->sec_priv = chan; chan->gate_ctrl = chan->fe->ops.i2c_gate_ctrl; chan->fe->ops.i2c_gate_ctrl = drxk_gate_ctrl; return 0; } static int demod_attach_cxd28xx(struct ngene_channel *chan, struct i2c_adapter *i2c, int osc24) { struct device *pdev = &chan->dev->pci_dev->dev; struct cxd2841er_config cfg; /* the cxd2841er driver expects 8bit/shifted I2C addresses */ cfg.i2c_addr = ((chan->number & 1) ? 0x6d : 0x6c) << 1; cfg.xtal = osc24 ? SONY_XTAL_24000 : SONY_XTAL_20500; cfg.flags = CXD2841ER_AUTO_IFHZ | CXD2841ER_EARLY_TUNE | CXD2841ER_NO_WAIT_LOCK | CXD2841ER_NO_AGCNEG | CXD2841ER_TSBITS | CXD2841ER_TS_SERIAL; /* attach frontend */ chan->fe = dvb_attach(cxd2841er_attach_t_c, &cfg, i2c); if (!chan->fe) { dev_err(pdev, "CXD28XX attach failed!\n"); return -ENODEV; } chan->fe->sec_priv = chan; chan->gate_ctrl = chan->fe->ops.i2c_gate_ctrl; chan->fe->ops.i2c_gate_ctrl = drxk_gate_ctrl; return 0; } static void cineS2_tuner_i2c_lock(struct dvb_frontend *fe, int lock) { struct ngene_channel *chan = fe->analog_demod_priv; if (lock) down(&chan->dev->pll_mutex); else up(&chan->dev->pll_mutex); } static int port_has_stv0900(struct i2c_adapter *i2c, int port) { u8 val; if (i2c_read_reg16(i2c, 0x68+port/2, 0xf100, &val) < 0) return 0; return 1; } static int port_has_drxk(struct i2c_adapter *i2c, int port) { u8 val; if (i2c_read(i2c, 0x29+port, &val) < 0) return 0; return 1; } static int port_has_stv0367(struct i2c_adapter *i2c) { u8 val; if (i2c_read_reg16(i2c, 0x1e, 0xf000, &val) < 0) return 0; if (val != 0x60) return 0; if (i2c_read_reg16(i2c, 0x1f, 0xf000, &val) < 0) return 0; if (val != 0x60) return 0; return 1; } int ngene_port_has_cxd2099(struct i2c_adapter *i2c, u8 *type) { u8 val; u8 probe[4] = { 0xe0, 0x00, 0x00, 0x00 }, data[4]; struct i2c_msg msgs[2] = {{ .addr = 0x40, .flags = 0, .buf = probe, .len = 4 }, { .addr = 0x40, .flags = I2C_M_RD, .buf = data, .len = 4 } }; val = i2c_transfer(i2c, msgs, 2); if (val != 2) return 0; if (data[0] == 0x02 && data[1] == 0x2b && data[3] == 0x43) *type = 2; else *type = 1; return 1; } static int demod_attach_drxk(struct ngene_channel *chan, struct i2c_adapter *i2c) { struct device *pdev = &chan->dev->pci_dev->dev; struct drxk_config config; memset(&config, 0, sizeof(config)); config.microcode_name = "drxk_a3.mc"; config.qam_demod_parameter_count = 4; config.adr = 0x29 + (chan->number ^ 2); chan->fe = dvb_attach(drxk_attach, &config, i2c); if (!chan->fe) { dev_err(pdev, "No DRXK found!\n"); return -ENODEV; } chan->fe->sec_priv = chan; chan->gate_ctrl = chan->fe->ops.i2c_gate_ctrl; chan->fe->ops.i2c_gate_ctrl = drxk_gate_ctrl; return 0; } /****************************************************************************/ /* XO2 related lists and functions ******************************************/ /****************************************************************************/ static char *xo2names[] = { "DUAL DVB-S2", "DUAL DVB-C/T/T2", "DUAL DVB-ISDBT", "DUAL DVB-C/C2/T/T2", "DUAL ATSC", "DUAL DVB-C/C2/T/T2/I", }; static int init_xo2(struct ngene_channel *chan, struct i2c_adapter *i2c) { struct device *pdev = &chan->dev->pci_dev->dev; u8 addr = 0x10; u8 val, data[2]; int res; res = i2c_read_regs(i2c, addr, 0x04, data, 2); if (res < 0) return res; if (data[0] != 0x01) { dev_info(pdev, "Invalid XO2 on channel %d\n", chan->number); return -1; } i2c_read_reg(i2c, addr, 0x08, &val); if (val != 0) { i2c_write_reg(i2c, addr, 0x08, 0x00); msleep(100); } /* Enable tuner power, disable pll, reset demods */ i2c_write_reg(i2c, addr, 0x08, 0x04); usleep_range(2000, 3000); /* Release demod resets */ i2c_write_reg(i2c, addr, 0x08, 0x07); /* * speed: 0=55,1=75,2=90,3=104 MBit/s * Note: The ngene hardware must be run at 75 MBit/s compared * to more modern ddbridge hardware which runs at 90 MBit/s, * else there will be issues with the data transport and non- * working secondary/slave demods/tuners. */ i2c_write_reg(i2c, addr, 0x09, 1); i2c_write_reg(i2c, addr, 0x0a, 0x01); i2c_write_reg(i2c, addr, 0x0b, 0x01); usleep_range(2000, 3000); /* Start XO2 PLL */ i2c_write_reg(i2c, addr, 0x08, 0x87); return 0; } static int port_has_xo2(struct i2c_adapter *i2c, u8 *type, u8 *id) { u8 probe[1] = { 0x00 }, data[4]; u8 addr = 0x10; *type = NGENE_XO2_TYPE_NONE; if (i2c_io(i2c, addr, probe, 1, data, 4)) return 0; if (data[0] == 'D' && data[1] == 'F') { *id = data[2]; *type = NGENE_XO2_TYPE_DUOFLEX; return 1; } if (data[0] == 'C' && data[1] == 'I') { *id = data[2]; *type = NGENE_XO2_TYPE_CI; return 1; } return 0; } /****************************************************************************/ /* Probing and port/channel handling ****************************************/ /****************************************************************************/ static int cineS2_probe(struct ngene_channel *chan) { struct device *pdev = &chan->dev->pci_dev->dev; struct i2c_adapter *i2c = i2c_adapter_from_chan(chan); struct stv090x_config *fe_conf; u8 buf[3]; u8 xo2_type, xo2_id, xo2_demodtype; u8 sony_osc24 = 0; struct i2c_msg i2c_msg = { .flags = 0, .buf = buf }; int rc; if (port_has_xo2(i2c, &xo2_type, &xo2_id)) { xo2_id >>= 2; dev_dbg(pdev, "XO2 on channel %d (type %d, id %d)\n", chan->number, xo2_type, xo2_id); switch (xo2_type) { case NGENE_XO2_TYPE_DUOFLEX: if (chan->number & 1) dev_dbg(pdev, "skipping XO2 init on odd channel %d", chan->number); else init_xo2(chan, i2c); xo2_demodtype = DEMOD_TYPE_XO2 + xo2_id; switch (xo2_demodtype) { case DEMOD_TYPE_SONY_CT2: case DEMOD_TYPE_SONY_ISDBT: case DEMOD_TYPE_SONY_C2T2: case DEMOD_TYPE_SONY_C2T2I: dev_info(pdev, "%s (XO2) on channel %d\n", xo2names[xo2_id], chan->number); chan->demod_type = xo2_demodtype; if (xo2_demodtype == DEMOD_TYPE_SONY_C2T2I) sony_osc24 = 1; demod_attach_cxd28xx(chan, i2c, sony_osc24); break; case DEMOD_TYPE_STV0910: dev_info(pdev, "%s (XO2) on channel %d\n", xo2names[xo2_id], chan->number); chan->demod_type = xo2_demodtype; demod_attach_stv0910(chan, i2c); break; default: dev_warn(pdev, "Unsupported XO2 module on channel %d\n", chan->number); return -ENODEV; } break; case NGENE_XO2_TYPE_CI: dev_info(pdev, "DuoFlex CI modules not supported\n"); return -ENODEV; default: dev_info(pdev, "Unsupported XO2 module type\n"); return -ENODEV; } } else if (port_has_stv0900(i2c, chan->number)) { chan->demod_type = DEMOD_TYPE_STV090X; fe_conf = chan->dev->card_info->fe_config[chan->number]; /* demod found, attach it */ rc = demod_attach_stv0900(chan); if (rc < 0 || chan->number < 2) return rc; /* demod #2: reprogram outputs DPN1 & DPN2 */ i2c_msg.addr = fe_conf->address; i2c_msg.len = 3; buf[0] = 0xf1; switch (chan->number) { case 2: buf[1] = 0x5c; buf[2] = 0xc2; break; case 3: buf[1] = 0x61; buf[2] = 0xcc; break; default: return -ENODEV; } rc = i2c_transfer(i2c, &i2c_msg, 1); if (rc != 1) { dev_err(pdev, "Could not setup DPNx\n"); return -EIO; } } else if (port_has_drxk(i2c, chan->number^2)) { chan->demod_type = DEMOD_TYPE_DRXK; demod_attach_drxk(chan, i2c); } else if (port_has_stv0367(i2c)) { chan->demod_type = DEMOD_TYPE_STV0367; dev_info(pdev, "STV0367 on channel %d\n", chan->number); demod_attach_stv0367(chan, i2c); } else { dev_info(pdev, "No demod found on chan %d\n", chan->number); return -ENODEV; } return 0; } static struct lgdt330x_config aver_m780 = { .demod_address = 0xb2 >> 1, .demod_chip = LGDT3303, .serial_mpeg = 0x00, /* PARALLEL */ .clock_polarity_flip = 1, }; static struct mt2131_config m780_tunerconfig = { 0xc0 >> 1 }; /* A single func to attach the demo and tuner, rather than * use two sep funcs like the current design mandates. */ static int demod_attach_lg330x(struct ngene_channel *chan) { struct device *pdev = &chan->dev->pci_dev->dev; chan->fe = dvb_attach(lgdt330x_attach, &aver_m780, &chan->i2c_adapter); if (chan->fe == NULL) { dev_err(pdev, "No LGDT330x found!\n"); return -ENODEV; } dvb_attach(mt2131_attach, chan->fe, &chan->i2c_adapter, &m780_tunerconfig, 0); return (chan->fe) ? 0 : -ENODEV; } static int demod_attach_drxd(struct ngene_channel *chan) { struct device *pdev = &chan->dev->pci_dev->dev; struct drxd_config *feconf; feconf = chan->dev->card_info->fe_config[chan->number]; chan->fe = dvb_attach(drxd_attach, feconf, chan, &chan->i2c_adapter, &chan->dev->pci_dev->dev); if (!chan->fe) { dev_err(pdev, "No DRXD found!\n"); return -ENODEV; } return 0; } static int tuner_attach_dtt7520x(struct ngene_channel *chan) { struct device *pdev = &chan->dev->pci_dev->dev; struct drxd_config *feconf; feconf = chan->dev->card_info->fe_config[chan->number]; if (!dvb_attach(dvb_pll_attach, chan->fe, feconf->pll_address, &chan->i2c_adapter, feconf->pll_type)) { dev_err(pdev, "No pll(%d) found!\n", feconf->pll_type); return -ENODEV; } return 0; } /****************************************************************************/ /* EEPROM TAGS **************************************************************/ /****************************************************************************/ #define MICNG_EE_START 0x0100 #define MICNG_EE_END 0x0FF0 #define MICNG_EETAG_END0 0x0000 #define MICNG_EETAG_END1 0xFFFF /* 0x0001 - 0x000F reserved for housekeeping */ /* 0xFFFF - 0xFFFE reserved for housekeeping */ /* Micronas assigned tags EEProm tags for hardware support */ #define MICNG_EETAG_DRXD1_OSCDEVIATION 0x1000 /* 2 Bytes data */ #define MICNG_EETAG_DRXD2_OSCDEVIATION 0x1001 /* 2 Bytes data */ #define MICNG_EETAG_MT2060_1_1STIF 0x1100 /* 2 Bytes data */ #define MICNG_EETAG_MT2060_2_1STIF 0x1101 /* 2 Bytes data */ /* Tag range for OEMs */ #define MICNG_EETAG_OEM_FIRST 0xC000 #define MICNG_EETAG_OEM_LAST 0xFFEF static int i2c_write_eeprom(struct i2c_adapter *adapter, u8 adr, u16 reg, u8 data) { struct device *pdev = adapter->dev.parent; u8 m[3] = {(reg >> 8), (reg & 0xff), data}; struct i2c_msg msg = {.addr = adr, .flags = 0, .buf = m, .len = sizeof(m)}; if (i2c_transfer(adapter, &msg, 1) != 1) { dev_err(pdev, "Error writing EEPROM!\n"); return -EIO; } return 0; } static int i2c_read_eeprom(struct i2c_adapter *adapter, u8 adr, u16 reg, u8 *data, int len) { struct device *pdev = adapter->dev.parent; u8 msg[2] = {(reg >> 8), (reg & 0xff)}; struct i2c_msg msgs[2] = {{.addr = adr, .flags = 0, .buf = msg, .len = 2 }, {.addr = adr, .flags = I2C_M_RD, .buf = data, .len = len} }; if (i2c_transfer(adapter, msgs, 2) != 2) { dev_err(pdev, "Error reading EEPROM\n"); return -EIO; } return 0; } static int ReadEEProm(struct i2c_adapter *adapter, u16 Tag, u32 MaxLen, u8 *data, u32 *pLength) { struct device *pdev = adapter->dev.parent; int status = 0; u16 Addr = MICNG_EE_START, Length, tag = 0; u8 EETag[3]; while (Addr + sizeof(u16) + 1 < MICNG_EE_END) { if (i2c_read_eeprom(adapter, 0x50, Addr, EETag, sizeof(EETag))) return -1; tag = (EETag[0] << 8) | EETag[1]; if (tag == MICNG_EETAG_END0 || tag == MICNG_EETAG_END1) return -1; if (tag == Tag) break; Addr += sizeof(u16) + 1 + EETag[2]; } if (Addr + sizeof(u16) + 1 + EETag[2] > MICNG_EE_END) { dev_err(pdev, "Reached EOEE @ Tag = %04x Length = %3d\n", tag, EETag[2]); return -1; } Length = EETag[2]; if (Length > MaxLen) Length = (u16) MaxLen; if (Length > 0) { Addr += sizeof(u16) + 1; status = i2c_read_eeprom(adapter, 0x50, Addr, data, Length); if (!status) { *pLength = EETag[2]; #if 0 if (Length < EETag[2]) status = STATUS_BUFFER_OVERFLOW; #endif } } return status; } static int WriteEEProm(struct i2c_adapter *adapter, u16 Tag, u32 Length, u8 *data) { struct device *pdev = adapter->dev.parent; int status = 0; u16 Addr = MICNG_EE_START; u8 EETag[3]; u16 tag = 0; int retry, i; while (Addr + sizeof(u16) + 1 < MICNG_EE_END) { if (i2c_read_eeprom(adapter, 0x50, Addr, EETag, sizeof(EETag))) return -1; tag = (EETag[0] << 8) | EETag[1]; if (tag == MICNG_EETAG_END0 || tag == MICNG_EETAG_END1) return -1; if (tag == Tag) break; Addr += sizeof(u16) + 1 + EETag[2]; } if (Addr + sizeof(u16) + 1 + EETag[2] > MICNG_EE_END) { dev_err(pdev, "Reached EOEE @ Tag = %04x Length = %3d\n", tag, EETag[2]); return -1; } if (Length > EETag[2]) return -EINVAL; /* Note: We write the data one byte at a time to avoid issues with page sizes. (which are different for each manufacture and eeprom size) */ Addr += sizeof(u16) + 1; for (i = 0; i < Length; i++, Addr++) { status = i2c_write_eeprom(adapter, 0x50, Addr, data[i]); if (status) break; /* Poll for finishing write cycle */ retry = 10; while (retry) { u8 Tmp; msleep(50); status = i2c_read_eeprom(adapter, 0x50, Addr, &Tmp, 1); if (status) break; if (Tmp != data[i]) dev_err(pdev, "eeprom write error\n"); retry -= 1; } if (status) { dev_err(pdev, "Timeout polling eeprom\n"); break; } } return status; } static int eeprom_read_ushort(struct i2c_adapter *adapter, u16 tag, u16 *data) { int stat; u8 buf[2]; u32 len = 0; stat = ReadEEProm(adapter, tag, 2, buf, &len); if (stat) return stat; if (len != 2) return -EINVAL; *data = (buf[0] << 8) | buf[1]; return 0; } static int eeprom_write_ushort(struct i2c_adapter *adapter, u16 tag, u16 data) { int stat; u8 buf[2]; buf[0] = data >> 8; buf[1] = data & 0xff; stat = WriteEEProm(adapter, tag, 2, buf); if (stat) return stat; return 0; } static s16 osc_deviation(void *priv, s16 deviation, int flag) { struct ngene_channel *chan = priv; struct device *pdev = &chan->dev->pci_dev->dev; struct i2c_adapter *adap = &chan->i2c_adapter; u16 data = 0; if (flag) { data = (u16) deviation; dev_info(pdev, "write deviation %d\n", deviation); eeprom_write_ushort(adap, 0x1000 + chan->number, data); } else { if (eeprom_read_ushort(adap, 0x1000 + chan->number, &data)) data = 0; dev_info(pdev, "read deviation %d\n", (s16)data); } return (s16) data; } /****************************************************************************/ /* Switch control (I2C gates, etc.) *****************************************/ /****************************************************************************/ static struct stv090x_config fe_cineS2 = { .device = STV0900, .demod_mode = STV090x_DUAL, .clk_mode = STV090x_CLK_EXT, .xtal = 27000000, .address = 0x68, .ts1_mode = STV090x_TSMODE_SERIAL_PUNCTURED, .ts2_mode = STV090x_TSMODE_SERIAL_PUNCTURED, .repeater_level = STV090x_RPTLEVEL_16, .adc1_range = STV090x_ADC_1Vpp, .adc2_range = STV090x_ADC_1Vpp, .diseqc_envelope_mode = true, .tuner_i2c_lock = cineS2_tuner_i2c_lock, }; static struct stv090x_config fe_cineS2_2 = { .device = STV0900, .demod_mode = STV090x_DUAL, .clk_mode = STV090x_CLK_EXT, .xtal = 27000000, .address = 0x69, .ts1_mode = STV090x_TSMODE_SERIAL_PUNCTURED, .ts2_mode = STV090x_TSMODE_SERIAL_PUNCTURED, .repeater_level = STV090x_RPTLEVEL_16, .adc1_range = STV090x_ADC_1Vpp, .adc2_range = STV090x_ADC_1Vpp, .diseqc_envelope_mode = true, .tuner_i2c_lock = cineS2_tuner_i2c_lock, }; static struct stv6110x_config tuner_cineS2_0 = { .addr = 0x60, .refclk = 27000000, .clk_div = 1, }; static struct stv6110x_config tuner_cineS2_1 = { .addr = 0x63, .refclk = 27000000, .clk_div = 1, }; static const struct ngene_info ngene_info_cineS2 = { .type = NGENE_SIDEWINDER, .name = "Linux4Media cineS2 DVB-S2 Twin Tuner", .io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN}, .demod_attach = {demod_attach_stv0900, demod_attach_stv0900}, .tuner_attach = {tuner_attach_stv6110, tuner_attach_stv6110}, .fe_config = {&fe_cineS2, &fe_cineS2}, .tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1}, .lnb = {0x0b, 0x08}, .tsf = {3, 3}, .fw_version = 18, .msi_supported = true, }; static const struct ngene_info ngene_info_satixS2 = { .type = NGENE_SIDEWINDER, .name = "Mystique SaTiX-S2 Dual", .io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN}, .demod_attach = {demod_attach_stv0900, demod_attach_stv0900}, .tuner_attach = {tuner_attach_stv6110, tuner_attach_stv6110}, .fe_config = {&fe_cineS2, &fe_cineS2}, .tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1}, .lnb = {0x0b, 0x08}, .tsf = {3, 3}, .fw_version = 18, .msi_supported = true, }; static const struct ngene_info ngene_info_satixS2v2 = { .type = NGENE_SIDEWINDER, .name = "Mystique SaTiX-S2 Dual (v2)", .io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN, NGENE_IO_TSIN, NGENE_IO_TSIN, NGENE_IO_TSOUT}, .demod_attach = {demod_attach_stv0900, demod_attach_stv0900, cineS2_probe, cineS2_probe}, .tuner_attach = {tuner_attach_stv6110, tuner_attach_stv6110, tuner_attach_probe, tuner_attach_probe}, .fe_config = {&fe_cineS2, &fe_cineS2, &fe_cineS2_2, &fe_cineS2_2}, .tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1, &tuner_cineS2_0, &tuner_cineS2_1}, .lnb = {0x0a, 0x08, 0x0b, 0x09}, .tsf = {3, 3}, .fw_version = 18, .msi_supported = true, }; static const struct ngene_info ngene_info_cineS2v5 = { .type = NGENE_SIDEWINDER, .name = "Linux4Media cineS2 DVB-S2 Twin Tuner (v5)", .io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN, NGENE_IO_TSIN, NGENE_IO_TSIN, NGENE_IO_TSOUT}, .demod_attach = {demod_attach_stv0900, demod_attach_stv0900, cineS2_probe, cineS2_probe}, .tuner_attach = {tuner_attach_stv6110, tuner_attach_stv6110, tuner_attach_probe, tuner_attach_probe}, .fe_config = {&fe_cineS2, &fe_cineS2, &fe_cineS2_2, &fe_cineS2_2}, .tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1, &tuner_cineS2_0, &tuner_cineS2_1}, .lnb = {0x0a, 0x08, 0x0b, 0x09}, .tsf = {3, 3}, .fw_version = 18, .msi_supported = true, }; static const struct ngene_info ngene_info_duoFlex = { .type = NGENE_SIDEWINDER, .name = "Digital Devices DuoFlex PCIe or miniPCIe", .io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN, NGENE_IO_TSIN, NGENE_IO_TSIN, NGENE_IO_TSOUT}, .demod_attach = {cineS2_probe, cineS2_probe, cineS2_probe, cineS2_probe}, .tuner_attach = {tuner_attach_probe, tuner_attach_probe, tuner_attach_probe, tuner_attach_probe}, .fe_config = {&fe_cineS2, &fe_cineS2, &fe_cineS2_2, &fe_cineS2_2}, .tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1, &tuner_cineS2_0, &tuner_cineS2_1}, .lnb = {0x0a, 0x08, 0x0b, 0x09}, .tsf = {3, 3}, .fw_version = 18, .msi_supported = true, }; static const struct ngene_info ngene_info_m780 = { .type = NGENE_APP, .name = "Aver M780 ATSC/QAM-B", /* Channel 0 is analog, which is currently unsupported */ .io_type = { NGENE_IO_NONE, NGENE_IO_TSIN }, .demod_attach = { NULL, demod_attach_lg330x }, /* Ensure these are NULL else the frame will call them (as funcs) */ .tuner_attach = { NULL, NULL, NULL, NULL }, .fe_config = { NULL, &aver_m780 }, .avf = { 0 }, /* A custom electrical interface config for the demod to bridge */ .tsf = { 4, 4 }, .fw_version = 15, }; static struct drxd_config fe_terratec_dvbt_0 = { .index = 0, .demod_address = 0x70, .demod_revision = 0xa2, .demoda_address = 0x00, .pll_address = 0x60, .pll_type = DVB_PLL_THOMSON_DTT7520X, .clock = 20000, .osc_deviation = osc_deviation, }; static struct drxd_config fe_terratec_dvbt_1 = { .index = 1, .demod_address = 0x71, .demod_revision = 0xa2, .demoda_address = 0x00, .pll_address = 0x60, .pll_type = DVB_PLL_THOMSON_DTT7520X, .clock = 20000, .osc_deviation = osc_deviation, }; static const struct ngene_info ngene_info_terratec = { .type = NGENE_TERRATEC, .name = "Terratec Integra/Cinergy2400i Dual DVB-T", .io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN}, .demod_attach = {demod_attach_drxd, demod_attach_drxd}, .tuner_attach = {tuner_attach_dtt7520x, tuner_attach_dtt7520x}, .fe_config = {&fe_terratec_dvbt_0, &fe_terratec_dvbt_1}, .i2c_access = 1, }; /****************************************************************************/ /****************************************************************************/ /* PCI Subsystem ID *********************************************************/ /****************************************************************************/ #define NGENE_ID(_subvend, _subdev, _driverdata) { \ .vendor = NGENE_VID, .device = NGENE_PID, \ .subvendor = _subvend, .subdevice = _subdev, \ .driver_data = (unsigned long) &_driverdata } /****************************************************************************/ static const struct pci_device_id ngene_id_tbl[] = { NGENE_ID(0x18c3, 0xab04, ngene_info_cineS2), NGENE_ID(0x18c3, 0xab05, ngene_info_cineS2v5), NGENE_ID(0x18c3, 0xabc3, ngene_info_cineS2), NGENE_ID(0x18c3, 0xabc4, ngene_info_cineS2), NGENE_ID(0x18c3, 0xdb01, ngene_info_satixS2), NGENE_ID(0x18c3, 0xdb02, ngene_info_satixS2v2), NGENE_ID(0x18c3, 0xdd00, ngene_info_cineS2v5), NGENE_ID(0x18c3, 0xdd10, ngene_info_duoFlex), NGENE_ID(0x18c3, 0xdd20, ngene_info_duoFlex), NGENE_ID(0x1461, 0x062e, ngene_info_m780), NGENE_ID(0x153b, 0x1167, ngene_info_terratec), {0} }; MODULE_DEVICE_TABLE(pci, ngene_id_tbl); /****************************************************************************/ /* Init/Exit ****************************************************************/ /****************************************************************************/ static pci_ers_result_t ngene_error_detected(struct pci_dev *dev, enum pci_channel_state state) { dev_err(&dev->dev, "PCI error\n"); if (state == pci_channel_io_perm_failure) return PCI_ERS_RESULT_DISCONNECT; if (state == pci_channel_io_frozen) return PCI_ERS_RESULT_NEED_RESET; return PCI_ERS_RESULT_CAN_RECOVER; } static pci_ers_result_t ngene_slot_reset(struct pci_dev *dev) { dev_info(&dev->dev, "slot reset\n"); return 0; } static void ngene_resume(struct pci_dev *dev) { dev_info(&dev->dev, "resume\n"); } static const struct pci_error_handlers ngene_errors = { .error_detected = ngene_error_detected, .slot_reset = ngene_slot_reset, .resume = ngene_resume, }; static struct pci_driver ngene_pci_driver = { .name = "ngene", .id_table = ngene_id_tbl, .probe = ngene_probe, .remove = ngene_remove, .err_handler = &ngene_errors, .shutdown = ngene_shutdown, }; static __init int module_init_ngene(void) { /* pr_*() since we don't have a device to use with dev_*() yet */ pr_info("nGene PCIE bridge driver, Copyright (C) 2005-2007 Micronas\n"); return pci_register_driver(&ngene_pci_driver); } static __exit void module_exit_ngene(void) { pci_unregister_driver(&ngene_pci_driver); } module_init(module_init_ngene); module_exit(module_exit_ngene); MODULE_DESCRIPTION("nGene"); MODULE_AUTHOR("Micronas, Ralph Metzler, Manfred Voelkel"); MODULE_LICENSE("GPL");
import json import os import pickle5 as pickle import shutil import signal import string import torch import ujson from functools import partial from hashlib import sha1 from random import choice from utils.logger import get_msg from utils.logger import print_msg from utils.node import PROP_DICT def data2tensor(batch, tensor_type='Long', gpu=False): if tensor_type == 'Long': batch = torch.LongTensor(batch) if gpu: batch = torch.cuda.LongTensor(batch) elif tensor_type == 'Byte': batch = torch.ByteTensor(batch) if gpu: batch = torch.cuda.ByteTensor(batch) elif tensor_type == 'Float': batch = torch.FloatTensor(batch) if gpu: batch = torch.cuda.FloatTensor(batch) return batch def get_node_type(node): return node['type'] def hash_frag(frag): return hash_val(stringify_frag(frag)) def hash_val(text): if type(text) is str: text = text.encode('utf-8') return sha1(text).hexdigest() def init_worker(): signal.signal(signal.SIGINT, signal.SIG_IGN) def is_node_list(node): return type(node) == list def is_single_node(node): return (type(node) == dict and 'type' in node) def kill_proc(proc): if proc.poll() is None: proc.kill() def list_dir(dir_path): return [os.path.join(dir_path, f) for f in os.listdir(dir_path)] def load_ast(ast_path): with open(ast_path, 'r') as f: try: ast = ujson.load(f) except Exception as e: dec = json.JSONDecoder() f.seek(0, 0) ast = f.read() ast = dec.decode(ast) js_name = os.path.basename(ast_path)[:-2] return js_name, ast def load_pickle(dpath): with open(dpath, 'rb') as f: data = pickle.load(f) return data def make_dir(dir_path): ans = 'y' if os.path.exists(dir_path): msg = 'Do you want to delete %s? (y/n): ' % (dir_path) msg = get_msg(msg, 'WARN') # ans = input(msg) # vscode jupyter mode does not allow for input, due to some unknown bug # print(msg + " (hardcoded to be 'y', otherwise it hangs due to some unknown vscode-jupyter bug)") ans = 'y' if ans == 'y': shutil.rmtree(dir_path) os.makedirs(dir_path) else: if ans != 'n': print_msg('Wrong Answer', 'ERROR') os._exit(1) else: os.makedirs(dir_path) return dir_path def make_tmp_dir(dir_path): dir_path = os.path.join(dir_path, random_string(10)) os.makedirs(dir_path) return dir_path def pool_map(pool, func, list, **args): try: func = partial(func, **args) return pool.map(func, list) except KeyboardInterrupt: print_msg('Terminating workers ...', 'INFO') pool.terminate() pool.join() print_msg('Killed processes', 'INFO') os.killpg(os.getpid(), signal.SIGKILL) def random_string(length): candidate = string.ascii_letters + string.digits rand_str = [choice(candidate) for i in range(length)] return ''.join(rand_str) def read(file_name, mode='rb', encoding=None): with open(file_name, mode, encoding=encoding) as f: return f.read() def store_pickle(dpath, data): with open(dpath, 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) def stringify_frag(node): str_val = '' if 'type' in node: node_type = get_node_type(node) prop_list = PROP_DICT[node_type] else: prop_list = sorted(node.keys()) for key in prop_list: if key not in node: continue child = node[key] # If it has a single child if type(child) == dict: str_val += '{' str_val += stringify_frag(child) str_val += '}' # If it has multiple children elif type(child) == list: str_val += '[' for _child in child: if _child is None: str_val += str(None) else: str_val += stringify_frag(_child) str_val += ']' # If it is a terminal else: str_val += str((key, node[key])) return str_val def trim_seed_name(seed_name): if '_aug.js' in seed_name: return seed_name.replace('_aug.js', '.js') else: return seed_name def write(file_name, content, mode='wb'): with open(file_name, mode) as f: f.write(content) def write_ast(ast_path, ast): ast = json.dumps(ast, indent=2) ast = str.encode(ast) write(ast_path, ast)
""" Univariate Polynomials over domains and fields AUTHORS: - William Stein: first version - Martin Albrecht: Added singular coercion. - David Harvey: split off polynomial_integer_dense_ntl.pyx (2007-09) - Robert Bradshaw: split off polynomial_modn_dense_ntl.pyx (2007-09) TESTS: We test coercion in a particularly complicated situation:: sage: W.<w>=QQ['w'] sage: WZ.<z>=W['z'] sage: m = matrix(WZ,2,2,[1,z,z,z^2]) sage: a = m.charpoly() sage: R.<x> = WZ[] sage: R(a) x^2 + (-z^2 - 1)*x """ # **************************************************************************** # Copyright (C) 2007 William Stein <wstein@gmail.com> # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** from sage.rings.polynomial.polynomial_element import Polynomial, Polynomial_generic_dense, Polynomial_generic_dense_inexact from sage.structure.element import IntegralDomainElement, EuclideanDomainElement from sage.rings.polynomial.polynomial_singular_interface import Polynomial_singular_repr from sage.libs.pari.all import pari_gen from sage.structure.richcmp import richcmp, richcmp_item, rich_to_bool, rich_to_bool_sgn from sage.structure.element import coerce_binop from sage.rings.infinity import infinity, Infinity from sage.rings.integer_ring import ZZ from sage.rings.integer import Integer from sage.structure.factorization import Factorization from sage.rings.padics.precision_error import PrecisionError class Polynomial_generic_sparse(Polynomial): """ A generic sparse polynomial. The ``Polynomial_generic_sparse`` class defines functionality for sparse polynomials over any base ring. A sparse polynomial is represented using a dictionary which maps each exponent to the corresponding coefficient. The coefficients must never be zero. EXAMPLES:: sage: R.<x> = PolynomialRing(PolynomialRing(QQ, 'y'), sparse=True) sage: f = x^3 - x + 17 sage: type(f) <class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_integral_domain_with_category.element_class'> sage: loads(f.dumps()) == f True A more extensive example:: sage: A.<T> = PolynomialRing(Integers(5),sparse=True) ; f = T^2+1 ; B = A.quo(f) sage: C.<s> = PolynomialRing(B) sage: C Univariate Polynomial Ring in s over Univariate Quotient Polynomial Ring in Tbar over Ring of integers modulo 5 with modulus T^2 + 1 sage: s + T s + Tbar sage: (s + T)**2 s^2 + 2*Tbar*s + 4 """ def __init__(self, parent, x=None, check=True, is_gen=False, construct=False): """ TESTS:: sage: PolynomialRing(RIF, 'z', sparse=True)([RIF(-1, 1), RIF(-1,1)]) 0.?*z + 0.? sage: PolynomialRing(CIF, 'z', sparse=True)([CIF(RIF(-1,1), RIF(-1,1)), RIF(-1,1)]) 0.?*z + 0.? + 0.?*I """ Polynomial.__init__(self, parent, is_gen=is_gen) if x is None: self.__coeffs = {} return R = parent.base_ring() if isinstance(x, Polynomial): if x.parent() == self.parent(): x = dict(x.dict()) elif x.parent() == R: x = {0:x} else: w = {} for n, c in x.dict().items(): w[n] = R(c) # The following line has been added in trac ticket #9944. # Apparently, the "else" case has never occured before. x = w elif isinstance(x, list): x = dict((i, c) for (i, c) in enumerate(x) if c) elif isinstance(x, pari_gen): y = {} for i in range(len(x)): y[i] = R(x[i]) x = y check = True elif not isinstance(x, dict): x = {0:x} # constant polynomials if check: self.__coeffs = {} for i, z in x.items(): self.__coeffs[i] = R(z) else: self.__coeffs = x if check: self.__normalize() def dict(self): """ Return a new copy of the dict of the underlying elements of ``self``. EXAMPLES:: sage: R.<w> = PolynomialRing(Integers(8), sparse=True) sage: f = 5 + w^1997 - w^10000; f 7*w^10000 + w^1997 + 5 sage: d = f.dict(); d {0: 5, 1997: 1, 10000: 7} sage: d[0] = 10 sage: f.dict() {0: 5, 1997: 1, 10000: 7} """ return dict(self.__coeffs) def coefficients(self, sparse=True): """ Return the coefficients of the monomials appearing in ``self``. EXAMPLES:: sage: R.<w> = PolynomialRing(Integers(8), sparse=True) sage: f = 5 + w^1997 - w^10000; f 7*w^10000 + w^1997 + 5 sage: f.coefficients() [5, 1, 7] TESTS: Check that all coefficients are in the base ring:: sage: S.<x> = PolynomialRing(QQ, sparse=True) sage: f = x^4 sage: all(c.parent() is QQ for c in f.coefficients(False)) True """ if sparse: return [self.__coeffs[e] for e in self.exponents()] else: zero = self.parent().base_ring().zero() return [self.__coeffs[i] if i in self.__coeffs else zero for i in range(self.degree() + 1)] def exponents(self): """ Return the exponents of the monomials appearing in ``self``. EXAMPLES:: sage: R.<w> = PolynomialRing(Integers(8), sparse=True) sage: f = 5 + w^1997 - w^10000; f 7*w^10000 + w^1997 + 5 sage: f.exponents() [0, 1997, 10000] """ return sorted(self.__coeffs) def valuation(self): """ Return the valuation of ``self``. EXAMPLES:: sage: R.<w> = PolynomialRing(GF(9,'a'), sparse=True) sage: f = w^1997 - w^10000 sage: f.valuation() 1997 sage: R(19).valuation() 0 sage: R(0).valuation() +Infinity """ if not self.__coeffs: return infinity return ZZ(min(self.__coeffs)) def _derivative(self, var=None): """ Return the formal derivative of this polynomial with respect to the given variable. If ``var`` is ``None`` or is the generator of this ring, the derivative is with respect to the generator. Otherwise, _derivative(var) is called recursively for each coefficient of this polynomial. .. SEEALSO:: :meth:`.derivative` EXAMPLES:: sage: R.<w> = PolynomialRing(ZZ, sparse=True) sage: f = R(range(9)); f 8*w^8 + 7*w^7 + 6*w^6 + 5*w^5 + 4*w^4 + 3*w^3 + 2*w^2 + w sage: f._derivative() 64*w^7 + 49*w^6 + 36*w^5 + 25*w^4 + 16*w^3 + 9*w^2 + 4*w + 1 sage: f._derivative(w) 64*w^7 + 49*w^6 + 36*w^5 + 25*w^4 + 16*w^3 + 9*w^2 + 4*w + 1 sage: R.<x> = PolynomialRing(ZZ) sage: S.<y> = PolynomialRing(R, sparse=True) sage: f = x^3*y^4 sage: f._derivative() 4*x^3*y^3 sage: f._derivative(y) 4*x^3*y^3 sage: f._derivative(x) 3*x^2*y^4 Check that :trac:`28187` is fixed:: sage: R = PolynomialRing(ZZ, 't', sparse=True) sage: t, u = var('t, u') sage: R.gen()._derivative(t) 1 sage: R.gen()._derivative(u) Traceback (most recent call last): ... ValueError: cannot differentiate with respect to u """ P = self.parent() if var is not None and var != P.gen(): try: # call _derivative() recursively on coefficients return P({n:self.__coeffs[n]._derivative(var) for n in self.__coeffs}) except AttributeError: raise ValueError('cannot differentiate with respect to {}'.format(var)) # compute formal derivative with respect to generator d = {} for n, c in self.__coeffs.items(): d[n-1] = n*c if -1 in d: del d[-1] return P(d) def integral(self, var=None): """ Return the integral of this polynomial. By default, the integration variable is the variable of the polynomial. Otherwise, the integration variable is the optional parameter ``var`` .. NOTE:: The integral is always chosen so that the constant term is 0. EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: (1 + 3*x^10 - 2*x^100).integral() -2/101*x^101 + 3/11*x^11 + x TESTS: Check that :trac:`18600` is fixed:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: (x^2^100).integral() 1/1267650600228229401496703205377*x^1267650600228229401496703205377 Check the correctness when the base ring is a polynomial ring:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: S.<t> = PolynomialRing(R, sparse=True) sage: (x*t+1).integral() 1/2*x*t^2 + t sage: (x*t+1).integral(x) 1/2*x^2*t + x Check the correctness when the base ring is not an integral domain:: sage: R.<x> = PolynomialRing(Zmod(4), sparse=True) sage: (x^4 + 2*x^2 + 3).integral() x^5 + 2*x^3 + 3*x sage: x.integral() Traceback (most recent call last): ... ZeroDivisionError: inverse of Mod(2, 4) does not exist """ R = self.parent() # TODO: # calling the coercion model bin_op is much more accurate than using the # true division (which is bypassed by polynomials). But it does not work # in all cases!! from sage.structure.element import coercion_model as cm import operator try: Q = cm.bin_op(R.one(), ZZ.one(), operator.truediv).parent() except TypeError: F = (R.base_ring().one()/ZZ.one()).parent() Q = R.change_ring(F) if var is not None and var != R.gen(): return Q({k:v.integral(var) for k,v in self.__coeffs.items()}, check=False) return Q({ k+1:v/(k+1) for k,v in self.__coeffs.items()}, check=False) def _dict_unsafe(self): """ Return unsafe access to the underlying dictionary of coefficients. ** DO NOT use this, unless you really really know what you are doing. ** EXAMPLES:: sage: R.<w> = PolynomialRing(ZZ, sparse=True) sage: f = w^15 - w*3; f w^15 - 3*w sage: d = f._dict_unsafe(); d {1: -3, 15: 1} sage: d[1] = 10; f w^15 + 10*w """ return self.__coeffs def _repr(self, name=None): r""" EXAMPLES:: sage: R.<w> = PolynomialRing(CDF, sparse=True) sage: f = CDF(1,2) + w^5 - CDF(pi)*w + CDF(e) sage: f._repr() # abs tol 1e-15 '1.0*w^5 - 3.141592653589793*w + 3.718281828459045 + 2.0*I' sage: f._repr(name='z') # abs tol 1e-15 '1.0*z^5 - 3.141592653589793*z + 3.718281828459045 + 2.0*I' TESTS:: sage: pol = RIF['x']([0, 0, (-1,1)]) sage: PolynomialRing(RIF, 'x', sparse=True)(pol) 0.?*x^2 AUTHOR: - David Harvey (2006-08-05), based on Polynomial._repr() - Francis Clarke (2008-09-08) improved for 'negative' coefficients """ s = " " m = self.degree() + 1 if name is None: name = self.parent().variable_name() atomic_repr = self.parent().base_ring()._repr_option('element_is_atomic') coeffs = sorted(self.__coeffs.items()) for (n, x) in reversed(coeffs): if x: if n != m-1: s += " + " x = y = repr(x) if y.find("-") == 0: y = y[1:] if not atomic_repr and n > 0 and (y.find("+") != -1 or y.find("-") != -1): x = "(%s)"%x if n > 1: var = "*%s^%s"%(name,n) elif n==1: var = "*%s"%name else: var = "" s += "%s%s"%(x,var) s = s.replace(" + -", " - ") s = s.replace(" 1*"," ") s = s.replace(" -1*", " -") if s==" ": return "0" return s[1:] def __normalize(self): x = self.__coeffs D = [n for n, z in x.items() if not z] for n in D: del x[n] def __getitem__(self,n): """ Return the `n`-th coefficient of this polynomial. Negative indexes are allowed and always return 0 (so you can view the polynomial as embedding Laurent series). EXAMPLES:: sage: R.<w> = PolynomialRing(RDF, sparse=True) sage: e = RDF(e) sage: f = sum(e^n*w^n for n in range(4)); f # abs tol 1.1e-14 20.085536923187664*w^3 + 7.3890560989306495*w^2 + 2.718281828459045*w + 1.0 sage: f[1] # abs tol 5e-16 2.718281828459045 sage: f[5] 0.0 sage: f[-1] 0.0 sage: R.<x> = PolynomialRing(RealField(19), sparse=True) sage: f = (2-3.5*x)^3; f -42.875*x^3 + 73.500*x^2 - 42.000*x + 8.0000 Using slices, we can truncate polynomials:: sage: f[:2] -42.000*x + 8.0000 Any other kind of slicing is deprecated or an error:: sage: f[1:3] doctest:...: DeprecationWarning: polynomial slicing with a start index is deprecated, use list() and slice the resulting list instead See http://trac.sagemath.org/18940 for details. 73.500*x^2 - 42.000*x sage: f[1:3:2] Traceback (most recent call last): ... NotImplementedError: polynomial slicing with a step is not defined sage: f["hello"] Traceback (most recent call last): ... TypeError: list indices must be integers, not str """ if isinstance(n, slice): d = self.degree() + 1 start, stop, step = n.start, n.stop, n.step if step is not None: raise NotImplementedError("polynomial slicing with a step is not defined") if start is None: start = 0 else: if start < 0: start = 0 from sage.misc.superseded import deprecation deprecation(18940, "polynomial slicing with a start index is deprecated, use list() and slice the resulting list instead") if stop is None or stop > d: stop = d x = self.__coeffs v = {k: x[k] for k in x.keys() if start <= k < stop} return self.parent()(v) try: n = n.__index__() except AttributeError: raise TypeError("list indices must be integers, not {0}".format(type(n).__name__)) try: return self.__coeffs[n] except KeyError: return self.base_ring().zero() def _unsafe_mutate(self, n, value): r""" Change the coefficient of `x^n` to value. ** NEVER USE THIS ** -- unless you really know what you are doing. EXAMPLES:: sage: R.<z> = PolynomialRing(CC, sparse=True) sage: f = z^2 + CC.0; f 1.00000000000000*z^2 + 1.00000000000000*I sage: f._unsafe_mutate(0, 10) sage: f 1.00000000000000*z^2 + 10.0000000000000 Much more nasty:: sage: z._unsafe_mutate(1, 0) sage: z 0 """ n = int(n) value = self.base_ring()(value) x = self.__coeffs if n < 0: raise IndexError("polynomial coefficient index must be nonnegative") if value == 0: if n in x: del x[n] else: x[n] = value def list(self, copy=True): """ Return a new copy of the list of the underlying elements of ``self``. EXAMPLES:: sage: R.<z> = PolynomialRing(Integers(100), sparse=True) sage: f = 13*z^5 + 15*z^2 + 17*z sage: f.list() [0, 17, 15, 0, 0, 13] """ zero = self.base_ring().zero() v = [zero] * (self.degree()+1) for n, x in self.__coeffs.items(): v[n] = x return v def degree(self, gen=None): """ Return the degree of this sparse polynomial. EXAMPLES:: sage: R.<z> = PolynomialRing(ZZ, sparse=True) sage: f = 13*z^50000 + 15*z^2 + 17*z sage: f.degree() 50000 """ if not self.__coeffs: return -1 return max(self.__coeffs) def _add_(self, right): r""" EXAMPLES:: sage: R.<x> = PolynomialRing(Integers(), sparse=True) sage: (x^100000 + 2*x^50000) + (4*x^75000 - 2*x^50000 + 3*x) x^100000 + 4*x^75000 + 3*x AUTHOR: - David Harvey (2006-08-05) """ output = dict(self.__coeffs) for (index, coeff) in right.__coeffs.items(): if index in output: output[index] += coeff else: output[index] = coeff output = self.parent()(output, check=False) output.__normalize() return output def _neg_(self): r""" EXAMPLES:: sage: R.<x> = PolynomialRing(Integers(), sparse=True) sage: a = x^10000000; a x^10000000 sage: -a -x^10000000 """ output = { } for (index, coeff) in self.__coeffs.items(): output[index] = -coeff output = self.parent()(output, check=False) return output def _mul_(self, right): r""" EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: (x^100000 - x^50000) * (x^100000 + x^50000) x^200000 - x^100000 sage: (x^100000 - x^50000) * R(0) 0 AUTHOR: - David Harvey (2006-08-05) """ output = {} for (index1, coeff1) in self.__coeffs.items(): for (index2, coeff2) in right.__coeffs.items(): product = coeff1 * coeff2 index = index1 + index2 if index in output: output[index] += product else: output[index] = product output = self.parent()(output, check=False) output.__normalize() return output def _rmul_(self, left): r""" EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: (x^100000 - x^50000) * (x^100000 + x^50000) x^200000 - x^100000 sage: 7 * (x^100000 - x^50000) # indirect doctest 7*x^100000 - 7*x^50000 AUTHOR: - Simon King (2011-03-31) """ output = {} for (index, coeff) in self.__coeffs.items(): output[index] = left * coeff output = self.parent()(output, check=False) output.__normalize() return output def _lmul_(self, right): r""" EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: (x^100000 - x^50000) * (x^100000 + x^50000) x^200000 - x^100000 sage: (x^100000 - x^50000) * 7 # indirect doctest 7*x^100000 - 7*x^50000 AUTHOR: - Simon King (2011-03-31) """ output = {} for (index, coeff) in self.__coeffs.items(): output[index] = coeff * right output = self.parent()(output, check=False) output.__normalize() return output def _richcmp_(self, other, op): """ Compare this polynomial with other. Polynomials are first compared by degree, then in dictionary order starting with the coefficient of largest degree. EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: 3*x^100 - 12 > 12*x + 5 True sage: 3*x^100 - 12 > 3*x^100 - x^50 + 5 True sage: 3*x^100 - 12 < 3*x^100 - x^50 + 5 False sage: x^100 + x^10 - 1 < x^100 + x^10 True sage: x^100 < x^100 - x^10 False TESTS:: sage: R.<x> = PolynomialRing(QQ, sparse=True) sage: 2*x^2^500 > x^2^500 True sage: Rd = PolynomialRing(ZZ, 'x', sparse=False) sage: Rs = PolynomialRing(ZZ, 'x', sparse=True) sage: for _ in range(100): ....: pd = Rd.random_element() ....: qd = Rd.random_element() ....: assert bool(pd < qd) == bool(Rs(pd) < Rs(qd)) """ d1 = self.degree() d2 = other.degree() # Special case constant polynomials if d1 <= 0 and d2 <= 0: return richcmp(self[0], other[0], op) # For different degrees, compare the degree if d1 != d2: return rich_to_bool_sgn(op, d1 - d2) degs = set(self.__coeffs) | set(other.__coeffs) for i in sorted(degs, reverse=True): x = self[i] y = other[i] res = richcmp_item(x, y, op) if res is not NotImplemented: return res return rich_to_bool(op, 0) def shift(self, n): r""" Returns this polynomial multiplied by the power `x^n`. If `n` is negative, terms below `x^n` will be discarded. Does not change this polynomial. EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: p = x^100000 + 2*x + 4 sage: type(p) <class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_integral_domain_with_category.element_class'> sage: p.shift(0) x^100000 + 2*x + 4 sage: p.shift(-1) x^99999 + 2 sage: p.shift(-100002) 0 sage: p.shift(2) x^100002 + 2*x^3 + 4*x^2 TESTS: Check that :trac:`18600` is fixed:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: p = x^2^100 - 5 sage: p.shift(10) x^1267650600228229401496703205386 - 5*x^10 sage: p.shift(-10) x^1267650600228229401496703205366 sage: p.shift(1.5) Traceback (most recent call last): ... TypeError: Attempt to coerce non-integral RealNumber to Integer AUTHOR: - David Harvey (2006-08-06) """ n = ZZ(n) if n == 0: return self if n > 0: output = {index+n: coeff for index, coeff in self.__coeffs.items()} return self.parent()(output, check=False) if n < 0: output = {index+n:coeff for index, coeff in self.__coeffs.items() if index + n >= 0} return self.parent()(output, check=False) @coerce_binop def quo_rem(self, other): """ Returns the quotient and remainder of the Euclidean division of ``self`` and ``other``. Raises ZerodivisionError if ``other`` is zero. Raises ArithmeticError if ``other`` has a nonunit leading coefficient. EXAMPLES:: sage: P.<x> = PolynomialRing(ZZ,sparse=True) sage: R.<y> = PolynomialRing(P,sparse=True) sage: f = R.random_element(10) sage: g = y^5+R.random_element(4) sage: q,r = f.quo_rem(g) sage: f == q*g + r and r.degree() < g.degree() True sage: g = x*y^5 sage: f.quo_rem(g) Traceback (most recent call last): ... ArithmeticError: Division non exact (consider coercing to polynomials over the fraction field) sage: g = 0 sage: f.quo_rem(g) Traceback (most recent call last): ... ZeroDivisionError: Division by zero polynomial TESTS:: sage: P.<x> = PolynomialRing(ZZ,sparse=True) sage: f = x^10-4*x^6-5 sage: g = 17*x^22+x^15-3*x^5+1 sage: q,r = g.quo_rem(f) sage: g == f*q + r and r.degree() < f.degree() True sage: zero = P(0) sage: zero.quo_rem(f) (0, 0) sage: Q.<y> = IntegerModRing(14)[] sage: f = y^10-4*y^6-5 sage: g = 17*y^22+y^15-3*y^5+1 sage: q,r = g.quo_rem(f) sage: g == f*q + r and r.degree() < f.degree() True sage: f += 2*y^10 # 3 is invertible mod 14 sage: q,r = g.quo_rem(f) sage: g == f*q + r and r.degree() < f.degree() True The following shows that :trac:`16649` is indeed fixed. :: sage: P.<x> = PolynomialRing(ZZ, sparse=True) sage: (4*x).quo_rem(2*x) (2, 0) AUTHORS: - Bruno Grenet (2014-07-09) """ if other.is_zero(): raise ZeroDivisionError("Division by zero polynomial") if self.is_zero(): return self, self R = self.parent() d = other.degree() if self.degree() < d: return R.zero(), self quo = R.zero() rem = self while rem.degree() >= d: try: c = R(rem.leading_coefficient() * ~other.leading_coefficient()) except TypeError: raise ArithmeticError("Division non exact (consider coercing to polynomials over the fraction field)") e = rem.degree() - d quo += c*R.one().shift(e) # we know that the leading coefficient of rem vanishes # thus we avoid doing a useless computation rem = rem[:rem.degree()] - c*other[:d].shift(e) return (quo,rem) @coerce_binop def gcd(self,other,algorithm=None): """ Return the gcd of this polynomial and ``other`` INPUT: - ``other`` -- a polynomial defined over the same ring as this polynomial. ALGORITHM: Two algorithms are provided: - ``generic``: Uses the generic implementation, which depends on the base ring being a UFD or a field. - ``dense``: The polynomials are converted to the dense representation, their gcd is computed and is converted back to the sparse representation. Default is ``dense`` for polynomials over ZZ and ``generic`` in the other cases. EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ,sparse=True) sage: p = x^6 + 7*x^5 + 8*x^4 + 6*x^3 + 2*x^2 + x + 2 sage: q = 2*x^4 - x^3 - 2*x^2 - 4*x - 1 sage: gcd(p,q) x^2 + x + 1 sage: gcd(p, q, algorithm = "dense") x^2 + x + 1 sage: gcd(p, q, algorithm = "generic") x^2 + x + 1 sage: gcd(p, q, algorithm = "foobar") Traceback (most recent call last): ... ValueError: Unknown algorithm 'foobar' TESTS: Check that :trac:`19676` is fixed:: sage: S.<y> = R[] sage: x.gcd(y) 1 sage: (6*x).gcd(9) 3 """ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing if algorithm is None: if self.base_ring() == ZZ: algorithm = "dense" else: algorithm = "generic" if algorithm=="dense": S = self.parent() # FLINT is faster but a bug makes the conversion extremely slow, # so NTL is used in those cases where the conversion is too slow. Cf # <https://groups.google.com/d/msg/sage-devel/6qhW90dgd1k/Hoq3N7fWe4QJ> sd = self.degree() od = other.degree() if max(sd,od)<100 or \ min(len(self.__coeffs)/sd, len(other.__coeffs)/od)>.06: implementation="FLINT" else: implementation="NTL" D = PolynomialRing(S.base_ring(),'x',implementation=implementation) g = D(self).gcd(D(other)) return S(g) elif algorithm=="generic": return Polynomial.gcd(self,other) else: raise ValueError("Unknown algorithm '%s'" % algorithm) def reverse(self, degree=None): """ Return this polynomial but with the coefficients reversed. If an optional degree argument is given the coefficient list will be truncated or zero padded as necessary and the reverse polynomial will have the specified degree. EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: p = x^4 + 2*x^2^100 sage: p.reverse() x^1267650600228229401496703205372 + 2 sage: p.reverse(10) x^6 """ if degree is None: degree = self.degree() if not isinstance(degree, (int,Integer)): raise ValueError("degree argument must be a nonnegative integer, got %s"%degree) d = {degree-k: v for k,v in self.__coeffs.items() if degree >= k} return self.parent()(d, check=False) def truncate(self, n): """ Return the polynomial of degree `< n` equal to `self` modulo `x^n`. EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ, sparse=True) sage: (x^11 + x^10 + 1).truncate(11) x^10 + 1 sage: (x^2^500 + x^2^100 + 1).truncate(2^101) x^1267650600228229401496703205376 + 1 """ return self[:n] def number_of_terms(self): """ Return the number of nonzero terms. EXAMPLES:: sage: R.<x> = PolynomialRing(ZZ,sparse=True) sage: p = x^100 - 3*x^10 + 12 sage: p.number_of_terms() 3 """ return len(self.__coeffs) class Polynomial_generic_domain(Polynomial, IntegralDomainElement): def __init__(self, parent, is_gen=False, construct=False): Polynomial.__init__(self, parent, is_gen=is_gen) def is_unit(self): r""" Return ``True`` if this polynomial is a unit. *EXERCISE* (Atiyah-McDonald, Ch 1): Let `A[x]` be a polynomial ring in one variable. Then `f=\sum a_i x^i \in A[x]` is a unit if and only if `a_0` is a unit and `a_1,\ldots, a_n` are nilpotent. EXAMPLES:: sage: R.<z> = PolynomialRing(ZZ, sparse=True) sage: (2 + z^3).is_unit() False sage: f = -1 + 3*z^3; f 3*z^3 - 1 sage: f.is_unit() False sage: R(-3).is_unit() False sage: R(-1).is_unit() True sage: R(0).is_unit() False """ if self.degree() > 0: return False return self[0].is_unit() class Polynomial_generic_field(Polynomial_singular_repr, Polynomial_generic_domain, EuclideanDomainElement): @coerce_binop def quo_rem(self, other): """ Returns a tuple (quotient, remainder) where self = quotient * other + remainder. EXAMPLES:: sage: R.<y> = PolynomialRing(QQ) sage: K.<t> = NumberField(y^2 - 2) sage: P.<x> = PolynomialRing(K) sage: x.quo_rem(K(1)) (x, 0) sage: x.xgcd(K(1)) (1, 0, 1) """ P = self.parent() if other.is_zero(): raise ZeroDivisionError("other must be nonzero") # This is algorithm 3.1.1 in Cohen GTM 138 A = self B = other R = A Q = P.zero() while R.degree() >= B.degree(): aaa = R.leading_coefficient()/B.leading_coefficient() diff_deg=R.degree()-B.degree() Q += P(aaa).shift(diff_deg) # We know that S*B exactly cancels the leading coefficient of R. # Thus, we skip the computation of this leading coefficient. # For most exact fields, this doesn't matter much; but for # inexact fields, the leading coefficient might not end up # exactly equal to zero; and for AA/QQbar, verifying that # the coefficient is exactly zero triggers exact computation. R = R[:R.degree()] - (aaa*B[:B.degree()]).shift(diff_deg) return (Q, R) class Polynomial_generic_sparse_field(Polynomial_generic_sparse, Polynomial_generic_field): """ EXAMPLES:: sage: R.<x> = PolynomialRing(Frac(RR['t']), sparse=True) sage: f = x^3 - x + 17 sage: type(f) <class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_field_with_category.element_class'> sage: loads(f.dumps()) == f True """ def __init__(self, parent, x=None, check=True, is_gen = False, construct=False): Polynomial_generic_sparse.__init__(self, parent, x, check, is_gen) class Polynomial_generic_dense_field(Polynomial_generic_dense, Polynomial_generic_field): def __init__(self, parent, x=None, check=True, is_gen = False, construct=False): Polynomial_generic_dense.__init__(self, parent, x, check, is_gen) ########################################## # Over discrete valuation rings and fields ########################################## class Polynomial_generic_cdv(Polynomial_generic_domain): """ A generic class for polynomials over complete discrete valuation domains and fields. AUTHOR: - Xavier Caruso (2013-03) """ def newton_slopes(self, repetition=True): """ Returns a list of the Newton slopes of this polynomial. These are the valuations of the roots of this polynomial. If ``repetition`` is ``True``, each slope is repeated a number of times equal to its multiplicity. Otherwise it appears only one time. EXAMPLES:: sage: K = Qp(5) sage: R.<t> = K[] sage: f = 5 + 3*t + t^4 + 25*t^10 sage: f.newton_polygon() Finite Newton polygon with 4 vertices: (0, 1), (1, 0), (4, 0), (10, 2) sage: f.newton_slopes() [1, 0, 0, 0, -1/3, -1/3, -1/3, -1/3, -1/3, -1/3] sage: f.newton_slopes(repetition=False) [1, 0, -1/3] AUTHOR: - Xavier Caruso (2013-03-20) """ polygon = self.newton_polygon() return [-s for s in polygon.slopes(repetition=repetition)] def newton_polygon(self): r""" Returns a list of vertices of the Newton polygon of this polynomial. .. NOTE:: If some coefficients have not enough precision an error is raised. EXAMPLES:: sage: K = Qp(5) sage: R.<t> = K[] sage: f = 5 + 3*t + t^4 + 25*t^10 sage: f.newton_polygon() Finite Newton polygon with 4 vertices: (0, 1), (1, 0), (4, 0), (10, 2) sage: g = f + K(0,0)*t^4; g (5^2 + O(5^22))*t^10 + O(5^0)*t^4 + (3 + O(5^20))*t + 5 + O(5^21) sage: g.newton_polygon() Traceback (most recent call last): ... PrecisionError: The coefficient of t^4 has not enough precision TESTS: Check that :trac:`22936` is fixed:: sage: S.<x> = PowerSeriesRing(GF(5)) sage: R.<y> = S[] sage: p = x^2+y+x*y^2 sage: p.newton_polygon() Finite Newton polygon with 3 vertices: (0, 2), (1, 0), (2, 1) AUTHOR: - Xavier Caruso (2013-03-20) """ d = self.degree() from sage.geometry.newton_polygon import NewtonPolygon polygon = NewtonPolygon([(x, self[x].valuation()) for x in range(d+1)]) polygon_prec = NewtonPolygon([ (x, self[x].precision_absolute()) for x in range(d+1) ]) vertices = polygon.vertices(copy=False) vertices_prec = polygon_prec.vertices(copy=False) if len(vertices_prec) > 0: if vertices[0][0] > vertices_prec[0][0]: raise PrecisionError("first term with non-infinite valuation must have determined valuation") elif vertices[-1][0] < vertices_prec[-1][0]: raise PrecisionError("last term with non-infinite valuation must have determined valuation") else: for (x, y) in vertices: if polygon_prec(x) <= y: raise PrecisionError("The coefficient of %s^%s has not enough precision" % (self.parent().variable_name(), x)) return polygon def hensel_lift(self, a): """ Lift `a` to a root of this polynomial (using Newton iteration). If `a` is not close enough to a root (so that Newton iteration does not converge), an error is raised. EXAMPLES:: sage: K = Qp(5, 10) sage: P.<x> = PolynomialRing(K) sage: f = x^2 + 1 sage: root = f.hensel_lift(2); root 2 + 5 + 2*5^2 + 5^3 + 3*5^4 + 4*5^5 + 2*5^6 + 3*5^7 + 3*5^9 + O(5^10) sage: f(root) O(5^10) sage: g = (x^2 + 1)*(x - 7) sage: g.hensel_lift(2) # here, 2 is a multiple root modulo p Traceback (most recent call last): ... ValueError: a is not close enough to a root of this polynomial AUTHOR: - Xavier Caruso (2013-03-23) """ selfa = self(a) der = self.derivative() dera = der(a) if selfa.valuation() <= 2 * dera.valuation(): raise ValueError("a is not close enough to a root of this polynomial") # Newton iteration # Todo: compute everything up to the adequate precision at each step b = ~dera while(True): na = a - selfa * b if na == a: return a a = na selfa = self(a) dera = der(a) b *= 2 - dera*b def _factor_of_degree(self, deg): """ Return a factor of ``self`` of degree ``deg``. Algorithm is Newton iteration. This fails if ``deg`` is not a breakpoint in the Newton polygon of ``self``. Only for internal use! EXAMPLES:: sage: K = Qp(5) sage: R.<x> = K[] sage: K = Qp(5) sage: R.<t> = K[] sage: f = 5 + 3*t + t^4 + 25*t^10 sage: g = f._factor_of_degree(4) sage: (f % g).is_zero() True sage: g = f._factor_of_degree(3) # not tested Traceback (most recent call last) ... KeyboardInterrupt: TESTS:: sage: S.<x> = PowerSeriesRing(GF(5)) sage: R.<y> = S[] sage: p = x^2+y+x*y^2 sage: p._factor_of_degree(1) (1 + O(x^20))*y + x^2 + x^5 + 2*x^8 + 4*x^14 + 2*x^17 + 2*x^20 + O(x^22) AUTHOR: - Xavier Caruso (2013-03-20) .. TODO:: Precision is not optimal, and can be improved. """ coeffs = self.list() a = coeffs[:deg+1] # The leading coefficient need to be known at finite precision # in order to ensure that the while loop below terminates if a[deg].precision_absolute() is Infinity: a[deg] = a[deg].add_bigoh(self.base_ring().default_prec()) parent = self.parent() a = parent(a) v = parent.one() x = self % a while not x.is_zero(): a += (v * x) % a b, x = self.quo_rem(a) b %= a v = (v * (2 - b * v)) % a return a def factor_of_slope(self, slope=None): """ INPUT: - slope -- a rational number (default: the first slope in the Newton polygon of ``self``) OUTPUT: The factor of ``self`` corresponding to the slope ``slope`` (i.e. the unique monic divisor of ``self`` whose slope is ``slope`` and degree is the length of ``slope`` in the Newton polygon). EXAMPLES:: sage: K = Qp(5) sage: R.<x> = K[] sage: K = Qp(5) sage: R.<t> = K[] sage: f = 5 + 3*t + t^4 + 25*t^10 sage: f.newton_slopes() [1, 0, 0, 0, -1/3, -1/3, -1/3, -1/3, -1/3, -1/3] sage: g = f.factor_of_slope(0) sage: g.newton_slopes() [0, 0, 0] sage: (f % g).is_zero() True sage: h = f.factor_of_slope() sage: h.newton_slopes() [1] sage: (f % h).is_zero() True If ``slope`` is not a slope of ``self``, the corresponding factor is `1`:: sage: f.factor_of_slope(-1) 1 + O(5^20) AUTHOR: - Xavier Caruso (2013-03-20) """ one = self.parent()(1) vertices = self.newton_polygon().vertices(copy=False) if len(vertices) < 2: if slope is Infinity: return self.parent().gen() ** self.degree() else: return one if slope is None: deg_first = vertices[0][0] deg_last = vertices[1][0] else: (deg_first, y_first) = vertices[0] for i in range(1, len(vertices)): (deg_last, y_last) = vertices[i] slope_cur = (y_first - y_last) / (deg_last - deg_first) if slope_cur == slope: break elif slope_cur < slope: return one deg_first = deg_last y_first = y_last if slope_cur > slope: return one if deg_last == self.degree(): div = self else: div = self._factor_of_degree(deg_last) if deg_first > 0: div2 = div._factor_of_degree(deg_first) div,_ = div.quo_rem(div2) return div.monic() def slope_factorization(self): """ Return a factorization of ``self`` into a product of factors corresponding to each slope in the Newton polygon. EXAMPLES:: sage: K = Qp(5) sage: R.<x> = K[] sage: K = Qp(5) sage: R.<t> = K[] sage: f = 5 + 3*t + t^4 + 25*t^10 sage: f.newton_slopes() [1, 0, 0, 0, -1/3, -1/3, -1/3, -1/3, -1/3, -1/3] sage: F = f.slope_factorization() sage: F.prod() == f True sage: for (f,_) in F: ....: print(f.newton_slopes()) [-1/3, -1/3, -1/3, -1/3, -1/3, -1/3] [0, 0, 0] [1] TESTS:: sage: S.<x> = PowerSeriesRing(GF(5)) sage: R.<y> = S[] sage: p = x^2+y+x*y^2 sage: p.slope_factorization() (x) * ((x + O(x^22))*y + 1 + 4*x^3 + 4*x^6 + 3*x^9 + x^15 + 3*x^18 + O(x^21)) * ((x^-1 + O(x^20))*y + x + x^4 + 2*x^7 + 4*x^13 + 2*x^16 + 2*x^19 + O(x^22)) AUTHOR: - Xavier Caruso (2013-03-20) """ vertices = self.newton_polygon().vertices(copy=False) unit = self.leading_coefficient() P = ~unit * self deg_first = vertices[0][0] factors = [ ] if deg_first > 0: P >>= deg_first factors.append((self._parent.gen(), deg_first)) if len(vertices) > 2: for i in range(1, len(vertices)-1): deg = vertices[i][0] div = P._factor_of_degree(deg-deg_first) factors.append((div,1)) P,_ = P.quo_rem(div) deg_first = deg if len(vertices) > 1: factors.append((P, 1)) factors.reverse() return Factorization(factors, sort=False, unit=unit) def _roots(self, secure, minval, hint): """ Return the roots of this polynomial whose valuation is at least ``minval``. This is a helper method for :meth:`roots`. It is not meant to be called directly. INPUT: - ``secure`` -- a boolean; whether we raise an error or not in case of multiple roots - ``minval`` -- an integer - ``hint`` -- a list or ``None``; if given, it must be the list of roots of the residual polynomial of slope ``minval`` OUTPUT: A list of pairs ``(root, multiplicity)`` TESTS:: sage: R = Zp(2) sage: S.<x> = R[] sage: P = (x-1) * (x-2) * (x-4) * (x-8) * (x-16) sage: Q = P^2 sage: Q.roots(algorithm="sage") # indirect doctest [(2^4 + O(2^14), 2), (2^3 + O(2^13), 2), (2^2 + O(2^12), 2), (2 + O(2^11), 2), (1 + O(2^10), 2)] """ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing K = self.base_ring() Pk = PolynomialRing(K.residue_field(), names='xbar') x = self.parent().gen() # Trivial cases if self.degree() == 0: return [ ] if self.degree() == 1: return [ (-self[0]/self[1], 1) ] # We consider the case where zero is a (possibly multiple) root i = 0 while self[i] == 0: i += 1 if secure and i > 1: raise PrecisionError("not enough precision to determine the number of roots") if i == 0: roots = [ ] P = self else: vali = self[i].valuation() prec = min((self[j].precision_absolute()-vali) / (i-j) for j in range(i)) if prec is not Infinity: prec = prec.ceil() roots = [ (K(0,prec), i) ] P = self // self[:i+1] # we do not shift because we need to track precision here # We use Newton polygon and slope factorisation to find roots vertices = P.newton_polygon().vertices(copy=False) deg = 0 for i in range(1, len(vertices)): deg_left, val_left = vertices[i-1] deg_right, val_right = vertices[i] slope = (val_right - val_left) / (deg_left - deg_right) if slope not in ZZ or slope < minval: continue if hint is not None and slope == minval: rootsbar = hint if not rootsbar: continue if i < len(vertices) - 1: F = P._factor_of_degree(deg_right - deg) P = P // F else: F = P if deg < deg_left: G = F._factor_of_degree(deg_left - deg) F //= G deg = deg_right val = F[0].valuation() if hint is None or slope != minval: Fbar = Pk([ F[j] >> (val - j*slope) for j in range(F.degree()+1) ]) rootsbar = [ r for (r, _) in Fbar.roots() ] if not rootsbar: continue rbar = rootsbar.pop() shift = K(rbar).lift_to_precision() << slope # probably we should choose a better lift roots += [(r+shift, m) for (r, m) in F(x+shift)._roots(secure, slope, [r-rbar for r in rootsbar])] # recursive call return roots class Polynomial_generic_dense_cdv(Polynomial_generic_dense_inexact, Polynomial_generic_cdv): pass class Polynomial_generic_sparse_cdv(Polynomial_generic_sparse, Polynomial_generic_cdv): pass class Polynomial_generic_cdvr(Polynomial_generic_cdv): pass class Polynomial_generic_dense_cdvr(Polynomial_generic_dense_cdv, Polynomial_generic_cdvr): pass class Polynomial_generic_sparse_cdvr(Polynomial_generic_sparse_cdv, Polynomial_generic_cdvr): pass class Polynomial_generic_cdvf(Polynomial_generic_cdv, Polynomial_generic_field): pass class Polynomial_generic_dense_cdvf(Polynomial_generic_dense_cdv, Polynomial_generic_cdvf): pass class Polynomial_generic_sparse_cdvf(Polynomial_generic_sparse_cdv, Polynomial_generic_cdvf): pass ############################################################################ # XXX: Ensures that the generic polynomials implemented in Sage via PARI # # until at least until 4.5.0 unpickle correctly as polynomials implemented # # via FLINT. # from sage.misc.persist import register_unpickle_override from sage.rings.polynomial.polynomial_rational_flint import Polynomial_rational_flint register_unpickle_override( \ 'sage.rings.polynomial.polynomial_element_generic', \ 'Polynomial_rational_dense', Polynomial_rational_flint)
""" Trains a network-enhanced autoencoder (netAE) for semi-supervised dimensionality reduction of single-cell RNA-sequencing. Hyperparameters are passed in through argument parser, and the default values are the hyperparameters we used in the paper. One can specify the autoencoder architecture (Dae, Vae, Dca, Vdca) for which to incorporate the semi-supervised idea of netAE, but netAE uses the Vdca architecture in our paper. The models are named `net{name_of_autoencoder}` if trained in a semi-supervised fashion as described by the netAE paper, and named `{name_of_autoencoder}` if trained in an unsupervised fashion but using the same network architecture (i.e. the `AE` baseline in the paper). @author: Leo Zhengyang Dong @contact: leozdong@stanford.edu @date: 10/16/2019 """ parser = argparse.ArgumentParser(description="Training netAE") # Training settings: parser.add_argument("-dpath", "--data-path", default="/", help="path to the dataset folder") parser.add_argument("-spath", "--save-path", default="output", help="path to output directory") parser.add_argument("-mc", "--model-code", default="full", help="code name of the current model (default: full)") parser.add_argument("-ds", "--dataset", default="cortex", help="name of the dataset (default: cortex)") parser.add_argument("-sl", "--silence", action="store_true", default=False, help="do not print any stats during training") parser.add_argument("-se", "--save-embd", type=bool_flag, default=True, help="saves the embedded space along with the model") # Model property: parser.add_argument("--ae", default="vdca", help="specify autoencoder structure (dae, vae, dca, or vdca)") parser.add_argument("-s", "--seed", type=int, default=0, help="random seed for loading dataset (default: 0)") # Model parameters: parser.add_argument("-opt", "--optim", default="adam", help="name of the optimizer to use (default: adam)") parser.add_argument("-bs", "--batch-size", type=int, default=100, help="batch size (default: 100)") parser.add_argument("--lr", type=float, default=2e-4, help="learning rate (default: 2e-4)") parser.add_argument("-lrd", "--lr-decay", type=float, default=1, help="learning rate decay (default: 1, i.e. no decay)") parser.add_argument("--dim", type=int, default=50, help="encoding dimension (default: 50)") parser.add_argument("-e", "--epochs", type=int, default=150, help="number of epochs (default: 100)") parser.add_argument("-es", "--early-stop", type=int, default=10, help="number of epochs to wait before early stop (default: 10)") parser.add_argument("-gm", "--gamma", type=float, default=2, help="RBF coefficient in calculating similarity in modularity (default: 2)") parser.add_argument("-kp", "--kappa", type=float, default=5, help="weight for KL divergence term; only active when using variational autoencoder (default: 5)") parser.add_argument("-ld", "--lambd", type=float, default=150, help="weight for modularity loss (default: 150)") parser.add_argument("--phi", type=float, default=10, help="weight for logistic regression loss (default: 10)") parser.add_argument("-lsize", "--lab-size", type=int, default=10, help="labeled set size for each cell type (default: 10)") parser.add_argument("-lratio", "--lab-ratio", type=float, default=-1, help="labeled set ratio for each cell type (default: -1)") args = parser.parse_args() # make sure saving path exists import os if not os.path.exists(args.save_path): os.makedirs(args.save_path) from netAE import train_netAE def main(): if args.lambd == 0: print("Training without modularity loss!") if args.phi == 0: print("Training without logistic regression loss!") # Data loading from data import Data prep_method = "log" if args.lab_ratio != -1: # use labeled ratio dataset = Data(args.data_path, labeled_ratio=args.lab_ratio, seed=args.seed, prep_method=prep_method) else: # use labeled size dataset = Data(args.data_path, labeled_size=args.lab_size, seed=args.seed, prep_method=prep_method) # info contains information about the dataset (gene names, cell names, etc.) # it is not used in the program but one can take advantage of this data if needed data, lab_full, labeled_idx, unlabeled_idx, info = dataset.load_all() data = torch.tensor(data, dtype=torch.float) labeled_data = data[labeled_idx, :] labeled_lab = lab_full[labeled_idx].tolist() embd_save_path = None if args.lambd == 0 and args.phi == 0: model_save_path = args.save_path + "/{}_trained_{}.pt".format(args.ae.upper(), args.dataset) if args.save_embd: embd_save_path = args.save_path + "/{}_embd_space_{}.npy".format(args.ae.upper(), args.dataset) else: model_save_path = args.save_path + "/net{}_trained_{}_{}_{}.pt".format(args.ae.upper(), args.dataset, args.model_code, args.seed) if args.save_embd: embd_save_path = args.save_path + "/net{}_embd_space_{}_{}_{}.npy".format(args.ae.upper(), args.dataset, args.model_code, args.seed) trained_model = train_netAE(data, labeled_data, labeled_lab, model_save_path, embd_save_path, args=args) if __name__ == "__main__": main()
'use strict'; exports.__esModule = true; exports.CRLF = undefined; exports.createLineIterator = createLineIterator; exports.appendLine = appendLine; exports.startsWith = startsWith; exports.toReadableStream = toReadableStream; var _stream = require('stream'); const LF = 0x0A; const CR = 0x0D; const CRLF_LENGTH = 2; const CRLF = exports.CRLF = Buffer.from([CR, LF]); function createLineIterator(buffer) { return { [Symbol.iterator]: function* () { const lastIdx = buffer.length - 1; let start = 0; for (let i = 0; i < buffer.length; i++) { if (i === lastIdx) yield buffer.slice(start);else if (buffer[i] === CR && buffer[i + 1] === LF) { yield buffer.slice(start, i); start = i + CRLF_LENGTH; } } } }; } function appendLine(lines, line) { if (lines.length) lines.push(CRLF); lines.push(line); } function startsWith(buffer, searchBuffer) { if (buffer.length < searchBuffer.length) return false; for (let i = 0; i < searchBuffer.length; i++) { if (buffer[i] !== searchBuffer[i]) return false; } return true; } function toReadableStream(buffer) { const stream = new _stream.Readable(); stream.push(buffer); stream.push(null); return stream; }
from functools import partial import io import json import platform import sys import mujson import pytest import ujson from falcon import ASGI_SUPPORTED, media, testing from _util import create_app # NOQA orjson = None rapidjson = None if sys.version_info >= (3, 5): import rapidjson # type: ignore if platform.python_implementation() == 'CPython': try: import orjson # type: ignore except ImportError: pass COMMON_SERIALIZATION_PARAM_LIST = [ # Default json.dumps, with only ascii (None, {'test': 'value'}, b'{"test":"value"}'), (mujson.dumps, {'test': 'value'}, b'{"test":"value"}'), (ujson.dumps, {'test': 'value'}, b'{"test":"value"}'), (partial(lambda media, **kwargs: json.dumps([media, kwargs]), ensure_ascii=True), {'test': 'value'}, b'[{"test":"value"},{"ensure_ascii":true}]'), ] COMMON_DESERIALIZATION_PARAM_LIST = [ (None, b'[1, 2]', [1, 2]), (partial(json.loads, object_hook=lambda data: {k: v.upper() for k, v in data.items()}), b'{"key": "value"}', {'key': 'VALUE'}), (mujson.loads, b'{"test": "value"}', {'test': 'value'}), (ujson.loads, b'{"test": "value"}', {'test': 'value'}), ] YEN = b'\xc2\xa5' if orjson: SERIALIZATION_PARAM_LIST = COMMON_SERIALIZATION_PARAM_LIST + [ # Default json.dumps, with non-ascii characters (None, {'yen': YEN.decode()}, b'{"yen":"' + YEN + b'"}'), # Extra Python 3 json libraries (rapidjson.dumps, {'test': 'value'}, b'{"test":"value"}'), (orjson.dumps, {'test': 'value'}, b'{"test":"value"}'), ] DESERIALIZATION_PARAM_LIST = COMMON_DESERIALIZATION_PARAM_LIST + [ (rapidjson.loads, b'{"test": "value"}', {'test': 'value'}), (orjson.loads, b'{"test": "value"}', {'test': 'value'}), ] elif rapidjson: SERIALIZATION_PARAM_LIST = COMMON_SERIALIZATION_PARAM_LIST + [ # Default json.dumps, with non-ascii characters (None, {'yen': YEN.decode()}, b'{"yen":"' + YEN + b'"}'), # Extra Python 3 json libraries (rapidjson.dumps, {'test': 'value'}, b'{"test":"value"}'), ] DESERIALIZATION_PARAM_LIST = COMMON_DESERIALIZATION_PARAM_LIST + [ (rapidjson.loads, b'{"test": "value"}', {'test': 'value'}), ] else: SERIALIZATION_PARAM_LIST = COMMON_SERIALIZATION_PARAM_LIST + [ # Default json.dumps, with non-ascii characters (None, {'yen': YEN.decode('utf-8')}, b'{"yen":"' + YEN + b'"}'), ] DESERIALIZATION_PARAM_LIST = COMMON_DESERIALIZATION_PARAM_LIST @pytest.mark.parametrize('func, body, expected', SERIALIZATION_PARAM_LIST) def test_serialization(asgi, func, body, expected): handler = media.JSONHandler(dumps=func) args = (body, b'application/javacript') if asgi: result = testing.invoke_coroutine_sync(handler.serialize_async, *args) else: result = handler.serialize(*args) # NOTE(nZac) PyPy and CPython render the final string differently. One # includes spaces and the other doesn't. This replace will normalize that. assert result.replace(b' ', b'') == expected # noqa @pytest.mark.parametrize('func, body, expected', DESERIALIZATION_PARAM_LIST) def test_deserialization(asgi, func, body, expected): handler = media.JSONHandler(loads=func) args = ['application/javacript', len(body)] if asgi: if not ASGI_SUPPORTED: pytest.skip('ASGI requires Python 3.6+') from falcon.asgi.stream import BoundedStream s = BoundedStream(testing.ASGIRequestEventEmitter(body)) args.insert(0, s) result = testing.invoke_coroutine_sync(handler.deserialize_async, *args) else: args.insert(0, io.BytesIO(body)) result = handler.deserialize(*args) assert result == expected def test_deserialization_raises(asgi): app = create_app(asgi) class SuchException(Exception): pass class FaultyHandler(media.BaseHandler): def deserialize(self, stream, content_type, content_length): raise SuchException('Wow such error.') def deserialize_async(self, stream, content_type, content_length): raise SuchException('Wow such error.') def serialize(self, media, content_type): raise SuchException('Wow such error.') handlers = media.Handlers({'application/json': FaultyHandler()}) app.req_options.media_handlers = handlers app.resp_options.media_handlers = handlers class Resource: def on_get(self, req, resp): resp.media = {} def on_post(self, req, resp): req.media class ResourceAsync: async def on_get(self, req, resp): resp.media = {} async def on_post(self, req, resp): # NOTE(kgriffs): In this one case we use the property # instead of get_media(), in order to test that the # alias works as expected. await req.media app.add_route('/', ResourceAsync() if asgi else Resource()) # NOTE(kgriffs): Now that we install a default handler for # Exception, we have to clear them to test the path we want # to trigger. # TODO(kgriffs): Since we always add a default error handler # for Exception, should we take out the checks in the WSGI/ASGI # callable and just always assume it will be handled? If so, # it makes testing that the right exception is propagated harder; # I suppose we'll have to look at what is logged. app._error_handlers.clear() with pytest.raises(SuchException): testing.simulate_get(app, '/') with pytest.raises(SuchException): testing.simulate_post(app, '/', json={}) def test_sync_methods_not_overridden(asgi): app = create_app(asgi) class FaultyHandler(media.BaseHandler): pass handlers = media.Handlers({'application/json': FaultyHandler()}) app.req_options.media_handlers = handlers app.resp_options.media_handlers = handlers class Resource: def on_get(self, req, resp): resp.media = {} def on_post(self, req, resp): req.media class ResourceAsync: async def on_get(self, req, resp): resp.media = {} async def on_post(self, req, resp): await req.get_media() app.add_route('/', ResourceAsync() if asgi else Resource()) result = testing.simulate_get(app, '/') assert result.status_code == 500 result = testing.simulate_post(app, '/', json={}) assert result.status_code == 500 def test_async_methods_not_overridden(): app = create_app(asgi=True) class SimpleHandler(media.BaseHandler): def serialize(self, media, content_type): return json.dumps(media).encode() def deserialize(self, stream, content_type, content_length): return json.load(stream) handlers = media.Handlers({'application/json': SimpleHandler()}) app.req_options.media_handlers = handlers app.resp_options.media_handlers = handlers class ResourceAsync: async def on_post(self, req, resp): resp.media = await req.get_media() app.add_route('/', ResourceAsync()) doc = {'event': 'serialized'} result = testing.simulate_post(app, '/', json=doc) assert result.status_code == 200 assert result.json == doc def test_async_handler_returning_none(): app = create_app(asgi=True) class SimpleHandler(media.BaseHandler): def serialize(self, media, content_type): return json.dumps(media).encode() def deserialize(self, stream, content_type, content_length): return None handlers = media.Handlers({'application/json': SimpleHandler()}) app.req_options.media_handlers = handlers app.resp_options.media_handlers = handlers class ResourceAsync: async def on_post(self, req, resp): resp.media = [await req.get_media()] app.add_route('/', ResourceAsync()) doc = {'event': 'serialized'} result = testing.simulate_post(app, '/', json=doc) assert result.status_code == 200 assert result.json == [None]
from model.group import Group class GroupHelper: group_cache = None def __init__(self, app): self.app = app def create(self, group): wd = self.app.wd self.open_group_page() wd.find_element_by_name("new").click() self.fill_group_form(group) wd.find_element_by_name("submit").click() self.open_group_page() self.group_cache = None def fill_group_form(self, group): wd = self.app.wd self.change_field_value("group_name", group.name) self.change_field_value("group_header", group.header) self.change_field_value("group_footer", group.footer) def change_field_value(self, field_name, text): wd = self.app.wd if text is not None: wd.find_element_by_name(field_name).click() wd.find_element_by_name(field_name).clear() wd.find_element_by_name(field_name).send_keys(text) def open_group_page(self): wd = self.app.wd if not (wd.current_url.endswith("/group.php") and len(wd.find_elements_by_name("new"))>0): wd.find_element_by_link_text("groups").click() def del_first_group(self): wd = self.app.wd self.del_group_by_index(0) def del_group_by_index(self, index): wd = self.app.wd self.open_group_page() self.select_group_by_index(index) wd.find_element_by_name("delete").click() self.open_group_page() self.group_cache = None def del_group_by_id(self, id): wd = self.app.wd self.open_group_page() self.select_group_by_id(id) wd.find_element_by_name("delete").click() self.open_group_page() self.group_cache = None def select_group_by_index(self, index): wd = self.app.wd wd.find_elements_by_name("selected[]")[index].click() def select_group_by_id(self, id): wd = self.app.wd wd.find_element_by_css_selector("input[value='%s']" % id).click() def select_first_group(self): wd = self.app.wd wd.find_element_by_name("selected[]").click() def edit_group_by_index(self, index, new_group_data): wd = self.app.wd self.open_group_page() self.select_group_by_index(index) wd.find_element_by_name("edit").click() self.fill_group_form(new_group_data) wd.find_element_by_name("update").click() self.open_group_page() self.group_cache = None def edit_group_by_id(self, id, new_group_data): wd = self.app.wd self.open_group_page() self.select_group_by_id(id) wd.find_element_by_name("edit").click() self.fill_group_form(new_group_data) wd.find_element_by_name("update").click() self.open_group_page() self.group_cache = None def edit_first_group(self, new_group_data): wd = self.app.wd self.edit_group_by_index(0) def count(self): wd = self.app.wd self.open_group_page() return len (wd.find_elements_by_name("selected[]")) def get_group_list(self): if self.group_cache is None: wd = self.app.wd self.open_group_page() self.group_cache=[] for element in wd.find_elements_by_css_selector("span.group"): text=element.text id=element.find_element_by_name("selected[]").get_attribute("value") self.group_cache.append(Group(name=text, id=id)) return list(self.group_cache)
test("FormData", function() { var FormData = H.API( window, "FormData", true ); assert( !!FormData, "FormData supported" ); }); asyncTest("FormData Send and Receive", function( async ) { var FormData = H.API( window, "FormData", true ), formdata, xhr; if ( !FormData ) { assert( false, "FormData not supported, skipping tests" ); async.done(); } else { formdata = new FormData(); xhr = new XMLHttpRequest(); formdata.append("a", "alpha"); formdata.append("b", "beta"); xhr.onreadystatechange = function() { var response; if ( this.readyState === 4 && this.status === 200 ) { response = JSON.parse( this.responseText ); async.step(function() { assert( response.a === "alpha", "Expected value, 'alpha'" ); assert( response.b === "beta", "Expected value, 'beta'" ); async.done(); }); } }; xhr.open( "POST", "/suite/_resources/echo.php" ); xhr.send( formdata ); } }); asyncTest("FormData from HTMLFormElement", function( async ) { var FormData = H.API( window, "FormData", true ), form = document.getElementById("simpleForm"), formdata, xhr; if ( !FormData ) { assert( false, "FormData not supported, skipping tests" ); async.done(); } else { formdata = new FormData( form ); xhr = new XMLHttpRequest(); formdata.append("d", "delta"); xhr.onreadystatechange = function() { var response; if ( this.readyState === 4 && this.status === 200 ) { response = JSON.parse( this.responseText ); async.step(function() { assert( response.a === "alpha", "Expected value, 'alpha'" ); assert( response.b === "beta", "Expected value, 'beta'" ); assert( response.d === "delta", "Expected value, 'delta'" ); async.done(); }); } }; xhr.open( "POST", "/suite/_resources/echo.php" ); xhr.send( formdata ); } }); // TODO: Write a test for handling file uploads. // Problematic because we can't progmatically set the contents of input type="file"
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com import subprocess from thumbor.optimizers import BaseOptimizer class Optimizer(BaseOptimizer): def should_run(self, image_extension, buffer): return 'jpg' in image_extension or 'jpeg' in image_extension def optimize(self, buffer, input_file, output_file): jpegtran_path = self.context.config.JPEGTRAN_PATH command = '%s -copy comments -optimize %s-outfile %s %s ' % ( jpegtran_path, '-progressive ' if self.context.config.PROGRESSIVE_JPEG else '', output_file, input_file, ) subprocess.call(command, shell=True)
# -*- coding: utf-8 -*- # # panda-rootfs documentation build configuration file, created by # sphinx-quickstart on Wed Dec 2 09:44:14 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import subprocess # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'PandABlocks-rootfs' copyright = u'2015-2016, Michael Abbott, Tom Cobb' author = u'Michael Abbott' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # try: # Something like 1.5.0-3-g3ab26eb release = subprocess.check_output([ "git", "describe", "--abbrev=7", "--dirty","--always", "--tags"], text=True) except: # No git, or not under a git repo release = "0.0" # The short X.Y version version = ".".join(release.split(".")[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. default_role = "any" # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # If true, Sphinx will warn about all references where the target can't be found nitpicky = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. try: import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' # Options for the sphinx rtd theme, use DLS blue html_theme_options = dict(style_nav_header_background="black") except ImportError: html_theme = 'default' # Add some CSS classes for columns and other tweaks in a custom css file html_css_files = ["theme_overrides.css"] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. html_logo = 'PandA-logo-for-black-background.svg' # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = 'favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'panda-serverdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'panda-rootfs.tex', u'panda-rootfs Documentation', u'Michael Abbott, Tom Cobb', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'panda-rootfs', u'panda-rootfs Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'panda-rootfs', u'panda-rootfs Documentation', author, 'panda-rootfs', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This is application show how to extract the accelerometer, gyroscope and magnetometer measurements from the Dataset of "Towards Artefact Aware Human Motion Capture using Inertial Sensors Integrated into Loose Clothing" https://zenodo.org/record/5948725 @author: michael lorenz, lorenz@cs.uni-kl.de """ import addpaths import h5py import matplotlib.pyplot as plt # %% Settings IDX_PERSON = 1 # chose between Person 1 to 12 DIR_TO_H5 = 'DIR/TO/DATA'# -> Download the data From https://zenodo.org/record/5948725 <- SEQUENCE = 'shoulder_abduction' # choose between ['longterm', 'shoulder_abduction', 'shoulder_flexion', 'squat'] TAKE_SEGMENT = 'L-Forearm' # choose from ['L-Forearm', 'L-Upperarm', 'L-Shoulder', 'R-Forearm', 'R-Upperarm', 'R-Shoulder', # 'Sternum', 'Pelvis', 'L-Tigh', 'L-Shank', 'R-Tigh', 'R-Shank', 'Head', 'L-Hand', 'R-Hand', 'L-Foot', 'R-Foot'] # %% Load Data from files getValuesOf = lambda h5, name : h5['P'+str(IDX_PERSON)][name] # Tight H5_Filename= (DIR_TO_H5+ 'Tight_' +SEQUENCE+'.h5') h5T = h5py.File(H5_Filename,'r') #get the order of the quaternions order_abs = [n.decode('utf-8') for n in list(h5T['P'+str(IDX_PERSON)]['orderAbs'][...])] idx_segment_take = order_abs.index(TAKE_SEGMENT) acc_tight = getValuesOf(h5T, 'acc')[idx_segment_take,:,:] gyr_tight = getValuesOf(h5T, 'gyr')[idx_segment_take,:,:] mag_tight = getValuesOf(h5T, 'mag')[idx_segment_take,:,:] h5T.close() # Loose H5_Filename= (DIR_TO_H5+ 'Loose_' +SEQUENCE+'.h5') h5L = h5py.File(H5_Filename,'r') acc_loose = getValuesOf(h5L, 'acc')[idx_segment_take,:,:] gyr_loose = getValuesOf(h5L, 'gyr')[idx_segment_take,:,:] mag_loose = getValuesOf(h5L, 'mag')[idx_segment_take,:,:] h5L.close() # %% plot measurements plt.figure() plt.plot(acc_tight,label='acc_tight') plt.plot(acc_loose,':',label='acc_loose') plt.legend() plt.grid(True) plt.title('Accelerometer measurements') plt.figure() plt.plot(gyr_tight,label='gyr_tight') plt.plot(gyr_loose,':',label='gyr_loose') plt.legend() plt.grid(True) plt.title('Gyroscope measurements') plt.figure() plt.plot(mag_tight,label='mag_tight') plt.plot(mag_loose,':',label='mag_loose') plt.legend() plt.grid(True) plt.title('Magnetometer measurements')
/* istanbul instrument in package npmtest_homebridge_sonos */ /*jslint bitwise: true, browser: true, maxerr: 8, maxlen: 96, node: true, nomen: true, regexp: true, stupid: true */ (function () { 'use strict'; var local; // run shared js-env code - pre-init (function () { // init local local = {}; // init modeJs local.modeJs = (function () { try { return typeof navigator.userAgent === 'string' && typeof document.querySelector('body') === 'object' && typeof XMLHttpRequest.prototype.open === 'function' && 'browser'; } catch (errorCaughtBrowser) { return module.exports && typeof process.versions.node === 'string' && typeof require('http').createServer === 'function' && 'node'; } }()); // init global local.global = local.modeJs === 'browser' ? window : global; // init utility2_rollup local = local.global.utility2_rollup || local; // init lib local.local = local.npmtest_homebridge_sonos = local; // init exports if (local.modeJs === 'browser') { local.global.utility2_npmtest_homebridge_sonos = local; } else { module.exports = local; module.exports.__dirname = __dirname; module.exports.module = module; } }()); }());
import os import rasa import logging import asyncio import time import tempfile from rasa.telemetry import TELEMETRY_ENABLED_ENVIRONMENT_VARIABLE logger = logging.getLogger(__name__) from rasa.core.constants import DEFAULT_REQUEST_TIMEOUT # hard code false here, since a number of things must be done to # add support with BF os.environ[TELEMETRY_ENABLED_ENVIRONMENT_VARIABLE] = "false" CONFIG_QUERY = """ query($projectId: String!, $environment: String) { getConfig(projectId: $projectId, environment:$environment) { credentials endpoints } } """ def auto_retry(function): bf_url = os.environ.get("BF_URL", "server") async def auto_retried(): tries = 1 resp = None while not resp: if tries != 1: time.sleep(0.5) logger.debug(f"Trying to fetch config from {bf_url} (retry #{str(tries)})") resp = await function() tries += 1 return resp return auto_retried async def get_config_via_graphql(bf_url, project_id): from sgqlc.endpoint.http import HTTPEndpoint logging.getLogger("sgqlc.endpoint.http").setLevel(logging.WARNING) import urllib.error environment = os.environ.get("BOTFRONT_ENV", "development") api_key = os.environ.get("API_KEY") headers = [{"Authorization": api_key}] if api_key else [] endpoint = HTTPEndpoint(bf_url, *headers) @auto_retry async def load(): try: response = endpoint( CONFIG_QUERY, {"projectId": project_id, "environment": environment} ) if response.get("errors"): raise urllib.error.URLError( ", ".join([e.get("message") for e in response.get("errors")]) ) return endpoint( CONFIG_QUERY, {"projectId": project_id, "environment": environment} )["data"] except urllib.error.URLError as e: logger.debug(e.reason) return None data = await load() return data["getConfig"] async def get_config_via_legacy_route(bf_url, project_id): from rasa.utils.endpoints import EndpointConfig import aiohttp response = {} base_url = f"{bf_url}/project/{project_id}" for endpoint in ["credentials", "endpoints"]: server = EndpointConfig(url=f"{base_url}/{endpoint}") async with server.session() as session: params = server.combine_parameters() url = server.url @auto_retry async def load(): try: return await session.request( "GET", url, timeout=DEFAULT_REQUEST_TIMEOUT, params=params ) except aiohttp.ClientError: return None data = await load() response[endpoint] = await data.json() return response def set_endpoints_credentials_args_from_remote(args): bf_url = os.environ.get("BF_URL") project_id = os.environ.get("BF_PROJECT_ID") args.endpoints = None # aurora (default argument value was changed from rasa-for-botfront to rasa 2.8) if not project_id or not bf_url: return here = os.listdir(os.getcwd()) if "endpoints.yml" in here and not args.endpoints: args.endpoints = "endpoints.yml" if "credentials.yml" in here and not args.credentials: args.credentials = "credentials.yml" if args.endpoints and args.credentials: return query_function = ( get_config_via_graphql if "graphql" in bf_url else get_config_via_legacy_route ) config = asyncio.get_event_loop().run_until_complete( query_function(bf_url, project_id) ) if not args.endpoints: with tempfile.NamedTemporaryFile(mode="w", delete=False) as yamlfile: rasa.shared.utils.io.write_yaml(config["endpoints"], yamlfile.name) args.endpoints = yamlfile.name if not args.credentials: with tempfile.NamedTemporaryFile(mode="w", delete=False) as yamlfile: rasa.shared.utils.io.write_yaml(config["credentials"], yamlfile.name) args.credentials = yamlfile.name
#include "../../../../../src/designer/src/lib/shared/qdesigner_command2_p.h"
window.onload = function() { var button = document.getElementById("previewButton"); button.onclick = previewHandler; }; function previewHandler() { var canvas = document.getElementById("tshirtCanvas"); //The getContext method has several drawing contexts. They are '2d', `webgl`, 'webgl2', and 'bitmaprenderer'. //only '2d' is within the scope of the HF HTML5 book. var context = canvas.getContext("2d"); /*the values are in relation to the top left corner of the canvas box default color is black. The fillStyle property can be used to specify colors, gradients, etc. context.fillRect(10, 10, 100, 100); */ //calling fillBackgroundColor before drawing ensures that the canvas background is reset to the fill color after //each Preview button press. Otherwise the canvas would just continue to fill with squares! fillBackgroundColor(canvas, context); //this grabs the select menu for shapes, and since the selectObj gives the option tags as an array with the one selected //in the menu as the index value, access the index for its shape and set the shape variable to the value of the selected option var selectObj = document.getElementById("shape"); var index = selectObj.selectedIndex; var shape = selectObj[index].value; if (shape == "squares") { for (var squares = 0; squares < 20; squares++) { drawSquare(canvas, context); } } else if (shape == "circles") { for (var circles = 0; circles < 20; circles++) { drawCircle(canvas, context); } } drawText(canvas, context); drawBird(canvas, context); } function drawSquare(canvas, context) { //largest square size var w = Math.floor(Math.random() * 40); //randomizes the postion of each square var x = Math.floor(Math.random() * canvas.width); var y = Math.floor(Math.random() * canvas.height); //fillStyle sets the color of the square(can be any color value type: rgba, hex, etc) context.fillStyle = "lightblue"; //fillRect actually draws the rectangle once its variables have been set context.fillRect(x, y, w, w); } function drawCircle(canvas, context) { //circles require the Path methods to draw curves var r = Math.floor(Math.random() * 40); var x = Math.floor(Math.random() * canvas.width); var y = Math.floor(Math.random() * canvas.height); //all 4 of these are needed to draw a path context.beginPath(); //tells browser to begin drawing the path context.arc(x, y, r, 0, 2 * Math.PI) //specifies the position, radius, and begin/ending angles for the path (in radians) context.fillStyle = "lightblue"; //color of the shape context.fill(); //tells the browser to draw the path and fill it //an alternative to the .fill() method is the .stroke(). The stroke method will draw the path without filling in a color for the empty space. } function drawText(canvas, context) { //set foreground color var selectObj = document.getElementById("foregroundColor"); var index = selectObj.selectedIndex; var fgColor = selectObj[index].value; //left-aligned text context.fillStyle = fgColor; context.font = "bold 1em sans-serif"; context.textAlign = "left"; context.fillText("I saw this tweet", 20, 40); //add the tweet text selectObj = document.getElementById("tweets"); index = selectObj.selectedIndex; var tweet = selectObj[index].value; context.font = "italic 1.2em serif"; //using this code doesn't wrap the text of long tweets //context.fillText(tweet, 30, 100); //this doesn't work all that great, I wonder if some string methods and regex would be more effective if (tweet.length > 60) { var tweetLines = splitIntoLines(tweet); for (var i = 0; i < tweetLines.length; i++) { context.fillText(tweetLines[i], 30, 70+(i*25)); } } else { context.fillText(tweet, 30, 100); } //right-aligned text context.font = "bold 1em sans-serif"; context.textAlign = "right"; context.fillText("and all I got was this lousy t-shirt!", canvas.width - 20, canvas.height - 40); } //twitter bird function drawBird(canvas, context) { var twitterBird = new Image(); twitterBird.src = "twitterBird.png"; //use an onload handler to ensure the image if fully loaded before it is drawn on to the canvas twitterBird.onload = function() { context.drawImage(twitterBird, 20, 120, 70, 70); }; } function fillBackgroundColor(canvas, context) { var selectObj = document.getElementById("backgroundColor"); var index = selectObj.selectedIndex; var bgColor = selectObj.options[index].value; context.fillStyle = bgColor; context.fillRect(0, 0, canvas.width, canvas.height); } //this is the callback function specified in the HTML Twitter json script call function updateTweets(tweets) { var tweetSelection = document.getElementById("tweets"); for (var i = 0; i < tweets.length; i++) { tweet = tweets[i]; var option = document.createElement("option"); option.text = tweet.text; option.value = tweet.text.replace("\"", "'"); tweetSelection.options.add(option); } tweetSelection.selectedIndex = 0; } function splitIntoLines(str) { var strs = new Array(); var space = str.indexOf(' ', 60); strs[0] = str.substring(0, space); strs[1] = str.substring(space+1); if (strs[1].length > 60) { space = strs[1].indexOf(' ', 60); strs[2] = strs[1].substring(space+1); strs[1] = strs[1].substring(0, space); } return strs; }
'use babel'; export default class NgcView { constructor(serializedState) { // Create root element this.element = document.createElement('div'); this.element.classList.add('ngc'); // Create message element const message = document.createElement('div'); message.textContent = 'The Ngc package is Alive! It\'s ALIVE!'; message.classList.add('message'); this.element.appendChild(message); } // Returns an object that can be retrieved when package is activated serialize() {} // Tear down any state and detach destroy() { this.element.remove(); } getElement() { return this.element; } }
/* ** Copyright 2001 Addison Wesley. All Rights Reserved. */ #ifndef _THREAD_PER_CONNECTION_LOGGING_SERVER_H #define _THREAD_PER_CONNECTION_LOGGING_SERVER_H #include "ace/SOCK_Stream.h" #include "Logging_Server.h" class Thread_Per_Connection_Logging_Server : public Logging_Server { private: struct Thread_Args { Thread_Args (Thread_Per_Connection_Logging_Server *lsp) : this_ (lsp) {} Thread_Per_Connection_Logging_Server *this_; ACE_SOCK_Stream logging_peer_; }; // Passed as a parameter to <ACE_Thread_Manager::spawn>. static ACE_THR_FUNC_RETURN run_svc (void *arg); protected: virtual int handle_connections (); virtual int handle_data (ACE_SOCK_Stream * = 0); public: // Template Method that runs logging server's event loop. Need to // reimplement this here because the threads spawned from handle_connections // call handle_data; therefore, this method must not. virtual int run (int argc, char *argv[]) { if (open (argc > 1 ? atoi (argv[1]) : 0) == -1) return -1; for (;;) { if (wait_for_multiple_events () == -1) return -1; if (handle_connections () == -1) return -1; } ACE_NOTREACHED (return 0;) } }; #endif /* _THREAD_PER_CONNECTION_LOGGING_SERVER_H */
#!/usr/bin/env python # coding: utf-8 from __future__ import absolute_import, division, print_function import json import logging import math import os import random import warnings from dataclasses import asdict from multiprocessing import cpu_count import tempfile from pathlib import Path from collections import Counter import numpy as np import pandas as pd import torch from scipy.stats import mode, pearsonr from scipy.special import softmax from sklearn.metrics import ( confusion_matrix, label_ranking_average_precision_score, matthews_corrcoef, mean_squared_error, roc_curve, auc, average_precision_score, ) from tensorboardX import SummaryWriter from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from torch.utils.data.distributed import DistributedSampler from tqdm.auto import tqdm, trange from tqdm.contrib import tenumerate from transformers.optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_linear_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.optimization import AdamW, Adafactor from transformers import ( AlbertConfig, AlbertTokenizer, AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, BertConfig, BertTokenizer, BertweetTokenizer, CamembertConfig, CamembertTokenizer, DebertaConfig, DebertaForSequenceClassification, DebertaTokenizer, DistilBertConfig, DistilBertTokenizer, ElectraConfig, ElectraTokenizer, FlaubertConfig, FlaubertTokenizer, LayoutLMConfig, LayoutLMTokenizer, LongformerConfig, LongformerTokenizer, MPNetConfig, MPNetForSequenceClassification, MPNetTokenizer, MobileBertConfig, MobileBertTokenizer, RobertaConfig, RobertaTokenizer, SqueezeBertConfig, SqueezeBertForSequenceClassification, SqueezeBertTokenizer, WEIGHTS_NAME, XLMConfig, XLMRobertaConfig, XLMRobertaTokenizer, XLMTokenizer, XLNetConfig, XLNetTokenizer, ) from transformers.convert_graph_to_onnx import convert, quantize from simpletransformers.classification.classification_utils import ( InputExample, LazyClassificationDataset, ClassificationDataset, convert_examples_to_features, ) from simpletransformers.classification.transformer_models.albert_model import AlbertForSequenceClassification from simpletransformers.classification.transformer_models.bert_model import BertForSequenceClassification from simpletransformers.classification.transformer_models.camembert_model import CamembertForSequenceClassification from simpletransformers.classification.transformer_models.distilbert_model import DistilBertForSequenceClassification from simpletransformers.classification.transformer_models.flaubert_model import FlaubertForSequenceClassification from simpletransformers.classification.transformer_models.layoutlm_model import LayoutLMForSequenceClassification from simpletransformers.classification.transformer_models.longformer_model import LongformerForSequenceClassification from simpletransformers.classification.transformer_models.mobilebert_model import MobileBertForSequenceClassification from simpletransformers.classification.transformer_models.roberta_model import RobertaForSequenceClassification from simpletransformers.classification.transformer_models.xlm_model import XLMForSequenceClassification from simpletransformers.classification.transformer_models.xlm_roberta_model import XLMRobertaForSequenceClassification from simpletransformers.classification.transformer_models.xlnet_model import XLNetForSequenceClassification from simpletransformers.config.global_args import global_args from simpletransformers.config.model_args import ClassificationArgs from simpletransformers.config.utils import sweep_config_to_sweep_values from simpletransformers.custom_models.models import ElectraForSequenceClassification try: import wandb wandb_available = True except ImportError: wandb_available = False logger = logging.getLogger(__name__) MODELS_WITHOUT_CLASS_WEIGHTS_SUPPORT = ["squeezebert", "deberta", "mpnet"] MODELS_WITH_EXTRA_SEP_TOKEN = ["roberta", "camembert", "xlmroberta", "longformer", "mpnet"] MODELS_WITH_ADD_PREFIX_SPACE = ["roberta", "camembert", "xlmroberta", "longformer", "mpnet"] MODELS_WITHOUT_SLIDING_WINDOW_SUPPORT = ["squeezebert"] class ClassificationModel: def __init__( self, model_type, model_name, tokenizer_type=None, tokenizer_name=None, num_labels=None, weight=None, args=None, use_cuda=True, cuda_device=-1, onnx_execution_provider=None, **kwargs, ): """ Initializes a ClassificationModel model. Args: model_type: The type of model (bert, xlnet, xlm, roberta, distilbert) model_name: The exact architecture and trained weights to use. This may be a Hugging Face Transformers compatible pre-trained model, a community model, or the path to a directory containing model files. tokenizer_type: The type of tokenizer (auto, bert, xlnet, xlm, roberta, distilbert, etc.) to use. If a string is passed, Simple Transformers will try to initialize a tokenizer class from the available MODEL_CLASSES. Alternatively, a Tokenizer class (subclassed from PreTrainedTokenizer) can be passed. tokenizer_name: The name/path to the tokenizer. If the tokenizer_type is not specified, the model_type will be used to determine the type of the tokenizer. num_labels (optional): The number of labels or classes in the dataset. weight (optional): A list of length num_labels containing the weights to assign to each label for loss calculation. args (optional): Default args will be used if this parameter is not provided. If provided, it should be a dict containing the args that should be changed in the default args. use_cuda (optional): Use GPU if available. Setting to False will force model to use CPU only. cuda_device (optional): Specific GPU that should be used. Will use the first available GPU by default. onnx_execution_provider (optional): ExecutionProvider to use with ONNX Runtime. Will use CUDA (if use_cuda) or CPU (if use_cuda is False) by default. **kwargs (optional): For providing proxies, force_download, resume_download, cache_dir and other options specific to the 'from_pretrained' implementation where this will be supplied. """ # noqa: ignore flake8" MODEL_CLASSES = { "albert": (AlbertConfig, AlbertForSequenceClassification, AlbertTokenizer), "auto": (AutoConfig, AutoModelForSequenceClassification, AutoTokenizer), "bert": (BertConfig, BertForSequenceClassification, BertTokenizer), "bertweet": (RobertaConfig, RobertaForSequenceClassification, BertweetTokenizer), "camembert": (CamembertConfig, CamembertForSequenceClassification, CamembertTokenizer), "deberta": (DebertaConfig, DebertaForSequenceClassification, DebertaTokenizer), "distilbert": (DistilBertConfig, DistilBertForSequenceClassification, DistilBertTokenizer), "electra": (ElectraConfig, ElectraForSequenceClassification, ElectraTokenizer), "flaubert": (FlaubertConfig, FlaubertForSequenceClassification, FlaubertTokenizer), "layoutlm": (LayoutLMConfig, LayoutLMForSequenceClassification, LayoutLMTokenizer), "longformer": (LongformerConfig, LongformerForSequenceClassification, LongformerTokenizer), "mobilebert": (MobileBertConfig, MobileBertForSequenceClassification, MobileBertTokenizer), "mpnet": (MPNetConfig, MPNetForSequenceClassification, MPNetTokenizer), "roberta": (RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer), "squeezebert": (SqueezeBertConfig, SqueezeBertForSequenceClassification, SqueezeBertTokenizer), "xlm": (XLMConfig, XLMForSequenceClassification, XLMTokenizer), "xlmroberta": (XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer), "xlnet": (XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer), } self.args = self._load_model_args(model_name) if isinstance(args, dict): self.args.update_from_dict(args) elif isinstance(args, ClassificationArgs): self.args = args if model_type in MODELS_WITHOUT_SLIDING_WINDOW_SUPPORT and self.args.sliding_window: raise ValueError("{} does not currently support sliding window".format(model_type)) if self.args.thread_count: torch.set_num_threads(self.args.thread_count) if "sweep_config" in kwargs: self.is_sweeping = True sweep_config = kwargs.pop("sweep_config") sweep_values = sweep_config_to_sweep_values(sweep_config) self.args.update_from_dict(sweep_values) else: self.is_sweeping = False if self.args.manual_seed: random.seed(self.args.manual_seed) np.random.seed(self.args.manual_seed) torch.manual_seed(self.args.manual_seed) if self.args.n_gpu > 0: torch.cuda.manual_seed_all(self.args.manual_seed) if self.args.labels_list: if num_labels: assert num_labels == len(self.args.labels_list) if self.args.labels_map: try: assert list(self.args.labels_map.keys()) == self.args.labels_list except AssertionError: assert [int(key) for key in list(self.args.labels_map.keys())] == self.args.labels_list self.args.labels_map = {int(key): value for key, value in self.args.labels_map.items()} else: self.args.labels_map = {label: i for i, label in enumerate(self.args.labels_list)} else: len_labels_list = 2 if not num_labels else num_labels self.args.labels_list = [i for i in range(len_labels_list)] config_class, model_class, tokenizer_class = MODEL_CLASSES[model_type] if tokenizer_type is not None: if isinstance(tokenizer_type, str): _, _, tokenizer_class = MODEL_CLASSES[tokenizer_type] else: tokenizer_class = tokenizer_type if num_labels: self.config = config_class.from_pretrained(model_name, num_labels=num_labels, **self.args.config) self.num_labels = num_labels else: self.config = config_class.from_pretrained(model_name, **self.args.config) self.num_labels = self.config.num_labels if model_type in MODELS_WITHOUT_CLASS_WEIGHTS_SUPPORT and weight is not None: raise ValueError("{} does not currently support class weights".format(model_type)) else: self.weight = weight if use_cuda: if torch.cuda.is_available(): if cuda_device == -1: self.device = torch.device("cuda") else: self.device = torch.device(f"cuda:{cuda_device}") else: raise ValueError( "'use_cuda' set to True when cuda is unavailable." " Make sure CUDA is available or set use_cuda=False." ) else: self.device = "cpu" if self.args.onnx: from onnxruntime import InferenceSession, SessionOptions if not onnx_execution_provider: onnx_execution_provider = "CUDAExecutionProvider" if use_cuda else "CPUExecutionProvider" options = SessionOptions() options.intra_op_num_threads = 1 if self.args.dynamic_quantize: model_path = quantize(Path(os.path.join(model_name, "onnx_model.onnx"))) self.model = InferenceSession(model_path.as_posix(), options, providers=[onnx_execution_provider]) else: model_path = os.path.join(model_name, "onnx_model.onnx") self.model = InferenceSession(model_path, options, providers=[onnx_execution_provider]) else: if not self.args.quantized_model: if self.weight: self.model = model_class.from_pretrained( model_name, config=self.config, weight=torch.Tensor(self.weight).to(self.device), **kwargs, ) else: self.model = model_class.from_pretrained(model_name, config=self.config, **kwargs) else: quantized_weights = torch.load(os.path.join(model_name, "pytorch_model.bin")) if self.weight: self.model = model_class.from_pretrained( None, config=self.config, state_dict=quantized_weights, weight=torch.Tensor(self.weight).to(self.device), ) else: self.model = model_class.from_pretrained(None, config=self.config, state_dict=quantized_weights) if self.args.dynamic_quantize: self.model = torch.quantization.quantize_dynamic(self.model, {torch.nn.Linear}, dtype=torch.qint8) if self.args.quantized_model: self.model.load_state_dict(quantized_weights) if self.args.dynamic_quantize: self.args.quantized_model = True self.results = {} if not use_cuda: self.args.fp16 = False if self.args.fp16: try: from torch.cuda import amp except AttributeError: raise AttributeError("fp16 requires Pytorch >= 1.6. Please update Pytorch or turn off fp16.") if tokenizer_name is None: tokenizer_name = model_name if tokenizer_name in [ "vinai/bertweet-base", "vinai/bertweet-covid19-base-cased", "vinai/bertweet-covid19-base-uncased", ]: self.tokenizer = tokenizer_class.from_pretrained( tokenizer_name, do_lower_case=self.args.do_lower_case, normalization=True, **kwargs ) else: self.tokenizer = tokenizer_class.from_pretrained( tokenizer_name, do_lower_case=self.args.do_lower_case, **kwargs ) if self.args.special_tokens_list: self.tokenizer.add_tokens(self.args.special_tokens_list, special_tokens=True) self.model.resize_token_embeddings(len(self.tokenizer)) self.args.model_name = model_name self.args.model_type = model_type self.args.tokenizer_name = tokenizer_name self.args.tokenizer_type = tokenizer_type if model_type in ["camembert", "xlmroberta"]: warnings.warn( f"use_multiprocessing automatically disabled as {model_type}" " fails when using multiprocessing for feature conversion." ) self.args.use_multiprocessing = False if self.args.wandb_project and not wandb_available: warnings.warn("wandb_project specified but wandb is not available. Wandb disabled.") self.args.wandb_project = None def train_model( self, train_df, multi_label=False, output_dir=None, show_running_loss=True, args=None, eval_df=None, verbose=True, **kwargs, ): """ Trains the model using 'train_df' Args: train_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two columns, with the first column containing the text, and the second column containing the label. The model will be trained on this Dataframe. output_dir: The directory where model files will be saved. If not given, self.args.output_dir will be used. show_running_loss (optional): Set to False to prevent running loss from being printed to console. Defaults to True. args (optional): Optional changes to the args dict of the model. Any changes made will persist for the model. eval_df (optional): A DataFrame against which evaluation will be performed when evaluate_during_training is enabled. Is required if evaluate_during_training is enabled. **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use). E.g. f1=sklearn.metrics.f1_score. A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Returns: global_step: Number of global steps trained training_details: Average training loss if evaluate_during_training is False or full training progress scores if evaluate_during_training is True """ # noqa: ignore flake8" if args: self.args.update_from_dict(args) if self.args.silent: show_running_loss = False if self.args.evaluate_during_training and eval_df is None: raise ValueError( "evaluate_during_training is enabled but eval_df is not specified." " Pass eval_df to model.train_model() if using evaluate_during_training." ) if not output_dir: output_dir = self.args.output_dir if os.path.exists(output_dir) and os.listdir(output_dir) and not self.args.overwrite_output_dir: raise ValueError( "Output directory ({}) already exists and is not empty." " Set overwrite_output_dir: True to automatically overwrite.".format(output_dir) ) self._move_model_to_device() if isinstance(train_df, str) and self.args.lazy_loading: if self.args.sliding_window: raise ValueError("Lazy loading cannot be used with sliding window.") if self.args.model_type == "layoutlm": raise NotImplementedError("Lazy loading is not implemented for LayoutLM models") train_dataset = LazyClassificationDataset(train_df, self.tokenizer, self.args) else: if self.args.lazy_loading: raise ValueError("Input must be given as a path to a file when using lazy loading") if "text" in train_df.columns and "labels" in train_df.columns: if self.args.model_type == "layoutlm": train_examples = [ InputExample(i, text, None, label, x0, y0, x1, y1) for i, (text, label, x0, y0, x1, y1) in enumerate( zip( train_df["text"].astype(str), train_df["labels"], train_df["x0"], train_df["y0"], train_df["x1"], train_df["y1"], ) ) ] else: train_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(train_df["text"].astype(str), train_df["labels"])) ] elif "text_a" in train_df.columns and "text_b" in train_df.columns: if self.args.model_type == "layoutlm": raise ValueError("LayoutLM cannot be used with sentence-pair tasks") else: train_examples = [ InputExample(i, text_a, text_b, label) for i, (text_a, text_b, label) in enumerate( zip(train_df["text_a"].astype(str), train_df["text_b"].astype(str), train_df["labels"]) ) ] else: warnings.warn( "Dataframe headers not specified. Falling back to using column 0 as text and column 1 as labels." ) train_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(train_df.iloc[:, 0], train_df.iloc[:, 1])) ] train_dataset = self.load_and_cache_examples(train_examples, verbose=verbose) train_sampler = RandomSampler(train_dataset) train_dataloader = DataLoader( train_dataset, sampler=train_sampler, batch_size=self.args.train_batch_size, num_workers=self.args.dataloader_num_workers, ) os.makedirs(output_dir, exist_ok=True) global_step, training_details = self.train( train_dataloader, output_dir, multi_label=multi_label, show_running_loss=show_running_loss, eval_df=eval_df, verbose=verbose, **kwargs, ) # model_to_save = self.model.module if hasattr(self.model, "module") else self.model # model_to_save.save_pretrained(output_dir) # self.tokenizer.save_pretrained(output_dir) # torch.save(self.args, os.path.join(output_dir, "training_args.bin")) self.save_model(model=self.model) if verbose: logger.info(" Training of {} model complete. Saved to {}.".format(self.args.model_type, output_dir)) return global_step, training_details def train( self, train_dataloader, output_dir, multi_label=False, show_running_loss=True, eval_df=None, verbose=True, **kwargs, ): """ Trains the model on train_dataset. Utility function to be used by the train_model() method. Not intended to be used directly. """ model = self.model args = self.args tb_writer = SummaryWriter(logdir=args.tensorboard_dir) t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [] custom_parameter_names = set() for group in self.args.custom_parameter_groups: params = group.pop("params") custom_parameter_names.update(params) param_group = {**group} param_group["params"] = [p for n, p in model.named_parameters() if n in params] optimizer_grouped_parameters.append(param_group) for group in self.args.custom_layer_parameters: layer_number = group.pop("layer") layer = f"layer.{layer_number}." group_d = {**group} group_nd = {**group} group_nd["weight_decay"] = 0.0 params_d = [] params_nd = [] for n, p in model.named_parameters(): if n not in custom_parameter_names and layer in n: if any(nd in n for nd in no_decay): params_nd.append(p) else: params_d.append(p) custom_parameter_names.add(n) group_d["params"] = params_d group_nd["params"] = params_nd optimizer_grouped_parameters.append(group_d) optimizer_grouped_parameters.append(group_nd) if not self.args.train_custom_parameters_only: optimizer_grouped_parameters.extend( [ { "params": [ p for n, p in model.named_parameters() if n not in custom_parameter_names and not any(nd in n for nd in no_decay) ], "weight_decay": args.weight_decay, }, { "params": [ p for n, p in model.named_parameters() if n not in custom_parameter_names and any(nd in n for nd in no_decay) ], "weight_decay": 0.0, }, ] ) warmup_steps = math.ceil(t_total * args.warmup_ratio) args.warmup_steps = warmup_steps if args.warmup_steps == 0 else args.warmup_steps if args.optimizer == "AdamW": optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) elif args.optimizer == "Adafactor": optimizer = Adafactor( optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adafactor_eps, clip_threshold=args.adafactor_clip_threshold, decay_rate=args.adafactor_decay_rate, beta1=args.adafactor_beta1, weight_decay=args.weight_decay, scale_parameter=args.adafactor_scale_parameter, relative_step=args.adafactor_relative_step, warmup_init=args.adafactor_warmup_init, ) print("Using Adafactor for T5") else: raise ValueError( "{} is not a valid optimizer class. Please use one of ('AdamW', 'Adafactor') instead.".format( args.optimizer ) ) if args.scheduler == "constant_schedule": scheduler = get_constant_schedule(optimizer) elif args.scheduler == "constant_schedule_with_warmup": scheduler = get_constant_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps) elif args.scheduler == "linear_schedule_with_warmup": scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total ) elif args.scheduler == "cosine_schedule_with_warmup": scheduler = get_cosine_schedule_with_warmup( optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total, num_cycles=args.cosine_schedule_num_cycles, ) elif args.scheduler == "cosine_with_hard_restarts_schedule_with_warmup": scheduler = get_cosine_with_hard_restarts_schedule_with_warmup( optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total, num_cycles=args.cosine_schedule_num_cycles, ) elif args.scheduler == "polynomial_decay_schedule_with_warmup": scheduler = get_polynomial_decay_schedule_with_warmup( optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total, lr_end=args.polynomial_decay_schedule_lr_end, power=args.polynomial_decay_schedule_power, ) else: raise ValueError("{} is not a valid scheduler.".format(args.scheduler)) if args.n_gpu > 1: model = torch.nn.DataParallel(model) global_step = 0 training_progress_scores = None tr_loss, logging_loss = 0.0, 0.0 model.zero_grad() train_iterator = trange(int(args.num_train_epochs), desc="Epoch", disable=args.silent, mininterval=0) epoch_number = 0 best_eval_metric = None early_stopping_counter = 0 steps_trained_in_current_epoch = 0 epochs_trained = 0 current_loss = "Initializing" if args.model_name and os.path.exists(args.model_name): try: # set global_step to gobal_step of last saved checkpoint from model path checkpoint_suffix = args.model_name.split("/")[-1].split("-") if len(checkpoint_suffix) > 2: checkpoint_suffix = checkpoint_suffix[1] else: checkpoint_suffix = checkpoint_suffix[-1] global_step = int(checkpoint_suffix) epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps) steps_trained_in_current_epoch = global_step % ( len(train_dataloader) // args.gradient_accumulation_steps ) logger.info(" Continuing training from checkpoint, will skip to saved global_step") logger.info(" Continuing training from epoch %d", epochs_trained) logger.info(" Continuing training from global step %d", global_step) logger.info(" Will skip the first %d steps in the current epoch", steps_trained_in_current_epoch) except ValueError: logger.info(" Starting fine-tuning.") if args.evaluate_during_training: training_progress_scores = self._create_training_progress_scores(multi_label, **kwargs) if args.wandb_project: if not wandb.setup().settings.sweep_id: logger.info(" Initializing WandB run for training.") wandb.init(project=args.wandb_project, config={**asdict(args)}, **args.wandb_kwargs) wandb.watch(self.model) if self.args.fp16: from torch.cuda import amp scaler = amp.GradScaler() for _ in train_iterator: model.train() if epochs_trained > 0: epochs_trained -= 1 continue train_iterator.set_description(f"Epoch {epoch_number + 1} of {args.num_train_epochs}") batch_iterator = tqdm( train_dataloader, desc=f"Running Epoch {epoch_number} of {args.num_train_epochs}", disable=args.silent, mininterval=0, ) for step, batch in enumerate(batch_iterator): if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 continue inputs = self._get_inputs_dict(batch) if self.args.fp16: with amp.autocast(): outputs = model(**inputs) # model outputs are always tuple in pytorch-transformers (see doc) loss = outputs[0] else: outputs = model(**inputs) # model outputs are always tuple in pytorch-transformers (see doc) loss = outputs[0] if args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training current_loss = loss.item() if show_running_loss: batch_iterator.set_description( f"Epochs {epoch_number}/{args.num_train_epochs}. Running Loss: {current_loss:9.4f}" ) if args.gradient_accumulation_steps > 1: loss = loss / args.gradient_accumulation_steps if self.args.fp16: scaler.scale(loss).backward() else: loss.backward() tr_loss += loss.item() if (step + 1) % args.gradient_accumulation_steps == 0: if self.args.fp16: scaler.unscale_(optimizer) if args.optimizer == "AdamW": torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) if self.args.fp16: scaler.step(optimizer) scaler.update() else: optimizer.step() scheduler.step() # Update learning rate schedule model.zero_grad() global_step += 1 if args.logging_steps > 0 and global_step % args.logging_steps == 0: # Log metrics tb_writer.add_scalar("lr", scheduler.get_last_lr()[0], global_step) tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args.logging_steps, global_step) logging_loss = tr_loss if args.wandb_project or self.is_sweeping: wandb.log( { "Training loss": current_loss, "lr": scheduler.get_last_lr()[0], "global_step": global_step, } ) if args.save_steps > 0 and global_step % args.save_steps == 0: # Save model checkpoint output_dir_current = os.path.join(output_dir, "checkpoint-{}".format(global_step)) self.save_model(output_dir_current, optimizer, scheduler, model=model) if args.evaluate_during_training and ( args.evaluate_during_training_steps > 0 and global_step % args.evaluate_during_training_steps == 0 ): # Only evaluate when single GPU otherwise metrics may not average well results, _, _ = self.eval_model( eval_df, verbose=verbose and args.evaluate_during_training_verbose, silent=args.evaluate_during_training_silent, wandb_log=False, **kwargs, ) for key, value in results.items(): tb_writer.add_scalar("eval_{}".format(key), value, global_step) output_dir_current = os.path.join(output_dir, "checkpoint-{}".format(global_step)) if args.save_eval_checkpoints: self.save_model(output_dir_current, optimizer, scheduler, model=model, results=results) training_progress_scores["global_step"].append(global_step) training_progress_scores["train_loss"].append(current_loss) for key in results: training_progress_scores[key].append(results[key]) report = pd.DataFrame(training_progress_scores) report.to_csv( os.path.join(args.output_dir, "training_progress_scores.csv"), index=False, ) if args.wandb_project or self.is_sweeping: wandb.log(self._get_last_metrics(training_progress_scores)) if not best_eval_metric: best_eval_metric = results[args.early_stopping_metric] self.save_model(args.best_model_dir, optimizer, scheduler, model=model, results=results) if best_eval_metric and args.early_stopping_metric_minimize: if best_eval_metric - results[args.early_stopping_metric] > args.early_stopping_delta: best_eval_metric = results[args.early_stopping_metric] self.save_model( args.best_model_dir, optimizer, scheduler, model=model, results=results ) early_stopping_counter = 0 else: if args.use_early_stopping: if early_stopping_counter < args.early_stopping_patience: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args.early_stopping_metric}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args.early_stopping_patience}") else: if verbose: logger.info(f" Patience of {args.early_stopping_patience} steps reached") logger.info(" Training terminated.") train_iterator.close() return ( global_step, tr_loss / global_step if not self.args.evaluate_during_training else training_progress_scores, ) else: if results[args.early_stopping_metric] - best_eval_metric > args.early_stopping_delta: best_eval_metric = results[args.early_stopping_metric] self.save_model( args.best_model_dir, optimizer, scheduler, model=model, results=results ) early_stopping_counter = 0 else: if args.use_early_stopping: if early_stopping_counter < args.early_stopping_patience: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args.early_stopping_metric}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args.early_stopping_patience}") else: if verbose: logger.info(f" Patience of {args.early_stopping_patience} steps reached") logger.info(" Training terminated.") train_iterator.close() return ( global_step, tr_loss / global_step if not self.args.evaluate_during_training else training_progress_scores, ) model.train() epoch_number += 1 output_dir_current = os.path.join(output_dir, "checkpoint-{}-epoch-{}".format(global_step, epoch_number)) if args.save_model_every_epoch or args.evaluate_during_training: os.makedirs(output_dir_current, exist_ok=True) if args.save_model_every_epoch: self.save_model(output_dir_current, optimizer, scheduler, model=model) if args.evaluate_during_training and args.evaluate_each_epoch: results, _, _ = self.eval_model( eval_df, verbose=verbose and args.evaluate_during_training_verbose, silent=args.evaluate_during_training_silent, wandb_log=False, **kwargs, ) self.save_model(output_dir_current, optimizer, scheduler, results=results) training_progress_scores["global_step"].append(global_step) training_progress_scores["train_loss"].append(current_loss) for key in results: training_progress_scores[key].append(results[key]) report = pd.DataFrame(training_progress_scores) report.to_csv(os.path.join(args.output_dir, "training_progress_scores.csv"), index=False) if args.wandb_project or self.is_sweeping: wandb.log(self._get_last_metrics(training_progress_scores)) if not best_eval_metric: best_eval_metric = results[args.early_stopping_metric] self.save_model(args.best_model_dir, optimizer, scheduler, model=model, results=results) if best_eval_metric and args.early_stopping_metric_minimize: if best_eval_metric - results[args.early_stopping_metric] > args.early_stopping_delta: best_eval_metric = results[args.early_stopping_metric] self.save_model(args.best_model_dir, optimizer, scheduler, model=model, results=results) early_stopping_counter = 0 else: if args.use_early_stopping and args.early_stopping_consider_epochs: if early_stopping_counter < args.early_stopping_patience: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args.early_stopping_metric}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args.early_stopping_patience}") else: if verbose: logger.info(f" Patience of {args.early_stopping_patience} steps reached") logger.info(" Training terminated.") train_iterator.close() return ( global_step, tr_loss / global_step if not self.args.evaluate_during_training else training_progress_scores, ) else: if results[args.early_stopping_metric] - best_eval_metric > args.early_stopping_delta: best_eval_metric = results[args.early_stopping_metric] self.save_model(args.best_model_dir, optimizer, scheduler, model=model, results=results) early_stopping_counter = 0 else: if args.use_early_stopping and args.early_stopping_consider_epochs: if early_stopping_counter < args.early_stopping_patience: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args.early_stopping_metric}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args.early_stopping_patience}") else: if verbose: logger.info(f" Patience of {args.early_stopping_patience} steps reached") logger.info(" Training terminated.") train_iterator.close() return ( global_step, tr_loss / global_step if not self.args.evaluate_during_training else training_progress_scores, ) return ( global_step, tr_loss / global_step if not self.args.evaluate_during_training else training_progress_scores, ) def eval_model( self, eval_df, multi_label=False, output_dir=None, verbose=True, silent=False, wandb_log=True, **kwargs ): """ Evaluates the model on eval_df. Saves results to output_dir. Args: eval_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two columns, with the first column containing the text, and the second column containing the label. The model will be evaluated on this Dataframe. output_dir: The directory where model files will be saved. If not given, self.args.output_dir will be used. verbose: If verbose, results will be printed to the console on completion of evaluation. silent: If silent, tqdm progress bars will be hidden. wandb_log: If True, evaluation results will be logged to wandb. **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use). E.g. f1=sklearn.metrics.f1_score. A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Returns: result: Dictionary containing evaluation results. model_outputs: List of model outputs for each row in eval_df wrong_preds: List of InputExample objects corresponding to each incorrect prediction by the model """ # noqa: ignore flake8" if not output_dir: output_dir = self.args.output_dir self._move_model_to_device() result, model_outputs, wrong_preds = self.evaluate( eval_df, output_dir, multi_label=multi_label, verbose=verbose, silent=silent, wandb_log=wandb_log, **kwargs ) self.results.update(result) if verbose: logger.info(self.results) return result, model_outputs, wrong_preds def evaluate( self, eval_df, output_dir, multi_label=False, prefix="", verbose=True, silent=False, wandb_log=True, **kwargs ): """ Evaluates the model on eval_df. Utility function to be used by the eval_model() method. Not intended to be used directly. """ model = self.model args = self.args eval_output_dir = output_dir results = {} if isinstance(eval_df, str) and self.args.lazy_loading: if self.args.model_type == "layoutlm": raise NotImplementedError("Lazy loading is not implemented for LayoutLM models") eval_dataset = LazyClassificationDataset(eval_df, self.tokenizer, self.args) eval_examples = None else: if self.args.lazy_loading: raise ValueError("Input must be given as a path to a file when using lazy loading") if "text" in eval_df.columns and "labels" in eval_df.columns: if self.args.model_type == "layoutlm": eval_examples = [ InputExample(i, text, None, label, x0, y0, x1, y1) for i, (text, label, x0, y0, x1, y1) in enumerate( zip( eval_df["text"].astype(str), eval_df["labels"], eval_df["x0"], eval_df["y0"], eval_df["x1"], eval_df["y1"], ) ) ] else: eval_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(eval_df["text"].astype(str), eval_df["labels"])) ] elif "text_a" in eval_df.columns and "text_b" in eval_df.columns: if self.args.model_type == "layoutlm": raise ValueError("LayoutLM cannot be used with sentence-pair tasks") else: eval_examples = [ InputExample(i, text_a, text_b, label) for i, (text_a, text_b, label) in enumerate( zip(eval_df["text_a"].astype(str), eval_df["text_b"].astype(str), eval_df["labels"]) ) ] else: warnings.warn( "Dataframe headers not specified. Falling back to using column 0 as text and column 1 as labels." ) eval_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(eval_df.iloc[:, 0], eval_df.iloc[:, 1])) ] if args.sliding_window: eval_dataset, window_counts = self.load_and_cache_examples( eval_examples, evaluate=True, verbose=verbose, silent=silent ) else: eval_dataset = self.load_and_cache_examples( eval_examples, evaluate=True, verbose=verbose, silent=silent ) os.makedirs(eval_output_dir, exist_ok=True) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) if args.n_gpu > 1: model = torch.nn.DataParallel(model) eval_loss = 0.0 nb_eval_steps = 0 n_batches = len(eval_dataloader) preds = np.empty((len(eval_dataset), self.num_labels)) if multi_label: out_label_ids = np.empty((len(eval_dataset), self.num_labels)) else: out_label_ids = np.empty((len(eval_dataset))) model.eval() if self.args.fp16: from torch.cuda import amp for i, batch in enumerate(tqdm(eval_dataloader, disable=args.silent or silent, desc="Running Evaluation")): # batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = self._get_inputs_dict(batch) if self.args.fp16: with amp.autocast(): outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] else: outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] if multi_label: logits = logits.sigmoid() if self.args.n_gpu > 1: tmp_eval_loss = tmp_eval_loss.mean() eval_loss += tmp_eval_loss.item() nb_eval_steps += 1 start_index = self.args.eval_batch_size * i end_index = start_index + self.args.eval_batch_size if i != (n_batches - 1) else len(eval_dataset) preds[start_index:end_index] = logits.detach().cpu().numpy() out_label_ids[start_index:end_index] = inputs["labels"].detach().cpu().numpy() # if preds is None: # preds = logits.detach().cpu().numpy() # out_label_ids = inputs["labels"].detach().cpu().numpy() # else: # preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) # out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) eval_loss = eval_loss / nb_eval_steps if args.sliding_window: count = 0 window_ranges = [] for n_windows in window_counts: window_ranges.append([count, count + n_windows]) count += n_windows preds = [preds[window_range[0] : window_range[1]] for window_range in window_ranges] out_label_ids = [ out_label_ids[i] for i in range(len(out_label_ids)) if i in [window[0] for window in window_ranges] ] model_outputs = preds preds = [np.argmax(pred, axis=1) for pred in preds] final_preds = [] for pred_row in preds: val_freqs_desc = Counter(pred_row).most_common() if len(val_freqs_desc) > 1 and val_freqs_desc[0][1] == val_freqs_desc[1][1]: final_preds.append(args.tie_value) else: final_preds.append(val_freqs_desc[0]) preds = np.array(final_preds) elif not multi_label and args.regression is True: preds = np.squeeze(preds) model_outputs = preds else: model_outputs = preds if not multi_label: preds = np.argmax(preds, axis=1) result, wrong = self.compute_metrics(preds, model_outputs, out_label_ids, eval_examples, **kwargs) result["eval_loss"] = eval_loss results.update(result) output_eval_file = os.path.join(eval_output_dir, "eval_results.txt") with open(output_eval_file, "w") as writer: for key in sorted(result.keys()): writer.write("{} = {}\n".format(key, str(result[key]))) if self.args.wandb_project and wandb_log and not multi_label and not self.args.regression: if not wandb.setup().settings.sweep_id: logger.info(" Initializing WandB run for evaluation.") wandb.init(project=args.wandb_project, config={**asdict(args)}, **args.wandb_kwargs) if not args.labels_map: self.args.labels_map = {i: i for i in range(self.num_labels)} labels_list = sorted(list(self.args.labels_map.keys())) inverse_labels_map = {value: key for key, value in self.args.labels_map.items()} truth = [inverse_labels_map[out] for out in out_label_ids] # Confusion Matrix wandb.sklearn.plot_confusion_matrix( truth, [inverse_labels_map[pred] for pred in preds], labels=labels_list, ) if not self.args.sliding_window: # ROC` wandb.log({"roc": wandb.plots.ROC(truth, model_outputs, labels_list)}) # Precision Recall wandb.log({"pr": wandb.plots.precision_recall(truth, model_outputs, labels_list)}) return results, model_outputs, wrong def load_and_cache_examples( self, examples, evaluate=False, no_cache=False, multi_label=False, verbose=True, silent=False ): """ Converts a list of InputExample objects to a TensorDataset containing InputFeatures. Caches the InputFeatures. Utility function for train() and eval() methods. Not intended to be used directly. """ process_count = self.args.process_count tokenizer = self.tokenizer args = self.args if not no_cache: no_cache = args.no_cache if not multi_label and args.regression: output_mode = "regression" else: output_mode = "classification" if not no_cache: os.makedirs(self.args.cache_dir, exist_ok=True) mode = "dev" if evaluate else "train" if args.sliding_window or self.args.model_type == "layoutlm": cached_features_file = os.path.join( args.cache_dir, "cached_{}_{}_{}_{}_{}".format( mode, args.model_type, args.max_seq_length, self.num_labels, len(examples), ), ) if os.path.exists(cached_features_file) and ( (not args.reprocess_input_data and not no_cache) or (mode == "dev" and args.use_cached_eval_features and not no_cache) ): features = torch.load(cached_features_file) if verbose: logger.info(f" Features loaded from cache at {cached_features_file}") else: if verbose: logger.info(" Converting to features started. Cache is not used.") if args.sliding_window: logger.info(" Sliding window enabled") # If labels_map is defined, then labels need to be replaced with ints if self.args.labels_map and not self.args.regression: for example in examples: if multi_label: example.label = [self.args.labels_map[label] for label in example.label] else: example.label = self.args.labels_map[example.label] features = convert_examples_to_features( examples, args.max_seq_length, tokenizer, output_mode, # XLNet has a CLS token at the end cls_token_at_end=bool(args.model_type in ["xlnet"]), cls_token=tokenizer.cls_token, cls_token_segment_id=2 if args.model_type in ["xlnet"] else 0, sep_token=tokenizer.sep_token, # RoBERTa uses an extra separator b/w pairs of sentences, # cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805 sep_token_extra=args.model_type in MODELS_WITH_EXTRA_SEP_TOKEN, # PAD on the left for XLNet pad_on_left=bool(args.model_type in ["xlnet"]), pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0], pad_token_segment_id=4 if args.model_type in ["xlnet"] else 0, process_count=process_count, multi_label=multi_label, silent=args.silent or silent, use_multiprocessing=args.use_multiprocessing_for_evaluation, sliding_window=args.sliding_window, flatten=not evaluate, stride=args.stride, add_prefix_space=args.model_type in MODELS_WITH_ADD_PREFIX_SPACE, # avoid padding in case of single example/online inferencing to decrease execution time pad_to_max_length=bool(len(examples) > 1), args=args, ) if verbose and args.sliding_window: logger.info(f" {len(features)} features created from {len(examples)} samples.") if not no_cache: torch.save(features, cached_features_file) if args.sliding_window and evaluate: features = [ [feature_set] if not isinstance(feature_set, list) else feature_set for feature_set in features ] window_counts = [len(sample) for sample in features] features = [feature for feature_set in features for feature in feature_set] all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long) if self.args.model_type == "layoutlm": all_bboxes = torch.tensor([f.bboxes for f in features], dtype=torch.long) if output_mode == "classification": all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.long) elif output_mode == "regression": all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.float) if self.args.model_type == "layoutlm": dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids, all_bboxes) else: dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids) if args.sliding_window and evaluate: return dataset, window_counts else: return dataset else: dataset = ClassificationDataset( examples, self.tokenizer, self.args, mode=mode, multi_label=multi_label, output_mode=output_mode ) return dataset def compute_metrics(self, preds, model_outputs, labels, eval_examples=None, multi_label=False, **kwargs): """ Computes the evaluation metrics for the model predictions. Args: preds: Model predictions model_outputs: Model outputs labels: Ground truth labels eval_examples: List of examples on which evaluation was performed **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use). E.g. f1=sklearn.metrics.f1_score. A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Returns: result: Dictionary containing evaluation results. For non-binary classification, the dictionary format is: (Matthews correlation coefficient, tp, tn, fp, fn). For binary classification, the dictionary format is: (Matthews correlation coefficient, tp, tn, fp, fn, AUROC, AUPRC). wrong: List of InputExample objects corresponding to each incorrect prediction by the model """ # noqa: ignore flake8" assert len(preds) == len(labels) extra_metrics = {} for metric, func in kwargs.items(): extra_metrics[metric] = func(labels, preds) if multi_label: threshold_values = self.args.threshold if self.args.threshold else 0.5 if isinstance(threshold_values, list): mismatched = labels != [ [self._threshold(pred, threshold_values[i]) for i, pred in enumerate(example)] for example in preds ] else: mismatched = labels != [ [self._threshold(pred, threshold_values) for pred in example] for example in preds ] else: mismatched = labels != preds if eval_examples: wrong = [i for (i, v) in zip(eval_examples, mismatched) if v.any()] else: wrong = ["NA"] if multi_label: label_ranking_score = label_ranking_average_precision_score(labels, preds) return {**{"LRAP": label_ranking_score}, **extra_metrics}, wrong elif self.args.regression: return {**extra_metrics}, wrong mcc = matthews_corrcoef(labels, preds) if self.model.num_labels == 2: tn, fp, fn, tp = confusion_matrix(labels, preds, labels=[0, 1]).ravel() if self.args.sliding_window: return ( {**{"mcc": mcc, "tp": tp, "tn": tn, "fp": fp, "fn": fn}, **extra_metrics}, wrong, ) else: scores = np.array([softmax(element)[1] for element in model_outputs]) fpr, tpr, thresholds = roc_curve(labels, scores) auroc = auc(fpr, tpr) auprc = average_precision_score(labels, scores) return ( { **{"mcc": mcc, "tp": tp, "tn": tn, "fp": fp, "fn": fn, "auroc": auroc, "auprc": auprc}, **extra_metrics, }, wrong, ) else: return {**{"mcc": mcc}, **extra_metrics}, wrong def predict(self, to_predict, multi_label=False): """ Performs predictions on a list of text. Args: to_predict: A python list of text (str) to be sent to the model for prediction. Returns: preds: A python list of the predictions (0 or 1) for each text. model_outputs: A python list of the raw model outputs for each text. """ model = self.model args = self.args eval_loss = 0.0 nb_eval_steps = 0 preds = np.empty((len(to_predict), self.num_labels)) if multi_label: out_label_ids = np.empty((len(to_predict), self.num_labels)) else: out_label_ids = np.empty((len(to_predict))) if not multi_label and self.args.onnx: model_inputs = self.tokenizer.batch_encode_plus( to_predict, return_tensors="pt", padding=True, truncation=True ) for i, (input_ids, attention_mask) in enumerate( zip(model_inputs["input_ids"], model_inputs["attention_mask"]) ): input_ids = input_ids.unsqueeze(0).detach().cpu().numpy() attention_mask = attention_mask.unsqueeze(0).detach().cpu().numpy() inputs_onnx = {"input_ids": input_ids, "attention_mask": attention_mask} # Run the model (None = get all the outputs) output = self.model.run(None, inputs_onnx) preds[i] = output[0] # if preds is None: # preds = output[0] # else: # preds = np.append(preds, output[0], axis=0) model_outputs = preds preds = np.argmax(preds, axis=1) else: self._move_model_to_device() dummy_label = 0 if not self.args.labels_map else next(iter(self.args.labels_map.keys())) if args.n_gpu > 1: model = torch.nn.DataParallel(model) if multi_label: if isinstance(to_predict[0], list): eval_examples = [ InputExample(i, text[0], text[1], [dummy_label for i in range(self.num_labels)]) for i, text in enumerate(to_predict) ] else: eval_examples = [ InputExample(i, text, None, [dummy_label for i in range(self.num_labels)]) for i, text in enumerate(to_predict) ] else: if isinstance(to_predict[0], list): eval_examples = [ InputExample(i, text[0], text[1], dummy_label) for i, text in enumerate(to_predict) ] else: eval_examples = [InputExample(i, text, None, dummy_label) for i, text in enumerate(to_predict)] if args.sliding_window: eval_dataset, window_counts = self.load_and_cache_examples(eval_examples, evaluate=True, no_cache=True) preds = np.empty((len(eval_dataset), self.num_labels)) if multi_label: out_label_ids = np.empty((len(eval_dataset), self.num_labels)) else: out_label_ids = np.empty((len(eval_dataset))) else: eval_dataset = self.load_and_cache_examples( eval_examples, evaluate=True, multi_label=multi_label, no_cache=True ) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) if self.args.fp16: from torch.cuda import amp if self.config.output_hidden_states: model.eval() preds = None out_label_ids = None for i, batch in enumerate(tqdm(eval_dataloader, disable=args.silent, desc="Running Prediction")): # batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = self._get_inputs_dict(batch) if self.args.fp16: with amp.autocast(): outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] else: outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] embedding_outputs, layer_hidden_states = outputs[2][0], outputs[2][1:] if multi_label: logits = logits.sigmoid() if self.args.n_gpu > 1: tmp_eval_loss = tmp_eval_loss.mean() eval_loss += tmp_eval_loss.item() nb_eval_steps += 1 if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = inputs["labels"].detach().cpu().numpy() all_layer_hidden_states = np.array( [state.detach().cpu().numpy() for state in layer_hidden_states] ) all_embedding_outputs = embedding_outputs.detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) all_layer_hidden_states = np.append( all_layer_hidden_states, np.array([state.detach().cpu().numpy() for state in layer_hidden_states]), axis=1, ) all_embedding_outputs = np.append( all_embedding_outputs, embedding_outputs.detach().cpu().numpy(), axis=0 ) else: n_batches = len(eval_dataloader) for i, batch in enumerate(tqdm(eval_dataloader, disable=args.silent)): model.eval() # batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = self._get_inputs_dict(batch) if self.args.fp16: with amp.autocast(): outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] else: outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] if multi_label: logits = logits.sigmoid() if self.args.n_gpu > 1: tmp_eval_loss = tmp_eval_loss.mean() eval_loss += tmp_eval_loss.item() nb_eval_steps += 1 start_index = self.args.eval_batch_size * i end_index = start_index + self.args.eval_batch_size if i != (n_batches - 1) else len(eval_dataset) preds[start_index:end_index] = logits.detach().cpu().numpy() out_label_ids[start_index:end_index] = inputs["labels"].detach().cpu().numpy() # if preds is None: # preds = logits.detach().cpu().numpy() # out_label_ids = inputs["labels"].detach().cpu().numpy() # else: # preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) # out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) eval_loss = eval_loss / nb_eval_steps if args.sliding_window: count = 0 window_ranges = [] for n_windows in window_counts: window_ranges.append([count, count + n_windows]) count += n_windows preds = [preds[window_range[0] : window_range[1]] for window_range in window_ranges] model_outputs = preds preds = [np.argmax(pred, axis=1) for pred in preds] final_preds = [] for pred_row in preds: mode_pred, counts = mode(pred_row) if len(counts) > 1 and counts[0] == counts[1]: final_preds.append(args.tie_value) else: final_preds.append(mode_pred[0]) preds = np.array(final_preds) elif not multi_label and args.regression is True: preds = np.squeeze(preds) model_outputs = preds else: model_outputs = preds if multi_label: if isinstance(args.threshold, list): threshold_values = args.threshold preds = [ [self._threshold(pred, threshold_values[i]) for i, pred in enumerate(example)] for example in preds ] else: preds = [[self._threshold(pred, args.threshold) for pred in example] for example in preds] else: preds = np.argmax(preds, axis=1) if self.args.labels_map and not self.args.regression: inverse_labels_map = {value: key for key, value in self.args.labels_map.items()} preds = [inverse_labels_map[pred] for pred in preds] if self.config.output_hidden_states: return preds, model_outputs, all_embedding_outputs, all_layer_hidden_states else: return preds, model_outputs def convert_to_onnx(self, output_dir=None, set_onnx_arg=True): """Convert the model to ONNX format and save to output_dir Args: output_dir (str, optional): If specified, ONNX model will be saved to output_dir (else args.output_dir will be used). Defaults to None. set_onnx_arg (bool, optional): Updates the model args to set onnx=True. Defaults to True. """ # noqa if not output_dir: output_dir = os.path.join(self.args.output_dir, "onnx") os.makedirs(output_dir, exist_ok=True) if os.listdir(output_dir): raise ValueError( "Output directory ({}) already exists and is not empty." " Output directory for onnx conversion must be empty.".format(output_dir) ) onnx_model_name = os.path.join(output_dir, "onnx_model.onnx") with tempfile.TemporaryDirectory() as temp_dir: self.save_model(output_dir=temp_dir, model=self.model) convert( framework="pt", model=temp_dir, tokenizer=self.tokenizer, output=Path(onnx_model_name), pipeline_name="sentiment-analysis", opset=11, ) self.args.onnx = True self.tokenizer.save_pretrained(output_dir) self.config.save_pretrained(output_dir) self.save_model_args(output_dir) def _threshold(self, x, threshold): if x >= threshold: return 1 return 0 def _move_model_to_device(self): self.model.to(self.device) def _get_inputs_dict(self, batch): if isinstance(batch[0], dict): inputs = {key: value.squeeze(1).to(self.device) for key, value in batch[0].items()} inputs["labels"] = batch[1].to(self.device) else: batch = tuple(t.to(self.device) for t in batch) inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} # XLM, DistilBERT and RoBERTa don't use segment_ids if self.args.model_type != "distilbert": inputs["token_type_ids"] = ( batch[2] if self.args.model_type in ["bert", "xlnet", "albert", "layoutlm"] else None ) if self.args.model_type == "layoutlm": inputs["bbox"] = batch[4] return inputs def _get_last_metrics(self, metric_values): return {metric: values[-1] for metric, values in metric_values.items()} def _create_training_progress_scores(self, multi_label, **kwargs): extra_metrics = {key: [] for key in kwargs} if multi_label: training_progress_scores = { "global_step": [], "LRAP": [], "train_loss": [], "eval_loss": [], **extra_metrics, } else: if self.model.num_labels == 2: if self.args.sliding_window: training_progress_scores = { "global_step": [], "tp": [], "tn": [], "fp": [], "fn": [], "mcc": [], "train_loss": [], "eval_loss": [], **extra_metrics, } else: training_progress_scores = { "global_step": [], "tp": [], "tn": [], "fp": [], "fn": [], "mcc": [], "train_loss": [], "eval_loss": [], "auroc": [], "auprc": [], **extra_metrics, } elif self.model.num_labels == 1: training_progress_scores = { "global_step": [], "train_loss": [], "eval_loss": [], **extra_metrics, } else: training_progress_scores = { "global_step": [], "mcc": [], "train_loss": [], "eval_loss": [], **extra_metrics, } return training_progress_scores def save_model(self, output_dir=None, optimizer=None, scheduler=None, model=None, results=None): if not output_dir: output_dir = self.args.output_dir os.makedirs(output_dir, exist_ok=True) if model and not self.args.no_save: # Take care of distributed/parallel training model_to_save = model.module if hasattr(model, "module") else model model_to_save.save_pretrained(output_dir) self.tokenizer.save_pretrained(output_dir) torch.save(self.args, os.path.join(output_dir, "training_args.bin")) if optimizer and scheduler and self.args.save_optimizer_and_scheduler: torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) self.save_model_args(output_dir) if results: output_eval_file = os.path.join(output_dir, "eval_results.txt") with open(output_eval_file, "w") as writer: for key in sorted(results.keys()): writer.write("{} = {}\n".format(key, str(results[key]))) def save_model_args(self, output_dir): os.makedirs(output_dir, exist_ok=True) self.args.save(output_dir) def _load_model_args(self, input_dir): args = ClassificationArgs() args.load(input_dir) return args def get_named_parameters(self): return [n for n, p in self.model.named_parameters()]
'use strict'; const co = require('co'); const chai = require('chai'); chai.should(); chai.use(require('chai-like')); const utils = require('./utils'); const SocketMock = require('socket-io-mock'); const Context = require('../lib/context'); const Event = require('../lib/event'); const Router = require('../lib'); describe('context', function() { let router; let server; let socket; let event; beforeEach(co.wrap(function*() { server = yield utils.createServer(); socket = new SocketMock(); router = new Router(server); event = new Event('test', ':test'); })); it('check properties', function() { let data = {test: 'example'}; let event = new Event('test', ':test'); let context = new Context(router.options, socket, event, data); context.should.have.property('socket', socket); context.should.have.property('s', socket); context.should.have.property('data', data); }); it('check success', function(done) { let data = {test: 'example'}; let context = new Context(router.options, socket, event, data); socket.socketClient.on(':test:success', (data) => { data.should.be.equal('data'); done(); }); context.success('data'); }); it('check error', function(done) { let data = {test: 'example'}; let context = new Context(router.options, socket, event, data); socket.socketClient.on(':test:error', (data) => { data.should.be.equal('data'); done(); }); context.error('data'); }); it('success should call once', () => { let context = new Context(router.options, socket, event); context.success('data'); chai.expect(() => context.success('err')).to.throw(/call once/); }); it('result callback should call once', () => { let context = new Context(router.options, socket, event); context.success('data'); chai.expect(() => context.error('err')).to.throw(/call once/); }); it('ctx.emit should append postfix in emit()', (done) => { let context = new Context(router.options, socket, event); socket.socketClient.on(':test:fuck', done); context.emit('fuck'); }); it('ctx.broadcast(arg) should append postfix', (done) => { let context = new Context(router.options, socket, event); socket.onEmit('test:fuck', () => done()); context.broadcast('fuck'); }); it('ctx.broadcast(arg) should not append postfix if arg is null', (done) => { let context = new Context(router.options, socket, event); socket.onEmit('test', (data) => { data.should.be.equal('fuuu'); done(); }); context.broadcast(null, 'fuuu'); }); it('to(roomName) should broadcast message to room', (done) => { let context = new Context(router.options, socket, event); socket.onEmit('test:ttt', (data) => { socket.broadcastLog[0].room.should.be.equal('test-room'); data.a.should.be.equal('ggg'); done(); }); context.to('test-room').emit('ttt', {a: 'ggg'}); }); it('to(roomName).emit(path, data) path may be null', (done) => { let context = new Context(router.options, socket, event); socket.onEmit('test', (data) => { socket.broadcastLog[0].room.should.be.equal('test-room'); data.a.should.be.equal('ccc'); done(); }); context.to('test-room').emit(null, {a: 'ccc'}); }); it('test on("before-result") and on("result")', function(done) { let context = new Context(router.options, socket, event); context.emitter.on('before-result', (ctx) => { ctx.result = 'notfuck'; }); context.emitter.on('result', (ctx) => { ctx.result.should.be.equal('notfuck'); done(); }); context.success('fuck'); }); it('on("before-result") should may prevent success()', function(done) { let context = new Context(router.options, socket, event); context.emitter.on('before-result', () => { return Promise.reject({wtf: 'fuck you'}); }); context.emitter.on('result', (ctx) => { ctx.status.should.be.equal('error'); ctx.result.code.should.be.equal(503); done(); }); context.success('fuck'); }); });
import styled from 'styled-components'; import { MIN_WIDTH } from './config'; export const TransCtrl = styled.div` border: 1px dashed #4885ed; position: absolute; width: 100%; height: 100%; z-index: 100; `; export const TranContainer = styled.div` left: 0px; top: 0px; z-index: ${(props) => props.disabled ? 100 : 1000}; min-width: ${MIN_WIDTH}px; min-height: ${({ transScale }) => transScale ? `${MIN_WIDTH / transScale}px` : `${MIN_WIDTH}px`};; position: absolute; &:focus { border: none; outline: none; } `; export const ContrlArrow = styled.div` position: absolute; width: 100%; height: 100%; `; export const Arrow = styled.span` width: 7px; height: 7px; border: 1px solid #4885ED; background-color: rgba(255,255,255,0.8); display: inline-block; position: absolute; z-index: 10000; `; export const ArrowLeft = styled(Arrow)` left: -3px; top: calc(50% - 3px); cursor: w-resize; `; export const ArrowRight = styled(Arrow)` right: -3px; top: calc(50% - 3px); cursor: e-resize; `; export const ArrowTop = styled(Arrow)` top: -3px; left: calc(50% - 3px); cursor: n-resize; `; export const ArrowBottom = styled(Arrow)` bottom: -3px; left: calc(50% - 3px); cursor: s-resize; `; export const ArrowLeftTop = styled(Arrow)` left: -3px; top: -3px; cursor: nw-resize; // border-left: 3px solid #FFF; // border-top: 3px solid #FFF; `; export const ArrowRightTop = styled(Arrow)` right: -3px; top: -3px; cursor: ne-resize; // border-right: 3px solid #FFF; // border-top: 3px solid #FFF; `; export const ArrowBottomLeft = styled(Arrow)` bottom: -3px; left: -3px; cursor: sw-resize; // border-bottom: 3px solid #FFF; // border-left: 3px solid #FFF; `; export const ArrowBottomRight = styled(Arrow)` bottom: -3px; right: -3px; cursor: se-resize; // border-bottom: 3px solid #FFF; // border-right: 3px solid #FFF; `; export const Rotate = styled.p` width: 8px; height: 25px; position: absolute; left: 50%; top: -25px; display: flex; flex-direction: column; align-items: center; `; export const RoDrag = styled.span` display: inline-block; width: 8px; height: 8px; cursor: move; background-color: #FFF; border-radius: 50%; `; export const Line = styled.span` width: 1px; flex: 1; border: 1px dashed #FFF; `;
from keras.models import Model from keras.layers.core import Flatten, Dense, Dropout, Activation, Lambda from keras.layers.recurrent import SimpleRNN from keras.layers.convolutional import Convolution2D from keras.layers.pooling import AveragePooling2D, GlobalAveragePooling2D from keras.layers import Input, merge from keras.layers.normalization import BatchNormalization from keras.regularizers import l2 import keras.backend as K def conv_factory(x, nb_filter, dropout_rate=None, weight_decay=1E-4): """Apply BatchNorm, Relu 3x3Conv2D, optional dropout :param x: Input keras network :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weight decay factor :returns: keras network with b_norm, relu and convolution2d added :rtype: keras network """ x = BatchNormalization(mode=0, axis=1, gamma_regularizer=l2(weight_decay), beta_regularizer=l2(weight_decay))(x) x = Activation('relu')(x) x = Convolution2D(nb_filter, 3, 3, init="he_uniform", border_mode="same", bias=False, W_regularizer=l2(weight_decay))(x) if dropout_rate: x = Dropout(dropout_rate)(x) return x def transition(x, nb_filter, dropout_rate=None, weight_decay=1E-4): """Apply BatchNorm, Relu 1x1Conv2D, optional dropout and Maxpooling2D :param x: keras model :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weight decay factor :returns: model :rtype: keras model, after applying batch_norm, relu-conv, dropout, maxpool """ x = BatchNormalization(mode=0, axis=1, gamma_regularizer=l2(weight_decay), beta_regularizer=l2(weight_decay))(x) x = Activation('relu')(x) x = Convolution2D(nb_filter, 1, 1, init="he_uniform", border_mode="same", bias=False, W_regularizer=l2(weight_decay))(x) if dropout_rate: x = Dropout(dropout_rate)(x) x = AveragePooling2D((2, 2), strides=(2, 2))(x) return x def denseblock(x, nb_layers, nb_filter, growth_rate, dropout_rate=None, weight_decay=1E-4): """Build a denseblock where the output of each conv_factory is fed to subsequent ones :param x: keras model :param nb_layers: int -- the number of layers of conv_ factory to append to the model. :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weight decay factor :returns: keras model with nb_layers of conv_factory appended :rtype: keras model """ list_feat = [x] if K.image_dim_ordering() == "th": concat_axis = 1 elif K.image_dim_ordering() == "tf": concat_axis = -1 for i in range(nb_layers): x = conv_factory(x, growth_rate, dropout_rate, weight_decay) list_feat.append(x) x = merge(list_feat, mode='concat', concat_axis=concat_axis) nb_filter += growth_rate return x, nb_filter def denseblock_altern(x, nb_layers, nb_filter, growth_rate, dropout_rate=None, weight_decay=1E-4): """Build a denseblock where the output of each conv_factory is fed to subsequent ones. (Alternative of a above) :param x: keras model :param nb_layers: int -- the number of layers of conv_ factory to append to the model. :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weight decay factor :returns: keras model with nb_layers of conv_factory appended :rtype: keras model * The main difference between this implementation and the implementation above is that the one above """ if K.image_dim_ordering() == "th": concat_axis = 1 elif K.image_dim_ordering() == "tf": concat_axis = -1 for i in range(nb_layers): merge_tensor = conv_factory(x, growth_rate, dropout_rate, weight_decay) x = merge([merge_tensor, x], mode='concat', concat_axis=concat_axis) nb_filter += growth_rate return x, nb_filter def DenseNet(nb_classes, img_dim, depth, nb_dense_block, growth_rate, nb_filter, dropout_rate=None, weight_decay=1E-4): """ Build the DenseNet model :param nb_classes: int -- number of classes :param img_dim: tuple -- (channels, rows, columns) :param depth: int -- how many layers :param nb_dense_block: int -- number of dense blocks to add to end :param growth_rate: int -- number of filters to add :param nb_filter: int -- number of filters :param dropout_rate: float -- dropout rate :param weight_decay: float -- weight decay :returns: keras model with nb_layers of conv_factory appended :rtype: keras model """ model_input = Input(shape=img_dim) def lambda_output(input_shape): return (input_shape[0], 1, input_shape[1]) Expand = Lambda(lambda x: K.expand_dims(x, 1), output_shape=lambda_output) assert (depth - 4) % 3 == 0, "Depth must be 3 N + 4" # layers in each dense block nb_layers = int((depth - 4) / 3) # Initial convolution x = Convolution2D(nb_filter, 3, 3, init="he_uniform", border_mode="same", name="initial_conv2D", bias=False, W_regularizer=l2(weight_decay))(model_input) list_RNN_input = [] # Add dense blocks for block_idx in range(nb_dense_block - 1): x, nb_filter = denseblock(x, nb_layers, nb_filter, growth_rate, dropout_rate=dropout_rate, weight_decay=weight_decay) # add transition x = transition(x, nb_filter, dropout_rate=dropout_rate, weight_decay=weight_decay) x_RNN = Convolution2D(1, 3, 3, init="he_uniform", border_mode="same", bias=False, subsample=(2 - block_idx, 2 - block_idx), W_regularizer=l2(weight_decay))(x) x_RNN = Flatten()(x_RNN) x_RNN = Expand(x_RNN) list_RNN_input.append(x_RNN) # The last denseblock does not have a transition x, nb_filter = denseblock(x, nb_layers, nb_filter, growth_rate, dropout_rate=dropout_rate, weight_decay=weight_decay) x = BatchNormalization(mode=0, axis=1, gamma_regularizer=l2(weight_decay), beta_regularizer=l2(weight_decay))(x) x = Activation('relu')(x) x_RNN = Convolution2D(1, 3, 3, init="he_uniform", border_mode="same", bias=False, W_regularizer=l2(weight_decay))(x) x_RNN = Flatten()(x_RNN) x_RNN = Expand(x_RNN) list_RNN_input.append(x_RNN) if len(list_RNN_input) > 1: x_RNN = merge(list_RNN_input, mode='concat', concat_axis=1) x_RNN = SimpleRNN(100)(x_RNN) x = GlobalAveragePooling2D()(x) x = merge([x, x_RNN], mode="concat") x = Dense(nb_classes, activation='softmax', W_regularizer=l2(weight_decay), b_regularizer=l2(weight_decay))(x) densenet = Model(input=[model_input], output=[x], name="DenseNet") return densenet
'use strict'; var dbm; var type; var seed; /** * We receive the dbmigrate dependency from dbmigrate initially. * This enables us to not have to rely on NODE_PATH. */ exports.setup = function(options, seedLink) { dbm = options.dbmigrate; type = dbm.dataType; seed = seedLink; }; exports.up = function(db) { return db.createTable('cipher_salts', { id: {type: 'int', primaryKey: true, autoIncrement: true}, kms_cipher_text_blob: {type: 'blob'}, kms_key_id: {type: 'string'}, created_at: {type: 'datetime', notNull: true}, updated_at: {type: 'datetime', notNull: true}, }); }; exports.down = function(db) { return db.dropTable('cipher_salts'); }; exports._meta = { "version": 1 };
import os import json from tempfile import mktemp COMPILER_PATH = './camus-compiler' CAMUS_BIN = os.path.join(COMPILER_PATH, 'camus.exe') def run_command(command): print '>', command return os.WEXITSTATUS(os.system(command)) def generateQueryPipeline(spec_path=None, out_path=None): cmd = '%s -prog-out "%s" "%s"' % (CAMUS_BIN, out_path, spec_path) rc = run_command(cmd) assert rc == 0 return True def compileRules(spec_path=None, ingress_name=None, rules=None, rules_path=None, out_prefix=None): if out_prefix is None: out_prefix = mktemp() if rules_path is None: assert rules is not None rules_path = mktemp() with open(rules_path, 'w') as f: rules_str = rules if not isinstance(rules, basestring): rules_str = '' for r in rules: r = r.strip() if r[-1] != ';': r += ';' rules_str += r + '\n' f.write(rules_str) cmd = '%s -rt-out "%s" -rules "%s" "%s"' % (CAMUS_BIN, out_prefix, rules_path, spec_path) rc = run_command(cmd) assert rc == 0 with open(out_prefix + '_commands.txt', 'r') as f: cli_commands = f.read() with open(out_prefix + '_mcast_groups.txt', 'r') as f: mcast_groups = f.read() with open(out_prefix + '_entries.json', 'r') as f: entries = json.load(f) def prependIngressName(entry): if 'table_name' in entry: entry['table_name'] = '%s.%s' % (ingress_name, entry['table_name']) if 'action_name' in entry: entry['action_name'] = '%s.%s' % (ingress_name, entry['action_name']) return entry entries = filter(lambda e: e is not None, entries) if ingress_name: entries = map(prependIngressName, entries) return dict(cli_commands=cli_commands, mcast_groups=mcast_groups, entries=entries) def parseMcastGroups(mcast_groups_str): """ Parse a string of mcast groups to a dictionary """ groups = {} for l in mcast_groups_str.split('\n'): mgid, ports = l.split(':') groups[int(mgid)] = map(int, ports.split()) return groups class RuntimeConfig: def __init__(self, raw): self.raw = raw def mcastGroups(self): return parseMcastGroups(self.raw['mcast_groups']) def entries(self): return self.raw['entries'] class CamusApp: def __init__(self, spec_path=None, ingress_name=None): self.spec_path = spec_path self.ingress_name = ingress_name def generateQueryPipeline(self, out_path): generateQueryPipeline(self.spec_path, out_path) def compileRules(self, **kwargs): if 'spec_path' not in kwargs: kwargs['spec_path'] = self.spec_path if self.ingress_name and 'ingress_name' not in kwargs: kwargs['ingress_name'] = self.ingress_name config = compileRules(**kwargs) assert config return RuntimeConfig(config) if __name__ == '__main__': generateQueryPipeline('spec.p4', 'camus.p4') rules = ['add_order.shares = 1: fwd(1);', 'add_order.price = 2: fwd(2);', 'add_order.shares = 3 and add_order.price = 4: fwd(3);', 'add_order.shares > 100 and add_order.stock = "BFN": fwd(2);'] camus_runtime = compileRules(spec_path='spec.p4', rules=rules) print parseMcastGroups(camus_runtime['mcast_groups'])
// @flow import type { QueryJob } from "../query-runner" /** * Jobs of this module * - Ensure on bootstrap that all invalid page queries are run and report * when this is done * - Watch for when a page's query is invalidated and re-run it. */ const _ = require(`lodash`) const queue = require(`./query-queue`) const { store, emitter } = require(`../../redux`) let queuedDirtyActions = [] let active = false let running = false const runQueriesForPathnamesQueue = new Set() exports.queueQueryForPathname = pathname => { runQueriesForPathnamesQueue.add(pathname) } // Do initial run of graphql queries during bootstrap. // Afterwards we listen "API_RUNNING_QUEUE_EMPTY" and check // for dirty nodes before running queries. exports.runInitialQueries = async () => { await runQueries() active = true return } const runQueries = async () => { // Find paths dependent on dirty nodes queuedDirtyActions = _.uniq(queuedDirtyActions, a => a.payload.id) const dirtyIds = findDirtyIds(queuedDirtyActions) queuedDirtyActions = [] // Find ids without data dependencies (i.e. no queries have been run for // them before) and run them. const cleanIds = findIdsWithoutDataDependencies() // Construct paths for all queries to run const pathnamesToRun = _.uniq([ ...runQueriesForPathnamesQueue, ...dirtyIds, ...cleanIds, ]) runQueriesForPathnamesQueue.clear() // Run these paths await runQueriesForPathnames(pathnamesToRun) return } emitter.on(`CREATE_NODE`, action => { queuedDirtyActions.push(action) }) emitter.on(`DELETE_NODE`, action => { queuedDirtyActions.push({ payload: action.payload }) }) const runQueuedActions = async () => { if (active && !running) { try { running = true await runQueries() } finally { running = false if (queuedDirtyActions.length > 0) { runQueuedActions() } } } } exports.runQueuedActions = runQueuedActions // Wait until all plugins have finished running (e.g. various // transformer plugins) before running queries so we don't // query things in a 1/2 finished state. emitter.on(`API_RUNNING_QUEUE_EMPTY`, runQueuedActions) let seenIdsWithoutDataDependencies = [] const findIdsWithoutDataDependencies = () => { const state = store.getState() const allTrackedIds = _.uniq( _.flatten( _.concat( _.values(state.componentDataDependencies.nodes), _.values(state.componentDataDependencies.connections) ) ) ) // Get list of paths not already tracked and run the queries for these // paths. const notTrackedIds = _.difference( [ ...Array.from(state.pages.values(), p => p.path), ...[...state.staticQueryComponents.values()].map(c => c.jsonName), ], [...allTrackedIds, ...seenIdsWithoutDataDependencies] ) // Add new IDs to our seen array so we don't keep trying to run queries for them. // Pages without queries can't be tracked. seenIdsWithoutDataDependencies = _.uniq([ ...notTrackedIds, ...seenIdsWithoutDataDependencies, ]) return notTrackedIds } const runQueriesForPathnames = pathnames => { const staticQueries = pathnames.filter(p => p.slice(0, 4) === `sq--`) const pageQueries = pathnames.filter(p => p.slice(0, 4) !== `sq--`) const state = store.getState() staticQueries.forEach(id => { const staticQueryComponent = store.getState().staticQueryComponents.get(id) const queryJob: QueryJob = { id: staticQueryComponent.hash, hash: staticQueryComponent.hash, jsonName: staticQueryComponent.jsonName, query: staticQueryComponent.query, componentPath: staticQueryComponent.componentPath, context: { path: staticQueryComponent.jsonName }, } queue.push(queryJob) }) const pages = state.pages let didNotQueueItems = true pageQueries.forEach(id => { const page = pages.get(id) if (page) { didNotQueueItems = false queue.push( ({ id: page.path, jsonName: page.jsonName, query: store.getState().components.get(page.componentPath).query, isPage: true, componentPath: page.componentPath, context: { ...page, ...page.context, }, }: QueryJob) ) } }) if (didNotQueueItems || !pathnames || pathnames.length === 0) { return Promise.resolve() } return new Promise(resolve => { const onDrain = () => { queue.off(`drain`, onDrain) resolve() } queue.on(`drain`, onDrain) }) } const findDirtyIds = actions => { const state = store.getState() const uniqDirties = _.uniq( actions.reduce((dirtyIds, action) => { const node = action.payload if (!node || !node.id || !node.internal.type) return dirtyIds // Find components that depend on this node so are now dirty. dirtyIds = dirtyIds.concat(state.componentDataDependencies.nodes[node.id]) // Find connections that depend on this node so are now invalid. dirtyIds = dirtyIds.concat( state.componentDataDependencies.connections[node.internal.type] ) return _.compact(dirtyIds) }, []) ) return uniqDirties }
#!/usr/bin/env python from flask import Flask, jsonify, abort, request, make_response import requests import json import os import yaml import signal from app import config, issuer,routes class Controller(Flask): def __init__(self, ENV): print("Initializing " + __name__ + " ...") super().__init__(__name__) issuer.startup_init(ENV) self.ENV = ENV def create_app(ENV): app = Controller(ENV) routes.register_routes(app) wsgi_app = app.wsgi_app return app signal.signal(signal.SIGINT, issuer.signal_issuer_shutdown) signal.signal(signal.SIGTERM, issuer.signal_issuer_shutdown) # Load application settings (environment) config_root = os.environ.get('CONFIG_ROOT', './config') ENV = config.load_settings(config_root=config_root) app = create_app(ENV)
from django.contrib import admin from .models import Bucket, BucketPermission, Credentials, Object @admin.register(Credentials) class CredentialsAdmin(admin.ModelAdmin): list_display = ("username", "app_role_arn") search_fields = ("username",) class PermissionInline(admin.StackedInline): extra = 1 model = BucketPermission @admin.register(Bucket) class BucketAdmin(admin.ModelAdmin): list_display = ("name", "last_synced_at", "auto_sync") list_filter = ("name",) search_fields = ("name",) inlines = [ PermissionInline, ] @admin.register(Object) class ObjectAdmin(admin.ModelAdmin): list_display = ( "display_name", "bucket", "key", "type", "size", "etag", ) list_filter = ("type", "bucket") search_fields = ("key", "bucket") @admin.register(BucketPermission) class BucketPermissionAdmin(admin.ModelAdmin): list_display = ("bucket", "team", "mode")
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6320, generator: {generator}) # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class DatastoresOperations: """DatastoresOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~avs_client.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, resource_group_name: str, private_cloud_name: str, cluster_name: str, **kwargs ) -> AsyncIterable["_models.DatastoreList"]: """List cloud datastores in a private cloud. List cloud datastores in a private cloud. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param private_cloud_name: Name of the private cloud. :type private_cloud_name: str :param cluster_name: Name of the cluster in the private cloud. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DatastoreList or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~avs_client.models.DatastoreList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.DatastoreList"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-01-01-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'privateCloudName': self._serialize.url("private_cloud_name", private_cloud_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('DatastoreList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/clusters/{clusterName}/datastores'} # type: ignore async def get( self, resource_group_name: str, private_cloud_name: str, cluster_name: str, datastore_name: str, **kwargs ) -> "_models.Datastore": """Get a datastore in a private cloud cluster. Get a datastore in a private cloud cluster. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param private_cloud_name: Name of the private cloud. :type private_cloud_name: str :param cluster_name: Name of the cluster in the private cloud. :type cluster_name: str :param datastore_name: Name of the datastore in the private cloud cluster. :type datastore_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Datastore, or the result of cls(response) :rtype: ~avs_client.models.Datastore :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Datastore"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-01-01-preview" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'privateCloudName': self._serialize.url("private_cloud_name", private_cloud_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'datastoreName': self._serialize.url("datastore_name", datastore_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Datastore', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/clusters/{clusterName}/datastores/{datastoreName}'} # type: ignore async def _create_initial( self, resource_group_name: str, private_cloud_name: str, cluster_name: str, datastore_name: str, datastore: "_models.Datastore", **kwargs ) -> "_models.Datastore": cls = kwargs.pop('cls', None) # type: ClsType["_models.Datastore"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-01-01-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'privateCloudName': self._serialize.url("private_cloud_name", private_cloud_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'datastoreName': self._serialize.url("datastore_name", datastore_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(datastore, 'Datastore') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('Datastore', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('Datastore', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/clusters/{clusterName}/datastores/{datastoreName}'} # type: ignore async def begin_create( self, resource_group_name: str, private_cloud_name: str, cluster_name: str, datastore_name: str, datastore: "_models.Datastore", **kwargs ) -> AsyncLROPoller["_models.Datastore"]: """Create a datastore in a private cloud cluster. Create a datastore in a private cloud cluster. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param private_cloud_name: Name of the private cloud. :type private_cloud_name: str :param cluster_name: Name of the cluster in the private cloud. :type cluster_name: str :param datastore_name: Name of the datastore in the private cloud cluster. :type datastore_name: str :param datastore: A datastore in a private cloud cluster. :type datastore: ~avs_client.models.Datastore :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Datastore or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~avs_client.models.Datastore] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Datastore"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( resource_group_name=resource_group_name, private_cloud_name=private_cloud_name, cluster_name=cluster_name, datastore_name=datastore_name, datastore=datastore, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Datastore', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'privateCloudName': self._serialize.url("private_cloud_name", private_cloud_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'datastoreName': self._serialize.url("datastore_name", datastore_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/clusters/{clusterName}/datastores/{datastoreName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, private_cloud_name: str, cluster_name: str, datastore_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-01-01-preview" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'privateCloudName': self._serialize.url("private_cloud_name", private_cloud_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'datastoreName': self._serialize.url("datastore_name", datastore_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/clusters/{clusterName}/datastores/{datastoreName}'} # type: ignore async def begin_delete( self, resource_group_name: str, private_cloud_name: str, cluster_name: str, datastore_name: str, **kwargs ) -> AsyncLROPoller[None]: """Delete a datastore in a private cloud cluster. Delete a datastore in a private cloud cluster. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param private_cloud_name: Name of the private cloud. :type private_cloud_name: str :param cluster_name: Name of the cluster in the private cloud. :type cluster_name: str :param datastore_name: Name of the datastore in the private cloud cluster. :type datastore_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, private_cloud_name=private_cloud_name, cluster_name=cluster_name, datastore_name=datastore_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'privateCloudName': self._serialize.url("private_cloud_name", private_cloud_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'datastoreName': self._serialize.url("datastore_name", datastore_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/clusters/{clusterName}/datastores/{datastoreName}'} # type: ignore
var React = require("react"); var PropTypes = require("prop-types"); var divStyle = { width: "100%", display: "flex" }; var buttonStyle = { flexGrow: 1 }; function RunSimulationButton(props) { return ( <div className="btn-group" style={divStyle}> <button type="button" className={"btn btn-success" + (props.disabled ? " disabled" : "")} style={buttonStyle} onClick={props.onClick}> {props.label} </button> {!props.disabled ? null : <button type="button" className="btn btn-danger" onClick={props.onCancel}> <span>&times;</span> </button>} </div> ); } RunSimulationButton.propTypes = { label: PropTypes.string.isRequired, disabled: PropTypes.bool.isRequired, onClick: PropTypes.func.isRequired, onCancel: PropTypes.func.isRequired }; module.exports = RunSimulationButton;
# -*- coding: utf-8 -*- """ Created on Fri Jul 14 08:14:24 2017 @author: Punyajoy Saha """ import csv import numpy as np import cv2 import sys import os import datetime def add_class(name): label=[] index=0 with open('label.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') count=0 for row in spamreader: label.append(str(row)) count=count+1 name_modi='[\''+name+'\']' if name_modi not in label: file=open('data/label.pbtxt','a') file.write('item {\n id: '+str(count)+'\n name: \''+name+'\'\n}\n\n') with open('label.csv', 'a', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow([name]) index=len(label) else: index=label.index(name_modi) return index #f=open('label.csv','a') #rect = (0,0,0,0) startPoint = False endPoint = False folder_created='training/' if not os.path.exists(folder_created): os.makedirs(folder_created) def on_mouse(event,x,y,flags,params): global rect,startPoint,endPoint # get mouse click if event == cv2.EVENT_LBUTTONDOWN: if startPoint == True and endPoint == True: startPoint = False endPoint = False rect = (0, 0, 0, 0) if startPoint == False: rect = (x, y, 0, 0) startPoint = True elif endPoint == False: rect = (rect[0], rect[1], x, y) endPoint = True cap = cv2.VideoCapture(0) waitTime = 50 rect=[0,0,0,0] #Reading the first frame (grabbed, frame) = cap.read() breadth=5 height=5 while(cap.isOpened()): (grabbed, frame) = cap.read() rect[0]=int(frame.shape[1]/2)-breadth rect[1]=int(frame.shape[0]/2)-height rect[2]=int(frame.shape[1]/2)+breadth rect[3]=int(frame.shape[0]/2)+height cv2.namedWindow('frame') # cv2.setMouseCallback('frame', on_mouse) cv2.rectangle(frame, (rect[0], rect[1]), (rect[2], rect[3]), (255, 0, 255), 2) cv2.imshow('frame',frame) key = cv2.waitKey(waitTime) if key == 27: break elif key == ord("q"): #q is inc breadth if breadth+5<frame.shape[1]: breadth=breadth+5 elif key == ord("w"): #w is dec breadth if breadth-5>0: breadth=breadth-5 elif key == ord("e"): #e is inc height if height+5<frame.shape[0]: height=height+5 elif key == ord("r"): #r is dec height if height-5>0: height=height-5 elif key == ord("s"): now = datetime.datetime.now() filename=folder_created+str(now.year)+str(now.month)+str(now.day)+str(now.hour)+str(now.minute)+str(now.second)+'.jpg' class_ob=input('give the class') index=add_class(class_ob) cv2.imwrite(filename,frame) height=frame.shape[0] width=frame.shape[1] xmin=rect[0] ymin=rect[1] xmax=rect[2] ymax=rect[3] with open('names.csv', 'w') as csvfile: fieldnames = ['file_name', 'class_ob','class_index','height','width','xmin','xmax','ymin','ymax'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'file_name': filename, 'class_ob': class_ob,'class_index':index,}) cap.release() cv2.destroyAllWindows() #add_class('cat') #add_class('cat') #add_class('dog') #add_class('person') #f.close()
#!/usr/bin/python2.5 # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A bare-bones test server for testing cloud policy support. This implements a simple cloud policy test server that can be used to test chrome's device management service client. The policy information is read from the file named device_management in the server's data directory. It contains enforced and recommended policies for the device and user scope, and a list of managed users. The format of the file is JSON. The root dictionary contains a list under the key "managed_users". It contains auth tokens for which the server will claim that the user is managed. The token string "*" indicates that all users are claimed to be managed. Other keys in the root dictionary identify request scopes. Each request scope is described by a dictionary that holds two sub-dictionaries: "mandatory" and "recommended". Both these hold the policy definitions as key/value stores, their format is identical to what the Linux implementation reads from /etc. Example: { "chromeos/device": { "mandatory": { "HomepageLocation" : "http://www.chromium.org" }, "recommended": { "JavascriptEnabled": false, }, }, "managed_users": [ "secret123456" ] } """ import cgi import logging import os import random import re import sys import time import tlslite import tlslite.api import tlslite.utils # The name and availability of the json module varies in python versions. try: import simplejson as json except ImportError: try: import json except ImportError: json = None import asn1der import device_management_backend_pb2 as dm import cloud_policy_pb2 as cp import chrome_device_policy_pb2 as dp # ASN.1 object identifier for PKCS#1/RSA. PKCS1_RSA_OID = '\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01' class RequestHandler(object): """Decodes and handles device management requests from clients. The handler implements all the request parsing and protobuf message decoding and encoding. It calls back into the server to lookup, register, and unregister clients. """ def __init__(self, server, path, headers, request): """Initialize the handler. Args: server: The TestServer object to use for (un)registering clients. path: A string containing the request path and query parameters. headers: A rfc822.Message-like object containing HTTP headers. request: The request data received from the client as a string. """ self._server = server self._path = path self._headers = headers self._request = request self._params = None def GetUniqueParam(self, name): """Extracts a unique query parameter from the request. Args: name: Names the parameter to fetch. Returns: The parameter value or None if the parameter doesn't exist or is not unique. """ if not self._params: self._params = cgi.parse_qs(self._path[self._path.find('?') + 1:]) param_list = self._params.get(name, []) if len(param_list) == 1: return param_list[0] return None; def HandleRequest(self): """Handles a request. Parses the data supplied at construction time and returns a pair indicating http status code and response data to be sent back to the client. Returns: A tuple of HTTP status code and response data to send to the client. """ rmsg = dm.DeviceManagementRequest() rmsg.ParseFromString(self._request) logging.debug('auth -> ' + self._headers.getheader('Authorization', '')) logging.debug('deviceid -> ' + self.GetUniqueParam('deviceid')) self.DumpMessage('Request', rmsg) request_type = self.GetUniqueParam('request') # Check server side requirements, as defined in # device_management_backend.proto. if (self.GetUniqueParam('devicetype') != '2' or self.GetUniqueParam('apptype') != 'Chrome' or (request_type != 'ping' and len(self.GetUniqueParam('deviceid')) >= 64) or len(self.GetUniqueParam('agent')) >= 64): return (400, 'Invalid request parameter') if request_type == 'register': return self.ProcessRegister(rmsg.register_request) elif request_type == 'unregister': return self.ProcessUnregister(rmsg.unregister_request) elif request_type == 'policy' or request_type == 'ping': return self.ProcessPolicy(rmsg.policy_request, request_type) else: return (400, 'Invalid request parameter') def CheckGoogleLogin(self): """Extracts the GoogleLogin auth token from the HTTP request, and returns it. Returns None if the token is not present. """ match = re.match('GoogleLogin auth=(\\w+)', self._headers.getheader('Authorization', '')) if not match: return None return match.group(1) def ProcessRegister(self, msg): """Handles a register request. Checks the query for authorization and device identifier, registers the device with the server and constructs a response. Args: msg: The DeviceRegisterRequest message received from the client. Returns: A tuple of HTTP status code and response data to send to the client. """ # Check the auth token and device ID. if not self.CheckGoogleLogin(): return (403, 'No authorization') device_id = self.GetUniqueParam('deviceid') if not device_id: return (400, 'Missing device identifier') token_info = self._server.RegisterDevice(device_id, msg.machine_id, msg.type) # Send back the reply. response = dm.DeviceManagementResponse() response.register_response.device_management_token = ( token_info['device_token']) response.register_response.machine_name = token_info['machine_name'] self.DumpMessage('Response', response) return (200, response.SerializeToString()) def ProcessUnregister(self, msg): """Handles a register request. Checks for authorization, unregisters the device and constructs the response. Args: msg: The DeviceUnregisterRequest message received from the client. Returns: A tuple of HTTP status code and response data to send to the client. """ # Check the management token. token, response = self.CheckToken(); if not token: return response # Unregister the device. self._server.UnregisterDevice(token); # Prepare and send the response. response = dm.DeviceManagementResponse() response.unregister_response.CopyFrom(dm.DeviceUnregisterResponse()) self.DumpMessage('Response', response) return (200, response.SerializeToString()) def ProcessInitialPolicy(self, msg): """Handles a 'preregister policy' request. Queries the list of managed users and responds the client if their user is managed or not. Args: msg: The PolicyFetchRequest message received from the client. Returns: A tuple of HTTP status code and response data to send to the client. """ # Check the GAIA token. auth = self.CheckGoogleLogin() if not auth: return (403, 'No authorization') chrome_initial_settings = dm.ChromeInitialSettingsProto() if ('*' in self._server.policy['managed_users'] or auth in self._server.policy['managed_users']): chrome_initial_settings.enrollment_provision = ( dm.ChromeInitialSettingsProto.MANAGED); else: chrome_initial_settings.enrollment_provision = ( dm.ChromeInitialSettingsProto.UNMANAGED); policy_data = dm.PolicyData() policy_data.policy_type = msg.policy_type policy_data.policy_value = chrome_initial_settings.SerializeToString() # Prepare and send the response. response = dm.DeviceManagementResponse() fetch_response = response.policy_response.response.add() fetch_response.policy_data = ( policy_data.SerializeToString()) self.DumpMessage('Response', response) return (200, response.SerializeToString()) def ProcessDevicePolicy(self, msg): """Handles a policy request that uses the deprecated protcol. TODO(gfeher): Remove this when we certainly don't need it. Checks for authorization, encodes the policy into protobuf representation and constructs the response. Args: msg: The DevicePolicyRequest message received from the client. Returns: A tuple of HTTP status code and response data to send to the client. """ # Check the management token. token, response = self.CheckToken() if not token: return response # Stuff the policy dictionary into a response message and send it back. response = dm.DeviceManagementResponse() response.policy_response.CopyFrom(dm.DevicePolicyResponse()) # Respond only if the client requested policy for the cros/device scope, # since that's where chrome policy is supposed to live in. if msg.policy_scope == 'chromeos/device': policy = self._server.policy['google/chromeos/user']['mandatory'] setting = response.policy_response.setting.add() setting.policy_key = 'chrome-policy' policy_value = dm.GenericSetting() for (key, value) in policy.iteritems(): entry = policy_value.named_value.add() entry.name = key entry_value = dm.GenericValue() if isinstance(value, bool): entry_value.value_type = dm.GenericValue.VALUE_TYPE_BOOL entry_value.bool_value = value elif isinstance(value, int): entry_value.value_type = dm.GenericValue.VALUE_TYPE_INT64 entry_value.int64_value = value elif isinstance(value, str) or isinstance(value, unicode): entry_value.value_type = dm.GenericValue.VALUE_TYPE_STRING entry_value.string_value = value elif isinstance(value, list): entry_value.value_type = dm.GenericValue.VALUE_TYPE_STRING_ARRAY for list_entry in value: entry_value.string_array.append(str(list_entry)) entry.value.CopyFrom(entry_value) setting.policy_value.CopyFrom(policy_value) self.DumpMessage('Response', response) return (200, response.SerializeToString()) def ProcessPolicy(self, msg, request_type): """Handles a policy request. Checks for authorization, encodes the policy into protobuf representation and constructs the response. Args: msg: The DevicePolicyRequest message received from the client. Returns: A tuple of HTTP status code and response data to send to the client. """ if msg.request: for request in msg.request: if request.policy_type == 'google/chromeos/unregistered_user': if request_type != 'ping': return (400, 'Invalid request type') return self.ProcessInitialPolicy(request) elif (request.policy_type in ('google/chromeos/user', 'google/chromeos/device')): if request_type != 'policy': return (400, 'Invalid request type') return self.ProcessCloudPolicy(request) else: return (400, 'Invalid policy_type') else: return self.ProcessDevicePolicy(msg) def SetProtobufMessageField(self, group_message, field, field_value): '''Sets a field in a protobuf message. Args: group_message: The protobuf message. field: The field of the message to set, it shuold be a member of group_message.DESCRIPTOR.fields. field_value: The value to set. ''' if field.label == field.LABEL_REPEATED: assert type(field_value) == list entries = group_message.__getattribute__(field.name) for list_item in field_value: entries.append(list_item) return elif field.type == field.TYPE_BOOL: assert type(field_value) == bool elif field.type == field.TYPE_STRING: assert type(field_value) == str or type(field_value) == unicode elif field.type == field.TYPE_INT64: assert type(field_value) == int elif (field.type == field.TYPE_MESSAGE and field.message_type.name == 'StringList'): assert type(field_value) == list entries = group_message.__getattribute__(field.name).entries for list_item in field_value: entries.append(list_item) return else: raise Exception('Unknown field type %s' % field.type) group_message.__setattr__(field.name, field_value) def GatherDevicePolicySettings(self, settings, policies): '''Copies all the policies from a dictionary into a protobuf of type CloudDeviceSettingsProto. Args: settings: The destination ChromeDeviceSettingsProto protobuf. policies: The source dictionary containing policies in JSON format. ''' for group in settings.DESCRIPTOR.fields: # Create protobuf message for group. group_message = eval('dp.' + group.message_type.name + '()') # Indicates if at least one field was set in |group_message|. got_fields = False # Iterate over fields of the message and feed them from the # policy config file. for field in group_message.DESCRIPTOR.fields: field_value = None if field.name in policies: got_fields = True field_value = policies[field.name] self.SetProtobufMessageField(group_message, field, field_value) if got_fields: settings.__getattribute__(group.name).CopyFrom(group_message) def GatherUserPolicySettings(self, settings, policies): '''Copies all the policies from a dictionary into a protobuf of type CloudPolicySettings. Args: settings: The destination: a CloudPolicySettings protobuf. policies: The source: a dictionary containing policies under keys 'recommended' and 'mandatory'. ''' for group in settings.DESCRIPTOR.fields: # Create protobuf message for group. group_message = eval('cp.' + group.message_type.name + '()') # We assume that this policy group will be recommended, and only switch # it to mandatory if at least one of its members is mandatory. group_message.policy_options.mode = cp.PolicyOptions.RECOMMENDED # Indicates if at least one field was set in |group_message|. got_fields = False # Iterate over fields of the message and feed them from the # policy config file. for field in group_message.DESCRIPTOR.fields: field_value = None if field.name in policies['mandatory']: group_message.policy_options.mode = cp.PolicyOptions.MANDATORY field_value = policies['mandatory'][field.name] elif field.name in policies['recommended']: field_value = policies['recommended'][field.name] if field_value != None: got_fields = True self.SetProtobufMessageField(group_message, field, field_value) if got_fields: settings.__getattribute__(group.name).CopyFrom(group_message) def ProcessCloudPolicy(self, msg): """Handles a cloud policy request. (New protocol for policy requests.) Checks for authorization, encodes the policy into protobuf representation, signs it and constructs the repsonse. Args: msg: The CloudPolicyRequest message received from the client. Returns: A tuple of HTTP status code and response data to send to the client. """ token_info, error = self.CheckToken() if not token_info: return error # Response is only given if the scope is specified in the config file. # Normally 'google/chromeos/device' and 'google/chromeos/user' should be # accepted. policy_value = '' if (msg.policy_type in token_info['allowed_policy_types'] and msg.policy_type in self._server.policy): if msg.policy_type == 'google/chromeos/user': settings = cp.CloudPolicySettings() self.GatherUserPolicySettings(settings, self._server.policy[msg.policy_type]) policy_value = settings.SerializeToString() elif msg.policy_type == 'google/chromeos/device': settings = dp.ChromeDeviceSettingsProto() self.GatherDevicePolicySettings(settings, self._server.policy[msg.policy_type]) policy_value = settings.SerializeToString() # Figure out the key we want to use. If multiple keys are configured, the # server will rotate through them in a round-robin fashion. signing_key = None req_key = None key_version = 1 nkeys = len(self._server.keys) if msg.signature_type == dm.PolicyFetchRequest.SHA1_RSA and nkeys > 0: if msg.public_key_version in range(1, nkeys + 1): # requested key exists, use for signing and rotate. req_key = self._server.keys[msg.public_key_version - 1]['private_key'] key_version = (msg.public_key_version % nkeys) + 1 signing_key = self._server.keys[key_version - 1] # Fill the policy data protobuf. policy_data = dm.PolicyData() policy_data.policy_type = msg.policy_type policy_data.timestamp = int(time.time() * 1000) policy_data.request_token = token_info['device_token']; policy_data.policy_value = policy_value policy_data.machine_name = token_info['machine_name'] if signing_key: policy_data.public_key_version = key_version policy_data.username = self._server.username policy_data.device_id = token_info['device_id'] signed_data = policy_data.SerializeToString() response = dm.DeviceManagementResponse() fetch_response = response.policy_response.response.add() fetch_response.policy_data = signed_data if signing_key: fetch_response.policy_data_signature = ( signing_key['private_key'].hashAndSign(signed_data).tostring()) if msg.public_key_version != key_version: fetch_response.new_public_key = signing_key['public_key'] if req_key: fetch_response.new_public_key_signature = ( req_key.hashAndSign(fetch_response.new_public_key).tostring()) self.DumpMessage('Response', response) return (200, response.SerializeToString()) def CheckToken(self): """Helper for checking whether the client supplied a valid DM token. Extracts the token from the request and passed to the server in order to look up the client. Returns: A pair of token information record and error response. If the first element is None, then the second contains an error code to send back to the client. Otherwise the first element is the same structure that is returned by LookupToken(). """ error = None dmtoken = None request_device_id = self.GetUniqueParam('deviceid') match = re.match('GoogleDMToken token=(\\w+)', self._headers.getheader('Authorization', '')) if match: dmtoken = match.group(1) if not dmtoken: error = dm.DeviceManagementResponse.DEVICE_MANAGEMENT_TOKEN_INVALID else: token_info = self._server.LookupToken(dmtoken) if (not token_info or not request_device_id or token_info['device_id'] != request_device_id): error = dm.DeviceManagementResponse.DEVICE_NOT_FOUND else: return (token_info, None) response = dm.DeviceManagementResponse() response.error = error self.DumpMessage('Response', response) return (None, (200, response.SerializeToString())) def DumpMessage(self, label, msg): """Helper for logging an ASCII dump of a protobuf message.""" logging.debug('%s\n%s' % (label, str(msg))) class TestServer(object): """Handles requests and keeps global service state.""" def __init__(self, policy_path, private_key_paths, policy_user): """Initializes the server. Args: policy_path: Names the file to read JSON-formatted policy from. private_key_paths: List of paths to read private keys from. """ self._registered_tokens = {} self.policy = {} # There is no way to for the testserver to know the user name belonging to # the GAIA auth token we received (short of actually talking to GAIA). To # address this, we have a command line parameter to set the username that # the server should report to the client. self.username = policy_user if json is None: print 'No JSON module, cannot parse policy information' else : try: self.policy = json.loads(open(policy_path).read()) except IOError: print 'Failed to load policy from %s' % policy_path self.keys = [] if private_key_paths: # Load specified keys from the filesystem. for key_path in private_key_paths: try: key = tlslite.api.parsePEMKey(open(key_path).read(), private=True) except IOError: print 'Failed to load private key from %s' % key_path continue assert key != None self.keys.append({ 'private_key' : key }) else: # Generate a key if none were specified. key = tlslite.api.generateRSAKey(1024) assert key != None self.keys.append({ 'private_key' : key }) # Derive the public keys from the loaded private keys. for entry in self.keys: key = entry['private_key'] algorithm = asn1der.Sequence( [ asn1der.Data(asn1der.OBJECT_IDENTIFIER, PKCS1_RSA_OID), asn1der.Data(asn1der.NULL, '') ]) rsa_pubkey = asn1der.Sequence([ asn1der.Integer(key.n), asn1der.Integer(key.e) ]) pubkey = asn1der.Sequence([ algorithm, asn1der.Bitstring(rsa_pubkey) ]) entry['public_key'] = pubkey; def HandleRequest(self, path, headers, request): """Handles a request. Args: path: The request path and query parameters received from the client. headers: A rfc822.Message-like object containing HTTP headers. request: The request data received from the client as a string. Returns: A pair of HTTP status code and response data to send to the client. """ handler = RequestHandler(self, path, headers, request) return handler.HandleRequest() def RegisterDevice(self, device_id, machine_id, type): """Registers a device or user and generates a DM token for it. Args: device_id: The device identifier provided by the client. Returns: The newly generated device token for the device. """ dmtoken_chars = [] while len(dmtoken_chars) < 32: dmtoken_chars.append(random.choice('0123456789abcdef')) dmtoken = ''.join(dmtoken_chars) allowed_policy_types = { dm.DeviceRegisterRequest.USER: ['google/chromeos/user'], dm.DeviceRegisterRequest.DEVICE: ['google/chromeos/device'], dm.DeviceRegisterRequest.TT: ['google/chromeos/user'], } self._registered_tokens[dmtoken] = { 'device_id': device_id, 'device_token': dmtoken, 'allowed_policy_types': allowed_policy_types[type], 'machine_name': 'chromeos-' + machine_id, } return self._registered_tokens[dmtoken] def LookupToken(self, dmtoken): """Looks up a device or a user by DM token. Args: dmtoken: The device management token provided by the client. Returns: A dictionary with information about a device or user that is registered by dmtoken, or None if the token is not found. """ return self._registered_tokens.get(dmtoken, None) def UnregisterDevice(self, dmtoken): """Unregisters a device identified by the given DM token. Args: dmtoken: The device management token provided by the client. """ if dmtoken in self._registered_tokens.keys(): del self._registered_tokens[dmtoken]
jQuery(function(){ jQuery('#camera_wrap_4').camera({ height: 'auto', loader: 'bar', pagination: false, thumbnails: true, hover: false, opacityOnGrid: false, imagePath: window.location.protocol+'//'+window.location.host+'/ecaglobal/global_views/assets/images' }); });
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Dispatcher as DispatcherType} from 'react-reconciler/src/ReactFiberHooks'; import type {ThreadID} from './ReactThreadIDAllocator'; import type {ReactContext} from 'shared/ReactTypes'; import {validateContextBounds} from './ReactPartialRendererContext'; import invariant from 'shared/invariant'; import warning from 'shared/warning'; import is from 'shared/objectIs'; type BasicStateAction<S> = (S => S) | S; type Dispatch<A> = A => void; type Update<A> = { action: A, next: Update<A> | null, }; type UpdateQueue<A> = { last: Update<A> | null, dispatch: any, }; type Hook = { memoizedState: any, queue: UpdateQueue<any> | null, next: Hook | null, }; let currentlyRenderingComponent: Object | null = null; let firstWorkInProgressHook: Hook | null = null; let workInProgressHook: Hook | null = null; // Whether the work-in-progress hook is a re-rendered hook let isReRender: boolean = false; // Whether an update was scheduled during the currently executing render pass. let didScheduleRenderPhaseUpdate: boolean = false; // Lazily created map of render-phase updates let renderPhaseUpdates: Map<UpdateQueue<any>, Update<any>> | null = null; // Counter to prevent infinite loops. let numberOfReRenders: number = 0; const RE_RENDER_LIMIT = 25; let isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook let currentHookNameInDev: ?string; function resolveCurrentlyRenderingComponent(): Object { invariant( currentlyRenderingComponent !== null, 'Hooks can only be called inside the body of a function component.', ); if (__DEV__) { warning( !isInHookUserCodeInDev, 'Hooks can only be called inside the body of a function component. ' + 'Do not call Hooks inside other Hooks. For more information, see ' + 'https://fb.me/rules-of-hooks', ); } return currentlyRenderingComponent; } function areHookInputsEqual( nextDeps: Array<mixed>, prevDeps: Array<mixed> | null, ) { if (prevDeps === null) { if (__DEV__) { warning( false, '%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev, ); } return false; } if (__DEV__) { // Don't bother comparing lengths in prod because these arrays should be // passed inline. if (nextDeps.length !== prevDeps.length) { warning( false, 'The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, `[${nextDeps.join(', ')}]`, `[${prevDeps.join(', ')}]`, ); } } for (let i = 0; i < prevDeps.length && i < nextDeps.length; i++) { if (is(nextDeps[i], prevDeps[i])) { continue; } return false; } return true; } function createHook(): Hook { if (numberOfReRenders > 0) { invariant(false, 'Rendered more hooks than during the previous render'); } return { memoizedState: null, queue: null, next: null, }; } function createWorkInProgressHook(): Hook { if (workInProgressHook === null) { // This is the first hook in the list if (firstWorkInProgressHook === null) { isReRender = false; firstWorkInProgressHook = workInProgressHook = createHook(); } else { // There's already a work-in-progress. Reuse it. isReRender = true; workInProgressHook = firstWorkInProgressHook; } } else { if (workInProgressHook.next === null) { isReRender = false; // Append to the end of the list workInProgressHook = workInProgressHook.next = createHook(); } else { // There's already a work-in-progress. Reuse it. isReRender = true; workInProgressHook = workInProgressHook.next; } } return workInProgressHook; } export function prepareToUseHooks(componentIdentity: Object): void { currentlyRenderingComponent = componentIdentity; if (__DEV__) { isInHookUserCodeInDev = false; } // The following should have already been reset // didScheduleRenderPhaseUpdate = false; // firstWorkInProgressHook = null; // numberOfReRenders = 0; // renderPhaseUpdates = null; // workInProgressHook = null; } export function finishHooks( Component: any, props: any, children: any, refOrContext: any, ): any { // This must be called after every function component to prevent hooks from // being used in classes. while (didScheduleRenderPhaseUpdate) { // Updates were scheduled during the render phase. They are stored in // the `renderPhaseUpdates` map. Call the component again, reusing the // work-in-progress hooks and applying the additional updates on top. Keep // restarting until no more updates are scheduled. didScheduleRenderPhaseUpdate = false; numberOfReRenders += 1; // Start over from the beginning of the list workInProgressHook = null; children = Component(props, refOrContext); } currentlyRenderingComponent = null; firstWorkInProgressHook = null; numberOfReRenders = 0; renderPhaseUpdates = null; workInProgressHook = null; if (__DEV__) { isInHookUserCodeInDev = false; } // These were reset above // currentlyRenderingComponent = null; // didScheduleRenderPhaseUpdate = false; // firstWorkInProgressHook = null; // numberOfReRenders = 0; // renderPhaseUpdates = null; // workInProgressHook = null; return children; } function readContext<T>( context: ReactContext<T>, observedBits: void | number | boolean, ): T { let threadID = currentThreadID; validateContextBounds(context, threadID); if (__DEV__) { warning( !isInHookUserCodeInDev, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().', ); } return context[threadID]; } function useContext<T>( context: ReactContext<T>, observedBits: void | number | boolean, ): T { if (__DEV__) { currentHookNameInDev = 'useContext'; } resolveCurrentlyRenderingComponent(); let threadID = currentThreadID; validateContextBounds(context, threadID); return context[threadID]; } function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S { return typeof action === 'function' ? action(state) : action; } export function useState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { if (__DEV__) { currentHookNameInDev = 'useState'; } return useReducer( basicStateReducer, // useReducer has a special case to support lazy useState initializers (initialState: any), ); } export function useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { if (__DEV__) { if (reducer !== basicStateReducer) { currentHookNameInDev = 'useReducer'; } } currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); workInProgressHook = createWorkInProgressHook(); if (isReRender) { // This is a re-render. Apply the new render phase updates to the previous // current hook. const queue: UpdateQueue<A> = (workInProgressHook.queue: any); const dispatch: Dispatch<A> = (queue.dispatch: any); if (renderPhaseUpdates !== null) { // Render phase updates are stored in a map of queue -> linked list const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); if (firstRenderPhaseUpdate !== undefined) { renderPhaseUpdates.delete(queue); let newState = workInProgressHook.memoizedState; let update = firstRenderPhaseUpdate; do { // Process this render phase update. We don't have to check the // priority because it will always be the same as the current // render's. const action = update.action; if (__DEV__) { isInHookUserCodeInDev = true; } newState = reducer(newState, action); if (__DEV__) { isInHookUserCodeInDev = false; } update = update.next; } while (update !== null); workInProgressHook.memoizedState = newState; return [newState, dispatch]; } } return [workInProgressHook.memoizedState, dispatch]; } else { if (__DEV__) { isInHookUserCodeInDev = true; } let initialState; if (reducer === basicStateReducer) { // Special case for `useState`. initialState = typeof initialArg === 'function' ? ((initialArg: any): () => S)() : ((initialArg: any): S); } else { initialState = init !== undefined ? init(initialArg) : ((initialArg: any): S); } if (__DEV__) { isInHookUserCodeInDev = false; } workInProgressHook.memoizedState = initialState; const queue: UpdateQueue<A> = (workInProgressHook.queue = { last: null, dispatch: null, }); const dispatch: Dispatch<A> = (queue.dispatch = (dispatchAction.bind( null, currentlyRenderingComponent, queue, ): any)); return [workInProgressHook.memoizedState, dispatch]; } } function useMemo<T>(nextCreate: () => T, deps: Array<mixed> | void | null): T { currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); workInProgressHook = createWorkInProgressHook(); const nextDeps = deps === undefined ? null : deps; if (workInProgressHook !== null) { const prevState = workInProgressHook.memoizedState; if (prevState !== null) { if (nextDeps !== null) { const prevDeps = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } } if (__DEV__) { isInHookUserCodeInDev = true; } const nextValue = nextCreate(); if (__DEV__) { isInHookUserCodeInDev = false; } workInProgressHook.memoizedState = [nextValue, nextDeps]; return nextValue; } function useRef<T>(initialValue: T): {current: T} { currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); workInProgressHook = createWorkInProgressHook(); const previousRef = workInProgressHook.memoizedState; if (previousRef === null) { const ref = {current: initialValue}; if (__DEV__) { Object.seal(ref); } workInProgressHook.memoizedState = ref; return ref; } else { return previousRef; } } export function useLayoutEffect( create: () => mixed, deps: Array<mixed> | void | null, ) { if (__DEV__) { currentHookNameInDev = 'useLayoutEffect'; } warning( false, 'useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client.', ); } function dispatchAction<A>( componentIdentity: Object, queue: UpdateQueue<A>, action: A, ) { invariant( numberOfReRenders < RE_RENDER_LIMIT, 'Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.', ); if (componentIdentity === currentlyRenderingComponent) { // This is a render phase update. Stash it in a lazily-created map of // queue -> linked list of updates. After this render pass, we'll restart // and apply the stashed updates on top of the work-in-progress hook. didScheduleRenderPhaseUpdate = true; const update: Update<A> = { action, next: null, }; if (renderPhaseUpdates === null) { renderPhaseUpdates = new Map(); } const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); if (firstRenderPhaseUpdate === undefined) { renderPhaseUpdates.set(queue, update); } else { // Append the update to the end of the list. let lastRenderPhaseUpdate = firstRenderPhaseUpdate; while (lastRenderPhaseUpdate.next !== null) { lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; } lastRenderPhaseUpdate.next = update; } } else { // This means an update has happened after the function component has // returned. On the server this is a no-op. In React Fiber, the update // would be scheduled for a future render. } } export function useCallback<T>( callback: T, deps: Array<mixed> | void | null, ): T { // Callbacks are passed as they are in the server environment. return callback; } function noop(): void {} export let currentThreadID: ThreadID = 0; export function setCurrentThreadID(threadID: ThreadID) { currentThreadID = threadID; } export const Dispatcher: DispatcherType = { readContext, useContext, useMemo, useReducer, useRef, useState, useLayoutEffect, useCallback, // useImperativeHandle is not run in the server environment useImperativeHandle: noop, // Effects are not run in the server environment. useEffect: noop, // Debugging effect useDebugValue: noop, };
/* eslint-disable */module.exports={languageData:{"plurals":function(n,ord){var s=String(n).split("."),i=s[0];if(ord)return"other";return i==0||i==1?"one":"other"}},messages:{"% of parent":"% de origem","% of total":"% do total","(Events)":"(Eventos)","(Extension)":"(Extens\xE3o)","(already installed)":"(j\xE1 instalado)","(auto)":"(auto)","(on the desktop app only)":"(s\xF3 na app para desktop)","(or paste actions)":"(ou a\xE7\xF5es de colar)","(or paste conditions)":"(ou condi\xE7\xF5es de colar)","* (multiply by)":"* (multiplicar por)","+ (add)":"+ (adicionar)",", objects /*{parameterObjects}*/":function(a){return[", objetos /*",a("parameterObjects"),"*/"]},"- (subtract)":"- (subtrair)","/ (divide by)":"/ (dividir por)","/* Click here to choose objects to pass to JavaScript */":"/* Clique aqui para escolher que objetos passar para JavaScript */","1st secondary editor":"1\xBA editor secundario","2nd secondary editor":"2\xBA editor secundario","3rd secondary editor":"3\xBA editor secundario","8-bit Space Shooter":"Atirador do espa\xE7o de 8 bits","< (less than)":"< (menor que)","<0>For every child in<1><2/>{0}</1>, store the child in variable<3><4/>{1}</3>, the child name in<5><6/>{2}</5>and do:</0>":function(a){return["<0>Para cada crian\xE7a em<1><2/>",a("0"),"</1>, armazene a crian\xE7a na vari\xE1vel<3><4/>",a("1"),"</3>, o nome da crian\xE7a em<5><6/>",a("2"),"</5>e fa\xE7a:</0>"]},"<Create a New Extension>":"<Criar uma nova extens\xE3o>","<Enter comment>":"Introduza um Coment\xE1rio<Enter comment>","<Enter group name>":"<Inserir nome do grupo>","<Enter the name of external events>":"Inserir o nome dos eventos externos<Enter the name of external events>","<Select a variable>":"Seleciona uma vari\xE1vel<Select a variable>","<Select a variable> (optional)":"<Select a variable> (opcional)","= (equal to)":"= (igual a)","= (set to)":"= (definir como)","> (greater than)":"> (maior que)","A beautiful, retro side-scrolling shooter where you must defeat incoming enemies with your mecha transforming spaceship. Huge boss included!":"Um bonito, atirador retro de desloca\xE7\xE3o lateral onde voc\xEA deve derrotar inimigos que chegam com sua nave espacial mec\xE2nica transformadora. Enorme chefe inclu\xEDdo!","A condition that can be used in other events sheet. You can define the conditions parameters: objects, texts, numbers, layers, etc...":"Uma condi\xE7\xE3o que pode ser usada em outras folhas de eventos. Tu podes definir os par\xE2metros das condi\xE7\xF5es: objetos, textos, n\xFAmeros, camadas, etc...","A demo of various high quality particle effects (fire, magic, snow, rune spell...) that you can try and use in your game.":"Uma demonstra\xE7\xE3o de v\xE1rios efeitos de part\xEDculas de alta qualidade (fogo, magia, neve, feiti\xE7o de runas...) que tu podes tentar usar no teu jogo.","A demo showing how to enhance the \"game feel\" of your project: VFX, shot trail, ambient sounds and SFX, screenshake, wobble...":"A demo showing how to enhance the \"game feel\" of your project: VFX, shot trail, ambient sounds and SFX, screenshake, wobble...","A hyper casual endless game where you have to collect shapes and avoid bombs, with a progressively increasing difficulty.":"A hyper casual endless game where you have to collect shapes and avoid bombs, with a progressively increasing difficulty.","A lighting layer was created. Lights will be placed on it automatically. You can change the ambient light color in the properties of this layer":"A lighting layer was created. Lights will be placed on it automatically. You can change the ambient light color in the properties of this layer","A new physics engine (Physics Engine 2.0) is now available. You should prefer using it for new game. For existing games, note that the two behaviors are not compatible, so you should only use one of them with your objects.":"Um novo motor de f\xEDsica (Physics Engine 2.0) est\xE1 agora dispon\xEDvel. Voc\xEA deve preferir us\xE1-lo para um novo jogo. Para jogos existentes, observe que os dois comportamentos n\xE3o s\xE3o compat\xEDveis, portanto, deve usar apenas um deles com os seus objetos.","A scale under 1 on a Bitmap text object can downgrade the quality text, prefer to remake a bitmap font smaller in the external bmFont editor.":"A scale under 1 on a Bitmap text object can downgrade the quality text, prefer to remake a bitmap font smaller in the external bmFont editor.","A simple platform game, with coins to collect, moving platforms and enemies.":"Um jogo de plataforma simples, com moedas para colecionar, plataformas m\xF3veis e inimigos.","A temporary image to help you visualize the shape/polygon":"A temporary image to help you visualize the shape/polygon","APK (for testing on device or sharing outside Google Play)":"APK (for testing on device or sharing outside Google Play)","Abandon":"Abandon","About GDevelop":"Sobre GDevelop","Action":"A\xE7\xE3o","Actions":"A\xE7\xF5es","Add":"Add","Add New Event Below":"Add New Event Below","Add Other":"Add Other","Add Sub Event":"Add Sub Event","Add a Long Description":"Add a Long Description","Add a behavior to the object":"Add a behavior to the object","Add a comment":"Add a comment","Add a layer":"Add a layer","Add a new behavior":"Adicionar novo comportamento","Add a new behavior to the object":"Adicionar um novo comportamento ao objeto","Add a new empty event":"Add a new empty event","Add a new event":"Add a new event","Add a new function":"Adicionar uma nova fun\xE7\xE3o","Add a new object":"Adicionar um novo objeto","Add a new object...":"Add a new object...","Add a new option":"Add a new option","Add a parameter":"Adicionar um par\xE2metro","Add a point":"Add a point","Add a property":"Adicionar uma propriedade","Add a sub-condition":"Adicionar uma sub-condi\xE7\xE3o","Add a sub-event to the selected event":"Add a sub-event to the selected event","Add a vertex":"Add a vertex","Add action":"Adicionar a\xE7\xE3o","Add an Instance of {0}":function(a){return["Add an Instance of ",a("0")]},"Add an animation":"Add an animation","Add an effect":"Adicionar um efeito","Add an object from the store":"Adicionar um objeto da loja","Add child variable":"Adicionar uma vari\xE1vel filho","Add collision mask":"Add collision mask","Add condition":"Adicionar condi\xE7\xE3o","Add lighting layer":"Add lighting layer","Add to the game":"Adicionar ao jogo","Add your first behavior using the button \"Add a behavior to the object\".":"Add your first behavior using the button \"Add a behavior to the object\".","Add your first event using the button \"Add a new event\".":"Adicione o seu primeiro evento pressionando o bot\xE3o \"Adiconar novo evento\".","Add...":"Adicionar...","Add/update {0} tag(s)":function(a){return["Adicionar/atualizar ",a("0")," tag(s)"]},"Additive rendering":"Renderiza\xE7\xE3o aditiva","Advanced":"Avan\xE7ado","Advanced preview options (debugger, network preview...)":"Op\xE7\xF5es de visualiza\xE7\xE3o avan\xE7adas (depurador, visualiza\xE7\xE3o da rede...)","After adding an effect, set up its parameters. Launch a preview to see the result. Using the events and the name of the effect, you can change the parameters during the game.":"After adding an effect, set up its parameters. Launch a preview to see the result. Using the events and the name of the effect, you can change the parameters during the game.","All assets":"Todos os objetos","All behaviors being directly referenced in the events:":"Todos os comportamentos est\xE3o a ser referenciados diretamente nos eventos:","All games":"All games","All objects potentially used in events: {0}":function(a){return["Todos os objetos potencialmente utilizados em eventos: ",a("0")]},"All your builds":"Todas as suas constru\xE7\xF5es","Already have an account?":"J\xE1 possui uma conta?","Always display the preview window on top of others":"Always display the preview window on top of others","Ambient light color":"Cor da luz ambiente","An action that can be used in other events sheet. You can define the action parameters: objects, texts, numbers, layers, etc...":"Uma a\xE7\xE3o que pode ser usada em outras folhas de eventos. Voc\xEA pode definir os par\xE2metros da a\xE7\xE3o: objetos, textos, n\xFAmeros, camadas, etc...","An action, condition or expression that can be used on objects that have the behavior attached to them. Use it from the events sheet as any other action/condition/expression.":"Uma a\xE7\xE3o, condi\xE7\xE3o ou express\xE3o que pode ser usada em objetos que t\xEAm o comportamento anexado a eles. Use-o da folha de eventos como qualquer outra a\xE7\xE3o/condi\xE7\xE3o/express\xE3o.","An autosave file (backup made automatically by GDevelop) that is newer than the project file exists. Would you like to load it instead?":"Um arquivo autosave (backup feito automaticamente pela GDevelop) que \xE9 mais recente do que o arquivo do projeto existe. Gostaria de carreg\xE1-lo em vez disso?","An error happened while loading this extension. Please check that it is a proper extension file and compatible with this version of GDevelop":"Ocorreu um erro ao carregar esta extens\xE3o. Por favor verifique que \xE9 um ficheiro de extens\xE3o adequado e compat\xEDvel com esta vers\xE3o do GDevelop","An error has occured during functions generation. If GDevelop is installed, verify that nothing is preventing GDevelop from writing on disk. If you're running GDevelop online, verify your internet connection and refresh functions from the Project Manager.":"Ocorreu um erro durante a gera\xE7\xE3o de fun\xE7\xF5es. Se o GDevelop estiver instalado, verifique se nada est\xE1 a impedir que o GDevelop grave no disco. Se estiver a executar o GDevelop online, verifique a sua liga\xE7\xE3o com a Internet e atualize as fun\xE7\xF5es do Gerenciador de Projetos.","An example of a 2D physics based game, where players have to reach the end as fast as possible.":"Um exemplo de um jogo de condu\xE7\xE3o baseado na f\xEDsica 2D, onde o jogador tem que chegar ao final o mais r\xE1pido poss\xEDvel.","An example of an isometric game where you can explore a map with your character.":"Um exemplo de um jogo isom\xE9trico onde pode explorar um mapa com a sua personagem.","An expression that can be used in formulas. Can either return a number or a string, and take some parameters.":"An expression that can be used in formulas. Can either return a number or a string, and take some parameters.","An extension with this name already exists in the project. Importing this extension will replace it: are you sure you want to continue?":"Uma extens\xE3o com este nome j\xE1 existe no projeto. A importa\xE7\xE3o desta extens\xE3o ir\xE1 substitu\xED-la: voc\xEA tem a certeza de que deseja continuar?","Analytics":"Analytics","Analyze Objects Used in this Event":"Analyze Objects Used in this Event","And {remainingResultsCount} more results.":function(a){return["And ",a("remainingResultsCount")," more results."]},"Android (& iOS coming soon)":"Android (& iOS coming soon)","Android App Bundle (for publishing on Google Play)":"Android App Bundle (for publishing on Google Play)","Android Build":"Android Build","Android icons:":"\xCDcones Android:","Angle":"\xC2ngulo","Animation":"Anima\xE7\xE3o","Animation #{i} {0}":function(a){return["Animation #",a("i")," ",a("0")]},"Another extension with this name already exists (or you used a reserved extension name). Please choose another name.":"Another extension with this name already exists (or you used a reserved extension name). Please choose another name.","Another external layout with this name already exists.":"J\xE1 existe outro layout externo com este nome.","Another scene with this name already exists.":"J\xE1 existe outra cena com este nome.","Any additional properties will appear here if you add behaviors to objects, like Physics behavior.":"Quaisquer propriedades adicionais aparecer\xE3o aqui se adicionar comportamentos a objects, como o comportamento de f\xEDsica.","Any object":"Qualquer object","Any unsaved changes in the project will be lost.":"Any unsaved changes in the project will be lost.","Appearance":"Appearance","Apply":"Aplicar","Apply changes":"Apply changes","Apply changes to preview":"Apply changes to preview","Apply changes to the running preview":"Apply changes to the running preview","Apply changes to the running preview, right click for more":"Apply changes to the running preview, right click for more","Are you sure you want to cancel your subscription?":"Are you sure you want to cancel your subscription?","Are you sure you want to quit GDevelop?":"Are you sure you want to quit GDevelop?","Are you sure you want to remove these external events? This can't be undone.":"Tem certeza de que deseja remover estes eventos externos? Isso n\xE3o pode ser desfeito.","Are you sure you want to remove this extension? This can't be undone.":"Tem certeza de que deseja remover esta extens\xE3o? Isso n\xE3o pode ser desfeito.","Are you sure you want to remove this external layout? This can't be undone.":"Tem certeza de que deseja remover este layout externo? Isso n\xE3o pode ser desfeito.","Are you sure you want to remove this scene? This can't be undone.":"Tem certeza de que deseja remover esta cena? Isso n\xE3o pode ser desfeito.","Are you sure you want to reset all shortcuts to their default values?":"Are you sure you want to reset all shortcuts to their default values?","Are you sure you want to subscribe to this new plan?":"Are you sure you want to subscribe to this new plan?","Array":"Array","As a percent of the game width.":"As a percent of the game width.","Assets (coming soon!)":"Assets (coming soon!)","Audio files":"Ficheiros de \xC1udio","Audio resource":"Recurso de \xE1udio","Author name":"Nome do autor","Authors":"Authors","Auto download and install updates (recommended)":"Download autom\xE1tico e instala\xE7\xE3o de atualiza\xE7\xF5es (recomendado)","Auto-save project on Preview":"Salvar automaticamente o projeto na visualiza\xE7\xE3o","Automatic creation of lighting layer":"Cria\xE7\xE3o autom\xE1tica da camada de ilumina\xE7\xE3o","Automatically follow the base layer.":"Seguir automaticamente a camada base.","Automatically re-open the project edited during last session":"Reabrir automaticamente o projeto editado durante a \xFAltima sess\xE3o","Back":"Voltar","Background":"Background","Background color":"Cor de Fundo","Background color:":"Cor de Fundo:","Background fade in duration (in seconds)":"Background fade in duration (in seconds)","Background image":"Background image","Base layer":"Camada base","Be careful with this action, you may have problems exiting the preview if you don't add a way to toggle it back.":"Be careful with this action, you may have problems exiting the preview if you don't add a way to toggle it back.","Behavior":"Comportamento","Behavior (for the previous object)":"Comportamento (para o objeto anterior)","Behavior functions":"Fun\xE7\xF5es de comportamento","Behavior name":"Nome do comportamento","Behavior type":"Tipo de comportamento","Behaviors":"Comportamentos","Behaviors are predefined actions that are assigned to objects. Behaviors can have no or multiple parameters.":"Behaviors are predefined actions that are assigned to objects. Behaviors can have no or multiple parameters.","Behaviors of {objectOrGroupName}: {0} ;":function(a){return["Comportamentos de ",a("objectOrGroupName"),": ",a("0")," ;"]},"Bio":"Bio","Bitmap font resource":"Bitmap font resource","Bold":"Negrito","Boolean (checkbox)":"Boleano (caixa de sele\xE7\xE3o)","Bottom margin":"Margem inferior","Box":"Caixa","Browse ready made objects in the Asset Store":"Browse ready made objects in the Asset Store","Browse the documentation":"Browse the documentation","Build and download":"Compilar e transferir","Build could not start or errored. Please check your internet connection or try again later.":"Build could not start or errored. Please check your internet connection or try again later.","Build is starting...":"A iniciar configura\xE7\xE3o...","Build the game locally and export it manually to Windows, macOS or Linux with third-party developer tools.":"Build the game locally and export it manually to Windows, macOS or Linux with third-party developer tools.","Build the game locally as a Cordova project, and export it manually then to iOS or Android with Cordova developers tools.":"Build the game locally as a Cordova project, and export it manually then to iOS or Android with Cordova developers tools.","Build the game locally as a Cordova project, and export it manually to iOS or Android with Cordova developers tools.":"Build the game locally as a Cordova project, and export it manually to iOS or Android with Cordova developers tools.","Build the game locally as a HTML5 game. You can then publish it on website like Kongregate, Game Jolt, itch.io, Poki...":"Build the game locally as a HTML5 game. You can then publish it on website like Kongregate, Game Jolt, itch.io, Poki...","By creating an account and using GDevelop, you agree to the [Terms and Conditions](https://gdevelop-app.com/legal/terms-and-conditions). Having an account allows you to export your game on Android or as a Desktop app and it unlocks other services for your project!":"By creating an account and using GDevelop, you agree to the [Terms and Conditions](https://gdevelop-app.com/legal/terms-and-conditions). Having an account allows you to export your game on Android or as a Desktop app and it unlocks other services for your project!","By:":"By:","Can't check if the game is registered online.":"Can't check if the game is registered online.","Can't load the example. Verify your internet connection or try again later.":"Can't load the example. Verify your internet connection or try again later.","Can't load the extension registry. Verify your internet connection or try again later.":"N\xE3o \xE9 poss\xEDvel carregar o registro de extens\xE3o. Verifique a sua conex\xE3o de Internet ou tente novamente mais tarde.","Can't load the games. Verify your internet connection or retry later.":"Can't load the games. Verify your internet connection or retry later.","Can't load the results. Verify your internet connection or retry later.":"Can't load the results. Verify your internet connection or retry later.","Can't properly export the game.":"Can't properly export the game.","Can't upload your game to the build service.":"Can't upload your game to the build service.","Cancel":"Cancelar","Cancel and close":"Cancelar e fechar","Cancel changes":"Cancel changes","Cancel your subscription":"Cancele a sua subscri\xE7\xE3o","Case insensitive":"N\xE3o distingue mai\xFAsculas de min\xFAsculas","Categories":"Categories","Cell height (in pixels)":"Altura da c\xE9lula (em p\xEDxeis)","Cell width (in pixels)":"Largura da c\xE9lula (em p\xEDxeis)","Center":"Centro","Center View":"Centrar Vista","Change color {propertyName} of _PARAM0_ to _PARAM2_":function(a){return["Change color ",a("propertyName")," of _PARAM0_ to _PARAM2_"]},"Change editor zoom":"Alterar zoom do editor","Change height to fit the screen or window size":"Change height to fit the screen or window size","Change my email":"Change my email","Change the content of {propertyLabel}":function(a){return["Change the content of ",a("propertyLabel")]},"Change the value of {propertyLabel}":function(a){return["Change the value of ",a("propertyLabel")]},"Change variable type":"Change variable type","Change width to fit the screen or window size":"Change width to fit the screen or window size","Change your email":"Change your email","Check that the file exists, that this file is a proper game created with GDevelop and that you have the authorizations to open it.":"Check that the file exists, that this file is a proper game created with GDevelop and that you have the authorizations to open it.","Check that the path/URL is correct, that you selected a file that is a game file created with GDevelop and that is was not removed.":"Check that the path/URL is correct, that you selected a file that is a game file created with GDevelop and that is was not removed.","Check that you don't have any blocked popup (if so, allow them and retry) and that you have the authorizations for reading the file you're trying to access.":"Check that you don't have any blocked popup (if so, allow them and retry) and that you have the authorizations for reading the file you're trying to access.","Check the color {propertyLabel}":function(a){return["Check the color ",a("propertyLabel")]},"Check the logs to see if there is an explanation about what went wrong, or try again later.":"Verifique os registos para ver se h\xE1 uma explica\xE7\xE3o sobre o que falhou, ou tente novamente mais tarde.","Check the value of {propertyLabel}":function(a){return["Verificar o valor de ",a("propertyLabel")]},"Check your inbox and click the link to verify your email address - and come back here when it's done.":"Check your inbox and click the link to verify your email address - and come back here when it's done.","Choose":"Escolha","Choose GDevelop language":"Escolha um idioma para o GDevelop","Choose a Json File from the library":"Choose a Json File from the library","Choose a bitmap font file":"Choose a bitmap font file","Choose a bitmap font from the library":"Choose a bitmap font from the library","Choose a category to display filters":"Choose a category to display filters","Choose a condition (or an object then a condition) on the left":"Choose a condition (or an object then a condition) on the left","Choose a file":"Escolha um ficheiro","Choose a file or folder":"Escolha um ficheiro ou pasta","Choose a folder for the new game":"Escolha uma pasta para o novo jogo","Choose a font":"Escolha o tipo de letra","Choose a font file":"Choose a font file","Choose a font from the library":"Escolha o tipo de letra na biblioteca","Choose a function, or a function of a behavior, to edit its events.":"Escolha uma fun\xE7\xE3o ou uma fun\xE7\xE3o de um comportamento para editar os seus eventos.","Choose a function, or a function of a behavior, to set the parameters that it accepts.":"Escolha uma fun\xE7\xE3o, ou uma fun\xE7\xE3o de um comportamento, para definir os par\xE2metros que ela aceita.","Choose a game to use as a starter:":"Escolha um jogo para usar de inicio:","Choose a json file":"Escolha um ficheiro json","Choose a key":"Escolher uma tecla","Choose a mouse button":"Escolher um bot\xE3o do rato","Choose a new behavior function (\"method\")":"Escolha uma nova fun\xE7\xE3o de comportamento (\"m\xE9todo\")","Choose a new extension function":"Choose a new extension function","Choose a project to use as a starter:":"Choose a project to use as a starter:","Choose a subscription":"Escolha uma subscri\xE7\xE3o","Choose a video file":"Escolha um ficheiro v\xEDdeo","Choose a video from the library":"Escolha um video da biblioteca","Choose an action (or an object then an action) on the left":"Choose an action (or an object then an action) on the left","Choose an animation and frame to edit the collision masks":"Escolha uma anima\xE7\xE3o e um quadro para editar as m\xE1scaras de colis\xE3o","Choose an animation and frame to edit the points":"Escolha uma anima\xE7\xE3o e um quadro para editar os pontos","Choose an audio file":"Escolha um ficheiro a\xFAdio","Choose an audio file from the library":"Escolha um ficheiro de \xE1udio da biblioteca","Choose an element to inspect in the list":"Escolha um elemento para inspecionar na lista","Choose an export folder":"Escolha uma pasta de exporta\xE7\xE3o","Choose an icon for the extension":"Choose an icon for the extension","Choose an image":"Choose an image","Choose an image from the library":"Escolha uma imagem da biblioteca","Choose an object":"Escolha um objeto","Choose an object to add to the group":"Escolha um objeto para adicionar ao grupo","Choose an operator":"Choose an operator","Choose an option":"Choose an option","Choose and add an event":"Choose and add an event","Choose and add an event...":"Choose and add an event...","Choose folder":"Escolher pasta","Choose the associated scene:":"Choose the associated scene:","Choose the audio file to use":"Escolha o ficheiro de \xE1udio para usar","Choose the bitmap font file (.fnt, .xml) to use":"Choose the bitmap font file (.fnt, .xml) to use","Choose the effect to apply":"Choose the effect to apply","Choose the json file to use":"Choose the json file to use","Choose the scene":"Escolha a cena","Choose the upload key to use to identify your Android App Bundle. In most cases you don't need to change this. Use the \"Old upload key\" if you used to publish your game as an APK and you activated Play App Signing before switching to Android App Bundle.":"Choose the upload key to use to identify your Android App Bundle. In most cases you don't need to change this. Use the \"Old upload key\" if you used to publish your game as an APK and you activated Play App Signing before switching to Android App Bundle.","Choose the video file to use":"Escolha o ficheiro de v\xEDdeo para usar","Choose this plan":"Escolher este plano","Choose where to create the game":"Escolher onde criar o jogo","Choose where to export the game":"Escolher para onde exportar o jogo","Choose where to load the project from":"Choose where to load the project from","Choose where to save the project to":"Choose where to save the project to","Choose...":"Choose...","Circle":"C\xEDrculo","Clear the rendered image between each frame":"Clear the rendered image between each frame","Click here to test the link.":"Click here to test the link.","Click on an instance in the scene to display its properties":"Clique numa inst\xE2ncia na cena para exibir as suas propriedades","Click to add a group":"Clique para adicionar um grupo","Click to add a scene":"Clique para adicionar uma cena","Click to add an external layout":"Clique para adicionar um layout externo","Click to add external events":"Clique para adicionar eventos externos","Click to add functions and behaviors":"Clique para adicionar fun\xE7\xF5es e comportamentos","Click to choose for which objects this event will be repeated":"Click to choose for which objects this event will be repeated","Click to choose how many times will be repeated":"Click to choose how many times will be repeated","Close":"Fechar","Close GDevelop":"Close GDevelop","Close Project":"Fechar projeto","Close all":"Close all","Close and launch a new preview":"Close and launch a new preview","Close others":"Close others","Close project":"Fechar projeto","Close the project? Any changes that have not been saved will be lost.":"Fechar o projeto? Quaisquer altera\xE7\xF5es que n\xE3o foram guardadas ser\xE3o perdidas.","Code editor Theme":"Tema do editor de c\xF3digo","Collisions handling with the Physics engine":"Collisions handling with the Physics engine","Color":"Cor","Color (text)":"Cor (texto)","Color {propertyName}":function(a){return["Color ",a("propertyName")]},"Color:":"Cor:","Command palette keyboard shortcut":"Command palette keyboard shortcut","Community Discord Chat":"Chat da Comunidade no Discord","Community Forums":"F\xF3runs da comunidade","Community forum":"F\xF3rum da comunidade","Compare the content of {propertyLabel}":function(a){return["Comparar o conte\xFAdo de ",a("propertyLabel")]},"Compare the value of {propertyLabel}":function(a){return["Comparar o valor de ",a("propertyLabel")]},"Compressing before upload...":"Comprimindo antes de enviar...","Condition":"Condi\xE7\xE3o","Conditions":"Condi\xE7\xF5es","Configuration":"Configura\xE7\xE3o","Configure the external events":"Configure the external events","Configure the external layout":"Configure the external layout","Confirm the opening":"Confirm the opening","Congratulations, your new subscription is now active! nYou can now use the services unlocked with this plan.":"Congratulations, your new subscription is now active! nYou can now use the services unlocked with this plan.","Console":"Console","Continue anyway":"Continuar mesmo assim","Contribute to GDevelop":"Contribua para o GDevelop","Contributions":"Contributions","Contributors":"Colaboradores","Contributors, in no particular order:":"Colaboradores, sem ordem espec\xEDfica:","Convert the variable to a collection before adding children":"Convert the variable to a collection before adding children","Convert to array":"Convert to array","Convert to boolean":"Convert to boolean","Convert to number":"Convert to number","Convert to string":"Convert to string","Convert to structure":"Convert to structure","Copy":"Copy","Copy File Path":"Copy File Path","Cordova":"Cordova","Could not launch the preview":"Could not launch the preview","Create":"Criar","Create Extensions for GDevelop":"Criar extens\xF5es para o GDevelop","Create a 2D platform game where the player can shoot at enemies chasing him.":"Create a 2D platform game where the player can shoot at enemies chasing him.","Create a GDevelop account to continue. It's free and you'll be able to access to online services like one-click builds:":"Create a GDevelop account to continue. It's free and you'll be able to access to online services like one-click builds:","Create a New Project...":"Criar um novo projeto...","Create a game from scratch using physics and particles.":"Create a game from scratch using physics and particles.","Create a new GDevelop account":"Create a new GDevelop account","Create a new instance on the scene (will be at position 0;0):":"Criar uma nova inst\xE2ncia na cena (estar\xE1 na posi\xE7\xE3o 0; 0):","Create a new project":"Criar um novo projeto","Create a simple breakout game where you must destroy all the bricks on the screen.":"Create a simple breakout game where you must destroy all the bricks on the screen.","Create a simple game where you must dodge the cars on the road.":"Criar um jogo simples onde voc\xEA deve evitar os carros na estrada.","Create a trampoline in your platformer game, making the player jump very high when stepped on.":"Create a trampoline in your platformer game, making the player jump very high when stepped on.","Create an account to register your games and to get access to metrics collected anonymously, like the number of daily players and retention of the players after a few days.":"Create an account to register your games and to get access to metrics collected anonymously, like the number of daily players and retention of the players after a few days.","Create animated buttons that can be shown in your game menus (main menu, selection screen, etc...).":"Create animated buttons that can be shown in your game menus (main menu, selection screen, etc...).","Create my account":"Criar minha conta","Create your own behavior":"Crie o seu pr\xF3prio comportamento","Custom":"Personalizado","Custom (action, condition or expression)":"Personalizado (a\xE7\xE3o, condi\xE7\xE3o ou express\xE3o)","Custom size":"Custom size","Custom size?":"Custom size?","Custom upload key (not available yet)":"Custom upload key (not available yet)","Cut":"Cut","Dark (colored)":"Dark (colored)","Dark (plain)":"Dark (plain)","Dashboard":"Dashboard","Day":"Day","Day {dayIndex} retained players":function(a){return["Day ",a("dayIndex")," retained players"]},"Debugger":"Depurador","Debugger is starting...":"Depurador a iniciar...","Default height (in pixels)":"Altura padr\xE3o (em p\xEDxeis)","Default value":"Valor padr\xE3o","Default width (in pixels)":"Largura padr\xE3o (em p\xEDxeis)","Delete":"Apagar","Delete collision mask":"Delete collision mask","Delete option":"Delete option","Delete selection":"Delete selection","Delete the layer":"Delete the layer","Delete the selected event(s)":"Delete the selected event(s)","Delete the selected instances from the scene":"Delete the selected instances from the scene","Delete the selected resource":"Delete the selected resource","Delete when out of particles":"Apagar quando estiver sem part\xEDculas","Dependencies":"Dependencies","Dependencies allow to add additional libraries in the exported games. NPM dependencies will be included for Electron builds (Windows, macOS, Linux) and Cordova dependencies will be included for Cordova builds (Android, iOS). Note that this is intended for usage in JavaScript events only. If you are only using standard events, you should not worry about this.":"Dependencies allow to add additional libraries in the exported games. NPM dependencies will be included for Electron builds (Windows, macOS, Linux) and Cordova dependencies will be included for Cordova builds (Android, iOS). Note that this is intended for usage in JavaScript events only. If you are only using standard events, you should not worry about this.","Dependency type":"Dependency type","Description":"Descri\xE7\xE3o","Description (markdown supported)":"Descri\xE7\xE3o (suporta markdown)","Description, displayed in editor":"Descri\xE7\xE3o, exibida no editor","Desktop (Windows, macOS and Linux) icon:":"\xCDcone do Desktop (Windows, macOS e Linux):","Details":"Details","Device orientation (for iOS and Android)":"Orienta\xE7\xE3o do dispositivo (para iOS e Android)","Dialog backdrop click behavior":"Dialog backdrop click behavior","Dialogs":"Dialogs","Direction":"Dire\xE7\xE3o","Direction #{i}":function(a){return["Direction #",a("i")]},"Disable GDevelop splash at startup":"Desativar o splash do GDevelop na inicializa\xE7\xE3o","Display GDevelop logo at startup (in exported game)":"Display GDevelop logo at startup (in exported game)","Display What's New when a new version is launched (recommended)":"Mostrar o que h\xE1 de novo quando uma nova vers\xE3o \xE9 lan\xE7ada (recomendado)","Display assignment operators in Events Sheets":"Display assignment operators in Events Sheets","Display object thumbnails in Events Sheets":"Exibir miniaturas do objeto nas folhas de eventos","Do nothing":"Do nothing","Don't have an account yet?":"Don't have an account yet?","Done":"Done","Done!":"Done!","Double click on a condition or action to edit it.":"Double click on a condition or action to edit it.","Double tap a condition or action to edit it. Long press to show more options.":"Double tap a condition or action to edit it. Long press to show more options.","Download":"Download","Download (APK)":"Download (APK)","Download (Android App Bundle)":"Download (Android App Bundle)","Download GDevelop desktop app":"Download GDevelop desktop app","Download GDevelop desktop version":"Descarregar a vers\xE3o desktop do GDevelop","Download GDevelop desktop version to generate the Android and iOS icons of your game.":"Fa\xE7a o download da vers\xE3o para desktop do GDevelop para gerar os \xEDcones do Android e do iOS do seu jogo.","Download GDevelop to import your images":"Download GDevelop to import your images","Download a copy":"Download a copy","Download game file":"Descarregar ficheiro do jogo","Download the Instant Game archive":"Download the Instant Game archive","Download the exported game":"Download the exported game","Download the full version of GDevelop on your desktop computer to create your own game without limits!":"Download the full version of GDevelop on your desktop computer to create your own game without limits!","Downloading game resources...":"Downloading game resources...","Drag and Drop the object icon to the scene or long press to show options to edit the object.":"Drag and Drop the object icon to the scene or long press to show options to edit the object.","Drag and Drop the object to the scene or use the right click menu to add an instance of it.":"Arraste e solte o objeto para a cena ou use o menu do bot\xE3o direito para adicionar uma inst\xE2ncia nele.","Draw the shapes relative to the object position on the scene":"Desenhe as formas relativas \xE0 posi\xE7\xE3o do objeto na cena","Dropbox (coming soon)":"Dropbox (coming soon)","Duplicate":"Duplicate","Duplicate selection":"Duplicate selection","Duration":"Dura\xE7\xE3o","Dynamic":"Din\xE2mica","Edge":"Borda","Edit":"Editar","Edit Grid Options":"Edit Grid Options","Edit Layer Properties":"Edit Layer Properties","Edit Object Variables":"Editar vari\xE1veis de objeto","Edit Object {0}":function(a){return["Edit Object ",a("0")]},"Edit Scene Properties":"Edit Scene Properties","Edit Scene Variables":"Editar vari\xE1veis da cena","Edit behavior properties":"Editar propriedades do comportamento","Edit behaviors":"Edit behaviors","Edit behaviors ({eventsBasedBehaviorsCount})":function(a){return["Editar comportamentos (",a("eventsBasedBehaviorsCount"),")"]},"Edit collision masks":"Edit collision masks","Edit effects":"Edit effects","Edit effects ({effectsCount})":function(a){return["Editar efeitos (",a("effectsCount"),")"]},"Edit extension options":"Editar op\xE7\xF5es de extens\xE3o","Edit functions (not attached to behaviors) ({eventsFunctionsCount})":function(a){return["Editar fun\xE7\xF5es (n\xE3o anexadas a comportamentos) (",a("eventsFunctionsCount"),")"]},"Edit global variables":"Modificar vari\xE1veis globais","Edit group":"Modificar grupo","Edit layer effects...":"Editar efeitos da camada...","Edit layer...":"Editar camada...","Edit lighting properties":"Editar propriedades de ilumina\xE7\xE3o","Edit loading screen":"Edit loading screen","Edit my profile":"Edit my profile","Edit object":"Modificar objeto","Edit object behaviors...":"Edit object behaviors...","Edit object effects...":"Edit object effects...","Edit object group...":"Modificar grupo de objetos...","Edit object variables":"Modificar vari\xE1veis do objeto","Edit object variables...":"Modificar vari\xE1veis do objeto...","Edit object...":"Modificar objeto...","Edit points":"Editar pontos","Edit properties":"Modificar propriadades","Edit scene variables":"Editar vari\xE1veis de cena","Edit shortcut":"Modificar atalho","Edit the behavior":"Editar o comportamento","Edit the event text":"Modificar texto do evento","Edit your GDevelop profile":"Edit your GDevelop profile","Edit your profile to pick a username!":"Edit your profile to pick a username!","Editor without transitions":"Editor sem transi\xE7\xF5es","Effect name:":"Nome do efeito:","Effects":"Efeitos","Effects can change how layers or objects are rendered on screen.":"Effects can change how layers or objects are rendered on screen.","Email":"Correio electr\xF3nico","Email sent!":"Email sent!","Empty game":"Jogo vazio","Empty project":"Empty project","End opacity (0-255)":"Opacidade final (0-255)","Enter the effect name":"Insira o nome do efeito","Enter the expression parameters":"Insira os par\xE2metros da express\xE3o","Enter the name of an object.":"Digitar o nome de um object.","Enter the name of the object":"Digite o nome do objeto","Enter the parameter name (mandatory)":"Insira o nome do par\xE2metro (obrigat\xF3rio)","Enter the property name":"Digitar o nome da propriedade","Enter the sentence that will be displayed in the events sheet":"Digite a frase que ser\xE1 exibida na folha de eventos","Enter the text to be displayed":"Insira o texto a ser exibido","Enter the text to be displayed by the object":"Digite o texto a ser exibido pelo objeto","Error retrieving the examples":"Error retrieving the examples","Error retrieving the extensions":"Error retrieving the extensions","Error while loading the asset. Verify your internet connection or try again later.":"Erro ao carregar o objeto. Verifique a sua conex\xE3o com a internet ou tente novamente mais tarde.","Escape key behavior when editing an parameter inline":"Escape key behavior when editing an parameter inline","Events":"Eventos","Events Sheet":"Folha de Eventos","Events are composed of conditions (on the left of an event) and actions (on the right). When conditions are fulfilled, the actions are executed.":"Eventos s\xE3o compostos por condi\xE7\xF5es (\xE0 esquerda de um evento) e a\xE7\xF5es (\xE0 direita). Quando as condi\xE7\xF5es s\xE3o cumpridas, as a\xE7\xF5es s\xE3o executadas.","Events that will be run at every frame (roughly 60 times per second), after the events from the events sheet of the scene.":"Eventos que ser\xE3o executados em cada quadro (cerca de 60 vezes por segundo), ap\xF3s os eventos da folha de eventos da cena.","Events that will be run at every frame (roughly 60 times per second), before the events from the events sheet of the scene.":"Events that will be run at every frame (roughly 60 times per second), before the events from the events sheet of the scene.","Events that will be run at every frame (roughly 60 times per second), for every object that has the behavior attached, after the events from the events sheet.":"Eventos que ser\xE3o executados em cada quadro (aproximadamente 60 vezes por segundo), para cada objeto que tenha o comportamento anexado, ap\xF3s os eventos da folha de eventos.","Events that will be run at every frame (roughly 60 times per second), for every object that has the behavior attached, before the events from the events sheet are launched.":"Eventos que ser\xE3o executados em cada quadro (aproximadamente 60 vezes por segundo), para cada objeto que tenha o comportamento anexado, antes que os eventos da folha de eventos sejam iniciados.","Events that will be run once when a scene is about to be unloaded from memory. The previous scene that was paused will be resumed after this.":"Events that will be run once when a scene is about to be unloaded from memory. The previous scene that was paused will be resumed after this.","Events that will be run once when a scene is paused (another scene is run on top of it).":"Events that will be run once when a scene is paused (another scene is run on top of it).","Events that will be run once when a scene is resumed (after it was previously paused).":"Events that will be run once when a scene is resumed (after it was previously paused).","Events that will be run once when a scene of the game is loaded, before the scene events.":"Events that will be run once when a scene of the game is loaded, before the scene events.","Events that will be run once when the behavior is deactivated on an object (step events won't be run until the behavior is activated again).":"Events that will be run once when the behavior is deactivated on an object (step events won't be run until the behavior is activated again).","Events that will be run once when the behavior is re-activated on an object (after it was previously deactivated).":"Events that will be run once when the behavior is re-activated on an object (after it was previously deactivated).","Events that will be run once when the first scene of the game is loaded, before any other events.":"Events that will be run once when the first scene of the game is loaded, before any other events.","Events that will be run once, after the object is removed from the scene and before it is entirely removed from memory.":"Eventos que ser\xE3o executados uma vez, depois do objeto ser removido da cena e antes de ser totalmente removido da mem\xF3ria.","Events that will be run once, when an object is created with this behavior being attached to it.":"Eventos que ser\xE3o executados uma vez, quando um objeto \xE9 criado com esse comportamento sendo anexado a ele.","Example: Check if the object is flashing.":"Example: Check if the object is flashing.","Example: Equipped shield name":"Example: Equipped shield name","Example: Flash the object":"Example: Flash the object","Example: Is flashing?":"Exemplo: Est\xE1 a piscar?","Example: Life remaining":"Exemplo: Vida restante","Example: Life remaining for the player.":"Example: Life remaining for the player.","Example: Make the object flash for 5 seconds.":"Example: Make the object flash for 5 seconds.","Example: Name of the shield equipped by the player.":"Example: Name of the shield equipped by the player.","Examples":"Exemplos","Examples ({0})":function(a){return["Examples (",a("0"),")"]},"Examples:":"Exemplos:","Exit GDevelop":"Sair do GDevelop","Explanation after an object is installed from the store":"Explanation after an object is installed from the store","Export":"Exportar","Export (web, iOS, Android)...":"Exportar (web, iOS, Android)...","Export as a HTML5 game":"Exportar como um jogo HTML5","Export extension":"Exportar extens\xE3o","Export game":"Exportar jogo","Export in progress...":"Exporta\xE7\xE3o em progresso...","Export name":"Export name","Export project to a standalone game":"Exportar projeto para um jogo aut\xF4nomo","Export the game (Web, Android, iOS...)":"Exportar o jogo (Web, Android, iOS...)","Export to a file":"Exportar para ficheiro","Expression":"Express\xE3o","Extension (storing the function)":"Extens\xE3o (armazenando a fun\xE7\xE3o)","Extensions ({0})":function(a){return["Extensions (",a("0"),")"]},"Extensions can provide functions (which can be actions, conditions or expressions) or new behaviors.":"Extensions can provide functions (which can be actions, conditions or expressions) or new behaviors.","External events":"Eventos externos","External layouts":"Layouts externos","Extract Events to a Function":"Extract Events to a Function","Extract the events in a function":"Extrair os eventos numa fun\xE7\xE3o","FNT, XML file":"FNT, XML file","FPS:":"FPS:","Facebook Instant Games":"Jogos instant\xE2neos do Facebook","False":"Falso","False (not checked)":"Falso (n\xE3o verificado)","File":"Ficheiro","Fill color":"Cor de preenchimento","Fill opacity (0-255)":"Preencher opacidade (0-255)","Filter the logs by group":"Filter the logs by group","Filters":"Filters","Find all matching pairs of cards in this relaxing game. Use tweens to create smooth, natural animations with a few events.":"Encontre todos os pares de cartas neste jogo relaxante. Use interpola\xE7\xF5es para criar anima\xE7\xF5es suaves e naturais com alguns eventos.","Find more on GDevelop Youtube channel":"Find more on GDevelop Youtube channel","First editor":"First editor","Flow of particles (particles/seconds)":"Fluxo de part\xEDculas (part\xEDculas/segundos)","Font files":"Font files","Font:":"Font:","For a given video resource, only one video will be played in memory and displayed. If you put this object multiple times on the scene, all the instances will be displaying the exact same video (with the same timing and paused/played/stopped state).":"Para um determinado recurso de v\xEDdeo, apenas um v\xEDdeo ser\xE1 reproduzido na mem\xF3ria e exibido. Se colocar este objeto v\xE1rias vezes na cena, todas as inst\xE2ncias estar\xE3o a mostrar exatamente o mesmo v\xEDdeo (com o mesmo tempo e estado em pausa/reproduzindo/ parado).","For a pixel type font, you must disable the Smooth checkbox related to your texture in the game resources to disable anti-aliasing.":"For a pixel type font, you must disable the Smooth checkbox related to your texture in the game resources to disable anti-aliasing.","For example, you can have a variable called Life representing the health of the object.":"For example, you can have a variable called Life representing the health of the object.","For example, you can have a variable called Score representing the current score of the player.":"For example, you can have a variable called Score representing the current score of the player.","For example, you can have a variable called UnlockedLevelsCount representing the number of levels unlocked by the player.":"For example, you can have a variable called UnlockedLevelsCount representing the number of levels unlocked by the player.","For example: player, spaceship, inventory...":"Por exemplo: jogador, nave espacial, invent\xE1rio...","For the lifecycle functions to be executed, you need the extension to be used in the game, either by having at least one action, condition or expression used, or a behavior of the extension added to an object. Otherwise, the extension won't be included in the game.":"For the lifecycle functions to be executed, you need the extension to be used in the game, either by having at least one action, condition or expression used, or a behavior of the extension added to an object. Otherwise, the extension won't be included in the game.","Frame":"Moldura","Frame #{i}":function(a){return["Frame #",a("i")]},"Free":"Free","Full name displayed in editor":"Nome completo exibido no editor","Function Configuration":"Configura\xE7\xE3o de Fun\xE7\xE3o","Function name":"Nome da fun\xE7\xE3o","Function type":"Function type","Functions":"Fun\xE7\xF5es","Functions/Behaviors":"Fun\xE7\xF5es/Comportamentos","GDevelop 5":"GDevelop 5","GDevelop Games":"GDevelop Games","GDevelop Preferences":"GDevelop Preferences","GDevelop Website":"Site do GDevelop","GDevelop is an easy-to-use game creator with no programming language to learn.":"O GDevelop \xE9 um criador de jogos f\xE1cil de usar, sem linguagem de programa\xE7\xE3o para aprender.","GDevelop logo style":"GDevelop logo style","GDevelop on Discord":"GDevelop on Discord","GDevelop on Facebook":"GDevelop on Facebook","GDevelop on Reddit":"GDevelop on Reddit","GDevelop on Twitter":"GDevelop on Twitter","GDevelop was created by Florian \"4ian\" Rival.":"GDevelop foi criado por Florian Rival \"4ian\".","GDevelop was upgraded to a new version! Check out the changes.":"O GDevelop foi atualizado para uma nova vers\xE3o! Veja as mudan\xE7as.","GDevelop website":"Site do GDevelop","GDevelop {0} based on GDevelop.js {1}":function(a){return["GDevelop ",a("0")," baseado no GDevelop.js ",a("1")]},"Game Feel Demo":"Game Feel Demo","Game currently edited":"Game currently edited","Game export":"Game export","Game name":"Nome do jogo","Game preview #{id}":function(a){return["Game preview #",a("id")]},"Game resolution height":"Game resolution height","Game resolution resize mode (fullscreen or window)":"Game resolution resize mode (fullscreen or window)","Game resolution width":"Game resolution width","Game settings":"Configura\xE7\xF5es do jogo","Games Dashboard":"Games Dashboard","Games showcase":"Games showcase","General":"General","General:":"Geral:","Generate icons from a file":"Gerar \xEDcones de um ficheiro","Geometry Monster":"Geometry Monster","Get a subscription":"Obter uma subscri\xE7\xE3o","Get a subscription or login":"Obter uma subscri\xE7\xE3o ou entrar","Get a subscription to gain more one-click exports, remove the GDevelop splashscreen and messages asking you to get a subscription. With a subscription, you're also supporting the development of GDevelop, which is an open-source software maintained by volunteers in their free time.":"Get a subscription to gain more one-click exports, remove the GDevelop splashscreen and messages asking you to get a subscription. With a subscription, you're also supporting the development of GDevelop, which is an open-source software maintained by volunteers in their free time.","Get a subscription to gain more one-click exports, remove the GDevelop splashscreen, this message asking you to get a subscription.":"Get a subscription to gain more one-click exports, remove the GDevelop splashscreen, this message asking you to get a subscription.","Get started by following a tutorial, the best way to understand how GDevelop works.":"Get started by following a tutorial, the best way to understand how GDevelop works.","Getting Started":"Getting Started","Getting Started and Tutorials":"Getting Started and Tutorials","Global Variables":"Global Variables","Global variable":"Global variable","Global variables":"Vari\xE1veis globais","Global variables are variables that are persisted across the scenes during the game.":"Global variables are variables that are persisted across the scenes during the game.","Global variables are variables that are shared amongst all the scenes of the game.":"Global variables are variables that are shared amongst all the scenes of the game.","Google Drive":"Google Drive","Google Drive could not be loaded. Check that you are not offline and have a proper internet connection, then try again.":"Google Drive could not be loaded. Check that you are not offline and have a proper internet connection, then try again.","Google Drive folder or existing file to overwrite":"Google Drive folder or existing file to overwrite","Got it":"Entendi","Gravity on particles on X axis":"Gravidade em part\xEDculas no eixo X","Gravity on particles on Y axis":"Gravidade em part\xEDculas no eixo Y","Group: {0}":function(a){return["Group: ",a("0")]},"HTML5 game (zip)":"Jogo HTML5 (zip)","Height":"Altura","Help":"Ajuda","Help and documentation":"Help and documentation","Help for this action":"Ajuda para esta a\xE7\xE3o","Help for this condition":"Ajuda para esta condi\xE7\xE3o","Help page URL":"Link da p\xE1gina de ajuda","Help to Translate GDevelop":"Ajude a traduzir GDevelop","Help to translate GD in your language":"Ajude a traduzir o GD para o seu idioma","Help!":"Ajuda!","Hidden":"Escondido","Hide":"Esconder","Hide details":"Hide details","Hide experimental exports":"Ocultar exporta\xE7\xF5es experimentais","Hide experimental objects":"Ocultar objetos experimentais","Hide lifecycle functions (advanced)":"Hide lifecycle functions (advanced)","Hide the menu bar in the preview window":"Hide the menu bar in the preview window","Hints & explanations":"Dicas e explica\xE7\xF5es","How to create a joystick displayed on screen, useful to control the player in mobile games.":"How to create a joystick displayed on screen, useful to control the player in mobile games.","How to edit instructions":"How to edit instructions","How to open a loot chest with a key that the player can find in the level":"How to open a loot chest with a key that the player can find in the level","How to show a health bar on screen and a potion to give back health to the player.":"How to show a health bar on screen and a potion to give back health to the player.","I forgot my password":"Esqueci a minha palavra-chave","IDE":"IDE","Icon URL":"URL do \xCDcone","Icons":"\xCDcones","Ideal for advanced game makers":"Ideal for advanced game makers","Ideal for beginners":"Ideal para principiantes","If the parameter is a string or a number, you probably want to use the expressions \"GetArgumentAsString\" or \"GetArgumentAsNumber\", along with the conditions \"Compare two strings\" or \"Compare two numbers\".":"If the parameter is a string or a number, you probably want to use the expressions \"GetArgumentAsString\" or \"GetArgumentAsNumber\", along with the conditions \"Compare two strings\" or \"Compare two numbers\".","If you close this window while the build is being done, you can see its progress and download the game later by clicking on See All My Builds below.":"Se fechar esta janela enquanto a compila\xE7\xE3o est\xE1 a ser efetuada, pode ver o seu progresso e fazer o download do jogo mais tarde clicando em See All My Builds em baixo.","If you don't have a subscription, consider getting one now. Accounts allow you to access all of the online services. With just one click, you can build your game for Android, Windows, macOS and Linux!":"Se n\xE3o tiver uma assinatura, considere comprar uma agora. Contas permitem que voc\xEA aceda todos os servi\xE7os online. Com apenas um clique, pode construir seu jogo para Android, Windows, macOS e Linux!","If you have a popup blocker interrupting the opening, allow the popups and try a second time to open the project.":"If you have a popup blocker interrupting the opening, allow the popups and try a second time to open the project.","Image files":"Ficheiro de imagem","Immerse your players by removing GDevelop logo when the game loads":"Immerse your players by removing GDevelop logo when the game loads","Immerse your players by removing GDevelop logo when the game loads.":"Immerse your players by removing GDevelop logo when the game loads.","Import extension":"Importar extens\xE3o","In order to see your objects in the scene, you need to add an action \"Create objects from external layout\" in your events sheet.":"In order to see your objects in the scene, you need to add an action \"Create objects from external layout\" in your events sheet.","In order to use these external events, you still need to add a \"Link\" event in the events sheet of the corresponding scene":"In order to use these external events, you still need to add a \"Link\" event in the events sheet of the corresponding scene","In pixels. 0 to ignore.":"In pixels. 0 to ignore.","Include events from":"Incluir eventos de","Initial text to display":"Texto inicial a ser exibido","Insert a New Object":"Inserir um Novo Objeto","Inspectors":"Inspectores","Install in project":"Instalar no projeto","Installed Behaviors":"Comportamentos instalados","Instance Variables":"Vari\xE1veis de inst\xE2ncia","Instance variables will override the default values of the variables of the object.":"Instance variables will override the default values of the variables of the object.","Instance variables:":"Vari\xE1veis de inst\xE2ncia:","Instances list":"Lista de inst\xE2ncias","Instances panel is already opened. You can search instances in the scene and click one to move the view to it.":"Instances panel is already opened. You can search instances in the scene and click one to move the view to it.","Instant":"Instant","Instant or permanent force":"Instant or permanent force","Internal Name":"Nome interno","Invert Condition":"Inverter Condi\xE7\xE3o","Invert condition":"Inverter condi\xE7\xE3o","Isometric":"Isometric","Isometric game":"Jogo isom\xE9trico","It is recommended to use your own custom broker server. Read the wiki page for more info.":"It is recommended to use your own custom broker server. Read the wiki page for more info.","It looks like your email is not verified. Click on the link received by email to verify your account. Didn't receive it?":"It looks like your email is not verified. Click on the link received by email to verify your account. Didn't receive it?","Italic":"It\xE1lico","JSON file":"Arquivo JSON","JSON resource":"Recurso JSON","Keyboard Key (text)":"Tecla do Teclado (texto)","Keyboard Shortcuts":"Atalhos do Teclado","Keyboard key":"Tecla de teclado","Kinematic":"Cinem\xE1tico","Label":"R\xF3tulo","Label, shown in the editor":"R\xF3tulo, mostrado no editor","Landscape":"Paisagem","Language":"Idioma","Last run collected on {0} frames.":function(a){return["\xDAltima execu\xE7\xE3o coletada em ",a("0")," quadros."]},"Last updated on":"\xDAltima actualiza\xE7\xE3o em","Launch a preview of the external layout inside the scene, right click for more":"Launch a preview of the external layout inside the scene, right click for more","Launch a preview of the scene, right click for more":"Launch a preview of the scene, right click for more","Launch another preview in a new window":"Launch another preview in a new window","Launch network preview over WiFi/LAN":"Launch network preview over WiFi/LAN","Launch new preview":"Iniciar nova pr\xE9-visualiza\xE7\xE3o","Launch preview with debugger and profiler":"Launch preview with debugger and profiler","Launch the preview":"Lan\xE7ar a pr\xE9-visualiza\xE7\xE3o","Layer":"Camada","Layer (text)":"Camada (texto)","Layer effect name":"Layer effect name","Layer effect parameter name":"Layer effect parameter name","Layer visible":"Camada vis\xEDvel","Layers":"Camadas","Layers panel is already opened. You can add new layers and apply effects on them from this panel.":"Layers panel is already opened. You can add new layers and apply effects on them from this panel.","Layers:":"Camadas:","Layouts":"Layouts","Learn how to add a screen shake effect when the player falls from a very high platform in a platformer.":"Learn how to add a screen shake effect when the player falls from a very high platform in a platformer.","Learn how to add a selector to choose a character (or anything else) in your game.":"Learn how to add a selector to choose a character (or anything else) in your game.","Learn how to add responsive UI using anchors.":"Learn how to add responsive UI using anchors.","Learn how to create a dynamic light following the player, with a flickering effect.":"Learn how to create a dynamic light following the player, with a flickering effect.","Learn how to create a physics based car movement.":"Learn how to create a physics based car movement.","Learn how to make a melee/sword attack with a randomly triggered animation each time a key is pressed.":"Learn how to make a melee/sword attack with a randomly triggered animation each time a key is pressed.","Learn how to make a platformer game using the physics engine.":"Learn how to make a platformer game using the physics engine.","Learn how to make the camera follow the player in a smooth movement.":"Learn how to make the camera follow the player in a smooth movement.","Learn how to push objects, like a box, in a platform game.":"Learn how to push objects, like a box, in a platform game.","Learn how to save the player progress, and other information, and to load them again later.":"Learn how to save the player progress, and other information, and to load them again later.","Learn how to stop the time and make a pause menu.":"Learn how to stop the time and make a pause menu.","Learn how to use particle emitters in GDevelop to create effects like fire, explosion, magic beam, etc...":"Learn how to use particle emitters in GDevelop to create effects like fire, explosion, magic beam, etc...","Learn how to use the Tween Behavior and how it can be used to add more life and animation to you projects.":"Learn how to use the Tween Behavior and how it can be used to add more life and animation to you projects.","Learn more":"Saber mais","Learn more about Instant Games publication":"Saiba mais sobre a publica\xE7\xE3o de jogos instant\xE2neos","Learn more about publishing":"Saiba mais sobre publica\xE7\xE3o","Left (primary)":"Esquerda (prim\xE1rio)","Left margin":"Margem esquerda","License: <0>{0}</0>":function(a){return["License: <0>",a("0"),"</0>"]},"Lifecycle functions (advanced)":"Lifecycle functions (advanced)","Lifecycle functions only included when extension used":"Lifecycle functions only included when extension used","Light (colored)":"Light (colored)","Light (plain)":"Light (plain)","Light object automatically put in lighting layer":"Light object automatically put in lighting layer","Lighting settings":"Lighting settings","Line":"Linha","Line color":"Line color","Linear (antialiased rendering, good for most games)":"Linear (renderiza\xE7\xE3o suavizada, boa para a maioria dos jogos)","Lines length":"Comprimento das linhas","Lines thickness":"Espessura das linhas","Linux (AppImage)":"Linux (AppImage)","Live preview (apply changes to the running preview)":"Live preview (apply changes to the running preview)","Loading Screen":"Loading Screen","Loading...":"A carregar...","Local file system":"Local file system","Local folder":"Local folder","Locate File":"Locate File","Lock position/angle in the editor":"Lock position/angle in the editor","Login":"Iniciar sess\xE3o","Login to your GDevelop account":"Login to your GDevelop account","Logo":"Logo","Logo and progress fade in delay (in seconds)":"Logo and progress fade in delay (in seconds)","Logo and progress fade in duration (in seconds)":"Logo and progress fade in duration (in seconds)","Logout":"Terminar sess\xE3o","Long description":"Long description","Loop":"Loop","Main lifecycle methods":"Principais m\xE9todos do ciclo de vida","Main metrics":"Main metrics","Make a ghost like enemy floating toward the player.":"Make a ghost like enemy floating toward the player.","Make a hyper-casual mobile game where the player must grab shapes and avoid bombs.":"Make a hyper-casual mobile game where the player must grab shapes and avoid bombs.","Make a platform game from scratch.":"Fazer um jogo de plataforma a partir do zero.","Make a simple game where the player must jump on platforms for as long as possible.":"Fazer um jogo simples onde o jogador deve saltar nas plataformas pelo maior tempo poss\xEDvel.","Make a simple tank shooter game from scratch.":"Fazer um simples jogo de tiro de tanques a partir do zero.","Make a space shooter game from scratch.":"Make a space shooter game from scratch.","Make private":"Make private","Make public":"Make public","Make sure to verify all your events creating objects, and optionally add an action to set the Z order back to 0 if it's important for your game. Do you want to continue (recommened)?":"Make sure to verify all your events creating objects, and optionally add an action to set the Z order back to 0 if it's important for your game. Do you want to continue (recommened)?","Make sure you're online, have a proper internet connection and try again. If you download and use GDevelop desktop application, you can also run previews without any internet connection.":"Make sure you're online, have a proper internet connection and try again. If you download and use GDevelop desktop application, you can also run previews without any internet connection.","Maximum FPS (0 to disable)":"FPS M\xE1ximo (0 para desativar)","Maximum Fps is too low":"Maximum Fps is too low","Maximum emitter force applied on particles":"For\xE7a m\xE1xima de emiss\xE3o aplicada em part\xEDculas","Maximum number of particles displayed":"N\xFAmero m\xE1ximo de part\xEDculas exibidas","Middle (Auxiliary button, usually the wheel button)":"Meio (bot\xE3o auxiliar, geralmente o bot\xE3o da roda do rato)","Minimize":"Minimizar","Minimum FPS":"FPS m\xEDnimo","Minimum Fps is too low":"Fps m\xEDnimos s\xE3o demasiado baixos","Minimum duration of the screen (in seconds)":"Minimum duration of the screen (in seconds)","Minimum emitter force applied on particles":"For\xE7a m\xEDnima de emissor aplicada em part\xEDculas","Missing some contributions? If you are the author, create a Pull Request on the corresponding GitHub repository after adding your username in the authors of the example or the extension - or directly ask the original author to add your username.":"Missing some contributions? If you are the author, create a Pull Request on the corresponding GitHub repository after adding your username in the authors of the example or the extension - or directly ask the original author to add your username.","Monetization":"Monetiza\xE7\xE3o","Most browsers will require the user to have interacted with your game before allowing any video to play. Make sure that the player click/touch the screen at the beginning of the game before starting any video.":"A maioria dos navegadores exige que o utilizador tenha interagido com o seu jogo antes de permitir que qualquer v\xEDdeo seja reproduzido. Certifique-se de que o jogador clica/toca no ecr\xE3 no in\xEDcio do jogo antes de iniciar qualquer v\xEDdeo.","Most monitors have a refresh rate of 60 FPS. Setting a maximum number of FPS under 60 will force the game to skip frames, and the real number of FPS will be way below 60, making the game laggy and impacting the gameplay negatively. Consider putting 60 or more for the maximum number or FPS, or disable it by setting 0.":"A maioria dos monitores tem uma taxa de atualiza\xE7\xE3o de 60 FPS. Definir um n\xFAmero m\xE1ximo de FPS abaixo de 60 for\xE7ar\xE1 o jogo a saltar quadros, e o n\xFAmero real de FPS ficar\xE1 muito abaixo de 60, tornando o jogo lento e impactando negativamente o jogo. Considere colocar 60 ou mais para o n\xFAmero m\xE1ximo ou FPS ou desative-o definindo 0.","Mouse button":"Bot\xE3o do mouse","Mouse button (text)":"Bot\xE3o do rato (texto)","Move Events into a Group":"Mover Eventos para um Grupo","Move down":"Mover para baixo","Move objects":"Mover objects","Move objects on layer {0} to:":function(a){return["Mover objects na camada ",a("0")," para:"]},"Move up":"Mover para cima","Multiple files, saved in folder next to the main file":"V\xE1rios ficheiros, salvos na pasta ao lado do ficheiro principal","Musics will only be played if the user has interacted with the game before (by clicking/touching it or pressing a key on the keyboard). This is due to browser limitations. Make sure to have the user interact with the game before using this action.":"As m\xFAsicas s\xF3 ser\xE3o tocadas se o usu\xE1rio tiver interagido com o jogo antes (clicando/tocando nele ou pressionando uma tecla no teclado). Isto \xE9 devido \xE0s limita\xE7\xF5es do navegador. Certifique-se de que o usu\xE1rio interage com o jogo antes de usar esta a\xE7\xE3o.","My Profile":"Meu Profile","My profile":"O meu perfil","NPM":"NPM","Name":"Nome","Name displayed in editor":"Nome exibido no editor","Nearest (no antialiasing, good for pixel perfect games)":"Mais pr\xF3ximo (sem suaviza\xE7\xE3o, bom para jogos perfect pixel)","Need more power? You can upgrade to a new plan to increase the limit!":"Precisa de mais poder? Pode atualizar para um novo plano para aumentar o limite!","New color to set":"New color to set","New extension name":"Novo nome de extens\xE3o","New file name":"Novo nome do arquivo","New object from scratch":"Novo objeto do zero","New players count":"Novo n\xFAmero de jogadores","New upload key (recommended)":"New upload key (recommended)","New value to set":"Novo valor a definir","No":"N\xE3o","No behavior found for your search. Try another search, or search for new behaviors to install.":"Nenhum comportamento encontrado para a sua pesquisa. Tente outra pesquisa ou pesquise por novos comportamentos para instalar.","No bio defined.":"No bio defined.","No bio defined. Edit your profile to tell us what you are using GDevelop for!":"No bio defined. Edit your profile to tell us what you are using GDevelop for!","No changes to the game size":"Nenhuma altera\xE7\xE3o no tamanho do jogo","No filters in this category.":"Sem filtros nesta categoria.","No inspector, choose another element in the list or toggle the raw data view.":"Nenhum inspetor, escolha outro elemento na lista ou alterne a visualiza\xE7\xE3o de dados brutos.","No parameters for this function.":"Nenhum par\xE2metro para esta fun\xE7\xE3o.","No preview running. Run a preview and you will be able to inspect it with the debugger":"Nenhuma pr\xE9-visualiza\xE7\xE3o em execu\xE7\xE3o. Execute uma pr\xE9-visualiza\xE7\xE3o para a inspecionar com o depurador","No properties for this behavior. Add one to store data inside this behavior (for example: health, ammo, speed, etc...)":"Sem propriedades para este comportamento. Adicionar um para armazenar dados dentro deste comportamento (por exemplo: sa\xFAde, muni\xE7\xE3o, velocidade, etc...)","No results":"No results","No results returned for your search. Try something else or browse the categories.":"No results returned for your search. Try something else or browse the categories.","No results returned for your search. Try something else, browse the categories or create your object from scratch!":"No results returned for your search. Try something else, browse the categories or create your object from scratch!","No shortcut":"Nenhum atalho","No tags - add a tag to an object first":"Sem etiquetas - adicionar primeiro uma etiqueta a um object","No username":"No username","Not compatible":"N\xE3o compat\xEDvel","Not now, thanks":"Agora n\xE3o, obrigado","Not now, thanks!":"Agora n\xE3o, obrigado!","Note that the distinction between what is a mobile device and what is not is becoming blurry (with devices like iPad pro and other \"desktop-class\" tablets). If you use this for mobile controls, prefer to check if the device has touchscreen support.":"Note that the distinction between what is a mobile device and what is not is becoming blurry (with devices like iPad pro and other \"desktop-class\" tablets). If you use this for mobile controls, prefer to check if the device has touchscreen support.","Note: write _PARAMx_ for parameters, e.g: Flash _PARAM1_ for 5 seconds":"Note: write _PARAMx_ for parameters, e.g: Flash _PARAM1_ for 5 seconds","Nothing corresponding to your search. Choose an object first or browse the list of actions/conditions.":"Nothing corresponding to your search. Choose an object first or browse the list of actions/conditions.","Nothing corresponding to your search. Try browsing the list instead.":"Nothing corresponding to your search. Try browsing the list instead.","Number":"N\xFAmero","Number between 0 and 1":"Number between 0 and 1","Number of particles in tank (-1 for infinite)":"N\xFAmero de part\xEDculas no tanque (-1 para infinito)","OK":"Certo","Object":"Objeto","Object Groups":"Grupos de Object","Object Name":"Object Name","Object Variables":"Object Variables","Object animation (text)":"Object animation (text)","Object animation name":"Object animation name","Object effect name":"Object effect name","Object effect parameter name":"Object effect parameter name","Object groups":"Grupos de object","Object name":"Nome do object","Object on which this behavior can be used":"Object no qual este comportamento pode ser usado","Object point (text)":"Object point (text)","Object point name":"Object point name","Object type":"Tipo de object","Object variable":"Vari\xE1vel do objeto","Objects":"Objects","Objects on {0}":function(a){return["Objects em ",a("0")]},"Objects or groups being directly referenced in the events: {0}":function(a){return["Objetos ou grupos sendo diretamente refer\xEAnciados nos eventos: ",a("0")]},"Objects panel is already opened: use it to add and edit objects.":"Painel de objects j\xE1 aberto: use-o para adicionar e editar objects.","Ok":"Certo","Old upload key (only if you used to publish your game as an APK and already activated Play App Signing)":"Old upload key (only if you used to publish your game as an APK and already activated Play App Signing)","Once you're done, close this dialog and start adding some functions to the behavior. Then, test the behavior by adding it to an object in a scene.":"Quando terminar, feche esta caixa de di\xE1logo e comece a adicionar algumas fun\xE7\xF5es ao comportamento. Em seguida, teste o comportamento adicionando-o a um object numa scene.","Once you're done, come back to GDevelop and your account will be upgraded automatically, unlocking the extra exports and online services.":"Once you're done, come back to GDevelop and your account will be upgraded automatically, unlocking the extra exports and online services.","One-click packaging for Windows, macOS and Linux up to 10 times a day (every 24 hours).":"One-click packaging for Windows, macOS and Linux up to 10 times a day (every 24 hours).","One-click packaging for Windows, macOS and Linux up to 70 times a day (every 24 hours).":"One-click packaging for Windows, macOS and Linux up to 70 times a day (every 24 hours).","OneDrive (coming soon)":"OneDrive (brevemente)","Open":"Abrir","Open Debugger":"Abrir depurador","Open File":"Abrir Ficheiro","Open GDevelop documentation":"Open GDevelop documentation","Open My Games Dashboard":"Abrir o meu Painel de Jogos","Open My Profile":"Abrir o meu perfil","Open Project Manager":"Abrir gestor de projeto","Open Recent":"Abrir Recente","Open a project":"Abrir um projeto","Open advanced settings":"Abrir configura\xE7\xF5es avan\xE7adas","Open command palette":"Open command palette","Open details":"Open details","Open extension settings":"Open extension settings","Open extension...":"Open extension...","Open external events...":"Open external events...","Open external layout...":"Open external layout...","Open folder":"Abrir pasta","Open in a new tab":"Open in a new tab","Open in the web-app":"Open in the web-app","Open project":"Abrir projeto","Open project icons":"Abrir \xEDcones do projeto","Open project manager":"Abrir gestor de projeto","Open project properties":"Abrir propriedades do projeto","Open project resources":"Open project resources","Open recent project...":"Open recent project...","Open scene properties":"Open scene properties","Open scene variables":"Open scene variables","Open scene...":"Open scene...","Open settings":"Open settings","Open start page":"Open start page","Open the console":"Open the console","Open the exported game folder":"Open the exported game folder","Open the layers editor":"Open the layers editor","Open the list of instances":"Open the list of instances","Open the object groups editor":"Open the object groups editor","Open the objects editor":"Open the objects editor","Open the objects groups editor":"Open the objects groups editor","Open the performance profiler":"Abrir o perfil de desempenho","Open the project":"Open the project","Open the project folder":"Open the project folder","Open the properties panel":"Open the properties panel","Open...":"Abrir...","Operator":"Operator","Optional animation name":"Nome de anima\xE7\xE3o opcional","Options":"Op\xE7\xF5es","Origin":"Origem","Other Community Tutorials":"Other Community Tutorials","Other actions":"Other actions","Other conditions":"Other conditions","Other external events with this name already exist.":"J\xE1 existem outros eventos externos com este nome.","Other lifecycle methods":"Outros m\xE9todos de ciclo de vida","Outline color":"Cor de contorno","Outline opacity (0-255)":"Opacidade do contorno (0-255)","Outline size (in pixels)":"Tamanho do contorno (em p\xEDxeis)","Overriding the ID may have unwanted consequences. Do not use this feature unless you really know what you are doing.":"Overriding the ID may have unwanted consequences. Do not use this feature unless you really know what you are doing.","Package":"Package","Package name (for iOS and Android)":"Nome do pacote (para iOS e Android)","Package your game as a Facebook Instant Games that can be played on Facebook Messenger.":"Package your game as a Facebook Instant Games that can be played on Facebook Messenger.","Package your game as an app for Windows, macOS or Linux directly from GDevelop.":"Package your game as an app for Windows, macOS or Linux directly from GDevelop.","Package your game for Android directly from GDevelop. iOS support is coming soon!":"Package your game for Android directly from GDevelop. iOS support is coming soon!","Package your game for Android up to 10 times a day (every 24 hours).":"Package your game for Android up to 10 times a day (every 24 hours).","Package your game for Android up to 70 times a day (every 24 hours).":"Package your game for Android up to 70 times a day (every 24 hours).","Packaging for Android":"Packaging for Android","Packaging your game for Android will create an APK file that can be installed on Android phones or an Android App Bundle that can be published to Google Play.":"Packaging your game for Android will create an APK file that can be installed on Android phones or an Android App Bundle that can be published to Google Play.","Parameter #{0}:":function(a){return["Par\xE2metro #",a("0"),":"]},"Parameter name in events: `{parameterName}`":function(a){return["Parameter name in events: `",a("parameterName"),"`"]},"Parameters":"Par\xE2metros","Particle Effects Demo":"Particle Effects Demo","Particle end size (in percents)":"Tamanho final da part\xEDcula (em porcentagem)","Particle maximum lifetime (in seconds)":"Vida \xFAtil m\xE1xima da part\xEDcula (em segundos)","Particle maximum rotation speed (degrees/second)":"Velocidade m\xE1xima de rota\xE7\xE3o da part\xEDcula (graus / segundo)","Particle minimum lifetime (in seconds)":"Vida \xFAtil m\xEDnima da part\xEDcula (em segundos)","Particle minimum rotation speed (degrees/second)":"Velocidade m\xEDnima de rota\xE7\xE3o da part\xEDcula (graus / segundo)","Particle start size (in percents)":"Tamanho inicial da part\xEDcula (em porcentagem)","Particles end color":"Cor final das part\xEDculas","Particles kind":"Tipo de part\xEDculas","Particles start color":"Cor inicial das part\xEDculas","Particles start height":"Altura inicial das part\xEDculas","Particles start width":"Largura inicial das part\xEDculas","Password":"Palavra-chave","Paste":"Colar","Paste action(s)":"Paste action(s)","Paste and Match Style":"Paste and Match Style","Paste condition(s)":"Paste condition(s)","Pause the game":"Pausar o jogo","Pause the game (from the toolbar) or hit refresh (on the left) to inspect the game":"Pause the game (from the toolbar) or hit refresh (on the left) to inspect the game","Peer to peer broker server recommendation":"Peer to peer broker server recommendation","Permanent":"Permanente","Platform default":"Padr\xE3o da plataforma","Platformer":"Plataforma","Play":"Play","Play or download":"Play or download","Play the game":"Jogar o jogo","Players count":"Players count","Please check your internet connection or try again later.":"Please check your internet connection or try again later.","Please double check online the changes to make sure that you are aware of anything new in this version that would require you to adapt your project.":"Please double check online the changes to make sure that you are aware of anything new in this version that would require you to adapt your project.","Please get a subscription to keep GDevelop running.":"Please get a subscription to keep GDevelop running.","Please note that your device should be connected on the same network as this computer.":"Por favor, note que o seu dispositivo deve estar conectado na mesma rede que este computador.","Please wait...":"Please wait...","Point":"Ponto","Polygon":"Pol\xEDgono","Polygon is not convex!":"Polygon is not convex!","Portrait":"Retrato","Position":"Posi\xE7\xE3o","Preferences":"Prefer\xEAncias","Prepare your game for Facebook Instant Games so that it can be play on Facebook Messenger. GDevelop will create a compressed file that you can upload on your Facebook Developer account.":"Prepare your game for Facebook Instant Games so that it can be play on Facebook Messenger. GDevelop will create a compressed file that you can upload on your Facebook Developer account.","Press a shortcut combination...":"Press a shortcut combination...","Preview":"Visualizar","Preview is overridden, right click for more":"Preview is overridden, right click for more","Preview over wifi":"Pr\xE9-visualizar via wifi","Profiler":"Perfil","Progress bar":"Progress bar","Progress bar color":"Progress bar color","Progress bar height":"Progress bar height","Progress bar maximum width":"Progress bar maximum width","Progress bar minimum width":"Progress bar minimum width","Progress bar width":"Progress bar width","Project":"Projeto","Project file type":"Tipo de ficheiro do projeto","Project files":"Project files","Project icons":"Project icons","Project manager":"Gestor de projeto","Project package names should not begin with com.example":"Project package names should not begin with com.example","Project properly saved":"Projeto salvo corretamente","Properties":"Propriedades","Properties panel is already opened. After selecting a resource, inspect and change its properties from this panel.":"Properties panel is already opened. After selecting a resource, inspect and change its properties from this panel.","Properties panel is already opened. After selecting an instance on the scene, inspect and change its properties from this panel.":"Properties panel is already opened. After selecting an instance on the scene, inspect and change its properties from this panel.","Property {propertyName} of _PARAM0_ is true":function(a){return["A propriedade ",a("propertyName")," de _PARAM0_ \xE9 verdadeira"]},"Publish online":"Publish online","Publish your game on Game Jolt":"Publicar o seu jogo no Game Jolt","Publish your game on Itch.io":"Publique seu jogo no Itch.io","Publish your game on Kongregate":"Publicar o seu jogo no Kongregate","Publish your game on Poki.com":"Publish your game on Poki.com","Published Games Dashboard":"Published Games Dashboard","Publisher name":"Publisher name","Publishing":"Publishing","Radius of the emitter":"Raio do emissor","Re-install/update":"Reinstalar / atualizar","Read the tutorial":"Read the tutorial","Read the wiki page for more info about the dataloss mode.":"Read the wiki page for more info about the dataloss mode.","Redo":"Redo","Redo the last changes":"Redo the last changes","Refine your search with more specific keyword to see them.":"Refine your search with more specific keyword to see them.","Refresh":"Atualizar","Register the project":"Register the project","Register to see the usage that you've made of the online services":"Registe-se para ver o uso que fez dos servi\xE7os online","Registered on {0}":function(a){return["Registered on ",a("0")]},"Registered on {0}.":function(a){return["Registered on ",a("0"),"."]},"Relational operator":"Relational operator","Remove":"Remove","Remove Resources with Invalid Path":"Remove Resources with Invalid Path","Remove Unused Audio":"Remove Unused Audio","Remove Unused Fonts":"Remove Unused Fonts","Remove Unused Images":"Remove Unused Images","Remove all tags":"Remover todas as etiquetas","Remove objects":"Remover objects","Remove shortcut":"Remove shortcut","Remove the Long Description":"Remove the Long Description","Rename":"Rename","Repeat borders and center textures (instead of stretching them)":"Repetir bordas e texturas centrais (em vez de estic\xE1-las)","Repeat for each instance of {objectName}:":function(a){return["Repeat for each instance of ",a("objectName"),":"]},"Repeat these:":"Repeat these:","Repeat {expression} times:":function(a){return["Repeat ",a("expression")," times:"]},"Replace":"Substituir","Replay":"Repetir","Report a wrong translation":"Reporte uma tradu\xE7\xE3o errada","Report the issue on GitHub":"Reportar o problema no GitHub","Required behavior":"Required behavior","Reset":"Redefinir","Reset Debugger layout":"Reset Debugger layout","Reset Extension Editor layout":"Reset Extension Editor layout","Reset Resource Editor layout":"Reset Resource Editor layout","Reset Scene Editor (small window) layout":"Reset Scene Editor (small window) layout","Reset Scene Editor layout":"Reset Scene Editor layout","Reset all shortcuts to default":"Reset all shortcuts to default","Reset to default":"Reset to default","Reset your password":"Redefinir a sua palavra-passe","Resolution and rendering":"Resolution and rendering","Resources":"Recursos","Resources are automatically added to your project whenever you add an image, a font or a video to an object or when you choose an audio file in events. Choose a resource to display its properties.":"Os recursos s\xE3o automaticamente adicionados ao seu projeto sempre que adiciona uma imagem, um tipo de letra ou um v\xEDdeo a um objeto ou quando escolhe um ficheiro de \xE1udio nos eventos. Escolha um recurso para mostrar as suas propriedades.","Resources needed for the project are downloaded...":"Resources needed for the project are downloaded...","Restart":"Reiniciar","Restarting the preview from scratch is required":"Restarting the preview from scratch is required","Restore original size":"Restore original size","Restore the default collision mask":"Restaurar a m\xE1scara de colis\xE3o padr\xE3o","Retention of players":"Retention of players","Retry":"Tente novamente","Right (secondary)":"Direito (secund\xE1rio)","Right margin":"Margem direita","Round pixels when rendering, useful for pixel perfect games.":"Round pixels when rendering, useful for pixel perfect games.","Run a preview":"Run a preview","Run a preview (with loading screen)":"Run a preview (with loading screen)","Run a preview and you will be able to inspect it with the debugger.":"Execute uma visualiza\xE7\xE3o e poder\xE1 inspecion\xE1-lo com o depurador.","Run on this computer":"Executar neste computador","Save":"Salvar","Save as...":"Salvar como...","Save on Google Drive":"Save on Google Drive","Save project":"Save project","Save project as...":"Save project as...","Saving...":"Saving...","Scale mode (also called \"Sampling\")":"Modo de escala (tamb\xE9m chamado de \"Sampling\")","Scan for Audio":"Scan for Audio","Scan for Fonts":"Scan for Fonts","Scan for Images":"Scan for Images","Scan for Videos":"Scan for Videos","Scene":"Cena","Scene Variables":"Scene Variables","Scene background color":"Cor de fundo da Scene","Scene name":"Scene name","Scene name (text)":"Nome da Scene (texto)","Scene properties":"Scene properties","Scene variable":"Vari\xE1vel de cena","Scene variables can be used to store any value or text during the game.":"Scene variables can be used to store any value or text during the game.","Scenes":"Scenes","Search":"Pesquisar","Search Asset Store":"Search Asset Store","Search New Behaviors":"Pesquisar novos comportamentos","Search and replace in parameters":"Search and replace in parameters","Search for New Extensions":"Pesquisar por Novas Extens\xF5es","Search for new extensions":"Pesquisar por novas extens\xF5es","Search in event sentences":"Search in event sentences","Search in events":"Search in events","Search in:":"Search in:","Search on the documentation.":"Search on the documentation.","Search {searchPlaceholderObjectName} actions":function(a){return["Search ",a("searchPlaceholderObjectName")," actions"]},"Search {searchPlaceholderObjectName} conditions":function(a){return["Search ",a("searchPlaceholderObjectName")," conditions"]},"Search/import extensions":"Search/import extensions","Section name":"Nome da sec\xE7\xE3o","See all my builds":"Ver todas as minhas constru\xE7\xF5es","See all the releases notes":"Veja todas as notas de lan\xE7amentos","See details":"See details","See examples":"Ver exemplos","See logs":"Ver registros","See the releases notes online":"Veja as notas de lan\xE7amento online","Select All":"Select All","Select a behavior to display the functions inside this behavior.":"Selecione um comportamento para exibir as fun\xE7\xF5es dentro deste comportamento.","Select an image":"Selecione uma imagem","Select log groups to display":"Select log groups to display","Select the usernames of the authors of this project. They will be displayed in the selected order, if you publish this game as an example or in the community.":"Select the usernames of the authors of this project. They will be displayed in the selected order, if you publish this game as an example or in the community.","Select the usernames of the contributors to this extension. They will be displayed in the order selected. Do not see your name? Go to the Profile section and create an account!":"Select the usernames of the contributors to this extension. They will be displayed in the order selected. Do not see your name? Go to the Profile section and create an account!","Send it again":"Send it again","Sentence in Events Sheet":"Sentence in Events Sheet","Services Usage":"Services Usage","Sessions count":"Sessions count","Set as Global group":"Set as Global group","Set as a global object":"Set as a global object","Set property {propertyName} of _PARAM0_ to _PARAM2_":function(a){return["Definir a propriedade ",a("propertyName")," de _PARAM0_ para _PARAM2_"]},"Set shortcut":"Set shortcut","Setting the minimum number of FPS below 20 will increase a lot the time that is allowed between the simulation of two frames of the game. If case of a sudden slowdown, or on slow computers, this can create buggy behaviors like objects passing beyond a wall. Consider setting 20 as the minimum FPS.":"Definir o n\xFAmero m\xEDnimo de FPS abaixo de 20 aumentar\xE1 muito o tempo permitido entre a simula\xE7\xE3o de dois quadros do jogo. Em caso de lentid\xE3o repentina, ou em computadores lentos, isso pode criar comportamentos de bugs, como objetos a passar por uma parede. Considere definir 20 como o FPS m\xEDnimo.","Setup grid":"Setup grid","Share same collision masks for all animations":"Partilhe as mesmas m\xE1scaras de colis\xE3o para todas as anima\xE7\xF5es","Share same collision masks for all sprites of this animation":"Partilhe as mesmas m\xE1scaras de colis\xE3o para todos os sprites desta anima\xE7\xE3o","Share same points for all animations":"Partilhe os mesmos pontos para todas as anima\xE7\xF5es","Share same points for all sprites of this animation":"Partilhe os mesmos pontos para todos os sprites desta anima\xE7\xE3o","Short description":"Pequena descri\xE7\xE3o","Should finish soon.":"Deve terminar em breve.","Show Mask":"Show Mask","Show Parameter Names":"Show Parameter Names","Show Project Manager":"Mostrar gestor de projeto","Show Start Page":"Mostrar P\xE1gina Inicial","Show deprecated (old) behaviors":"Mostrar comportamentos obsoletos (antigos)","Show details":"Show details","Show experimental exports":"Mostrar exporta\xE7\xF5es experimentais","Show experimental objects":"Mostrar objects experimentais","Show grid":"Show grid","Show internal":"Show internal","Show lifecycle functions (advanced)":"Show lifecycle functions (advanced)","Show link to tutorials:":"Show link to tutorials:","Show progress bar":"Show progress bar","Showing {0} of {resultsCount}":function(a){return["Showing ",a("0")," of ",a("resultsCount")]},"Signing options":"Signing options","Single file (default)":"\xDAnico ficheiro (padr\xE3o)","Size":"Tamanho","Size:":"Tamanho:","Something wrong happened :(":"Aconteceu algo de errado :(","Speech":"Discurso","Spray cone angle (in degrees)":"\xC2ngulo do cone do spray (em graus)","Start Network Preview (Preview over WiFi/LAN)":"Start Network Preview (Preview over WiFi/LAN)","Start Page":"P\xE1gina Inicial","Start Preview with Debugger and Performance Profiler":"Start Preview with Debugger and Performance Profiler","Start a new game from scratch.":"Comece um novo jogo do zero.","Start a new project from scratch.":"Start a new project from scratch.","Start all previews from external layout {0}":function(a){return["Start all previews from external layout ",a("0")]},"Start all previews from scene {0}":function(a){return["Start all previews from scene ",a("0")]},"Start opacity (0-255)":"Opacidade inicial (0-255)","Start profiling":"Iniciar profiling","Start profiling and then stop it after a few seconds to see the results.":"Comece a criar o perfil e pare depois de alguns segundos para ver os resultados.","Start typing a command...":"Start typing a command...","Start typing a username":"Start typing a username","Start using GDevelop":"Start using GDevelop","Starters":"Iniciantes","Static":"Est\xE1tico","Stop music and sounds on startup":"Stop music and sounds on startup","Stop profiling":"Parar profiling","String":"S\xE9rie de texto","String (text)":"String (texto)","String Expression":"Express\xE3o de string","String from a list of options (text)":"String from a list of options (text)","Structure":"Structure","Submit extension to the community":"Enviar extens\xE3o para a comunidade","Submit your game to the showcase":"Submit your game to the showcase","Submit your project as an example":"Submit your project as an example","Subscriptions can be stopped at any time. GDevelop uses Stripe.com for secure payment. No credit card data is stored by GDevelop: everything is managed by Stripe secure infrastructure.":"As assinaturas podem ser interrompidas a qualquer momento. O GDevelop usa Stripe.com para pagamento seguro. Nenhum dado de cart\xE3o de cr\xE9dito \xE9 armazenado pelo GDevelop: tudo \xE9 gerido pela infraestrutura segura do Stripe.","Suggest names of variables used in events but not declared in the list of variables":"Suggest names of variables used in events but not declared in the list of variables","Support for translations is still new and in beta. GDevelop needs your help to be translated in your language!":"O suporte para tradu\xE7\xF5es ainda \xE9 novo e est\xE1 em vers\xE3o beta. O GDevelop precisa da sua ajuda para ser traduzido no seu idioma!","Switch to create objects with the highest Z order of the layer":"Switch to create objects with the highest Z order of the layer","Tags":"Tags","Tags (comma separated)":"Tags (separadas por v\xEDrgulas)","Text color:":"Text color:","Text in the format R;G;B, like 100;200;180":"Text in the format R;G;B, like 100;200;180","Text to replace in parameters":"Text to replace in parameters","Text to search in event sentences":"Text to search in event sentences","Text to search in parameters":"Text to search in parameters","Texts":"Texts","Textured":"Texturizado","Thanks for getting a subscription and supporting GDevelop!":"Thanks for getting a subscription and supporting GDevelop!","Thanks to all users of GDevelop! There must be missing tons of people, please send your name if you've contributed and you're not listed.":"Obrigado a todos os utilizadores do GDevelop! Deve estar a faltar toneladas de pessoas, por favor, envie seu nome, se voc\xEA contribuiu e n\xE3o est\xE1 listado.","Thanks!":"Obrigado!","The behavior is not attached to this object. Please select another object or add this behavior.":"O comportamento n\xE3o est\xE1 anexado a este object. Por favor, selecione outro object ou adicione esse comportamento.","The behavior was added to the project. You can now add it to your object.":"The behavior was added to the project. You can now add it to your object.","The description of the behavior should explain what the behavior is doing to the object, and, briefly, how to use it.":"A descri\xE7\xE3o do comportamento deve explicar o que o comportamento est\xE1 fazendo com o object, e resumidamente, como us\xE1-lo.","The extension was added to the project. You can now use it in the list of actions/conditions and, if it's a behavior, in the list of behaviors for an object.":"The extension was added to the project. You can now use it in the list of actions/conditions and, if it's a behavior, in the list of behaviors for an object.","The font size is stored directly inside the font. If you want to change it, export again your font using an external editor like bmFont. Click on the help button to learn more.":"The font size is stored directly inside the font. If you want to change it, export again your font using an external editor like bmFont. Click on the help button to learn more.","The force will only push the object during the time of one frame. Typically used in an event with no conditions or with conditions that stay valid for a certain amount of time.":"A for\xE7a s\xF3 ir\xE1 empurrar o objeto durante o tempo de um frame. Normalmente usado em um evento sem condi\xE7\xF5es ou com condi\xE7\xF5es que permanecem v\xE1lidas por um determinado per\xEDodo de tempo.","The force will push the object forever, unless you use the action \"Stop the object\". Typically used in an event with conditions that are only true once, or with a \"Trigger Once\" condition.":"A for\xE7a empurrar\xE1 o object para sempre, a menos que voc\xEA use a a\xE7\xE3o \"Pare o object\". Normalmente usada num evento com condi\xE7\xF5es que s\xF3 s\xE3o verdadeiras uma vez ou com uma condi\xE7\xE3o \"Trigger Once\".","The game was properly exported. You can now use Electron Builder (you need Node.js installed and to use the command-line on your computer to run it) to create an executable.":"The game was properly exported. You can now use Electron Builder (you need Node.js installed and to use the command-line on your computer to run it) to create an executable.","The light object was automatically placed on the Lighting layer.":"The light object was automatically placed on the Lighting layer.","The lighting layer renders an ambient light on the scene. All lights should be placed on this layer so that shadows are properly rendered. By default, the layer follows the base layer camera. Uncheck this if you want to manually move the camera using events.":"The lighting layer renders an ambient light on the scene. All lights should be placed on this layer so that shadows are properly rendered. By default, the layer follows the base layer camera. Uncheck this if you want to manually move the camera using events.","The name of a parameter can not be empty. Enter a name for the parameter or you won't be able to use it.":"The name of a parameter can not be empty. Enter a name for the parameter or you won't be able to use it.","The name of a property cannot be \"name\" or \"type\", as they are used by GDevelop internally.":"O nome de uma propriedade n\xE3o pode ser \"nome\" ou \"tipo\", uma vez que eles s\xE3o usados pelo GDevelop internamente.","The name of a property cannot be empty.":"O nome de uma propriedade n\xE3o pode estar vazio.","The object does not exist or can't be used here.":"O object n\xE3o existe ou n\xE3o pode ser usado aqui.","The object was added to the list of objects. You can now use it on the scene, in events, and customize it.":"The object was added to the list of objects. You can now use it on the scene, in events, and customize it.","The package name begins with com.example, make sure you replace it with an unique one to be able to publish your game on app stores.":"The package name begins with com.example, make sure you replace it with an unique one to be able to publish your game on app stores.","The package name begins with com.example, make sure you replace it with an unique one, else installing your game might overwrite other games.":"The package name begins with com.example, make sure you replace it with an unique one, else installing your game might overwrite other games.","The package name is containing invalid characters or not following the convention \"xxx.yyy.zzz\" (numbers allowed after a letter only).":"The package name is containing invalid characters or not following the convention \"xxx.yyy.zzz\" (numbers allowed after a letter only).","The polygon is not convex. Ensure it is, otherwise the collision mask won't work.":"The polygon is not convex. Ensure it is, otherwise the collision mask won't work.","The preview could not be launched because an error happened: {0}.":function(a){return["The preview could not be launched because an error happened: ",a("0"),"."]},"The preview could not be launched because you're offline.":"The preview could not be launched because you're offline.","The project file appears to be malformed, but an autosave file exists (backup made automatically by GDevelop). Would you like to try to load it instead?":"O ficheiro de projeto parece estar malformado, mas existe um arquivo de autosave (c\xF3pia de seguran\xE7a feita automaticamente pela GDevelop). Voc\xEA gostaria de tentar carreg\xE1-lo?","The sentence is probably missing this/these parameter(s):":"A frase provavelmente est\xE1 faltando este/estes par\xE2metro(s):","The shape used in the Physics behavior is independent from the collision mask of the object. Be sure to use the \"Collision\" condition provided by the Physics behavior in the events. The usual \"Collision\" condition won't take into account the shape that you've set up here.":"The shape used in the Physics behavior is independent from the collision mask of the object. Be sure to use the \"Collision\" condition provided by the Physics behavior in the events. The usual \"Collision\" condition won't take into account the shape that you've set up here.","The specified external events do not exist in the game. Be sure that the name is correctly spelled or create them using the project manager.":"Os eventos externos especificados n\xE3o existem no jogo. Certifique-se de que o nome est\xE1 escrito corretamente ou crie-os usando o gerente de projeto.","The tilemap must be designed in a separated program, Tiled, that can be downloaded on mapeditor.org. Save your map as a JSON file, then select here the Atlas image that you used and the Tile map JSON file.":"The tilemap must be designed in a separated program, Tiled, that can be downloaded on mapeditor.org. Save your map as a JSON file, then select here the Atlas image that you used and the Tile map JSON file.","The usage of a number or expression is deprecated. Please now use only \"Permanent\" or \"Instant\" for configuring forces.":"O uso de um n\xFAmero ou express\xE3o \xE9 descontinuado. Por favor agora use apenas \"Permanente\" ou \"Instant\xE2neo\" para configurar for\xE7as.","There are no behaviors here.":"There are no behaviors here.","There are no events here.":"There are no events here.","There are no objects. Objects will appear if you add some as parameters.":"There are no objects. Objects will appear if you add some as parameters.","There is no object in your game or in this scene. Start by adding an new object in the scene editor, using the objects list.":"There is no object in your game or in this scene. Start by adding an new object in the scene editor, using the objects list.","There is nothing to configure for this behavior. You can still use events to interact with the object and this behavior.":"N\xE3o h\xE1 nada a configurar para esse comportamento. Voc\xEA ainda pode usar eventos para interagir com o object e esse comportamento.","There is nothing to configure for this object. You can still use events to interact with the object.":"N\xE3o h\xE1 nada para configurar para este object. Voc\xEA ainda pode usar eventos para interagir com o object.","There is nothing to configure.":"N\xE3o h\xE1 nada para configurar.","There was an error while making an auto-save of the project. Verify that you have permissions to write in the project folder.":"There was an error while making an auto-save of the project. Verify that you have permissions to write in the project folder.","There was an issue getting the game analytics.":"There was an issue getting the game analytics.","There were errors when fetching resources for the project.":"There were errors when fetching resources for the project.","There were no players or stored metrics for this day. Be sure to publish your game and get players to try it to see the collected anonymous analytics.":"There were no players or stored metrics for this day. Be sure to publish your game and get players to try it to see the collected anonymous analytics.","Third editor":"Third editor","This action is deprecated and should not be used anymore. Instead, use for all your objects the behavior called \"Physics2\" and the associated actions (in this case, all objects must be set up to use Physics2, you can't mix the behaviors).":"Esta a\xE7\xE3o est\xE1 obsoleta e n\xE3o deve mais ser usada. Em vez disso, use para todos os seus objects o comportamento chamado \"Physics2\" e as a\xE7\xF5es associadas (neste caso, todos os objects devem ser configurados para usar Physics2, voc\xEA n\xE3o pode misturar os comportamentos).","This action will create a new texture and re-render the text each time it is called, which is expensive and can reduce performances. Prefer to avoid changing a lot the character size of a text.":"Esta a\xE7\xE3o ir\xE1 criar uma nova textura e renderizar novamente o texto de cada vez que for chamada, o que \xE9 caro e pode reduzir o desempenho. Prefira evitar alterar muito o tamanho dos caracteres de um texto.","This behavior is being used by multiple types of objects. Thus, you can't restrict its usage to any particular object type. All the object types using this behavior are listed here: {0}":function(a){return["Este comportamento est\xE1 sendo usado por v\xE1rios tipos de objects. Portanto, voc\xEA n\xE3o pode restringir o seu uso a nenhum object type espec\xEDfico. Todos os object types que usam este comportamento s\xE3o listados aqui: ",a("0")]},"This behavior is unknown. It might be a behavior that was defined in an extension and that was later removed. You should delete it.":"This behavior is unknown. It might be a behavior that was defined in an extension and that was later removed. You should delete it.","This build is old and the generated games can't be downloaded anymore.":"Esta compila\xE7\xE3o \xE9 antiga e os jogos gerados n\xE3o podem mais ser descarregados.","This can either be a URL to a web page, or a path starting with a slash that will be opened in the GDevelop wiki. Leave empty if there is no help page, although it's recommended you eventually write one if you distribute the extension.":"This can either be a URL to a web page, or a path starting with a slash that will be opened in the GDevelop wiki. Leave empty if there is no help page, although it's recommended you eventually write one if you distribute the extension.","This condition may have unexpected results when the object is on different floors at the same time, due to the fact that the engine only considers the first floor the object comes into contact with.":"This condition may have unexpected results when the object is on different floors at the same time, due to the fact that the engine only considers the first floor the object comes into contact with.","This file is an extension file for GDevelop 5. You should instead import it, using the window to add a new extension to your project.":"This file is an extension file for GDevelop 5. You should instead import it, using the window to add a new extension to your project.","This file is not recognized as a GDevelop 5 project. Be sure to open a file that was saved using GDevelop.":"This file is not recognized as a GDevelop 5 project. Be sure to open a file that was saved using GDevelop.","This function will have a lot of parameters. Consider creating groups or functions for a smaller set of objects so that the function is easier to reuse.":"Esta fun\xE7\xE3o ter\xE1 muitos par\xE2metros. Considere criar grupos ou fun\xE7\xF5es para um conjunto menor de objects, para que a fun\xE7\xE3o seja mais f\xE1cil de reutilizar.","This is a \"lifecycle function\". It will be called automatically by the game engine. It has no parameters. Only global objects can be used as the events will be run for all scenes in your game.":"This is a \"lifecycle function\". It will be called automatically by the game engine. It has no parameters. Only global objects can be used as the events will be run for all scenes in your game.","This is a \"lifecycle method\". It will be called automatically by the game engine and has two parameters: \"Object\" (the object the behavior is acting on) and \"Behavior\" (the behavior itself).":"This is a \"lifecycle method\". It will be called automatically by the game engine and has two parameters: \"Object\" (the object the behavior is acting on) and \"Behavior\" (the behavior itself).","This is a \"lifecycle method\". It will be called automatically by the game engine for each instance living on the scene having the behavior.":"This is a \"lifecycle method\". It will be called automatically by the game engine for each instance living on the scene having the behavior.","This is a UI component dev environment for GDevelop.":"Este \xE9 um ambiente de dev de componente de UI para GDevelop.","This is a relative path that will open in the GDevelop wiki.":"This is a relative path that will open in the GDevelop wiki.","This is a version of GDevelop 5 that you can try online.":"Esta \xE9 uma vers\xE3o do GDevelop 5 que voc\xEA pode experimentar online.","This is link to a webpage.":"This is link to a webpage.","This is not a URL starting with \"http://\" or \"https://\".":"This is not a URL starting with \"http://\" or \"https://\".","This is the configuration of your behavior. Make sure to choose a proper internal name as it's hard to change it later. Enter a description explaining what the behavior is doing to the object.":"This is the configuration of your behavior. Make sure to choose a proper internal name as it's hard to change it later. Enter a description explaining what the behavior is doing to the object.","This is the list of builds that you've done. Note that you can download games generated during the last 7 days, after which they are removed.":"This is the list of builds that you've done. Note that you can download games generated during the last 7 days, after which they are removed.","This is your current plan":"Este \xE9 o seu plano atual","This name cannot be empty, please enter a new name.":"This name cannot be empty, please enter a new name.","This name is already taken":"This name is already taken","This name is already taken by another extension.":"Este nome j\xE1 \xE9 usado por outra extens\xE3o.","This name is already taken by another function. Choose another name.":"Este nome j\xE1 \xE9 usado por outra fun\xE7\xE3o. Escolha outro nome.","This name is already used by another property. Choose a unique name for each property.":"Este nome j\xE1 \xE9 usado por outra propriedade. Escolha um nome \xFAnico para cada propriedade.","This name is invalid. Only use alphanumeric characters (0-9, a-z) and underscores. Digits are not allowed as the first character.":"This name is invalid. Only use alphanumeric characters (0-9, a-z) and underscores. Digits are not allowed as the first character.","This name is not valid. Only use alphanumeric characters (0-9, a-z) and underscores.":"Este nome n\xE3o \xE9 v\xE1lido. Use apenas caracteres alfanum\xE9ricos (0 a 9, a-z) e sublinhados.","This name is reserved for a lifecycle function of the extension. Choose another name for your function.":"This name is reserved for a lifecycle function of the extension. Choose another name for your function.","This name is reserved for a lifecycle method of the behavior. Choose another name for your custom function.":"Este nome \xE9 reservado para um m\xE9todo de ciclo de vida do comportamento. Escolha outro nome para sua fun\xE7\xE3o personalizada.","This object does not have any specific configuration. Add it on the scene and use events to interact with it.":"Este object n\xE3o possui nenhuma configura\xE7\xE3o espec\xEDfica. Adicione-o na scene e use eventos para interagir com ele.","This object has no animations containing images. Start by adding an animation.":"This object has no animations containing images. Start by adding an animation.","This object has no behaviors: please add this behavior to the object first.":"Este object n\xE3o tem comportamentos: por favor adicione primeiro este comportamento ao object.","This object is experimental and not yet complete. It might have bugs or incomplete support in GDevelop, be sure to read the wiki by clicking on help button bellow.":"This object is experimental and not yet complete. It might have bugs or incomplete support in GDevelop, be sure to read the wiki by clicking on help button bellow.","This project is not registered online. Register it now to get access to metrics collected anonymously, like the number of daily players and retention of the players after a few days.":"This project is not registered online. Register it now to get access to metrics collected anonymously, like the number of daily players and retention of the players after a few days.","This project is registered online but you don't have access to it. Ask the original owner of the game to share it with you to get access to the game metrics.":"This project is registered online but you don't have access to it. Ask the original owner of the game to share it with you to get access to the game metrics.","This shortcut clashes with another action.":"This shortcut clashes with another action.","This should make the purpose of the property easy to understand":"Isto deve tornar o prop\xF3sito da propriedade f\xE1cil de entender","This sprite uses the default collision mask, a rectangle that is as large as the sprite.":"Este sprite usa a m\xE1scara de colis\xE3o padr\xE3o, um ret\xE2ngulo t\xE3o grande como o sprite.","This will be used when packaging and submitting your application to the stores.":"This will be used when packaging and submitting your application to the stores.","This will export your game and upload it on GDevelop games hosting. The game will be freely accessible from the link, available for a few days and playable from any computer browser or mobile phone (iOS, Android 5+).":"This will export your game and upload it on GDevelop games hosting. The game will be freely accessible from the link, available for a few days and playable from any computer browser or mobile phone (iOS, Android 5+).","This will export your game as a Cordova project. Cordova is a technology that enables HTML5 games to be packaged for iOS and Android.":"This will export your game as a Cordova project. Cordova is a technology that enables HTML5 games to be packaged for iOS and Android.","This will export your game so that you can package it for Windows, macOS or Linux. You will need to install third-party tools (Node.js, Electron Builder) to package your game.":"This will export your game so that you can package it for Windows, macOS or Linux. You will need to install third-party tools (Node.js, Electron Builder) to package your game.","This will export your game to a folder.":"This will export your game to a folder.","This/these file(s) are outside the project folder. Would you like to make a copy of them in your project folder first (recommended)?":"This/these file(s) are outside the project folder. Would you like to make a copy of them in your project folder first (recommended)?","Time (ms)":"Tempo (ms)","Timestamp: {0}":function(a){return["Timestamp: ",a("0")]},"To begin, open or create a new project.":"Para come\xE7ar, abrir ou criar um novo projeto.","To edit the external events, choose the scene in which it will be included:":"To edit the external events, choose the scene in which it will be included:","To edit the external layout, choose the scene in which it will be included:":"To edit the external layout, choose the scene in which it will be included:","To obtain the best pixel-perfect effect possible, go in the resources editor and disable the Smoothing for all images of your game. It will be done automatically for new images added from now.":"Para obter o melhor efeito pixel-perfect poss\xEDvel, v\xE1 ao editor de recursos e desabilite a suaviza\xE7\xE3o para todas as imagens do seu jogo. Isso ser\xE1 feito automaticamente para novas imagens adicionadas a partir de agora.","To preview the shape that the Physics engine will use for this object, choose first a temporary image to use for the preview.":"To preview the shape that the Physics engine will use for this object, choose first a temporary image to use for the preview.","To skip this dialog and <0>directly open the preview next time</0>, please allow popups to be opened for this website in your browser.":"Para saltar este di\xE1logo e <0>abrir diretamente a visualiza\xE7\xE3o da pr\xF3xima vez</0>, por favor, permita que os popups sejam abertos para este site no seu navegador.","To use this feature, we ask you to get a subscription to GDevelop.":"Para usar este recurso, pedimos que voc\xEA obtenha uma subscri\xE7\xE3o para o GDevelop.","Today (so far, in real time)":"Today (so far, in real time)","Toggle Developer Tools":"Toggle Developer Tools","Toggle Fullscreen":"Toggle Fullscreen","Toggle disabled":"Toggle disabled","Toggle grid":"Toggle grid","Toggle mask":"Toggle mask","Toggle/edit grid":"Toggle/edit grid","Top margin":"Margem superior","Top-Left":"Superior-Esquerdo","Trailer":"Trailer","True":"Verdade","True (checked)":"Verdadeiro (verificado)","True or False":"True or False","True or False (boolean)":"True or False (boolean)","Tutorials":"Tutoriais","Tutorials on YouTube":"Tutorials on YouTube","Type":"Tipo","Type:":"Type:","UI Theme":"Tema UI","URL":"URL","Unable to create the game in the specified folder. Check that you have permissions to write in this folder: {outputPath} or choose another folder.":function(a){return["N\xE3o \xE9 poss\xEDvel criar o jogo na pasta especificada. Verifique se voc\xEA tem permiss\xE3o para escrever nesta pasta: ",a("outputPath")," ou escolha outra pasta."]},"Unable to download and install the extension. Verify that your internet connection is working or try again later.":"N\xE3o \xE9 poss\xEDvel baixar e instalar a extens\xE3o. Verifique se sua conex\xE3o com a internet est\xE1 a funcionar ou tente novamente mais tarde.","Unable to download the icon. Verify your internet connection or try again later.":"Unable to download the icon. Verify your internet connection or try again later.","Unable to fetch the example.":"Unable to fetch the example.","Unable to load the code editor":"N\xE3o \xE9 poss\xEDvel carregar o editor de c\xF3digo","Unable to load the example or save it on disk.":"Unable to load the example or save it on disk.","Unable to load the image":"N\xE3o \xE9 poss\xEDvel carregar a imagem","Unable to load the information about the latest GDevelop releases. Verify your internet connection or retry later.":"N\xE3o \xE9 poss\xEDvel carregar as informa\xE7\xF5es sobre os \xFAltimos lan\xE7amentos do GDevelop. Verifique a sua conex\xE3o com a internet ou tente novamente mais tarde.","Unable to load the profile, please verify your internet connection or try again later.":"Unable to load the profile, please verify your internet connection or try again later.","Unable to open the preview! Be sure that popup are allowed for this website.":"N\xE3o \xE9 poss\xEDvel abrir a visualiza\xE7\xE3o! Certifique-se de que s\xE3o permitidos popups para este website.","Unable to open the project because this provider is unknown: {storageProviderName}. Try to open the project again from another location.":function(a){return["Unable to open the project because this provider is unknown: ",a("storageProviderName"),". Try to open the project again from another location."]},"Unable to open the project.":"Unable to open the project.","Unable to open this file.":"Unable to open this file.","Unable to save as the project! Please try again by choosing another location.":"Unable to save as the project! Please try again by choosing another location.","Unable to search in the documentation. Are you sure you are online and have a proper internet connection?":"Unable to search in the documentation. Are you sure you are online and have a proper internet connection?","Unable to start the debugger server! Make sure that you are authorized to run servers on this computer.":"N\xE3o \xE9 poss\xEDvel iniciar o servidor de depura\xE7\xE3o! Certifique-se de que voc\xEA est\xE1 autorizado a executar servidores neste computador.","Unable to start the server for the preview! Make sure that you are authorized to run servers on this computer. Otherwise, use classic preview to test your game.":"N\xE3o \xE9 poss\xEDvel iniciar o servidor para a visualiza\xE7\xE3o! Certifique-se de que voc\xEA est\xE1 autorizado a executar servidores neste computador. Caso contr\xE1rio, use a pr\xE9-visualiza\xE7\xE3o cl\xE1ssica para testar seu jogo.","Undo":"Undo","Undo the last changes":"Undo the last changes","Unfortunately, this example requires a newer version of GDevelop to work. Upgrade GDevelop to be able to use this extension in your project.":"Unfortunately, this example requires a newer version of GDevelop to work. Upgrade GDevelop to be able to use this extension in your project.","Unfortunately, this extension requires a newer version of GDevelop to work. Upgrade GDevelop to be able to use this extension in your project.":"Unfortunately, this extension requires a newer version of GDevelop to work. Upgrade GDevelop to be able to use this extension in your project.","Unknown behavior":"Comportamento desconhecido","Unknown status":"Estatuto desconhecido","Unregister this game":"Unregister this game","Update":"Atualizar","Update resolution during the game to fit the screen or window size":"Update resolution during the game to fit the screen or window size","Update the color of {propertyLabel}":function(a){return["Update the color of ",a("propertyLabel")]},"Update the game details from the project":"Update the game details from the project","Update the value of {propertyLabel}":function(a){return["Atualizar o valor de ",a("propertyLabel")]},"Updates":"Updates","Upgrade my account":"Atualizar a minha conta","Upgrade/change":"Atualizar/alterar","Upload to build service":"Upload to build service","Upload your game online directly from GDevelop and share the link to players. Play to your game using your browser on computers and mobile phones.":"Upload your game online directly from GDevelop and share the link to players. Play to your game using your browser on computers and mobile phones.","Use a custom collision mask":"Use uma m\xE1scara de colis\xE3o personalizada","Use the new action/condition editor":"Use the new action/condition editor","Use this external layout inside this scene to start all previews":"Use this external layout inside this scene to start all previews","Use this scene to start all previews":"Use this scene to start all previews","Username":"Username","Using Nearest Scale Mode":"Using Nearest Scale Mode","Using a lot of effects can have a severe negative impact on the rendering performance, especially on low-end or mobile devices. Consider using less effects if possible. You can also disable and re-enable effects as needed using events.":"Using a lot of effects can have a severe negative impact on the rendering performance, especially on low-end or mobile devices. Consider using less effects if possible. You can also disable and re-enable effects as needed using events.","Using effects":"Using effects","Using empty events based behavior":"Using empty events based behavior","Using events based behavior":"Using events based behavior","Using function extractor":"Using function extractor","Using instance drag'n'drop":"Using instance drag'n'drop","Using lighting layer":"Using lighting layer","Using non smoothed textures":"Using non smoothed textures","Using the instance properties panel":"Using the instance properties panel","Using the instances panel":"Using the instances panel","Using the layers panel":"Using the layers panel","Using the objects panel":"Using the objects panel","Using the resource properties panel":"Using the resource properties panel","Using too much effects":"Using too much effects","Validate these parameters":"Validate these parameters","Verify that you have the authorizations for reading the file you're trying to access.":"Verify that you have the authorizations for reading the file you're trying to access.","Verify your internet connection or try again later.":"Verify your internet connection or try again later.","Version":"Vers\xE3o","Version number (X.Y.Z)":"N\xFAmero da vers\xE3o (X.Y.Z)","Version {0}":function(a){return["Version ",a("0")]},"Video Tutorials":"Video Tutorials","Video files":"Video files","Video format supported can vary according to devices and browsers. For maximum compatibility, use H.264/mp4 file format (and AAC for audio).":"O formato de v\xEDdeo suportado pode variar de acordo com os dispositivos e navegadores. Para m\xE1xima compatibilidade, use o formato de arquivo H.264 /mp4 (e AAC para \xE1udio).","Video resource":"Recurso de v\xEDdeo","View":"Ver","Visible":"Visible","Visible in editor":"Vis\xEDvel no editor","Warn/show explanation about:":"Warn/show explanation about:","Watch changes in game engine (GDJS) sources and auto import them (dev only)":"Watch changes in game engine (GDJS) sources and auto import them (dev only)","Watch the tutorial":"Watch the tutorial","We need your support!":"We need your support!","Web (upload online)":"Web (upload online)","Web (upload online) Build":"Web (upload online) Build","Welcome to GDevelop":"Welcome to GDevelop","What are you using GDevelop for?":"What are you using GDevelop for?","What's new in GDevelop?":"O que h\xE1 de novo no GDevelop?","What's new?":"O que h\xE1 de novo?","When previewing the game in the editor, this duration is ignored (the game preview starts as soon as possible).":"When previewing the game in the editor, this duration is ignored (the game preview starts as soon as possible).","When you add variables to an object, any instance of the object put on the scene or created during the game will have these variables attached to it.":"When you add variables to an object, any instance of the object put on the scene or created during the game will have these variables attached to it.","When you create an object using an action, GDevelop now sets the Z order of the object to the maximum value that was found when starting the scene for each layer. This allow to make sure that objects that you create are in front of others. This game was created before this change, so GDevelop maintains the old behavior: newly created objects Z order is set to 0. It's recommended that you switch to the new behavior by clicking the following button.":"When you create an object using an action, GDevelop now sets the Z order of the object to the maximum value that was found when starting the scene for each layer. This allow to make sure that objects that you create are in front of others. This game was created before this change, so GDevelop maintains the old behavior: newly created objects Z order is set to 0. It's recommended that you switch to the new behavior by clicking the following button.","While these conditions are true:":"While these conditions are true:","Width":"Largura","Window":"Window","Window title":"T\xEDtulo da janela","Windows (auto-installer file)":"Windows (ficheiro de instala\xE7\xE3o autom\xE1tica)","Windows (exe)":"Windows (exe)","Windows (zip file)":"Windows (ficheiro zip)","Windows (zip)":"Windows (zip)","Windows/macOS/Linux":"Windows/macOS/Linux","Windows/macOS/Linux (manual)":"Windows/macOS/Linux (manual)","Windows/macOS/Linux Build":"Windows/macOS/Linux Build","X":"X","X offset (in pixels)":"Deslocamento X (em p\xEDxeis)","Y":"Y","Y offset (in pixels)":"Deslocamento Y (em p\xEDxeis)","Yes":"Sim","Yes or No":"Yes or No","Yes or No (boolean)":"Yes or No (boolean)","Yesterday":"Yesterday","You are in raw mode. You can edit the fields, but be aware that this can lead to unexpected results or even crash the debugged game!":"Voc\xEA est\xE1 em modo bruto. Voc\xEA pode editar os campos, mas esteja ciente de que isso pode levar a resultados inesperados ou at\xE9 mesmo travar o jogo depurado!","You are not connected. Create an account to build your game for Android, Windows, macOS and Linux in one click, and get access to metrics for your game.":"You are not connected. Create an account to build your game for Android, Windows, macOS and Linux in one click, and get access to metrics for your game.","You are subscribed to {0}. Congratulations! You have access to more online services, including building your game for Android, Windows, macOS and Linux in one click!":function(a){return["Voc\xEA est\xE1 inscrito em ",a("0"),". Parab\xE9ns! Voc\xEA tem acesso a mais servi\xE7os online, incluindo a constru\xE7\xE3o do seu jogo para Android, Windows, macOS e Linux em um clique!"]},"You can also launch a preview from this external layout, but remember that it will still create objects from the scene, as well as trigger its events. Make sure to disable any action loading the external layout before doing so to avoid having duplicate objects!":"You can also launch a preview from this external layout, but remember that it will still create objects from the scene, as well as trigger its events. Make sure to disable any action loading the external layout before doing so to avoid having duplicate objects!","You can contribute and create your own themes:":"You can contribute and create your own themes:","You can download the file of your game to continue working on it using the full GDevelop version:":"Voc\xEA pode descarregar o ficheiro do seu jogo para continuar a trabalhar nele usando a vers\xE3o completa do GDevelop:","You can export the extension to a file to easily import it in another project. If your extension is providing useful and reusable functions or behaviors, consider sharing it with the GDevelop community!":"Voc\xEA pode exportar a extens\xE3o para um ficheiro para import\xE1-lo facilmente noutro projeto. Se sua extens\xE3o estiver fornecendo fun\xE7\xF5es ou comportamentos \xFAteis e reutiliz\xE1veis, considere compartilh\xE1-la com a comunidade GDevelop!","You can now compile the game by yourself using Cordova command-line tool to iOS (XCode is required) or Android (Android SDK is required).":"You can now compile the game by yourself using Cordova command-line tool to iOS (XCode is required) or Android (Android SDK is required).","You can now create a game on Facebook Instant Games, if not already done, and upload the generated archive.":"You can now create a game on Facebook Instant Games, if not already done, and upload the generated archive.","You can now upload the game to a web hosting to play to the game.":"Agora voc\xEA pode enviar o jogo para uma hospedagem na Web para jogar no jogo.","You can open the command palette by pressing":"You can open the command palette by pressing","You can then upload it on a website/game hosting service and share it on marketplaces and gaming portals like Kongregate, Game Jolt, itch.io, Poki...":"You can then upload it on a website/game hosting service and share it on marketplaces and gaming portals like Kongregate, Game Jolt, itch.io, Poki...","You can use GDevelop for free! Online packaging for Android, Windows, macOS and Linux is limited to twice a day (every 24 hours) to avoid overloading the services.":"You can use GDevelop for free! Online packaging for Android, Windows, macOS and Linux is limited to twice a day (every 24 hours) to avoid overloading the services.","You don't have a subscription. Get one to increase the limits!":"Voc\xEA n\xE3o tem uma subscri\xE7\xE3o. Obtenha uma para aumentar os limites!","You don't have any builds on the online services for now.":"You don't have any builds on the online services for now.","You don't have any usage of the online services for now":"Voc\xEA n\xE3o tem nenhum uso dos servi\xE7os online por enquanto","You have {0} remaining builds for today (out of {1}).":function(a){return["Voc\xEA tem ",a("0")," constru\xE7\xF5es restantes para hoje (de ",a("1"),")."]},"You must be online and have a proper internet connection to export your game.":"You must be online and have a proper internet connection to export your game.","You must select a key.":"Voc\xEA deve selecionar uma tecla.","You must select a valid key. \"{value}\" is not valid.":function(a){return["Voc\xEA deve selecionar uma tecla v\xE1lida. \"",a("value"),"\" n\xE3o \xE9 v\xE1lido."]},"You need to login first to see your builds.":"You need to login first to see your builds.","You should have received an email containing instructions to reset and set a new password. Once it's done, you can use your new password in GDevelop.":"Voc\xEA deve ter recebido um e-mail contendo instru\xE7\xF5es para redefinir e definir uma nova palavra-passe. Uma vez isso feito, voc\xEA pode usar a sua nova palavra-passe no GDevelop.","You'll also have access to online packaging for iOS or other services when they are released.":"You'll also have access to online packaging for iOS or other services when they are released.","You're about to open (or re-open) a project. Click on \"Open the Project\" to continue.":"You're about to open (or re-open) a project. Click on \"Open the Project\" to continue.","You're also supporting the development of GDevelop, an open-source software! In the future, more online services will be available for users with a subscription.":"Voc\xEA tamb\xE9m est\xE1 a apoiar o desenvolvimento do GDevelop, um software de c\xF3digo aberto! No futuro, mais servi\xE7os on-line estar\xE3o dispon\xEDveis para usu\xE1rios com subscri\xE7\xE3o.","You've made some changes here. Are you sure you want to discard them and open the function?":"Voc\xEA fez algumas altera\xE7\xF5es aqui. Tem a certeza de que deseja descart\xE1-las e abrir a fun\xE7\xE3o?","Your account is upgraded, with the extra exports and online services. If you wish to change later, come back to your profile and choose another plan.":"Your account is upgraded, with the extra exports and online services. If you wish to change later, come back to your profile and choose another plan.","Your browser will now open to enter your payment details (handled securely by Stripe.com).":"Your browser will now open to enter your payment details (handled securely by Stripe.com).","Your email is now verified!":"Your email is now verified!","Your game will be exported and packaged online as a stand-alone game for Windows, Linux and/or macOS.":"Your game will be exported and packaged online as a stand-alone game for Windows, Linux and/or macOS.","Your game won't work if you open index.html on your computer. You must upload it to a web hosting (Kongregate, Itch.io, etc...) or a web server to run it.":"O seu jogo n\xE3o funcionar\xE1 se voc\xEA abrir o index.html no seu computador. Voc\xEA deve envi\xE1-lo para um alojamento web (Kongregate, Itch.io, etc...) ou para um servidor web para execut\xE1-lo.","Your latest changes could not be applied to the preview(s) being run. You should start a new preview instead to make sure that all your changes are reflected in the game.":"Your latest changes could not be applied to the preview(s) being run. You should start a new preview instead to make sure that all your changes are reflected in the game.","Your name":"O seu nome","Your new plan is now activated":"Your new plan is now activated","Your preview is ready! Click on the button to launch the preview.":"Sua pr\xE9-visualiza\xE7\xE3o est\xE1 pronta! Clique no bot\xE3o para iniciar a pr\xE9-visualiza\xE7\xE3o.","Your preview is ready! On your mobile or tablet, open your browser and enter in the address bar:":"Sua pr\xE9-visualiza\xE7\xE3o est\xE1 pronta! No seu telem\xF3vel ou tablet, abra o navegador e insira na barra de endere\xE7o:","Your project is registered online. This allows you to get access to metrics collected anonymously, like the number of daily players and retention of the players after a few days.":"Your project is registered online. This allows you to get access to metrics collected anonymously, like the number of daily players and retention of the players after a few days.","Your subscription could not be updated. Please try again later!":"Your subscription could not be updated. Please try again later!","Your subscription was properly cancelled. Sorry to see you go!":"Your subscription was properly cancelled. Sorry to see you go!","YourGame.json":"YourGame.json","Z Order":"Ordem Z","Z Order of objects created from events":"Z Order of objects created from events","Zoom In":"Zoom In","Zoom Out":"Zoom Out","Zoom in":"Zoom in","Zoom in (you can also use Ctrl + Mouse wheel)":"Zoom in (you can also use Ctrl + Mouse wheel)","Zoom out":"Zoom out","Zoom out (you can also use Ctrl + Mouse wheel)":"Zoom out (you can also use Ctrl + Mouse wheel)","a permanent":"a permanent","add":"add","an instant":"an instant","by {0}":function(a){return["by ",a("0")]},"divide by":"divide by","false":"falso","iOS & Android (manual)":"iOS & Android (manual)","iOS (iPhone and iPad) icons:":"\xEDcones iOS (iPhone e iPad):","macOS (zip file)":"macOS (ficheiro zip)","macOS (zip)":"macOS (zip)","multiply by":"multiply by","no":"n\xE3o","or":"ou","set to":"set to","subtract":"subtract","the property {propertyName}":function(a){return["the property ",a("propertyName")]},"true":"verdadeiro","yes":"sim","{0}\u20AC/month":function(a){return[a("0"),"\u20AC/month"]},"{propertyName} property":function(a){return[a("propertyName")," propriedade"]},"{resultsCount} results":function(a){return[a("resultsCount")," results"]},"~{0} minutes.":function(a){return["~",a("0")," minutos."]},"\u2260 (not equal to)":"\u2260 (not equal to)","\u2264 (less or equal to)":"\u2264 (less or equal to)","\u2265 (greater or equal to)":"\u2265 (greater or equal to)","Javascript code":"C\xF3digo JavaScript","Insert some Javascript code into events":"Inserir algum c\xF3digo Javascript em eventos","Storage":"Armazenamento","Consider objects touching each other, but not overlapping, as in collision (default: no)":"Considere objects tocando uns nos outros, mas n\xE3o sobrepostos, como em colis\xE3o (padr\xE3o: n\xE3o)","Error during exporting! Unable to export events:\n":"Erro durante a exporta\xE7\xE3o. N\xE3o \xE9 poss\xEDvel exportar eventos: \n","Error during exporting! Unable to export source files:\n":"Erro durante a exporta\xE7\xE3o. N\xE3o \xE9 poss\xEDvel exportar arquivos de fonte: \n","Error during export:\n":"Erro durante a exporta\xE7\xE3o: \n","Unable to write ":"N\xE3o \xE9 poss\xEDvel gravar ","Could not copy external file":"N\xE3o pode copiar o arquivo externo","HTML5 (Web and Android games)":"HTML5 (Jogos Web e Android)","HTML5 and javascript based games for web browsers.":"Jogos em HTML5 e Javascript para navegadores web.","Enables the creation of 2D games that can be played in web browsers. These can also be exported to Android with third-party tools.":"Permite a cria\xE7\xE3o de jogos 2D que podem ser jogados em navegadores da web. Estes tamb\xE9m podem ser exportados para Android com ferramentas de terceiros.","Tiled Sprite Object":"Objeto Sprite em grade (Tiled)","Tiled Sprite":"Sprite em grade","Displays an image repeated over an area.":"Exibe uma imagem repetida ao longo de uma \xE1rea.","Opacity":"Opacidade","Compare the opacity of a Tiled Sprite, between 0 (fully transparent) to 255 (opaque).":"Comparar a opacidade de um Sprite em ladrilhado, entre 0 (totalmente transparente) at\xE9 255 (opaco).","the opacity":"a opacidade","Visibility":"Visibilidade","Change Tiled Sprite opacity":"Alterar a opacidade do Sprite ladrilhado","Change the opacity of a Tiled Sprite. 0 is fully transparent, 255 is opaque (default).":"Alterar a opacidade de um Sprite ladrilhado. 0 \xE9 totalmente transparente, 255 \xE9 opaco (padr\xE3o).","Tint color":"Tonalidade","Change the tint of a Tiled Sprite. The default color is white.":"Change the tint of a Tiled Sprite. The default color is white.","Change tint of _PARAM0_ to _PARAM1_":"Change tint of _PARAM0_ to _PARAM1_","Tint":"Tom","Modify the width of a Tiled Sprite.":"Modifica a largura de um Sprite em grade.","the width":"a largura","Size and angle":"Tamanho e \xE2ngulo","Test the width of a Tiled Sprite.":"Testar a largura de um Sprite em Grade.","Modify the height of a Tiled Sprite.":"Modificar a altura de um Sprite em Grade.","the height":"a altura","Test the height of a Tiled Sprite.":"Testar a altura de um Sprite em Grade.","Modify the angle of a Tiled Sprite.":"Modificar o \xE2ngulo de um Sprite em Grade.","the angle":"o \xE2ngulo","Image X Offset":"Deslocamento X da Imagem","Modify the offset used on the X axis when displaying the image.":"Modifica o deslocamento utilizado no eixo X ao exibir a imagem.","the X offset":"the X offset","Image offset":"Deslocamento da imagem","Test the offset used on the X axis when displaying the image.":"Teste o deslocamento utilizado no eixo X ao exibir a imagem.","Image Y Offset":"Deslocamento Y da Imagem","Modify the offset used on the Y axis when displaying the image.":"Modifica o deslocamento utilizado no eixo Y ao exibir a imagem.","the Y offset":"the Y offset","Test the offset used on the Y axis when displaying the image.":"Teste o deslocamento utilizado no eixo Y ao exibir a imagem.","Gravity":"Gravidade","Jump speed":"Velocidade de salto","Jump sustain time":"Tempo de sustenta\xE7\xE3o do salto","Maximum time (in seconds) during which the jump strength is sustained if the jump key is held - allowing variable height jumps.":"Tempo m\xE1ximo (em segundos) durante o qual a for\xE7a do salto \xE9 sustentada se a tecla de salto \xE9 mantida pressionada - permitindo alturas de salto vari\xE1veis.","Max. falling speed":"Velocidade max. de queda","Ladder climbing speed":"Ladder climbing speed","Acceleration":"Acelera\xE7\xE3o","Deceleration":"Desacelera\xE7\xE3o","Max. speed":"Max. velocidade","Default controls":"Controles padr\xE3o","Slope max. angle":"\xC2ngulo de Inclina\xE7\xE3o max.","Can grab platform ledges":"Pode agarrar nas bordas da plataforma","Grab offset on Y axis":"Deslocamento (offset) para fora do eixo y","Grab tolerance on X axis":"Pegue a toler\xE2ncia no eixo X","Round coordinates":"Coordenadas arredondadas","Platform Behavior":"Comportamento de plataforma","Platformer character":"Objeto que se movimenta em plataformas","Controllable character that can jump and run on platforms.":"Personagem control\xE1vel que pode saltar e correr em plataformas.","Is moving":"Est\xE1 se movendo","Check if the object is moving (whether it is on the floor or in the air).":"Verifique se o objeto est\xE1 se movendo (seja no ch\xE3o ou no ar).","_PARAM0_ is moving":"_PARAM0_ est\xE1 se movendo","Is on floor":"Est\xE1 no ch\xE3o","Check if the object is on a platform.":"Verifique se o objeto est\xE1 sobre uma plataforma.","_PARAM0_ is on floor":"_PARAM0_ est\xE1 no ch\xE3o","Is on ladder":"Est\xE1 numa escada","Check if the object is on a ladder.":"Verifique se o objeto est\xE1 numa escada.","_PARAM0_ is on ladder":"_PARAM0_ est\xE1 numa escada","Is jumping":"Est\xE1 a saltar","Check if the object is jumping.":"Verifique se o objeto est\xE1 a saltar.","_PARAM0_ is jumping":"_PARAM0_ est\xE1 a saltar","Is falling":"Est\xE1 caindo","Check if the object is falling.\nNote that the object can be flagged as jumping and falling at the same time: at the end of a jump, the fall speed becomes higher than the jump speed.":"Verifica se o objeto est\xE1 a cair.\nNote que o objeto pode ser marcado como estando a saltar e a cair ao mesmo tempo: no final de um salto, a velocidade de queda torna-se maior que a de salto.","_PARAM0_ is falling":"_PARAM0_ est\xE1 caindo","Is grabbing platform ledge":"Est\xE1 agarrado \xE0 borda de uma plataforma","Check if the object is grabbing a platform ledge.":"Verifica se o objeto est\xE1 agarrado \xE0 borda de uma plataforma.","_PARAM0_ is grabbing a platform ledge":"_PARAM0_ est\xE1 a agarrar a borda de uma plataforma","Compare the gravity applied on the object (in pixels per second per second).":"Compare a gravidade aplicada no objeto (em pixels por segundo).","the gravity":"a gravidade","Change the gravity applied on an object (in pixels per second per second).":"Altere a gravidade aplicada a um objeto (em pixels por segundo).","Maximum falling speed":"Velocidade m\xE1xima de queda","Compare the maximum falling speed of the object (in pixels per second).":"Compare a velocidade m\xE1xima de queda do objeto (em pixels por segundo).","the maximum falling speed":"the maximum falling speed","Change the maximum falling speed of an object (in pixels per second).":"Altere a velocidade m\xE1xima de queda de um objeto (em pixels por segundo).","Compare the ladder climbing speed (in pixels per second).":"Compare the ladder climbing speed (in pixels per second).","the ladder climbing speed":"the ladder climbing speed","Change the ladder climbing speed (in pixels per second).":"Change the ladder climbing speed (in pixels per second).","Compare the acceleration of the object (in pixels per second per second).":"Compare a acelera\xE7\xE3o do objeto (em pixels por segundo).","the acceleration":"a acelera\xE7\xE3o","Change the acceleration of an object (in pixels per second per second).":"Altere a acelera\xE7\xE3o de um objeto (em pixels por segundo).","Compare the deceleration of the object (in pixels per second per second).":"Compare a desacelera\xE7\xE3o do objeto (em pixels por segundo).","the deceleration":"a desacelera\xE7\xE3o","Change the deceleration of an object (in pixels per second per second).":"Mude a desacelera\xE7\xE3o de um objeto (em pixels por segundo).","Maximum speed":"Velocidade m\xE1xima","Compare the maximum speed of the object (in pixels per second).":"Compare a velocidade m\xE1xima do objeto (em pixels por segundo).","the maximum speed":"the maximum speed","Change the maximum speed of an object (in pixels per second).":"Altere a velocidade m\xE1xima de um objeto (em pixels por segundo).","Compare the jump speed of the object (in pixels per second).":"Compare a velocidade do salto do objeto (em pixels por segundo).","the jump speed":"the jump speed","Change the jump speed of an object (in pixels per second).":"Altere a velocidade do salto de um objeto (em pixels por segundo).","Compare the jump sustain time of the object (in seconds).":"Compare o tempo de sustenta\xE7\xE3o do salto de um objecto (em segundos).","the jump sustain time":"o tempo de sustenta\xE7\xE3o do salto","Change the jump sustain time of an object (in seconds).":"Alterar o tempo de sustenta\xE7\xE3o do salto de um objecto (em segundos).","Allow jumping again":"Permitir pular novamente","When this action is executed, the object is able to jump again, even if it is in the air: this can be useful to allow a double jump for example. This is not a permanent effect: you must call again this action everytime you want to allow the object to jump (apart if it's on the floor).":"Quando esta ac\xE7\xE3o \xE9 executada, o objecto pode saltar novamente, mesmo que esteja no ar: isto pode ser \xFAtil para permitir um salto duplo, por exemplo. Isto n\xE3o \xE9 um efeito permanente: voc\xEA deve usar esta ac\xE7\xE3o novamente, sempre que voc\xEA queira permitir que o objecto salte (a n\xE3o ser que esteja no ch\xE3o).","Allow _PARAM0_ to jump again":"Permitir _PARAM0_ saltar novamente","Forbid jumping again in the air":"Forbid jumping again in the air","This revokes the effect of \"Allow jumping again\". The object is made unable to jump while in mid air. This has no effect if the object is not in the air.":"This revokes the effect of \"Allow jumping again\". The object is made unable to jump while in mid air. This has no effect if the object is not in the air.","Forbid _PARAM0_ to air jump":"Forbid _PARAM0_ to air jump","Can jump":"Can jump","Check if the object can jump.":"Check if the object can jump.","_PARAM0_ can jump":"_PARAM0_ consegue saltar","Simulate left key press":"Simular o pressionamento da tecla esquerda","Simulate a press of the left key.":"Simule um pressionar da tecla esquerda.","Simulate pressing Left for _PARAM0_":"Simular o pressionamento da esquerda para _PARAM0_","Controls":"Controlos","Simulate right key press":"Simular o pressionamento da tecla direita","Simulate a press of the right key.":"Simula o pressionar da tecla direita.","Simulate pressing Right for _PARAM0_":"Simular o pressionamento da tecla direita para _PARAM0_","Simulate up key press":"Simular tecla para cima","Simulate a press of the up key (used when on a ladder).":"Simula o pressionar da tecla para cima(usado quando estiver em uma escada).","Simulate pressing Up for _PARAM0_":"Simule pressionar tecla para cima para _PARAM0_","Simulate down key press":"Simule pressionar tecla para baixo","Simulate a press of the down key (used when on a ladder).":"Simule o pressionar da tecla para baixo(usado quando estiver em uma escada).","Simulate pressing Down for _PARAM0_":"Simule pressionar tecla para baixo para _PARAM0_","Simulate ladder key press":"Simule pressionar tecla de escada","Simulate a press of the ladder key (used to grab a ladder).":"Simule pressionar tecla escada (usada para agarrar uma escada).","Simulate pressing Ladder key for _PARAM0_":"Simular que est\xE1 pressionando o bot\xE3o de escada para _PARAM0_","Simulate release ladder key press":"Simulate release ladder key press","Simulate a press of the Release Ladder key (used to get off a ladder).":"Simulate a press of the Release Ladder key (used to get off a ladder).","Simulate pressing Release Ladder key for _PARAM0_":"Simulate pressing Release Ladder key for _PARAM0_","Simulate jump key press":"Simular tecla para cima","Simulate a press of the jump key.":"Simule o pressionar da tecla pular.","Simulate pressing Jump key for _PARAM0_":"Simular que est\xE1 pressionando a tecla de salto para _PARAM0_","Simulate release platform key press":"Simulate release platform key press","Simulate a press of the release platform key (used when grabbing a platform ledge).":"Simulate a press of the release platform key (used when grabbing a platform ledge).","Simulate pressing Release Platform key for _PARAM0_":"Simulate pressing Release Platform key for _PARAM0_","Simulate control":"Simular controle","Simulate a press of a key.\nValid keys are Left, Right, Jump, Ladder, Release Ladder, Up, Down.":"Simulate a press of a key.\nValid keys are Left, Right, Jump, Ladder, Release Ladder, Up, Down.","Simulate pressing _PARAM2_ key for _PARAM0_":"Simular que est\xE1 pressionando _PARAM2_ para _PARAM0_","Key":"Tecla","Ignore default controls":"Ignorar controles padr\xE3o","De/activate the use of default controls.\nIf deactivated, use the simulated actions to move the object.":"Des/ativar o uso de controles padr\xE3o.\nSe desativado, use o simulador de a\xE7\xF5es para mover o objeto.","Ignore default controls for _PARAM0_: _PARAM2_":"Ignorar controles padr\xE3o para _PARAM0_: _PARAM2_","Ignore controls":"Ignorar controles","Platform grabbing":"Captura da plataforma","Enable (or disable) the ability of the object to grab platforms when falling near to one.":"Ativar (ou desativar) a habilidade do objeto de agarrar plataformas quando estiver a cair perto de uma.","Allow _PARAM0_ to grab platforms: _PARAM2_":"Permitir _PARAM0_ para agarrar as plataformas: _PARAM2_","Can grab platforms":"Pode agarrar plataformas","Check if the object can grab the platforms.":"Verifique se o objeto pode agarrar as plataformas.","_PARAM0_ can grab the platforms":"_PARAM0_ pode agarrar as plataformas","Current falling speed":"Current falling speed","Compare the current falling speed of the object (in pixels per second).":"Compare the current falling speed of the object (in pixels per second).","the current falling speed":"the current falling speed","Current jump speed":"Current jump speed","Compare the current jump speed of the object (in pixels per second).":"Compare the current jump speed of the object (in pixels per second).","the current jump speed":"the current jump speed","Current speed":"Current speed","Compare the current speed of the object (in pixels per second).":"Compare the current speed of the object (in pixels per second).","the current speed":"the current speed","Get the gravity applied on the object":"Obter a gravidade aplicada ao objeto","Get the maximum falling speed":"Obtenha a velocidade m\xE1xima de queda","Get the ladder climbing speed":"Get the ladder climbing speed","The time during which keeping the jump button held allow the initial jump speed to be maintained.":"A dura\xE7\xE3o do tempo a qual o bot\xE3o de saltar \xE9 mantido pressionado, permite que a velocidade inicial do salto seja mantida.","Current fall speed":"Current fall speed","Platform":"Plataforma","Platform that Platformer characters can run on.":"Plataforma na qual personagens de plataforma podem percorrer.","Change platform type":"Alterar o tipo de plataforma","Change the platform type of the object: Platform, Jump-Through, or Ladder.":"Alterar o tipo de plataforma do objeto: Plataforma, Pulo atrav\xE9s ou Escada.","Set platform type of _PARAM0_ to _PARAM2_":"Definir o tipo de plataforma de _PARAM0_ para _PARAM2_","Platforms":"Plataformas","Platform type (\"Platform\", \"Jumpthru\" or \"Ladder\")":"Tipo de plataforma (\"Plataforma\", \"Jumpthru\" ou \"Escada\")","Is object on given floor":"Is object on given floor","Test if an object is on a given floor.":"Test if an object is on a given floor.","_PARAM0_ is on floor _PARAM2_":"_PARAM0_ is on floor _PARAM2_","Ladder":"Escada","Jumpthru platform":"Plataforma de Pular Atrav\xE9s","Ledges can be grabbed":"Bordas podem ser agarradas","Gravity on X axis (in m/s\xB2)":"Gravidade no eixo X (em m/s\xB2)","Gravity on Y axis (in m/s\xB2)":"Gravidade no eixo Y (em m/s\xB2)","X Scale: number of pixels for 1 meter":"Escala X: n\xFAmero de p\xEDxeis para 1 metro","Y Scale: number of pixels for 1 meter":"Escala Y: n\xFAmero de p\xEDxeis para 1 metro","X scale: number of pixels for 1 meter":"Escala X: n\xFAmero de p\xEDxeis para 1 metro","Y scale: number of pixels for 1 meter":"Escala Y: n\xFAmero de p\xEDxeis para 1 metro","Physics Engine (deprecated)":"Mecanismo de F\xEDsica (obsoleto)","Physics Engine":"Mecanismo de F\xEDsica","Physics":"F\xEDsica","Make objects move as if they are subject to the laws of physics. If you're creating a new game, prefer Physics Engine 2.0":"Fa\xE7a mover os objects como se estivessem sujeitos \xE0s leis da f\xEDsica. Se voc\xEA est\xE1 a criar um novo jogo, prefira o Mecanismo de F\xEDsica 2.0","Make the object static":"Establecer como objeto est\xE1tico","Make the object immovable.":"Tornar o objeto im\xF3vel.","Make _PARAM0_ static":"Fazer _PARAM0_ est\xE1tico","Movement":"Movimento","Make the object dynamic":"Establecer como objeto din\xE2mico","Make the object dynamic ( affected by forces and other objects ).":"Tornar objeto din\xE2mico (afetado por for\xE7as e outros objetos).","Make _PARAM0_ dynamic":"Fazer _PARAM0_ din\xE2mico","The object is dynamic":"O objeto \xE9 din\xE2mico","Test if an object is dynamic ( affected by forces and other objects ).":"Testar se um objeto \xE9 din\xE2mico (afetado por for\xE7as e outros objetos).","_PARAM0_ is dynamic":"_PARAM0_ \xE9 din\xE2mico","Fix rotation":"Fixar a rota\xE7\xE3o","Prevent the object from rotating":"Impedir que o objeto rode","Fix rotation of _PARAM0_":"Fixar a rota\xE7\xE3o de _PARAM0_","Rotation":"Rota\xE7\xE3o","Add a hinge":"Adicionar uma dobradi\xE7a","Add a hinge that the object will rotate around.\nThe distance between the hinge and the object will remain identical.":"Adicionar uma articula\xE7\xE3o em torno da qual o objeto ir\xE1 girar.\nA dist\xE2ncia entre a articula\xE7\xE3o e o objeto ser\xE1 igual.","Add a hinge to _PARAM0_ at _PARAM2_;_PARAM3_":"Adicionar uma dobradi\xE7a para _PARAM0_ em _PARAM2_; _PARAM3_","Joints":"Articula\xE7\xF5es","Hinge X position":"Posi\xE7\xE3o X da dobradi\xE7a","Hinge Y position":"Posi\xE7\xE3o Y da dobradi\xE7a","Add a hinge between two objects":"Adicionar uma dobradi\xE7a entre dois objetos","Add a hinge that the object will rotate around.":"Adicionar uma articula\xE7\xE3o em torno da qual o objeto ir\xE1 girar.","Add a hinge between _PARAM0_ and _PARAM2_":"Adicionar uma dobradi\xE7a entre _PARAM0_ e _PARAM2_","X position of the hinge, from the first object mass center":"Posi\xE7\xE3o X da dobradi\xE7a, desde o centro da massa do primeiro objeto","Y position of the hinge, from the first object mass center":"Posi\xE7\xE3o Y da dobradi\xE7a, desde o centro da massa do primeiro objeto","Add a gear between two objects":"Adicionar uma engrenagem entre dois objetos","Add a virtual gear between two objects.":"Adicione uma engrenagem virtual entre dois objetos.","Add a gear between _PARAM0_ and _PARAM2_":"Adicionar uma engrenagem entre _PARAM0_ e _PARAM2_","Ratio":"R\xE1cio","Make object's rotation free":"Fazer o objeto rodar livremente","Allows the object to rotate.":"Permite que o objeto rode.","Allow _PARAM0_ to rotate":"Permitir que _PARAM0_ seja rodado","Fixed rotation":"Rota\xE7\xE3o fixa","Test if the object's rotation is fixed.":"Testar se a rota\xE7\xE3o do objeto \xE9 fixa.","The rotation of _PARAM0_ is fixed.":"A rota\xE7\xE3o de _PARAM0_ \xE9 fixa.","Treat object like a bullet.":"Tratar o objeto como uma bala.","Treat the object like a bullet, so it will have better collision handling.":"Tratar o objeto como uma bala para que tenha melhor resolu\xE7\xE3o de colis\xF5es.","Consider _PARAM0_ as a bullet":"Considerar o _PARAM0_ como uma bala","Other":"Outro","Do not treat object like a bullet":"N\xE3o tratar o objeto como uma bala","Do not treat the object like a bullet, so it will use standard collision handling.":"N\xE3o tratar o objeto como uma bala para que use a resolu\xE7\xE3o de colis\xF5es padr\xE3o.","Do not consider _PARAM0_ as a bullet.":"N\xE3o considere a _PARAM0_ como uma bala.","Object is treated like a bullet":"O objeto \xE9 tratado como uma bala","Test if the object is treated like a bullet":"Testa se o objeto \xE9 tratado como uma bala","_PARAM0_ is considered as a bullet":"_PARAM0_ \xE9 considerado como uma bala","Apply an impulse":"Aplique um impulso","Apply an impulse to the object.":"Aplique um impulso para o objeto.","Apply to _PARAM0_ impulse _PARAM2_;_PARAM3_":"Aplicar a _PARAM0_ impulso _PARAM2_; _PARAM3_","Displacement":"Deslocamento","X component ( Newtons/Seconds )":"Componente X (Newtons/segundos)","Y component ( Newtons/Seconds )":"Componente Y ( Newtons/Segundos )","Apply an impulse (angle)":"Aplique um impulso (\xE2ngulo)","Apply an impulse to an object, using an angle and a length as coordinates.":"Aplicar um impulso num objeto, usando um \xE2ngulo e um comprimento como coordenadas.","Apply to _PARAM0_ impulse _PARAM3_ with angle: _PARAM2_\xB0":"Aplicar a _PARAM0_ impulso _PARAM3_ com \xE2ngulo: _PARAM2_\xB0","Impulse value ( Newton/seconds )":"Valor de impulso (Newton/segundos)","Apply an impulse toward a position":"Aplicar um impulso em dire\xE7\xE3o a uma posi\xE7\xE3o","Apply an impulse, directed toward a position, to the object.":"Aplica um impulso, direcionado para uma posi\xE7\xE3o, para o objeto.","Apply to _PARAM0_ impulse _PARAM4_ toward position _PARAM2_;_PARAM3_":"Aplicar a _PARAM0_ _PARAM4_ de impulso em dire\xE7\xE3o \xE0 posi\xE7\xE3o _PARAM2_; _PARAM3_","X position":"Posi\xE7\xE3o X","Y position":"Posi\xE7\xE3o Y","Add a force":"Adicionar uma for\xE7a","Add a force to the object":"Adicionar uma for\xE7a ao objeto","Apply to _PARAM0_ force _PARAM2_;_PARAM3_":"Aplicar a _PARAM0_ for\xE7a _PARAM2_; _PARAM3_","X component ( Newtons )":"Componente (Newtons) x","Y component ( Newtons )":"Componente Y (Newtons)","Apply a force ( angle )":"Aplicar uma for\xE7a (\xE2ngulo)","Apply a force to an object, using an angle and a length as coordinates.":"Aplica uma for\xE7a a um objeto, usando um comprimento e um \xE2ngulo como coordenadas.","Apply to _PARAM0_ force _PARAM3_ at angle _PARAM2_":"Aplicar a _PARAM0_ for\xE7a _PARAM3_ no \xE2ngulo _PARAM2_","Length of the force ( Newtons )":"Comprimento da for\xE7a (Newton)","Apply a force toward a position":"Aplicar uma for\xE7a em dire\xE7\xE3o a uma posi\xE7\xE3o","Apply a force, directed toward a position, to the object.":"Aplica uma for\xE7a, direcionada para uma posi\xE7\xE3o, para o objeto.","Add to _PARAM0_ force _PARAM4_ toward position _PARAM2_;_PARAM3_":"Adicionar a _PARAM0_ for\xE7a _PARAM4_ em dire\xE7\xE3o \xE0 posi\xE7\xE3o _PARAM2_; _PARAM3_","Add a torque (a rotation)":"Adicionar um torque (uma rota\xE7\xE3o)","Add a torque (a rotation) to the object.":"Adiciona bin\xE1rio (uma rota\xE7\xE3o) ao objeto.","Add to _PARAM0_ torque _PARAM2_":"Adicionar a _PARAM0_ _PARAM2_ de torque","Torque value":"Valor de torque","Linear velocity":"Velocidade linear","Modify the velocity of an object.":"Modifica a velocidade de um objeto.","Set linear velocity of _PARAM0_ to _PARAM2_;_PARAM3_":"Defina a velocidade linear de _PARAM0_ para _PARAM2_; _PARAM3_","X Coordinate":"Coordenada Y","Y Coordinate":"Coordenada Y","X component":"Componente X","Compare the linear velocity on the X axis of the object.":"Compare a velocidade linear no eixo X do objeto.","the linear velocity on X axis":"a velocidade linear no eixo X","Y component":"Componente Y","Compare the linear velocity on the Y axis of the object.":"Compare a velocidade linear no eixo Y do objeto.","the linear velocity on Y axis":"a velocidade linear no eixo Y","Linear speed":"Velocidade linear","Compare the linear velocity of the object.":"Compare a velocidade linear do objeto.","the linear velocity":"a velocidade linear","Angular speed":"Velocidade angular","Modify the angular velocity of the object.":"Modificar a velocidade angular do objeto.","Set angular speed of _PARAM0_ to _PARAM2_":"Definir a velocidade angular de _PARAM0_ para _PARAM2_","New value":"Novo valor","Compare the angular speed of the object.":"Compare a velocidade angular do objeto.","the angular speed":"a velocidade angular","Linear damping":"Amortecimento linear","Compare the linear damping of the object.":"Compare o amortecimento linear do objeto.","the linear damping":"o amortecimento linear","Collision":"Colis\xE3o","Test if two objects are colliding.\nAttention! Only objects specified in the first parameter will be taken into account by the next actions and conditions, if they are colliding with the other objects.":"Testar se dois objetoscolidem. \nAten\xE7\xE3o! Apenas objetos especificados no primeiro par\xE2metro ser\xE3o tidos em conta pelas pr\xF3ximas a\xE7\xF5es e condi\xE7\xF5es, se colidirem com os outros objetos.","_PARAM0_ is in collision with a _PARAM2_":"_PARAM0_ est\xE1 em colis\xE3o com um _PARAM2_","Modify the linear damping of the object.":"Modifica a atenua\xE7\xE3o linear do objeto.","Set linear damping of _PARAM0_ to _PARAM2_":"Definir a atenua\xE7\xE3o angular de _PARAM0_ para _PARAM2_","Value":"Valor","Angular damping":"Amortecimento angular","Test the object's angular damping":"Testar a atenua\xE7\xE3o angular do objeto","the angular damping":"o amortecimento angular","Modify the angular damping of the object.":"Modificar a atenua\xE7\xE3o angular do objeto.","Set angular damping of _PARAM0_ to _PARAM2_":"Definir o amortecimento angular de _PARAM0_ para _PARAM2_","Modify the gravity":"Modificar a gravidade","Set gravity force to _PARAM2_;_PARAM3_":"Definir a for\xE7a da gravidade para _PARAM2_; _PARAM3_","Global options":"Op\xE7\xF5es globais","Change the X scale of a collision polygon":"Alterar a escala X de um pol\xEDgono de colis\xE3o","Change the X scale of the polygon. Use a value greater than 1 to enlarge the polygon, less than 1 to reduce it.":"Alterar a escala X do pol\xEDgono. Use um valor maior que 1 para ampliar o pol\xEDgono, menor que 1 para reduzi-lo.","Change the X scale of the collision polygon of _PARAM0_ to _PARAM2_":"Alterar a escala X do pol\xEDgono de colis\xE3o de _PARAM0_ para _PARAM2_","Collision polygon":"Pol\xEDgono de colis\xE3o","Scale":"Escala","Change the Y scale of a collision polygon":"Alterar a escala Y de um pol\xEDgono de colis\xE3o","Change the Y scale of the polygon. Use a value greater than 1 to enlarge the polygon, less than 1 to reduce it.":"Alterar a escala Y do pol\xEDgono. Use um valor maior que 1 para ampliar o pol\xEDgono, menor que 1 para reduzi-lo.","Change the Y scale of the collision polygon of _PARAM0_ Y to _PARAM2_":"Alterar a escala Y do pol\xEDgono de colis\xE3o de _PARAM0_ para _PARAM2_","Collision polygon X scale":"Escala X do pol\xEDgono de colis\xE3o","Test the value of the X scale of the collision polygon.":"Testar o valor da escala X do pol\xEDgono de colis\xE3o.","the X scale of the collision polygon":"a escala X do pol\xEDgono de colis\xE3o","Collision polygon Y scale":"Escala Y do pol\xEDgono de colis\xE3o","Test the value of the Y scale of the collision polygon.":"Testar o valor da escala Y do pol\xEDgono de colis\xE3o.","the Y scale of the collision polygon":"a escala Y do pol\xEDgono de colis\xE3o","Box (rectangle)":"Caixa (ret\xE2ngulo)","Custom polygon":"Pol\xEDgono personalizado","Shape":"Forma","Dynamic object":"Object din\xE2mico","Consider as bullet (better collision handling)":"Considere como bala (melhor manuseamento de colis\xE3o)","Mass density":"Densidade de massa","Friction":"Fric\xE7\xE3o","Restitution (elasticity)":"Restitui\xE7\xE3o (elasticidade)","Linear Damping":"Amortecimento Linear","Angular Damping":"Amortecimento Angular","Shape painter":"Pintor de forma","This provides an object that can be used to draw arbitrary shapes on the screen using events.":"This provides an object that can be used to draw arbitrary shapes on the screen using events.","Allows you to draw simple shapes on the screen":"Permite que voc\xEA desenhe formas simples na tela","Rectangle":"Ret\xE2ngulo","Draw a rectangle on screen":"Desenhe um ret\xE2ngulo no ecr\xE3","Draw from _PARAM1_;_PARAM2_ to _PARAM3_;_PARAM4_ a rectangle with _PARAM0_":"Desenhar de _PARAM1_; _PARAM2_ para _PARAM3_; _PARAM4_ um ret\xE2ngulo com _PARAM0_","Drawing":"Desenho","Shape Painter object":"Objeto pintor de forma","Top left side: X position":"Top left side: X position","Top left side: Y position":"Top left side: Y position","Bottom right side: X position":"Bottom right side: X position","Bottom right side: Y position":"Bottom right side: Y position","Draw a circle on screen":"Desenhe um c\xEDrculo no \xE9cran","Draw at _PARAM1_;_PARAM2_ a circle of radius _PARAM3_ with _PARAM0_":"Desenhe no _PARAM1_; _PARAM2_ um c\xEDrculo de raio _PARAM3_ com _PARAM0_","X position of center":"Centro : Posi\xE7ao X","Y position of center":"Centro : Posi\xE7ao Y","Radius (in pixels)":"Radius (in pixels)","X position of start point":"X position of start point","Y position of start point":"Y position of start point","X position of end point":"X position of end point","Y position of end point":"Y position of end point","Thickness (in pixels)":"Thickness (in pixels)","Draw a line on screen":"Desenhar uma linha no ecr\xE3","Draw from _PARAM1_;_PARAM2_ to _PARAM3_;_PARAM4_ a line (thickness: _PARAM5_) with _PARAM0_":"Draw from _PARAM1_;_PARAM2_ to _PARAM3_;_PARAM4_ a line (thickness: _PARAM5_) with _PARAM0_","Ellipse":"Ellipse","Draw an ellipse on screen":"Draw an ellipse on screen","Draw at _PARAM1_;_PARAM2_ an ellipse of width _PARAM3_ and height _PARAM4_ with _PARAM0_":"Draw at _PARAM1_;_PARAM2_ an ellipse of width _PARAM3_ and height _PARAM4_ with _PARAM0_","The width of the ellipse":"The width of the ellipse","The height of the ellipse":"The height of the ellipse","Rounded rectangle":"Rounded rectangle","Draw a rounded rectangle on screen":"Draw a rounded rectangle on screen","Draw from _PARAM1_;_PARAM2_ to _PARAM3_;_PARAM4_ a rounded rectangle (radius: _PARAM5_) with _PARAM0_":"Draw from _PARAM1_;_PARAM2_ to _PARAM3_;_PARAM4_ a rounded rectangle (radius: _PARAM5_) with _PARAM0_","Star":"Estrela","Draw a star on screen":"Desenhar uma estrela no ecr\xE3","Draw at _PARAM1_;_PARAM2_ a star with _PARAM3_ points and radius: _PARAM4_ (inner radius: _PARAM5_, rotation: _PARAM6_) with _PARAM0_":"Draw at _PARAM1_;_PARAM2_ a star with _PARAM3_ points and radius: _PARAM4_ (inner radius: _PARAM5_, rotation: _PARAM6_) with _PARAM0_","Number of points of the star (minimum: 2)":"Number of points of the star (minimum: 2)","Inner radius (in pixels, half radius by default)":"Inner radius (in pixels, half radius by default)","Rotation (in degrees)":"Rotation (in degrees)","Arc":"Arco","Draw an arc on screen. If \"Close path\" is set to yes, a line will be drawn between the start and end point of the arc, closing the shape.":"Draw an arc on screen. If \"Close path\" is set to yes, a line will be drawn between the start and end point of the arc, closing the shape.","Draw at _PARAM1_;_PARAM2_ an arc with radius: _PARAM3_, start angle: _PARAM4_, end angle: _PARAM5_ (anticlockwise: _PARAM6_, close path: _PARAM7_) with _PARAM0_":"Draw at _PARAM1_;_PARAM2_ an arc with radius: _PARAM3_, start angle: _PARAM4_, end angle: _PARAM5_ (anticlockwise: _PARAM6_, close path: _PARAM7_) with _PARAM0_","Start angle of the arc (in degrees)":"Start angle of the arc (in degrees)","End angle of the arc (in degrees)":"End angle of the arc (in degrees)","Anticlockwise":"Anticlockwise","Close path":"Close path","Bezier curve":"Bezier curve","Draw a bezier curve on screen":"Draw a bezier curve on screen","Draw from _PARAM1_;_PARAM2_ to _PARAM7_;_PARAM8_ a bezier curve (first control point: _PARAM3_;_PARAM4_, second control point: _PARAM5_;_PARAM6_) with _PARAM0_":"Draw from _PARAM1_;_PARAM2_ to _PARAM7_;_PARAM8_ a bezier curve (first control point: _PARAM3_;_PARAM4_, second control point: _PARAM5_;_PARAM6_) with _PARAM0_","First control point x":"First control point x","First control point y":"First control point y","Second Control point x":"Second Control point x","Second Control point y":"Second Control point y","Destination point x":"Destination point x","Destination point y":"Destination point y","Quadratic curve":"Quadratic curve","Draw a quadratic curve on screen":"Draw a quadratic curve on screen","Draw from _PARAM1_;_PARAM2_ to _PARAM5_;_PARAM6_ a quadratic curve (control point: _PARAM3_;_PARAM4_) with _PARAM0_":"Draw from _PARAM1_;_PARAM2_ to _PARAM5_;_PARAM6_ a quadratic curve (control point: _PARAM3_;_PARAM4_) with _PARAM0_","Control point x":"Control point x","Control point y":"Control point y","Begin fill path":"Begin fill path","Begin to draw a simple one-color fill. Subsequent actions, such as \"Path line\" (in the Advanced category) can be used to draw. Be sure to use \"End fill path\" action when you're done drawing the shape.":"Begin to draw a simple one-color fill. Subsequent actions, such as \"Path line\" (in the Advanced category) can be used to draw. Be sure to use \"End fill path\" action when you're done drawing the shape.","Begins drawing filling of an advanced path with _PARAM0_ (start: _PARAM1_;_PARAM2_)":"Begins drawing filling of an advanced path with _PARAM0_ (start: _PARAM1_;_PARAM2_)","Start drawing x":"Start drawing x","Start drawing y":"Start drawing y","End fill path":"End fill path","Finish the filling drawing in an advanced path":"Finish the filling drawing in an advanced path","Finish the filling drawing in an advanced path with _PARAM0_":"Finish the filling drawing in an advanced path with _PARAM0_","Move path drawing position":"Move path drawing position","Move the drawing position for the current path":"Move the drawing position for the current path","Move the drawing position of the path to _PARAM1_;_PARAM2_ with _PARAM0_":"Move the drawing position of the path to _PARAM1_;_PARAM2_ with _PARAM0_","Path line":"Path line","Add to a path a line to a position. The origin comes from the previous action or from \"Begin fill path\" or \"Move path drawing position\". By default, the start position will be the object's position.":"Add to a path a line to a position. The origin comes from the previous action or from \"Begin fill path\" or \"Move path drawing position\". By default, the start position will be the object's position.","Add to a path a line to the position _PARAM1_;_PARAM2_ with _PARAM0_":"Add to a path a line to the position _PARAM1_;_PARAM2_ with _PARAM0_","Path bezier curve":"Path bezier curve","Add to a path a bezier curve to a position. The origin comes from the previous action or from \"Begin fill path\" or \"Move path drawing position\". By default, the start position will be the object's position.":"Add to a path a bezier curve to a position. The origin comes from the previous action or from \"Begin fill path\" or \"Move path drawing position\". By default, the start position will be the object's position.","Add to a path a bezier curve to the position _PARAM5_;_PARAM6_ (first control point: _PARAM1_;_PARAM2_, second control point: _PARAM3_;_PARAM4_) with _PARAM0_":"Add to a path a bezier curve to the position _PARAM5_;_PARAM6_ (first control point: _PARAM1_;_PARAM2_, second control point: _PARAM3_;_PARAM4_) with _PARAM0_","Path arc":"Path arc","Add to a path an arc to a position. The origin comes from the previous action or from \"Begin fill path\" or \"Move path drawing position\". By default, the start position will be the object's position.":"Add to a path an arc to a position. The origin comes from the previous action or from \"Begin fill path\" or \"Move path drawing position\". By default, the start position will be the object's position.","Add to a path an arc at the position _PARAM1_;_PARAM2_ (radius: _PARAM3_, start angle: _PARAM4_, end angle: _PARAM5_, anticlockwise: _PARAM6_) with _PARAM0_":"Add to a path an arc at the position _PARAM1_;_PARAM2_ (radius: _PARAM3_, start angle: _PARAM4_, end angle: _PARAM5_, anticlockwise: _PARAM6_) with _PARAM0_","Center x of circle":"Center x of circle","Center y of circle":"Center y of circle","Start angle":"Start angle","End angle":"End angle","Path quadratic curve":"Path quadratic curve","Add to a path a quadratic curve to a position. The origin comes from the previous action or from \"Begin fill path\" or \"Move path drawing position\". By default, the start position will be the object's position.":"Add to a path a quadratic curve to a position. The origin comes from the previous action or from \"Begin fill path\" or \"Move path drawing position\". By default, the start position will be the object's position.","Add to a path a quadratic curve to the position _PARAM3_;_PARAM4_ (control point: _PARAM1_;_PARAM2_) with _PARAM0_":"Add to a path a quadratic curve to the position _PARAM3_;_PARAM4_ (control point: _PARAM1_;_PARAM2_) with _PARAM0_","Close Path":"Close Path","Close the path of the advanced shape. This closes the outline between the last and the first point.":"Close the path of the advanced shape. This closes the outline between the last and the first point.","Close the path with _PARAM0_":"Close the path with _PARAM0_","Clear shapes":"Clear shapes","Clear the rendered shape(s). Useful if not set to be done automatically.":"Clear the rendered shape(s). Useful if not set to be done automatically.","Clear the rendered image of _PARAM0_":"Clear the rendered image of _PARAM0_","Clear between frames":"Clear between frames","Activate (or deactivate) the clearing of the rendered shape at the beginning of each frame.":"Activate (or deactivate) the clearing of the rendered shape at the beginning of each frame.","Clear the rendered image of _PARAM0_ between each frame: _PARAM1_":"Clear the rendered image of _PARAM0_ between each frame: _PARAM1_","Setup":"Configura\xE7\xE3o","Clear between each frame":"Clear between each frame","Check if the rendered image is cleared between frames.":"Check if the rendered image is cleared between frames.","_PARAM0_ is clearing its rendered image between each frame":"_PARAM0_ is clearing its rendered image between each frame","Change the color used when filling":"Alterar a cor de preenchimento","Change fill color of _PARAM0_ to _PARAM1_":"Mudar a cor de preenchimento de _PARAM0_ para _PARAM1_","Filing color red component":"Filing color red component","Filing color green component":"Filing color green component","Filing color blue component":"Filing color blue component","Modify the color of the outline of future drawings.":"Modifica a cor do contorno dos desenhos futuros.","Change outline color of _PARAM0_ to _PARAM1_":"Muda a cor de contorno de _PARAM0_ para _PARAM1_","Outline color red component":"Outline color red component","Outline color green component":"Outline color green component","Outline color blue component":"Outline color blue component","Outline size":"Espessura do contorno","Modify the size of the outline of future drawings.":"Modifica o tamanho do contorno dos desenhos futuros.","the size of the outline":"the size of the outline","Test the size of the outline.":"Teste o tamanho do contorno.","Fill opacity":"Preencha a opacidade","Modify the opacity level used when filling future drawings.":"Modifica o n\xEDvel de opacidade usado quando futuros desenhos de enchimento.","the opacity of filling":"the opacity of filling","Test the value of the opacity level used when filling.":"Teste o valor da opacidade do preenchimento.","Filling opacity":"Filling opacity","Outline opacity":"Opacidade do contorno","Modify the opacity of the outline of future drawings.":"Modifica a opacidade do contorno dos desenhos futuros.","the opacity of the outline":"the opacity of the outline","Test the opacity of the outline.":"Teste a opacidade do contorno.","Use relative coordinates":"Use relative coordinates","Set if the object should use relative coordinates (by default) or not. It's recommended to use relative coordinates.":"Set if the object should use relative coordinates (by default) or not. It's recommended to use relative coordinates.","Use relative coordinates for _PARAM0_: _PARAM1_":"Use relative coordinates for _PARAM0_: _PARAM1_","Use relative coordinates?":"Use relative coordinates?","Relative coordinates":"Relative coordinates","Check if the coordinates of the shape painter is relative.":"Check if the coordinates of the shape painter is relative.","_PARAM0_ is using relative coordinates":"_PARAM0_ is using relative coordinates","Shopify":"Shopify","Interact with products and generate URLs for checkouts with your Shopify shop.":"Interaja com produtos e gere URLs para caixas com a sua loja do Shopify.","Initialize a shop":"Inicializar uma loja","Initialize a shop with your credentials. Call this action first, and then use the shop name in the other actions to interact with products.":"Inicializar uma loja com as suas credenciais. Primeiro chame essa a\xE7\xE3o, e depois use o nome da loja nas outras a\xE7\xF5es para interagir com os produtos.","Initialize shop _PARAM1_ (domain: _PARAM2_, appId: _PARAM3_)":"Inicializar loja _PARAM1_ (dom\xEDnio: _PARAM2_, appId: _PARAM3_)","Shop name":"Nome da loja","Domain (xxx.myshopify.com)":"Dom\xEDnio (xxx.myshopify.com)","App Id":"Id da aplica\xE7\xE3o","Access Token":"C\xF3digo de acesso","Get the URL for buying a product":"Obter o URL para comprar um produto","Get the URL for buying a product from a shop. The URL will be stored in the scene variable that you specify. You can then use the action to open an URL to redirect the player to the checkout.":"Obtenha o URL para comprar um producto de uma loja. O URL ser\xE1 armazenado na vari\xE1vel da cena especificada por si. Voc\xEA pode, ent\xE3o, utilizar a ac\xE7\xE3o para abrir um URL e redireccionar o jogador para a verifica\xE7\xE3o.","Get the URL for product #_PARAM2_ (quantity: _PARAM3_, variant: _PARAM4_) from shop _PARAM1_, and store it in _PARAM5_ (or _PARAM6_ in case of error)":"Obter o URL para o produto # _PARAM2_ (quantidade: _PARAM3_, variante: _PARAM4_) da loja _PARAM1_ e armazene-o em _PARAM5_ (ou _PARAM6_ em caso de erro)","Shop name (initialized with \"Initialize a shop\" action)":"Nome da loja (inicializado com a a\xE7\xE3o \"Inicializar uma loja\")","Product id":"Id do produto","Quantity":"Quantidade","Variant (0 by default)":"Variante (0 por padr\xE3o)","Scene variable where the URL for checkout must be stored":"Vari\xE1vel da cena onde o URL para a verifica\xE7\xE3o deve ser armazenada","Scene variable containing the error (if any)":"Vari\xE1vel da cena que cont\xE9m o erro (se houver)","Margin before deleting the object, in pixels":"Margem antes de excluir o objeto, em pixels","Destroy Outside Screen Behavior":"Destruir o comportamento fora da tela","This behavior can be used to destroy objects when they go outside of the bounds of the camera. Useful for bullets or other short-lived objects.":"Este comportamento pode ser usado para destruir objetos quando eles ficam fora dos limites da c\xE2mara. \xDAtil para balas ou outros objetos de curta dura\xE7\xE3o.","Destroy when outside of the screen":"Destruir quando fora do ecran","DestroyOutside":"Destruir Fora","Automatically destroy the object when it goes outside of the screen's borders.":"Destr\xF3i automaticamente o object quando ele vai para fora das fronteiras do ecr\xE3.","Additional border":"Fronteira adicional","Compare the additional border that the object must cross before being deleted.":"Compare a borda adicional que o objeto deve atravessar antes de sere exclu\xEDdo.","the additional border":"a borda adicional","Change the additional border that the object must cross before being deleted.":"Altere a borda adicional que o objeto deve cruzar antes de sere exclu\xEDdo.","Panel Sprite (9-patch) Object":"Objeto de painel Sprite (9-patch)","Panel Sprite (\"9-patch\")":"Painel Sprite (\"9-patch\")","An image with edges and corners that are stretched separately from the full image.":"Uma imagem com bordas e cantos que s\xE3o esticados independentemente da imagem completa.","Compare the opacity of a Panel Sprite, between 0 (fully transparent) to 255 (opaque).":"Compare a opacidade de um Painel de Sprite, desde 0 (totalmente transparente) at\xE9 255 (opaco).","Change Panel Sprite opacity":"Altere a opacidade do Painel Sprite","Change the opacity of a Panel Sprite. 0 is fully transparent, 255 is opaque (default).":"Altere a opacidade de um Painel Sprite. 0 \xE9 totalmente transparente, 255 \xE9 opaco (padr\xE3o).","Panel Sprite":"Painel Sprite","Change the tint of a Panel Sprite. The default color is white.":"Change the tint of a Panel Sprite. The default color is white.","Modify the width of a Panel Sprite.":"Modifica a largura de um Painel de Sprites.","Check the width of a Panel Sprite.":"Verifica a largura de um Panel Sprite.","Modify the height of a Panel Sprite.":"Modifica a altura de um Painel de Sprites.","Check the height of a Panel Sprite.":"Verifica a altura de um Panel Sprite.","Image name":"Nome da imagem","Change the image of a Panel Sprite.":"Mude a imagem de um painel de Sprite.","Set image _PARAM1_ on _PARAM0_":"Colocar imagem _PARAM1_ na _PARAM0_","Image":"Imagem","Text object":"Objeto de texto","An object that can be used to display any text on the screen: remaining life counter, some indicators, menu buttons, dialogues...":"Um objeto que pode ser usado para exibir qualquer texto na tela: contador de vida restante, alguns indicadores, bot\xF5es de menu, di\xE1logos...","Text":"Texto","Displays a text on the screen.":"Exibe um texto no ecr\xE3.","Modify the text":"Modificar o texto","Modify the text of a Text object.":"Modifica o texto de um objeto de texto.","the text":"o texto","Compare the text":"Compare o texto","Compare the text of a Text object.":"Compare o texto de um objeto de texto.","Font":"Fonte","Change the font of the text.":"Alterar a fonte do texto.","Change font of _PARAM0_ to _PARAM1_":"Alterar a fonte de _PARAM0_ para _PARAM1_","Scale on X axis":"Escala no eixo X","Compare the scale of the text on the X axis":"Comparar a escala do texto no eixo X","the scale on the X axis":"a escala no eixo X","Modify the scale of the text on the X axis (default scale is 1)":"Modificar a escala do texto no eixo X (a escala padr\xE3o \xE9 1)","Scale on Y axis":"Escala no eixo Y","Compare the scale of the text on the Y axis":"Comparar a escala do texto no eixo Y","the scale on the Y axis":"a escala no eixo Y","Modify the scale of the text on the Y axis (default scale is 1)":"Modificar a escala do texto no eixo Y (a escala padr\xE3o \xE9 1)","Modify the scale of the specified object (default scale is 1)":"Modificar a escala do object especificado (a escala padr\xE3o \xE9 1)","the scale":"a escala","Change the color of the text. The color is white by default.":"Altere a cor do texto. A cor \xE9 branca por padr\xE3o.","Change color of _PARAM0_ to _PARAM1_":"Alterar a cor de _PARAM0_ para _PARAM1_","Gradient":"Gradiente","Change the gradient of the text.":"Alterar o gradiente do texto.","Change gradient of _PARAM0_ to colors _PARAM1_ _PARAM2_ _PARAM3_ _PARAM4_ type _PARAM5_":"Alterar o gradiente de _PARAM0_ para cores _PARAM1_ _PARAM2_ _PARAM3_ _PARAM4_ tipo _PARAM5_","Gradient type":"Tipo de gradiente","First Color":"Primeira cor","Second Color":"Segunda cor","Third Color":"Terceira cor","Fourth Color":"Quarta cor","Outline":"Contorno","Change the outline of the text. A thickness of 0 disables the outline.":"Modificar o contorno do texto. Uma espessura de 0 desativa o contorno.","Change outline of _PARAM0_ to color _PARAM1_ with thickness _PARAM2_":"Alterar o contorno de _PARAM0_ para cor _PARAM1_ com espessura _PARAM2_","Thickness":"Espessura","Change Shadow":"Alterar Sombra","Change the shadow of the text.":"Alterar a sombra do texto.","Change the shadow of _PARAM0_ to color _PARAM1_ distance _PARAM2_ blur _PARAM3_ angle _PARAM4_":"Alterar a sombra de _PARAM0_ para colorir _PARAM1_ dist\xE2ncia _PARAM2_ desfoque _PARAM3_ \xE2ngulo _PARAM4_","Effects/Shadow":"Efeitos/Sombra","Distance":"Dist\xE2ncia","Blur":"Desfocagem","Show Shadow":"Mostrar Sombra","Show the shadow of the text.":"Mostrar a sombra do texto.","Show the shadow of _PARAM0_: _PARAM1_":"Mostrar a sombra de _PARAM0_: _PARAM1_","Show the shadow":"Mostrar a sombra","Change text opacity":"Altere a opacidade do texto","Change the opacity of a Text. 0 is fully transparent, 255 is opaque (default).":"Altere a opacidade de um texto. 0 \xE9 totalmente transparente, 255 \xE9 opaco (padr\xE3o).","Compare the opacity of a Text object, between 0 (fully transparent) to 255 (opaque).":"Compare a opacidade de um object de texto, entre 0 (totalmente transparente) at\xE9 255 (opaco).","Smoothing":"Suaviza\xE7\xE3o","Activate or deactivate text smoothing.":"Ativar ou desativar a suaviza\xE7\xE3o de texto.","Smooth _PARAM0_: _PARAM1_":"Suavizar_PARAM0_: _PARAM1_","Style":"Estilo","Smooth the text":"Suavize o texto","Check if an object is smoothed":"Verificar se um object \xE9 suavizado","_PARAM0_ is smoothed":"_PARAM0_ \xE9 suavizado","De/activate bold":"Des/ativar estilo negrito","Set bold style of _PARAM0_ : _PARAM1_":"Definir estilo negrito de _PARAM0_: _PARAM1_","Set bold style":"Defenir estilo negrito","Check if the bold style is activated":"Verifique se o estilo negrito est\xE1 ativado","_PARAM0_ bold style is set":"_PARAM0_ estilo negrito est\xE1 definido","De/activate italic.":"Des/ativar estilo it\xE1lico.","Set italic style for _PARAM0_ : _PARAM1_":"Definir estilo it\xE1lico para _PARAM0_: _PARAM1_","Set italic":"Defenir estilo it\xE1lico","Check if the italic style is activated":"Verifique se o estilo it\xE1lico est\xE1 ativado","_PARAM0_ italic style is set":"_PARAM0_ estilo it\xE1lico est\xE1 definido","Underlined":"Sublinhado","De/activate underlined style.":"Des/ativar estilo sublinhado.","Set underlined style of _PARAM0_: _PARAM1_":"Definir o estilo de sublinhado de _PARAM0_: _PARAM1_","Underline":"Sublinhado","Check if the underlined style of an object is set.":"Verifique se o estilo sublinhado de um object est\xE1 definido.","_PARAM0_ underlined style is activated":"_PARAM0_ estilo sublinhado est\xE1 ativo","Modify the angle of a Text object.":"Modifica o \xE2ngulo de um objeto de texto.","Compare the value of the angle of a Text object.":"Compare o valor do \xE2ngulo de um object de texto.","Padding":"Preenchimento","Compare the number of pixels around a text object. If the shadow or the outline around the text are getting cropped, raise this value.":"Comparar o n\xFAmero de p\xEDxeis em volta de um object de texto. Se a sombra ou o contorno em volta do texto est\xE3o a ser cortados, aumente este valor.","the padding":"o preenchimento","Set the number of pixels around a text object. If the shadow or the outline around the text are getting cropped, raise this value.":"Definir o n\xFAmero de p\xEDxeis em torno de um object de texto. Se a sombra ou o contorno em volta do texto est\xE3o a ser cortados, aumente este valor.","Alignment":"Alinhamento","Set the text alignment of a multiline text object (does not work with single line texts).":"Definir o alinhamento de texto de um object de texto de v\xE1rias linhas (n\xE3o funciona com textos de linha \xFAnica).","Align _PARAM0_: _PARAM1_":"Alinhar _PARAM0_: _PARAM1_","Compare the text alignment of a multiline text object.":"Comparar o alinhamento de texto de um object de texto de v\xE1rias linhas.","the alignment":"o alinhamento","Wrapping":"Inv\xF3lucro","De/activate word wrapping. Note that word wrapping is a graphical option,\nyou can't get the number of lines displayed":"De/ativar o envolvimento autom\xE1tico de palavras. Note que o envolvimento autom\xE1tico de palavras \xE9 uma op\xE7\xE3o gr\xE1fica, \n voc\xEA n\xE3o pode obter o n\xFAmero de linhas exibidas","Activate wrapping style of _PARAM0_: _PARAM1_":"Activate wrapping style of _PARAM0_: _PARAM1_","Test if the word wrapping style of an object is set.":"Testar se o estilo de envolvimento de palavras de um object est\xE1 definido.","_PARAM0_ word wrapping style is activated":"_PARAM0_ estilo de envolvimento de palavras est\xE1 ativado","Wrapping width":"Largura do envolvimento","Modify the word wrapping width of a Text object.":"Modificar a largura do envolvimento das palavras de um object de texto.","the wrapping width":"a largura do inv\xF3lucro","Test the word wrapping width of a Text object.":"Testar a largura de envolvimento das palavras de um object de texto.","X Scale of a Text object":"Escala X de um object de Texto","Y Scale of a Text object":"Escala Y de um object de Texto","Opacity of a Text object":"Opacidade de um object de texto","Font size":"Font size","the font size of a text object":"the font size of a text object","the font size":"the font size","Anchor":"\xC2ncora","Anchor objects to the window's bounds.":"Ancore objetos para os limites da ganela.","Behavior that anchors objects to the window's bounds.":"Comportamento que ancora objetos para limites da janela.","Window left":"Janela \xE1 esquerda","Window right":"Janela \xE1 direita","Proportional":"Proporcional","No anchor":"Sem \xE2ncora","Window top":"Parte superior da janela","Window bottom":"Parte inferior da janela","relativeToOriginalWindowSize":"relativoAoTamanhoOriginaldaJanela","Anchor relatively to original window size":"\xC2ncorar em rela\xE7\xE3o ao tamanho original da janela","otherwise, objects are anchored according to the window size when the object is created.":"caso contr\xE1rio, objetos s\xE3o ancorados de acordo com o tamanho da janela quando o objeto \xE9 criado.","Left edge anchor":"\xC2ncora de borda esquerda","Use this to anchor the object on X axis.":"Use isto para ancorar o objeto no eixo X.","Right edge anchor":"\xC2ncora de borda direita","Top edge anchor":"\xC2ncora de borda superior","Use this to anchor the object on Y axis.":"Use isto para ancorar o objeto no eixo Y.","Bottom edge anchor":"\xC2ncora de borda inferior","Top-down movement":"Movimento de cima para baixo (top-down)","Allows to move objects in either 4 or 8 directions, with the keyboard or using events.":"Allows to move objects in either 4 or 8 directions, with the keyboard or using events.","Top-down movement (4 or 8 directions)":"Movimento de cima para baixo (4 ou 8 dire\xE7\xF5es)","Objects with this behavior can be moved left, up, right, and down (and, optionally, diagonally).":"Objects with this behavior can be moved left, up, right, and down (and, optionally, diagonally).","Simulate a press of left key.":"Simule um pressionar de tecla esquerda.","Simulate a press of right key.":"Simule um pressionar de tecla direita.","Simulate a press of up key.":"Simular a press\xE3o da tecla para cima.","Simulate a press of down key.":"Simular a press\xE3o da tecla para baixo.","Simulate a press of a key.\nValid keys are Left, Right, Up, Down.":"Simulate a press of a key.\nValid keys are Left, Right, Up, Down.","Simulate stick control":"Simulate stick control","Simulate a stick control.":"Simulate a stick control.","Simulate a stick control for _PARAM0_ with a _PARAM2_ angle and a _PARAM3_ force":"Simulate a stick control for _PARAM0_ with a _PARAM2_ angle and a _PARAM3_ force","Stick angle (in degrees)":"Stick angle (in degrees)","Stick force (between 0 and 1)":"Stick force (between 0 and 1)","Check if the object is moving.":"Verifique se o objeto est\xE1-se movendo.","Change the acceleration of the object":"Alterar a acelera\xE7\xE3o do objeto","Compare the acceleration of the object":"Comparar a acelera\xE7\xE3o do objeto","Change the deceleration of the object":"Mudar a desacelera\xE7\xE3o do objeto","Compare the deceleration of the object":"Comparar a desacelera\xE7\xE3o do objeto","Change the maximum speed of the object":"Alterar a velocidade m\xE1xima do objeto","the max. speed":"a velocidade m\xE1xima","Compare the maximum speed of the object":"Comparar a velocidade m\xE1xima do objeto","Speed":"Velocidade","Compare the speed of the object":"Comparar a velocidade do objeto","the speed":"a velocidade","Angular maximum speed":"Velocidade angular m\xE1xima","Change the maximum angular speed of the object":"Alterar a velocidade angular m\xE1xima do objeto","the max. angular speed":"a velocidade angular m\xE1xima","Compare the maximum angular speed of the object":"Comparar a velocidade angular m\xE1xima do objeto","Rotation offset":"Deslocamento de rota\xE7\xE3o","Change the rotation offset applied when moving the object":"Alterar o deslocamento de rota\xE7\xE3o aplicado ao mover o objeto","the rotation offset":"o deslocamento de rota\xE7\xE3o","Compare the rotation offset applied when moving the object":"Comparar o deslocamento de rota\xE7\xE3o aplicado enquanto mover o objeto","Angle of movement":"\xC2ngulo de movimento","Compare the angle of the top-down movement of the object.":"Compare the angle of the top-down movement of the object.","the angle of movement":"o \xE2ngulo de movimento","Speed on X axis":"Velocidade no eixo X","Compare the velocity of the top-down movement of the object on the X axis.":"Compare the velocity of the top-down movement of the object on the X axis.","the speed of movement on X axis":"a velocidade de movimento no eixo X","Speed on Y axis":"Velocidade no eixo Y","Compare the velocity of the top-down movement of the object on the Y axis.":"Compare the velocity of the top-down movement of the object on the Y axis.","the speed of movement on Y axis":"a velocidade de movimento no eixo Y","Diagonal movement":"Movimento diagonal","Allow or restrict diagonal movemment":"Permite ou restringe o movimento diagonal","Allow diagonal moves for _PARAM0_: _PARAM2_":"Permitir movimentos na diagonal para _PARAM0_: _PARAM2_","Allow?":"Permitir?","Check if the object is allowed to move diagonally":"Verifique se o objeto est\xE1 autorizado a mover-se na diagonal","Allow diagonal moves for _PARAM0_":"Allow diagonal moves for _PARAM0_","Rotate the object":"Girar o objeto","Enable or disable rotation of the object":"Des/ativar a rota\xE7\xE3o do objeto","Enable rotation of _PARAM0_: _PARAM2_":"Ativar a rota\xE7\xE3o de _PARAM0_: _PARAM2_","Rotate object?":"Girar o objeto?","Object rotated":"Objeto rodado","Check if the object is rotated while traveling on its path.":"Check if the object is rotated while traveling on its path.","_PARAM0_ is rotated when moving":"_PARAM0_ \xE9 rodado quando se deslocam","Acceleration of the object":"Acelera\xE7\xE3o do objeto","Deceleration of the object":"Desacelera\xE7\xE3o do objeto","Maximum speed of the object":"Velocidade m\xE1xima do objeto","Speed of the object":"Velocidade do objeto","Angular maximum speed of the object":"Velocidade m\xE1xima angular do objeto","Rotation offset applied to the object":"Deslocamento de rota\xE7\xE3o aplicado ao objeto","Angle of the movement":"\xC2ngulo do movimento","Angle, in degrees, of the movement":"\xC2ngulo, em graus, do movimento","Speed on the X axis":"Velocidade no eixo X","Speed on the X axis of the movement":"Velocidade no eixo X do movimento","Speed on the Y axis":"Velocidade no eixo Y","Speed on the Y axis of the movement":"Velocidade no eixo Y do movimento","Movement angle offset":"Movement angle offset","the movement angle offset":"the movement angle offset","Allows diagonals":"Permite diagonais","Rotate speed":"Velocidade de rota\xE7\xE3o","Rotate object":"Girar o objeto","Angle offset":"Deslocamento angular","Viewpoint":"Viewpoint","Top-Down":"Top-Down","Isometry 2:1 (26.565\xB0)":"Isometry 2:1 (26.565\xB0)","True Isometry (30\xB0)":"True Isometry (30\xB0)","Custom Isometry":"Custom Isometry","Custom isometry angle":"Custom isometry angle","If you choose \"Custom Isometry\", this allows to specify the angle of your isometry projection.":"If you choose \"Custom Isometry\", this allows to specify the angle of your isometry projection.","Usually 0, unless you choose an *Isometry* viewpoint in which case -45 is recommended.":"Usually 0, unless you choose an *Isometry* viewpoint in which case -45 is recommended.","Linked objects":"Objetos vinculados","Link two objects":"Vincular dois objetos","Link two objects together, so as to be able to get one from the other.":"Interligar dois objetos, a fim de ser capaz de obter um do outro.","Link _PARAM1_ and _PARAM2_":"Link _PARAM1_ e _PARAM2_","Object 1":"Objeto 1","Object 2":"Objeto 2","Unlink two objects":"Desvincular os dois objetos","Unlink two objects.":"Desvincule os dois objetos.","Unlink _PARAM1_ and _PARAM2_":"Desvincular, _PARAM1_ e _PARAM2_","Unlink all objects from an object":"Desvincular todos os objetos de um objeto","Unlink all objects from an object.":"Desvincular todos os objetos de um objeto.","Unlink all objects from _PARAM1_":"Desvincular todos os objetos de _PARAM1_","Take into account linked objects":"Levar em conta os objetos vinculado","Take some objects linked to the object into account for next conditions and actions.\nThe condition will return false if no object was taken into account.":"Tome em conta que os objetos Unidos a outro objeto para as seguintes condi\xE7\xF5es e a\xE7\xF5es.\nA condi\xE7\xE3o retornar\xE1 Falso se nenhum objeto se Levou em conta.","Take into account all \"_PARAM1_\" linked to _PARAM2_":"Leve em conta todos os objetos \"_PARAM1_\" Unidos a _PARAM2_","Pick these objects...":"Escolha estes objetos...","...if they are linked to this object":"... se eles est\xE3o ligados a este objeto","Take objects linked to the object into account for next actions.":"Leve em conta os objetos Unidos a este objeto para as seguintes condi\xE7\xF5es e a\xE7\xF5es.","Emission minimal force":"For\xE7a m\xEDnima de emiss\xE3o","Modify minimal emission force of particles.":"Modifica a for\xE7a m\xEDnima de emiss\xE3o das part\xEDculas.","the minimal emission force":"a m\xEDnima for\xE7a de emiss\xE3o","Common":"Comum","Emission maximal force":"For\xE7a m\xE1xima de emiss\xE3o","Modify maximal emission force of particles.":"Modifica a for\xE7a m\xE1xima de emiss\xE3o de part\xEDculas.","the maximal emission force":"a m\xE1xima for\xE7a de emiss\xE3o","Emission angle":"\xC2ngulo de emiss\xE3o","Modify emission angle.":"Modifica o \xE2ngulo de emiss\xE3o.","the emission angle":"o \xE2ngulo da emiss\xE3o","Test the value of emission angle of the emitter.":"Teste o valor do \xE2ngulo de emiss\xE3o do emissor.","Emission angle 1":"\xC2ngulo de emiss\xE3o 1","Change emission angle #1":"Modificar o \xE2ngulo de emiss\xE3o #1","the 1st emission angle":"o primeiro \xE2ngulo de emiss\xE3o","Test the value of emission 1st angle of the emitter":"Testar o valor de emiss\xE3o do \xE2ngulo n\xBA1 do emissor","Emission angle 2":"\xC2ngulo de emiss\xE3o 2","Change emission angle #2":"Modificar o \xE2ngulo de emiss\xE3o #1","the 2nd emission angle":"o segundo \xE2ngulo de emiss\xE3o","Test the emission angle #2 of the emitter.":"Testar o valor de emiss\xE3o do \xE2ngulo n\xBA2 do emissor.","Angle of the spray cone":"\xC2ngulo do cone de pulveriza\xE7\xE3o","Modify the angle of the spray cone.":"Modifica o \xE2ngulo do cone de pulveriza\xE7\xE3o.","the angle of the spray cone":"o \xE2ngulo do cone de spray","Test the angle of the spray cone of the emitter":"Testar o \xE2ngulo do cone de pulveriza\xE7\xE3o do emissor","Creation radius":"Raio de cria\xE7\xE3o","Modify creation radius of particles.\nParticles have to be recreated in order to take changes in account.":"Modificar a cria\xE7\xE3o raio de part\xEDculas.\nA part\xEDculas precisam de ser recriada a fim de levar a altera\xE7\xF5es em conta.","the creation radius":"o raio de cria\xE7\xE3o","Test creation radius of particles.":"Teste da cria\xE7\xE3o do raio de part\xEDculas.","Minimum lifetime":"Tempo de vida m\xEDnimo","Modify particles minimum lifetime.Particles have to be recreated in order to take changes in account.":"Modifica o tempo de vida m\xEDnimo das part\xEDculas.Part\xEDculas precisam ser recriada a fim de terem as altera\xE7\xF5es na conta.","the minimum lifetime of particles":"a dura\xE7\xE3o de vida m\xEDnima das part\xEDculas","Test minimum lifetime of particles.":"Vida m\xEDnima de teste da part\xEDculas.","Maximum lifetime":"Tempo de vida m\xE1ximo","Modify particles maximum lifetime.\nParticles have to be recreated in order to take changes in account.":"Modifica o tempo de vida m\xE1ximo das part\xEDculas. \nAs part\xEDculas precisam ser recriadas para que as altera\xE7\xF5es sejam exibidas.","the maximum lifetime of particles":"a dura\xE7\xE3o de vida m\xE1xima das part\xEDculas","Test maximum lifetime of particles.":"Vida m\xE1xima do teste de part\xEDculas.","Gravity value on X axis":"Valor de gravidade no eixo X","Change value of the gravity on X axis.":"Altere o valor da gravidade no eixo X.","the gravity on X axis":"gravidade no eixo do X","Compare value of the gravity on X axis.":"Comparar o valor da gravidade no eixo X.","Gravity value on Y axis":"Valor da gravidade no eixo Y","Change value of the gravity on Y axis.":"Altere o valor da gravidade no eixo Y.","the gravity on Y axis":"gravidade no eixo do Y","Compare value of the gravity on Y axis.":"Comparar o valor da gravidade no eixo Y.","Gravity angle":"\xC2ngulo de gravidade","Change gravity angle":"Modifica o \xE2ngulo de gravidade","the gravity angle":"o \xE2ngulo de gravidade","Test the gravity angle of the emitter":"Testar o \xE2ngulo da gravidade do emissor","Change the gravity of the emitter.":"Altere a gravidade do emissor.","Test the gravity of the emitter.":"Teste a gravidade do emissor.","Start emission":"Start emission","Refill tank (if not infinite) and start emission of the particles.":"Refill tank (if not infinite) and start emission of the particles.","Start emission of _PARAM0_":"Start emission of _PARAM0_","Stop emission":"Stop emission","Stop the emission of particles.":"Stop the emission of particles.","Stop emission of _PARAM0_":"Stop emission of _PARAM0_","Recreate particles":"Recriar as part\xEDculas","Destroy and recreate particles, so as to take changes made to setup of the emitter in account.":"Destruir e recriar as part\xEDculas, a fim de levar as altera\xE7\xF5es feitas para a instala\xE7\xE3o do emissor na conta.","Recreate particles of _PARAM0_":"Recriar as part\xEDculas de _PARAM0_","Rendering first parameter":"Primeiro par\xE2metro de renderiza\xE7\xE3o","Modify first parameter of rendering ( Size/Length ).\nParticles have to be recreated in order to take changes in account.":"Modificar o primeiro par\xE2metro de renderiza\xE7\xE3o (tamanho/comprimento). \nAs part\xEDculas presi\xE7\xE3o de ser recriadas a fim de levar a altera\xE7\xF5es na conta.","the rendering 1st parameter":"a renderiza\xE7\xE3o 1\xBA par\xE2metro","Test the first parameter of rendering ( Size/Length ).":"Teste o primeiro par\xE2metro de renderiza\xE7\xE3o (tamanho/comprimento).","the 1st rendering parameter":"o primeiro par\xE2metro de renderiza\xE7\xE3o","Rendering second parameter":"Processando o segundo par\xE2metro","Modify the second parameter of rendering ( Size/Length ).\nParticles have to be recreated in order to take changes in account.":"Modificar o segundo par\xE2metro de renderiza\xE7\xE3o (tamanho/comprimento). \nAs part\xEDculas presi\xE7\xE3o de ser recriadas a fim de levar a altera\xE7\xF5es na conta.","the rendering 2nd parameter":"a renderiza\xE7\xE3o 2\xBA par\xE2metro","Test the second parameter of rendering ( Size/Length ).":"Teste o segundo par\xE2metro de renderiza\xE7\xE3o (tamanho/comprimento).","the 2nd rendering parameter":"o 2\xBA par\xE2metro de renderiza\xE7\xE3o","Capacity":"Capacidade","Change the capacity of the emitter.":"Altere a capacidade do emissor.","the capacity":"a capacidade","Test the capacity of the emitter.":"Teste a capacidade do emissor.","Flow":"Fluxo","Change the flow of the emitter.":"Altere o fluxo do emissor.","the flow":"o fluxo","Test the flow of the emitter.":"Teste o fluxo do emissor.","Change the image of particles ( if displayed ).":"Mude a imagem de part\xEDculas (se indicada).","Change the image of particles of _PARAM0_ to _PARAM1_":"Alterar a imagem de part\xEDculas de _PARAM0_ para _PARAM1_","New image":"Nova imagem","Test the name of the image displayed by particles.":"Teste o nome da imagem exibida por part\xEDculas.","the image displayed by particles":"a imagem exibida por part\xEDculas","Particles image":"Imagem de part\xEDculas","Name of the image displayed by particles":"Nome da imagem exibida por part\xEDculas","Particles":"Part\xEDculas","Particles number":"N\xFAmero de part\xEDculas","Particles count":"Particles count","Number of particles currently displayed":"Number of particles currently displayed","Emission angle A":"\xC2ngulo de emiss\xE3o A","Emission angle B":"\xC2ngulo de emiss\xE3o B","Radius of the emission zone":"Raio da zona de emiss\xE3o","X Gravity of particles":"X gravidade de part\xEDculas","Y Gravity of particles":"Y gravidade de part\xEDculas","Gravity value":"Valor de gravidade","Minimum lifetime of particles":"Tempo de vida m\xEDnimo de part\xEDculas","Maximum lifetime of particles":"Tempo de vida m\xE1ximo de part\xEDculas","Parameter 1 of red color":"Par\xE2metro 1 de cor vermelha","Parameter 2 of red color":"Par\xE2metro 2 de cor vermelha","Parameter 1 of blue color":"Par\xE2metro 1 da cor azul","Parameter 2 of blue color":"Par\xE2metro 2 de cor azul","Parameter 1 of green color":"Par\xE2metro 1 da cor verde","Parameter 2 of green color":"Par\xE2metro 2 de cor verde","Parameter 1 of transparency":"Par\xE2metro 1 da transpar\xEAncia","Parameter 2 of transparency":"Par\xE2metro 2 de transpar\xEAncia","Parameter 1 of size":"Par\xE2metro 1 de tamanho","Parameter 2 of size":"Par\xE2metro 2 de tamanho","Parameter 1 of angle":"Par\xE2metro 1 de \xE2ngulo","Parameter 2 of angle":"Par\xE2metro 2 de \xE2ngulo","Particle system":"Sistema de part\xEDculas","Particles emitter":"Emissor de part\xEDculas","Displays a large number of small particles to create visual effects.":"Exibe um grande n\xFAmero de pequenas part\xEDculas para criar efeitos visuais.","Initial color":"Cor inicial","Modify initial color of particles.":"Modifica a cor inicial das part\xEDculas.","Put initial color of particles of _PARAM0_ to _PARAM1_":"Colocar cor inicial das part\xEDculas de _PARAM0_ para _PARAM1_","Final color":"Cor final","Modify final color of particles.":"Modifica a cor final de part\xEDculas.","Put final color of particles of _PARAM0_ to _PARAM1_":"Colocar cor inicial das part\xEDculas de _PARAM0_ para _PARAM1_","Red color, parameter 1":"Cor vermelha, o par\xE2metro 1","Modify parameter 1 of the red color.":"Modifica o par\xE2metro 1 da cor vermelha.","the parameter 1 of red color":"o par\xE2metro 1 de cor vermelha","Test parameter 1 of the red color":"Testar o par\xE2metro 1 da cor vermelha","Red color, parameter 2":"Cor vermelha, par\xE2metro 2","Modify parameter 2 of the red color":"Modificar o par\xE2metro 2 da cor vermelha","the parameter 2 of red color":"o par\xE2metro 2 de cor vermelha","Test parameter 2 of the red color":"Testar o par\xE2metro 2 da cor vermelha","Blue color, parameter 1":"Cor azul, par\xE2metro 1","Modify parameter 1 of blue color":"Modificar o par\xE2metro 1 da cor azul","the parameter 1 of blue color":"o par\xE2metro 1 de cor azul","Test parameter 1 of blue color":"Testar o par\xE2metro 1 da cor azul","Blue color, parameter 2":"Cor azul, par\xE2metro 2","Modify parameter 2 of blue color":"Modificar o par\xE2metro 2 de cor azul","the parameter 2 of blue color":"o par\xE2metro 2 de cor azul","Test parameter 2 of blue color":"Testar o par\xE2metro 2 de cor azul","Green color, parameter 1":"Cor verde, par\xE2metro 1","Modify parameter 1 of green color":"Modificar o par\xE2metro 1 da cor verde","the parameter 1 of green color":"o par\xE2metro 1 de cor verde","Test parameter 1 of green color":"Testar o par\xE2metro 1 da cor verde","Green color, parameter 2":"Cor verde, par\xE2metro 2","Modify the parameter 2 of the green color":"Modifique o par\xE2metro 2 da cor verde","the parameter 2 of green color":"o par\xE2metro 2 de cor verde","Test the parameter 2 of the green color":"Testar o par\xE2metro 2 da cor verde","SIze, parameter 1":"Tamanho, par\xE2metro 1","Modify parameter 1 of the size of particles":"Modificar o par\xE2metro 1 do tamanho das part\xEDculas","the parameter 1 of size":"o par\xE2metro 1 do tamanho","Size, parameter 1":"Tamanho, par\xE2metro 1","Test parameter 1 of the size of particles":"Testar o par\xE2metro 1 da dimens\xE3o das part\xEDculas","the parameter 1 of the size":"o par\xE2metro 1 de tamanho","Size, parameter 2":"Tamanho, par\xE2metro 2","Modify parameter 2 of the size of particles":"Modificar o par\xE2metro 2 do tamanho de part\xEDculas","the parameter 2 of size":"o par\xE2metro 2 do tamanho","Test parameter 2 of the size of particles":"Testar o par\xE2metro 2 do tamanho de part\xEDculas","the parameter 2 of the size":"o par\xE2metro 2 do tamanho","Angle, parameter 1":"\xC2ngulo, par\xE2metro 1","Modify parameter 1 of the angle of particles":"Modificar o par\xE2metro 1 do \xE2ngulo de part\xEDculas","the parameter 1 of angle":"o par\xE2metro 1 do \xE2ngulo","Test parameter 1 of the angle of particles":"Testar o par\xE2metro 1 do \xE2ngulo de part\xEDculas","Angle, parameter 2":"\xC2ngulo, par\xE2metro 2","Modify parameter 2 of the angle of particles":"Modificar o par\xE2metro 2 do \xE2ngulo de part\xEDculas","the parameter 2 of angle":"o par\xE2metro 2 do \xE2ngulo","Test parameter 2 of the angle of particles":"Testar o par\xE2metro 2 do \xE2ngulo de part\xEDculas","Transparency, parameter 1":"Transpar\xEAncia, par\xE2metro 1","Modify parameter 1 of the transparency of particles":"Modificar o par\xE2metro 1 da transpar\xEAncia das part\xEDculas","the parameter 1 of the transparency":"o par\xE2metro 1 da transpar\xEAncia","Test parameter 1 of the transparency of particles":"Testar o par\xE2metro 1 da transpar\xEAncia das part\xEDculas","Transparency, parameter 2":"Transpar\xEAncia, par\xE2metro 2","Modify parameter 2 of the transparency of particles":"Modificar o par\xE2metro 2 da transpar\xEAncia das part\xEDculas","the parameter 2 of the transparency":"o par\xE2metro 2 da transpar\xEAncia","Test parameter 2 of the transparency of particles":"Testar o par\xE2metro 2 da transpar\xEAncia das part\xEDculas","No more particles":"N\xE3o h\xE1 mais part\xEDculas","Check if the object does not emit particles anylonger, so as to destroy it for example.":"Verifique se o objeto n\xE3o emite mais part\xEDculas, de forma a destru\xED-lo por exemplo.","_PARAM0_ does not emit anylonger.":"_PARAM0_ n\xE3o emite mais.","Impassable obstacle":"Obst\xE1culo intranspon\xEDvel","Cost (if not impassable)":"Custo (se n\xE3o intranspon\xEDvel)","Pathfinding behavior":"Comportamento de pathfinding","Pathfinding":"Encontrar o caminho (pathfinding)","With this behavior, the object will move while avoiding all objects that are flagged as obstacles.":"With this behavior, the object will move while avoiding all objects that are flagged as obstacles.","Move to a position":"Mover para uma posi\xE7\xE3o","Move the object to a position":"Mover o objeto para uma posi\xE7\xE3o","Move _PARAM0_ to _PARAM3_;_PARAM4_":"Mover a _PARAM0_ para _PARAM3_; _PARAM4_","Destination X position":"Posi\xE7\xE3o X do destino","Destination Y position":"Posi\xE7\xE3o de destino Y","Path found":"Caminho encontrado","Check if a path has been found.":"Check if a path has been found.","A path has been found for _PARAM0_":"Foi encontrado um caminho para _PARAM0_","Destination reached":"Destino alcan\xE7ado","Check if the destination was reached.":"Check if the destination was reached.","_PARAM0_ reached its destination":"_PARAM0_ chegou ao seu destino","Width of the cells":"Largura das c\xE9lulas","Change the width of the cells of the virtual grid.":"Altere a largura das c\xE9lulas da grelha virtual.","the width of the virtual cells":"the width of the virtual cells","Virtual grid":"Rede virtual","Width of the virtual grid":"Largura da grelha virtual","Compare the width of the cells of the virtual grid.":"Compare a largura das c\xE9lulas da grade virtual.","Height of the cells":"Altura das c\xE9lulas","Change the height of the cells of the virtual grid.":"Altere a largura das c\xE9lulas da grelha virtual.","the height of the virtual cells":"the height of the virtual cells","Height of the virtual grid":"Altura da grelha virtual","Compare the height of the cells of the virtual grid.":"Compare a largura das c\xE9lulas da grade virtual.","Change the acceleration when moving the object":"Alterar a acelera\xE7\xE3o quando mover o objeto","the acceleration on the path":"the acceleration on the path","Pathfinding configuration":"Pathfinding configuration","Compare the acceleration when moving the object":"Comparar a acelera\xE7\xE3o quando mover o objeto","Change the maximum speed when moving the object":"Alterar a velocidade m\xE1xima quando mover o objeto","the max. speed on the path":"the max. speed on the path","Compare the maximum speed when moving the object":"Comparar a velocidade m\xE1xima quando mover o objeto","Change the speed of the object on the path":"Altere a velocidade do objeto no caminho","the speed on the path":"the speed on the path","Movement on the path":"Movement on the path","Speed on its path":"Speed on its path","Compare the speed of the object on its path.":"Compare the speed of the object on its path.","Angle of movement on its path":"Angle of movement on its path","Compare the angle of movement of an object on its path.":"Compare the angle of movement of an object on its path.","Angle of movement of _PARAM0_ is _PARAM2_ (tolerance: _PARAM3_ degrees)":"Angle of movement of _PARAM0_ is _PARAM2_ (tolerance: _PARAM3_ degrees)","Angle, in degrees":"\xC2ngulo, em graus","Tolerance, in degrees":"Tolerance, in degrees","Change the maximum angular speed when moving the object":"Alterar a velocidade angular m\xE1xima ao mover o objeto","the max. angular speed on the path":"the max. angular speed on the path","Compare the maximum angular speed when moving the object":"Comparar a velocidade angular m\xE1xima ao mover o objeto","the rotation offset on the path":"the rotation offset on the path","Compare the rotation offset when moving the object":"Comparar o deslocamento de rota\xE7\xE3o ao mover o objeto","Extra border":"Borda extra","Change the size of the extra border applied to the object when planning a path":"Alterar o tamanho da borda extra aplicada ao objeto, ao planear um caminho","the size of the extra border on the path":"o tamanho da borda extra no caminho","Compare the size of the extra border applied to the object when planning a path":"Compare o tamanho da borda extra aplicada ao objeto, ao planear um caminho","Allow or restrict diagonal movement on the path":"Permitir ou restringir movimentos diagonais no caminho","Allow diagonal movement for _PARAM0_ on the path: _PARAM2_":"Permitir movimento diagonal para _PARAM0_ no caminho: _PARAM2_","Check if the object is allowed to move diagonally on the path":"Check if the object is allowed to move diagonally on the path","Diagonal moves allowed for _PARAM0_":"Movimentos diagunais permitidos para _PARAM0_","Enable or disable rotation of the object on the path":"Habilitar ou desabilitar a rota\xE7\xE3o do objeto no caminho","Enable rotation of _PARAM0_ on the path: _PARAM2_":"Ativar a rota\xE7\xE3o de _PARAM0_ no caminho: _PARAM2_","Check if the object is rotated when traveling on its path.":"Check if the object is rotated when traveling on its path.","_PARAM0_ is rotated when traveling on its path":"_PARAM0_ \xE9 rotacionado quando viaja em seu caminho","Get a waypoint X position":"Obter uma posi\xE7\xE3o de waypoint X","Get next waypoint X position":"Obter a pr\xF3xima posi\xE7\xE3o waypoint X","Node index (start at 0!)":"\xCDndice do n\xF3 (inicia em 0!)","Get a waypoint Y position":"Obter uma posi\xE7\xE3o de waypoint Y","Get next waypoint Y position":"Obter a pr\xF3xima posi\xE7\xE3o waypoint Y","Index of the next waypoint":"\xCDndice do pr\xF3ximo waypoint","Get the index of the next waypoint to reach":"Obter o \xEDndice do pr\xF3ximo waypoint a ser alcan\xE7ado","Waypoint count":"Contagem de waypoint","Get the number of waypoints on the path":"Obter o n\xFAmero de waypoints no caminho","Last waypoint X position":"\xDAltima posi\xE7\xE3o de waypoint X","Last waypoint Y position":"\xDAltima posi\xE7\xE3o de waypoint Y","Acceleration of the object on the path":"Acelera\xE7\xE3o do objeto no caminho","Maximum speed of the object on the path":"Velocidade m\xE1xima do objeto no caminho","Speed of the object on the path":"Velocidade do objeto no caminho","Angular maximum speed of the object on the path":"Velocidade angular m\xE1xima do objeto no caminho","Rotation offset applied the object on the path":"Deslocamento de rota\xE7\xE3o aplicado ao objeto no caminho","Extra border size":"Tamanho da borda extra","Extra border applied the object on the path":"Borda extra aplicada ao objeto no caminho","Width of a cell":"Largura de uma c\xE9lula","Height of a cell":"Altura de uma c\xE9lula","Grid X offset":"Grid X offset","X offset of the virtual grid":"X offset of the virtual grid","Grid Y offset":"Grid Y offset","Y offset of the virtual grid":"Y offset of the virtual grid","Obstacle for pathfinding":"Obst\xE1culo para o encontrar caminho","Flag the object as being an obstacle for pathfinding.":"Sinalizar o objeto como sendo um obst\xE1culo para pathfinding.","Cost":"Custo","Change the cost of going through the object.":"Alterar o custo de passar pelo objeto.","the cost":"the cost","Obstacles":"Obst\xE1culos","Compare the cost of going through the object":"Comparar o custo de passar pelo objeto","Should object be impassable?":"O objeto deve ser intranspon\xEDvel?","Decide if the object is an impassable obstacle":"Decidir se o objeto \xE9 um obst\xE1culo intranspon\xEDvel","Set _PARAM0_ as an impassable obstacle: _PARAM2_":"Definir _PARAM0_ como um obst\xE1culo intranspon\xEDvel: _PARAM2_","Impassable?":"Intranspon\xEDvel?","Is object impassable?":"O objeto \xE9 intranspon\xEDvel?","Check if the obstacle is impassable":"Check if the obstacle is impassable","_PARAM0_ is impassable":"_PARAM0_ \xE9 intranspon\xEDvel","Obstacle cost":"Custo de obst\xE1culo","Virtual cell width":"Largura da c\xE9lula virtual","Virtual cell height":"Altura da c\xE9lula virtual","Virtual grid X offset":"Virtual grid X offset","Virtual grid Y offset":"Virtual grid Y offset","Text entry object":"Objeto de entrada de texto","An object that can be used to capture the text entered with a keyboard by a player.":"Um objeto que pode ser usado para capturar o texto introduzido por um jogador com um teclado.","Text entry":"Entrada de texto","Invisible object used to get the text entered with the keyboard.":"Objeto invis\xEDvel utilizado para obter o texto inserido com um teclado.","Text in memory":"Texto na mem\xF3ria","Modify text in memory of the object":"Modificar o texto na mem\xF3ria do objeto","the text in memory":"o texto na mem\xF3ria","Test the text of a Text Entry object.":"Teste o texto de um objeto de entrada de texto.","De/activate capturing text input":"Des/activar captura de entrada de texto","Activate or deactivate the capture of text entered with keyboard.":"Ativar ou desativar a captura de texto inserido com o teclado.","Activate capture by _PARAM0_ of the text entered with keyboard: _PARAM1_":"Activar captura de _PARAM0_ do texto inserido com o teclado: _PARAM1_","Activate":"Ativar","Text input":"Entrada de texto","Test if the object captured text entered with keyboard.":"Teste se o objeto capturar texto digitado com o teclado.","_PARAM0_ capture the text entered with keyboard":"_PARAM0_ captura o texto digitado com o teclado","Text entered with keyboard":"Texto digitado com o teclado","System information":"Informa\xE7\xE3o de sistema","Get information about the system and device running the game.":"Obt\xE9m informa\xE7\xF5es sobre o sistema e dispositivo executando o jogo.","Is a mobile device":"\xC9 um dispositivo m\xF3vel","Check if the device running the game is a mobile device":"Verifique se o dispositivo que est\xE1 a executar o jogo \xE9 um dispositivo m\xF3vel","The device is a mobile device":"O dispositivo \xE9 um dispositivo m\xF3vel","Is WebGL supported":"\xC9 suportado pelo WebGL","Check if GPU accelerated WebGL is supported on the target device.":"Check if GPU accelerated WebGL is supported on the target device.","WebGL is available":"WebGL est\xE1 dispon\xEDvel","Is the game running as a preview":"O jogo est\xE1 sendo executado como pr\xE9-visualiza\xE7\xE3o","Check if the game is currently being previewed in the editor. This can be used to enable a \"Debug mode\" or do some work only in previews.":"Verifique se o jogo est\xE1 actualmente a ser pr\xE9-visualizado no editor. Isto pode ser usado para habilitar o \"Modo de depura\xE7\xE3o\" ou fazer algum trabalho somente nas pr\xE9-visualiza\xE7\xF5es.","The game is being previewed in the editor":"O jogo est\xE1 a ser pr\xE9-visualizado no editor","Device has a touchscreen":"O dispositivo tem um ecr\xE3 sens\xEDvel ao toque","Check if the device running the game has a touchscreen (typically Android phones, iPhones, iPads, but also some laptops).":"Verifique se o dispositivo que est\xE1 a executar o jogo tem um ecr\xE3 sens\xEDvel ao toque (normalmente telefones Android, iPhones, iPads, mas tamb\xE9m alguns computadores).","The device has a touchscreen":"O dispositivo tem um ecr\xE3 sens\xEDvel ao toque","Draggable Behavior":"Comportamento Arrast\xE1vel","Allows objects to be moved using the mouse (or touch). Add the behavior to an object to make it draggable. Use events to enable or disable the behavior when needed.":"Permite que os objetos sejam movidos usando o rato (ou toque). Adicione o comportamento a um objeto para conseguir arrast\xE1-lo. Use eventos para ativar ou desativar o comportamento quando necess\xE1rio.","Draggable object":"Objeto arrast\xE1vel","Draggable":"Arrast\xE1vel","Allows objects to be moved using the mouse (or touch).":"Permite que os objects sejam movidos usando o rato (ou toque).","Being dragged":"Sendo arrastado","Check if the object is being dragged":"Verifique se o objeto est\xE1 sendo arrastado","_PARAM0_ is being dragged":"_PARAM0_ est\xE1 sendo arrastado","Inventory":"Invent\xE1rio","Provides actions and conditions to add an inventory to your game, with items in memory.":"Fornece a\xE7\xF5es e condi\xE7\xF5es para adicionar um invent\xE1rio ao seu jogo, com itens em mem\xF3ria.","Add an item":"Adicionar item","Add an item in an inventory.":"Adiciona um item em um invent\xE1rio.","Add a _PARAM2_ to inventory _PARAM1_":"Adicionar um _PARAM2_ para _PARAM1_ de invent\xE1rio","Inventories":"Invent\xE1rios","Inventory name":"Nome do invent\xE1rio","Item name":"Nome do item","Remove an item":"Remover um item","Remove an item from an inventory.":"Remova um item de um invent\xE1rio.","Remove a _PARAM2_ from inventory _PARAM1_":"Remove um _PARAM2_ do invent\xE1rio de _PARAM1_","Item count":"Contagem de itens","Compare the number of an item in an inventory.":"Compare o n\xFAmero de um item no invent\xE1rio.","the count of _PARAM2_ in _PARAM1_":"a contagem de _PARAM2_ em _PARAM1_","Has an item":"Tem um item","Check if at least one of the specified items is in the inventory.":"Verifique se pelo menos um dos itens especificados est\xE1 no invent\xE1rio.","Inventory _PARAM1_ contains a _PARAM2_":"Invent\xE1rio _PARAM1_ cont\xE9m um_PARAM2_","Set a maximum count for an item":"Definir uma contagem m\xE1xima para um item","Set the maximum number of the specified item that can be added in the inventory. By default, the number allowed for each item is unlimited.":"Defina o n\xFAmero m\xE1ximo do item especificado que pode ser adicionado no invent\xE1rio. Por padr\xE3o, o n\xFAmero permitido para cada item \xE9 ilimitado.","Set the maximum count for _PARAM2_ in inventory _PARAM1_ to _PARAM3_":"Define a contagem m\xE1xima para _PARAM2_ em _PARAM1_ de invent\xE1rio para _PARAM3_","Maximum count":"Contagem m\xE1xima","Set unlimited count for an item":"Define uma contagem ilimitada para um item","Allow an unlimited amount of an object to be in an inventory. This is the case by default for each item.":"Permite que uma quantidade ilimitada de um objeto esteja em um inventario. Este e o caso padr\xE3o para cada item.","Allow an unlimited count of _PARAM2_ in inventory _PARAM1_: _PARAM3_":"Permite uma contagem ilimitada de _PARAM2_ em _PARAM1_ do invent\xE1rio: _PARAM3_","Allow an unlimited amount?":"Permitir uma quantidade ilimitada?","Item full":"Artigo completo","Check if an item has reached its maximum number allowed in the inventory.":"Verifica se um item atingiu seu n\xFAmero m\xE1ximo permitido no invent\xE1rio.","Inventory _PARAM1_ is full of _PARAM2_":"Invent\xE1rio _PARAM1_ est\xE1 cheio de _PARAM2_","Equip an item":"Equipar um item","Mark an item as being equipped. If the item count is 0, it won't be marked as equipped.":"Marca um item como estando equipado. Se a contagem de item \xE9 0, ele n\xE3o vai ser marcado como equipado.","Set _PARAM2_ as equipped in inventory _PARAM1_: _PARAM3_":"Defina _PARAM2_ como equipado no invent\xE1rio _PARAM1_: _PARAM3_","Equip?":"Equipar?","Item equipped":"Item equipado","Check if an item is equipped.":"Verifica se um item est\xE1 equipado.","_PARAM2_ is equipped in inventory _PARAM1_":"_PARAM2_ \xE9 equipada no invent\xE1rio _PARAM1_","Save an inventory in a scene variable":"Guarde um invent\xE1rio numa vari\xE1vel de cena","Save all the items of the inventory in a scene variable, so that it can be restored later.":"Guardar todos os itens do invent\xE1rio numa vari\xE1vel de cena, para que possa ser restaurado mais tarde.","Save inventory _PARAM1_ in variable _PARAM2_":"Salve o invent\xE1rio _PARAM1_ na vari\xE1vel _PARAM2_","Inventories/Variables":"Invent\xE1rios/vari\xE1veis","Load an inventory from a scene variable":"Carregar um invent\xE1rio de uma vari\xE1vel de cena","Load the content of the inventory from a scene variable.":"Carrega o conte\xFAdo do invent\xE1rio de uma vari\xE1vel de cena.","Load inventory _PARAM1_ from variable _PARAM2_":"Carga o invent\xE1rio _PARAM1_ desde a vari\xE1vel _PARAM2_","Get the number of an item in the inventory":"Obter o n\xFAmero de um item no invent\xE1rio","Device vibration":"Vibra\xE7\xE3o do dispositivo","Vibrate":"Vibrar","Vibrate (Duration in ms).":"Vibrar (dura\xE7\xE3o em ms).","Start vibration for _PARAM0_ ms":"Iniciar vibra\xE7\xE3o para _PARAM0_ ms","Vibration":"Vibra\xE7\xE3o","Vibrate by pattern":"Vibrar por padr\xE3o","Vibrate (Duration in ms). You can add multiple comma-separated values where every second value determines the period of silence between two vibrations. This is a string value so use quotes.":"Vibrar (dura\xE7\xE3o em ms). Voc\xEA pode adicionar v\xE1rios valores separados por v\xEDrgula, onde cada segundo determina o per\xEDodo de sil\xEAncio entre duas vibra\xE7\xF5es. Este \xE9 um valor de string por isso use aspas.","Intervals (for example \"500,100,200\"":"Intervalos (por exemplo, \"500,100,200\"","Stop vibration":"Parar vibra\xE7\xE3o","Stop the vibration":"Parar a vibra\xE7\xE3o","Filesystem":"Sistema de ficheiros","Access the filesystem of the operating system.":"Acessar o sistema de ficheiros do sistema operacional.","File or directory exists":"Ficheiro ou diret\xF3rio existe","Check if the file or directory exists.":"Verificar se o ficheiro ou diret\xF3rio existe.","The path _PARAM0_ exists":"O caminho _PARAM0_ existe","Filesystem/Windows, Linux, MacOS":"Sistema de ficheiros/Windows, Linux, MacOS","Path to file or directory":"Caminho para o ficheiro ou diret\xF3rio","Create a directory":"Criar um diret\xF3rio","Create a new directory at the specified path.":"Criar um novo diret\xF3rio no caminho especificado.","Create directory _PARAM0_":"Criar diret\xF3rio _PARAM0_","Directory":"Diret\xF3rio","(Optional) Variable to store the result. 'ok': task was successful, 'error': an error occured.":"(Opcional) Vari\xE1vel para armazenar o resultado. ok': a tarefa foi bem sucedida, 'error': ocorreu um erro.","Save a text into a file":"Salvar um texto num ficheiro","Save a text into a file. Only use this on small files to avoid any lag or freeze during the the game execution.":"Salvar um texto num ficheiro. Usar apenas em pequenos ficheiros para evitar qualquer atraso ou congelamento durante a execu\xE7\xE3o do jogo.","Save _PARAM0_ into file _PARAM1_":"Salvar _PARAM0_ no ficheiro _PARAM1_","Save path":"Salvar caminho","Save a text into a file (Async)":"Salvar um texto num ficheiro (Async)","Save a text into a file asynchronously. Use this for large files to avoid any lag or freeze during game execution. The 'result' variable gets updated when the operation has finished.":"Salvar um texto num ficheiro assincronamente. Usar para ficheiros grandes para evitar qualquer atraso ou congelamento durante a execu\xE7\xE3o do jogo. A vari\xE1vel 'resultado' \xE9 atualizada quando a opera\xE7\xE3o termina.","Filesystem/Windows, Linux, MacOS/Asynchronous":"Sistema de ficheiros/Windows, Linux, MacOS/Ass\xEDncrono","Save a scene variable into a JSON file":"Salvar uma vari\xE1vel de scene num ficheiro JSON","Save a scene variable (including, for structure, all the children) into a file in JSON format. Only use this on small files to avoid any lag or freeze during the the game execution.":"Salvar uma vari\xE1vel de scene (incluindo, para a estrutura, todas as crian\xE7as) num ficheiro no formato JSON. Usar apenas em pequenos ficheiros para evitar qualquer atraso ou congelamento durante a execu\xE7\xE3o do jogo.","Save scene variable _PARAM0_ into file _PARAM1_ as JSON":"Salvar a vari\xE1vel de scene _PARAM0_ no ficheiro _PARAM1_ como JSON","Save a scene variable into a JSON file (Async)":"Salvar uma vari\xE1vel de scene num ficheiro JSON (Async)","Save the scene variable (including, for structures, all the children) into a file in JSON format, asynchronously. Use this for large files to avoid any lag or freeze during game execution. The 'result' variable gets updated when the operation has finished.":"Salvar a vari\xE1vel de scene (incluindo, para estruturas, todas as crian\xE7as) num ficheiro no formato JSON, de forma ass\xEDncrona. Use isso para arquivos grandes para evitar qualquer atraso ou congelamento durante a execu\xE7\xE3o do jogo. A vari\xE1vel 'resultado' \xE9 actualizada quando a opera\xE7\xE3o termina.","Load a text from a file (Async)":"Carregar um texto de um ficheiro (Async)","Load a text from a file, asynchronously. Use this for large files to avoid any lag or freeze during game execution. The content of the file will be available in the scene variable after a small delay (usually a few milliseconds). The 'result' variable gets updated when the operation has finished.":"Carregar um texto de um ficheiro, de forma ass\xEDncrona. Use isso para ficheiros grandes para evitar qualquer atraso ou congelamento durante a execu\xE7\xE3o do jogo. O conte\xFAdo do ficheiro estar\xE1 dispon\xEDvel na vari\xE1vel de scene ap\xF3s um pequeno atraso (normalmente alguns milissegundos). A vari\xE1vel 'resultado' \xE9 actualizada quando a opera\xE7\xE3o termina.","Load text from _PARAM1_ into scene variable _PARAM0_ (Async)":"Carregar texto de _PARAM1_ na vari\xE1vel de scene _PARAM0_ (Async)","Load path":"Caminho de carregamento","Load a text from a file":"Carregar um texto de um ficheiro","Load a text from a file. Only use this on small files to avoid any lag or freeze during the the game execution.":"Carregar um texto de um ficheiro. Use-o apenas em pequenos ficheiros para evitar qualquer atraso ou congelamento durante a execu\xE7\xE3o do jogo.","Load text from _PARAM1_ into scene variable _PARAM0_":"Carregar texto de _PARAM1_ na vari\xE1vel de scene _PARAM0_","Load a scene variable from a JSON file":"Carregar uma vari\xE1vel de scene de um ficheiro JSON","Load a JSON formatted text from a file and convert it to a scene variable (potentially a structure variable with children). Only use this on small files to avoid any lag or freeze during the the game execution.":"Carregar um texto formatado JSON de um arquivo e converter para uma vari\xE1vel de scene (potencialmente uma vari\xE1vel de estrutura com crian\xE7as). Use-o apenas em pequenos ficheiros para evitar qualquer atraso ou congelamento durante a execu\xE7\xE3o do jogo.","Load JSON from _PARAM1_ into scene variable _PARAM0_":"Carregar JSON de _PARAM1_ na vari\xE1vel de scene _PARAM0_","Load a scene variable from a JSON file (Async)":"Carregar uma vari\xE1vel de scene de um ficheiro JSON (Async)","Load a JSON formatted text from a file and convert it to a scene variable (potentially a structure variable with children), asynchronously. Use this for large files to avoid any lag or freeze during game execution. The content of the file will be available as a scene variable after a small delay (usually a few milliseconds). The 'result' variable gets updated when the operation has finished.":"Carregar um texto formatado JSON de um arquivo e converter para uma vari\xE1vel de scene (potencialmente uma vari\xE1vel de estrutura com crian\xE7as), de forma ass\xEDncrona. Use isso para arquivos grandes para evitar qualquer atraso ou congelamento durante a execu\xE7\xE3o do jogo. O conte\xFAdo do ficheiro estar\xE1 dispon\xEDvel como uma vari\xE1vel de scene ap\xF3s um pequeno atraso (geralmente alguns milissegundos). A vari\xE1vel 'resultado' \xE9 actualizada quando a opera\xE7\xE3o termina.","Delete a file":"Excluir um arquivo","Delete a file from the filesystem.":"Eliminar um ficheiro do sistema de ficheiros.","Delete the file _PARAM0_":"Exclua o arquivo _PARAM0_","File path":"Caminho do ficheiro","Delete a file (Async)":"Eliminar um ficheiro (Async)","Delete a file from the filesystem asynchronously. The option result variable will be updated once the file is deleted.":"Delete a file from the filesystem asynchronously. The option result variable will be updated once the file is deleted.","Desktop folder":"Pasta Desktop","Get the path to the desktop folder.":"Obter o caminho para a pasta desktop.","Documents folder":"Pasta de documentos","Get the path to the documents folder.":"Obter o caminho para a pasta de documentos.","Pictures folder":"Pasta de imagens","Get the path to the pictures folder.":"Obter o caminho para a pasta de imagens.","Game executable file":"Game executable file","Get the path to this game executable file.":"Get the path to this game executable file.","Game executable folder":"Game executable folder","Get the path to this game executable folder.":"Get the path to this game executable folder.","Userdata folder (for application settings)":"Userdata folder (for application settings)","Get the path to userdata folder (for application settings).":"Get the path to userdata folder (for application settings).","User's Home folder":"Pasta In\xEDcio do usu\xE1rio","Get the path to the user home folder.":"Obter o caminho da pasta In\xEDcio do usu\xE1rio.","Temp folder":"Pasta Temp","Get the path to temp folder.":"Obter o caminho para a pasta temp.","Path delimiter":"Delimitador de caminho","Get the operating system path delimiter.":"Get the operating system path delimiter.","Get directory name from a path":"Get directory name from a path","Returns the portion of the path that represents the directories, without the ending file name.":"Returns the portion of the path that represents the directories, without the ending file name.","File or folder path":"File or folder path","Get file name from a path":"Get file name from a path","Returns the name of the file with its extension, if any.":"Returns the name of the file with its extension, if any.","Get the extension from a file path":"Get the extension from a file path","Returns the extension of the file designated by the given path, including the extension period. For example: \".txt\".":"Returns the extension of the file designated by the given path, including the extension period. For example: \".txt\".","Spatial sound":"Spatial sound","Allow positioning sounds in a 3D space. The stereo system of the device is used to simulate the position of the sound and to give the impression that the sound is located somewhere around the player.":"Allow positioning sounds in a 3D space. The stereo system of the device is used to simulate the position of the sound and to give the impression that the sound is located somewhere around the player.","Set position of sound":"Set position of sound","Sets the spatial position of a sound. When a sound is at a distance of 1 to the listener, it's heard at 100% volume. Then, it follows an *inverse distance model*. At a distance of 2, it's heard at 50%, and at a distance of 4 it's heard at 25%.":"Sets the spatial position of a sound. When a sound is at a distance of 1 to the listener, it's heard at 100% volume. Then, it follows an *inverse distance model*. At a distance of 2, it's heard at 50%, and at a distance of 4 it's heard at 25%.","Set position of sound on channel _PARAM1_ to position _PARAM2_, _PARAM3_, _PARAM4_":"Set position of sound on channel _PARAM1_ to position _PARAM2_, _PARAM3_, _PARAM4_","Audio/Spatial Sound":"Audio/Spatial Sound","Channel":"Canal","Z position":"Z position","Set position of the listener":"Set position of the listener","Sets the spatial position of the listener/player.":"Sets the spatial position of the listener/player.","Set the listener position to _PARAM0_, _PARAM1_, _PARAM2_":"Set the listener position to _PARAM0_, _PARAM1_, _PARAM2_","Tilemap":"Tilemap","Tilemap JSON file":"Tilemap JSON file","This is the JSON file that was saved or exported from Tiled.":"This is the JSON file that was saved or exported from Tiled.","Tileset JSON file (optional)":"Tileset JSON file (optional)","Optional, don't specify it if you've not saved the tileset in a different file.":"Optional, don't specify it if you've not saved the tileset in a different file.","Atlas image":"Atlas image","Display mode":"Display mode","Layer index to display":"Layer index to display","If \"index\" is selected as the display mode, this is the index of the layer to display.":"If \"index\" is selected as the display mode, this is the index of the layer to display.","Animation speed scale":"Escala da velocidade de anima\xE7\xE3o","Animation FPS":"Animation FPS","Displays a tiled-based map, made with the Tiled editor (download it separately on https://www.mapeditor.org/).":"Displays a tiled-based map, made with the Tiled editor (download it separately on https://www.mapeditor.org/).","Check the Tilemap JSON file being used.":"Check the Tilemap JSON file being used.","The Tilemap JSON file of _PARAM0_ is _PARAM1_":"The Tilemap JSON file of _PARAM0_ is _PARAM1_","Set the JSON file containing the Tilemap data to display. This is usually the JSON file exported from Tiled.":"Set the JSON file containing the Tilemap data to display. This is usually the JSON file exported from Tiled.","Set the Tilemap JSON file of _PARAM0_ to _PARAM1_":"Set the Tilemap JSON file of _PARAM0_ to _PARAM1_","Tileset JSON file":"Tileset JSON file","Check the tileset JSON file being used.":"Check the tileset JSON file being used.","The tileset JSON file of _PARAM0_ is _PARAM1_":"The tileset JSON file of _PARAM0_ is _PARAM1_","Set the JSON file with the tileset data (sometimes that is embeded in the Tilemap, so not needed)":"Set the JSON file with the tileset data (sometimes that is embeded in the Tilemap, so not needed)","Set the tileset JSON file of _PARAM0_ to _PARAM1_":"Set the tileset JSON file of _PARAM0_ to _PARAM1_","Compare the value of the display mode.":"Compare the value of the display mode.","The display mode of _PARAM0_ is _PARAM1_":"The display mode of _PARAM0_ is _PARAM1_","Set the display mode":"Set the display mode","Set the display mode of _PARAM0_ to _PARAM1_":"Set the display mode of _PARAM0_ to _PARAM1_","Layer index":"Layer index","Compare the value of the layer index.":"Compare the value of the layer index.","the layer index":"the layer index","Set the layer index of the Tilemap.":"Set the layer index of the Tilemap.","Get the layer index being displayed":"Get the layer index being displayed","Compare the animation speed scale.":"Compare the animation speed scale.","the animation speed scale":"the animation speed scale","Set the animation speed scale of the Tilemap (1 by default).":"Set the animation speed scale of the Tilemap (1 by default).","Get the Animation speed scale":"Get the Animation speed scale","Animation speed (FPS)":"Animation speed (FPS)","Compare the animation speed (in frames per second).":"Compare the animation speed (in frames per second).","the animation speed (FPS)":"the animation speed (FPS)","Set the animation speed (in frames per second) of the Tilemap.":"Set the animation speed (in frames per second) of the Tilemap.","Get the animation speed (in frames per second)":"Get the animation speed (in frames per second)","Device sensors":"Device sensors","Allow the game to access the sensors of a mobile device.":"Allow the game to access the sensors of a mobile device.","Sensor active":"Sensor active","The condition is true if the device orientation sensor is currently active":"The condition is true if the device orientation sensor is currently active","Orientation sensor is active":"Orientation sensor is active","Sensors/Orientation":"Sensors/Orientation","Compare the value of orientation alpha":"Compare the value of orientation alpha","Compare the value of orientation alpha. (Range: 0 to 360\xB0)":"Compare the value of orientation alpha. (Range: 0 to 360\xB0)","the orientation alpha":"the orientation alpha","Sign of the test":"Sinal do teste","Compare the value of orientation beta":"Compare the value of orientation beta","Compare the value of orientation beta. (Range: -180 to 180\xB0)":"Compare the value of orientation beta. (Range: -180 to 180\xB0)","the orientation beta":"the orientation beta","Compare the value of orientation gamma":"Compare the value of orientation gamma","Compare the value of orientation gamma. (Range: -90 to 90\xB0)":"Compare the value of orientation gamma. (Range: -90 to 90\xB0)","the orientation gamma":"the orientation gamma","Activate orientation sensor":"Activate orientation sensor","Activate the orientation sensor. (remember to turn it off again)":"Activate the orientation sensor. (remember to turn it off again)","Activate the orientation sensor.":"Activate the orientation sensor.","Deactivate orientation sensor":"Deactivate orientation sensor","Deactivate the orientation sensor.":"Deactivate the orientation sensor.","Is Absolute":"Is Absolute","Get if the devices orientation is absolute and not relative":"Get if the devices orientation is absolute and not relative","Alpha value":"Alpha value","Get the devices orientation Alpha (compass)":"Get the devices orientation Alpha (compass)","Beta value":"Beta value","Get the devices orientation Beta":"Get the devices orientation Beta","Gamma value":"Gamma value","Get the devices orientation Gamma value":"Get the devices orientation Gamma value","The condition is true if the device motion sensor is currently active":"The condition is true if the device motion sensor is currently active","Motion sensor is active":"Motion sensor is active","Sensors/Motion":"Sensors/Motion","Compare the value of rotation alpha":"Compare the value of rotation alpha","Compare the value of rotation alpha. (Note: few devices support this sensor)":"Compare the value of rotation alpha. (Note: few devices support this sensor)","the rotation alpha":"the rotation alpha","Value (m/s\xB2)":"Value (m/s\xB2)","Compare the value of rotation beta":"Compare the value of rotation beta","Compare the value of rotation beta. (Note: few devices support this sensor)":"Compare the value of rotation beta. (Note: few devices support this sensor)","the rotation beta":"the rotation beta","Compare the value of rotation gamma":"Compare the value of rotation gamma","Compare the value of rotation gamma. (Note: few devices support this sensor)":"Compare the value of rotation gamma. (Note: few devices support this sensor)","the rotation gamma":"the rotation gamma","Compare the value of acceleration on X-axis":"Compare the value of acceleration on X-axis","Compare the value of acceleration on the X-axis (m/s\xB2).":"Compare the value of acceleration on the X-axis (m/s\xB2).","the acceleration X":"the acceleration X","Compare the value of acceleration on Y-axis":"Compare the value of acceleration on Y-axis","Compare the value of acceleration on the Y-axis (m/s\xB2).":"Compare the value of acceleration on the Y-axis (m/s\xB2).","the acceleration Y":"the acceleration Y","Compare the value of acceleration on Z-axis":"Compare the value of acceleration on Z-axis","Compare the value of acceleration on the Z-axis (m/s\xB2).":"Compare the value of acceleration on the Z-axis (m/s\xB2).","the acceleration Z":"the acceleration Z","Activate motion sensor":"Activate motion sensor","Activate the motion sensor. (remember to turn it off again)":"Activate the motion sensor. (remember to turn it off again)","Activate the motion sensor.":"Activate the motion sensor.","Deactivate motion sensor":"Deactivate motion sensor","Deactivate the motion sensor.":"Deactivate the motion sensor.","Get the devices rotation Alpha":"Get the devices rotation Alpha","Get the devices rotation Beta":"Get the devices rotation Beta","Get the devices rotation Gamma":"Get the devices rotation Gamma","Acceleration X value":"Acceleration X value","Get the devices acceleration on the X-axis (m/s\xB2)":"Get the devices acceleration on the X-axis (m/s\xB2)","Acceleration Y value":"Acceleration Y value","Get the devices acceleration on the Y-axis (m/s\xB2)":"Get the devices acceleration on the Y-axis (m/s\xB2)","Acceleration Z value":"Acceleration Z value","Get the devices acceleration on the Z-axis (m/s\xB2)":"Get the devices acceleration on the Z-axis (m/s\xB2)","Bitmap Text":"Bitmap Text","Displays a text using a \"Bitmap Font\" (an image representing characters). This is more performant than a traditional Text object and it allows for complete control on the characters aesthetic.":"Displays a text using a \"Bitmap Font\" (an image representing characters). This is more performant than a traditional Text object and it allows for complete control on the characters aesthetic.","Opacity (0-255)":"Opacidade (0-255)","Alignment, when multiple lines are displayed":"Alignment, when multiple lines are displayed","Bitmap Font":"Bitmap Font","Bitmap atlas image":"Bitmap atlas image","Text scale":"Text scale","Font tint":"Font tint","Word wrapping":"Word wrapping","Bitmap text":"Bitmap text","the opacity, between 0 (fully transparent) and 255 (opaque)":"the opacity, between 0 (fully transparent) and 255 (opaque)","the font size, defined in the Bitmap Font":"the font size, defined in the Bitmap Font","the scale (1 by default)":"the scale (1 by default)","Font name":"Font name","the font name (defined in the Bitmap font)":"the font name (defined in the Bitmap font)","the font name":"the font name","Set the tint of the Bitmap Text object.":"Set the tint of the Bitmap Text object.","Set tint of _PARAM0_ to _PARAM1_":"Set tint of _PARAM0_ to _PARAM1_","Bitmap files resources":"Bitmap files resources","Change the Bitmap Font and/or the atlas image used by the object.":"Change the Bitmap Font and/or the atlas image used by the object.","Set the bitmap font of _PARAM0_ to _PARAM1_ and the atlas to _PARAM2_":"Set the bitmap font of _PARAM0_ to _PARAM1_ and the atlas to _PARAM2_","Bitmap font resource name":"Bitmap font resource name","Texture atlas resource name":"Texture atlas resource name","the text alignment":"the text alignment","Change the alignment of a Bitmap text object.":"Change the alignment of a Bitmap text object.","Set the alignment of _PARAM0_ to _PARAM1_":"Set the alignment of _PARAM0_ to _PARAM1_","Word wrap":"Word wrap","Check if word wrap is enabled.":"Check if word wrap is enabled.","_PARAM0_ word wrap is enabled":"_PARAM0_ word wrap is enabled","De/activate word wrapping.":"De/activate word wrapping.","Activate word wrap of _PARAM0_: _PARAM1_":"Activate word wrap of _PARAM0_: _PARAM1_","Activate word wrap":"Activate word wrap","the width, in pixels, after which the text is wrapped on next line":"the width, in pixels, after which the text is wrapped on next line","AdMob":"AdMob","Allow to display AdMob banners, interstitials and reward video ads.":"Allow to display AdMob banners, interstitials and reward video ads.","AdMob Android App ID":"AdMob Android App ID","AdMob iOS App ID":"AdMob iOS App ID","Enable test mode":"Enable test mode","Activate or deactivate the test mode (\"development\" mode).\nWhen activated, tests ads will be served instead of real ones.\n\nIt is important to enable test ads during development so that you can click on them without charging advertisers. If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.":"Activate or deactivate the test mode (\"development\" mode).\nWhen activated, tests ads will be served instead of real ones.\n\nIt is important to enable test ads during development so that you can click on them without charging advertisers. If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.","Enable test mode (serving test ads, for development): _PARAM0_":"Enable test mode (serving test ads, for development): _PARAM0_","Enable test mode?":"Enable test mode?","Banner loading":"A carregar banner","Check if a banner is currently loading. It will be shown automatically when loaded.":"Check if a banner is currently loading. It will be shown automatically when loaded.","Banner is loading":"Banner est\xE1 a carregar","Banner showing":"Mostrando Banner","Check if there is a banner being displayed.":"Verificar se h\xE1 um banner sendo exibido.","Banner is showing":"Banner est\xE1 sendo exibido","Banner had an error":"Banner had an error","Check if there was a error while displaying a banner.":"Check if there was a error while displaying a banner.","Banner ad had an error":"Banner ad had an error","Configure the banner":"Configure the banner","Configure a banner, which can then be displayed.\nIf test mode is set, a test banner will be displayed.\n\nOnce a banner is positioned (at the top or bottom of the game), it can't be moved anymore.":"Configure a banner, which can then be displayed.\nIf test mode is set, a test banner will be displayed.\n\nOnce a banner is positioned (at the top or bottom of the game), it can't be moved anymore.","Configure the banner with Android ad unit ID: _PARAM0_, iOS ad unit ID: _PARAM1_, display at top: _PARAM2_":"Configure the banner with Android ad unit ID: _PARAM0_, iOS ad unit ID: _PARAM1_, display at top: _PARAM2_","Android banner ID":"ID do banner Android","iOS banner ID":"ID do banner iOS","Display at top? (bottom otherwise)":"Exibir no topo? (inferior caso contr\xE1rio)","Show banner":"Mostrar banner","Show the banner that was previously set up.":"Show the banner that was previously set up.","Hide banner":"Esconder banner","Hide the banner. You can show it again with the corresponding action.":"Esconder o banner. Vo\xE7\xEA pode mostr\xE1-lo novamente com a a\xE7\xE3o correspondente.","Interstitial loading":"Carregando intersticial","Check if an interstitial is currently loading.":"Verificar se um intersticial est\xE1 atualmente a ser carregado.","Interstitial is loading":"Intersticial est\xE1 a carregar","Interstitial ready":"Intersticial pronto","Check if an interstitial is ready to be displayed.":"Verificar se um intersticial est\xE1 pronto para ser exibido.","Interstitial is ready":"Intersticial est\xE1 pronto","Interstitial showing":"Mostrando Intersticial","Check if there is an interstitial being displayed.":"Verificar se h\xE1 um intersticial sendo exibido.","Interstitial is showing":"A Intersticial est\xE1 a mostrar","Interstitial had an error":"Interstitial had an error","Check if there was a error while loading the interstitial.":"Check if there was a error while loading the interstitial.","Interstitial ad had an error":"Interstitial ad had an error","Load interstitial":"Carregar intersticial","Start loading an interstitial (that can be displayed automatically when the loading is finished).\nIf test mode is set, a test interstitial will be displayed.":"Start loading an interstitial (that can be displayed automatically when the loading is finished).\nIf test mode is set, a test interstitial will be displayed.","Load interstitial with Android ad unit ID: _PARAM0_, iOS ad unit ID: _PARAM1_ (display automatically when loaded: _PARAM2_)":"Load interstitial with Android ad unit ID: _PARAM0_, iOS ad unit ID: _PARAM1_ (display automatically when loaded: _PARAM2_)","Android interstitial ID":"ID intersticial do Android","iOS interstitial ID":"ID intersticial do iOS","Displayed automatically when loading is finished?":"Displayed automatically when loading is finished?","Show interstitial":"Mostrar intersticial","Show the interstitial that was loaded. Will work only when the interstitial is fully loaded.":"Show the interstitial that was loaded. Will work only when the interstitial is fully loaded.","Show the loaded interstitial":"Show the loaded interstitial","Video loading":"Carregamento de v\xEDdeo","Check if a reward video is currently loading.":"Verificar se um v\xEDdeo premiado est\xE1 actualmente a carregar.","Reward video is loading":"O v\xEDdeo premiado est\xE1 a carregar","Video ready":"V\xEDdeo pronto","Check if a reward video is ready to be displayed.":"Verificar se o v\xEDdeo premiado est\xE1 pronto para ser exibido.","Reward video is ready":"V\xEDdeo premiado est\xE1 pronto","Video showing":"Exibi\xE7\xE3o de v\xEDdeo","Check if there is a reward video being displayed.":"Verificar se existe um v\xEDdeo premiado em exibi\xE7\xE3o.","Reward video is showing":"V\xEDdeo premiado est\xE1 sendo exibido","Video had an error":"Video had an error","Check if there was a error while loading the rewarded video.":"Check if there was a error while loading the rewarded video.","Video ad had an error":"Video ad had an error","Video reward received":"Video reward received","Check if the reward of the video was given to the user.\nYou can mark this reward as cleared, so that the condition will be false and you can show later another reward video.":"Check if the reward of the video was given to the user.\nYou can mark this reward as cleared, so that the condition will be false and you can show later another reward video.","User got the reward of the video (and clear this reward: _PARAM0_)":"User got the reward of the video (and clear this reward: _PARAM0_)","Clear the reward (needed to show another video)":"Clear the reward (needed to show another video)","Load video":"Carregar v\xEDdeo","Start loading a reward video (that can be displayed automatically when the loading is finished).\nIf test mode is set, a test video will be displayed.":"Start loading a reward video (that can be displayed automatically when the loading is finished).\nIf test mode is set, a test video will be displayed.","Load reward video with Android ad unit ID: _PARAM0_, iOS ad unit ID: _PARAM1_ (display automatically when loaded: _PARAM2_)":"Load reward video with Android ad unit ID: _PARAM0_, iOS ad unit ID: _PARAM1_ (display automatically when loaded: _PARAM2_)","Android reward video ID":"ID do v\xEDdeo premiado do Android","iOS reward video ID":"ID do v\xEDdeo premiado do iOS","Show video":"Mostrar v\xEDdeo","Show the reward video that was loaded. Will work only when the video is fully loaded.":"Show the reward video that was loaded. Will work only when the video is fully loaded.","Show the loaded reward video":"Show the loaded reward video","Mark the reward of the video as claimed":"Mark the reward of the video as claimed","Mark the video reward as claimed. Useful if you used the condition to check if the reward was given to the user without clearing the reward.":"Mark the video reward as claimed. Useful if you used the condition to check if the reward was given to the user without clearing the reward.","Video opacity (0-255)":"Opacidade do v\xEDdeo (0-255)","Loop the video":"Repetir o v\xEDdeo","Video volume (0-100)":"Volume do v\xEDdeo (0-100)","Video":"V\xEDdeo","Displays a video.":"Exibir um v\xEDdeo.","Play a video":"Reproduzir um v\xEDdeo","Play a video (recommended file format is MPEG4, with H264 video codec and AAC audio codec).":"Reproduzir um v\xEDdeo (o formato de ficheiro recomendado \xE9 MPEG4, com codec de v\xEDdeo H264 e codec de \xE1udio AAC).","Play the video of _PARAM0_":"Reproduzir o v\xEDdeo de _PARAM0_","Video object":"Object de v\xEDdeo","Pause a video":"Pausar um v\xEDdeo","Pause the specified video.":"Pausar o v\xEDdeo especificado.","Pause video _PARAM0_":"Pausar v\xEDdeo _PARAM0_","Loop a video":"Repetir um v\xEDdeo","Loop the specified video.":"Repetir o v\xEDdeo especificado.","Loop video of _PARAM0_: _PARAM1_":"Repetir o v\xEDdeo de _PARAM0_: _PARAM1_","Activate loop":"Ativar repeti\xE7\xE3o","Mute a video":"Silenciar um v\xEDdeo","Mute, or unmute, the specified video.":"Silenciar ou ativar o som do v\xEDdeo especificado.","Mute video of _PARAM0_: _PARAM1_":"Silenciar v\xEDdeo de _PARAM0_: _PARAM1_","Activate mute":"Ativar mudo","Set time":"Definir tempo","Set the time of the video object in seconds":"Definir o tempo do object de v\xEDdeo em segundos","the time":"the time","Set volume":"Definir volume","Set the volume of the video object, between 0 (muted) and 100 (maximum).":"Definir o volume do object de v\xEDdeo entre 0 (mudo) e 100 (m\xE1ximo).","the volume":"the volume","Get the volume":"Obter o volume","Get the volume of a video object, between 0 (muted) and 100 (maximum).":"Obter o volume de um object de v\xEDdeo, entre 0 (silenciado) e 100 (m\xE1ximo).","Is played":"\xC9 reproduzido","Check if a video is played.":"Verificar se um v\xEDdeo \xE9 reproduzido.","_PARAM0_ is played":"_PARAM0_ \xE9 reproduzido","Is paused":"Est\xE1 em pausa","Check if the video is paused.":"Verificar se o v\xEDdeo est\xE1 em pausa.","_PARAM0_ is paused":"_PARAM0_ est\xE1 em pausa","Is looped":"Est\xE1 em repeti\xE7\xE3o","Check if the video is looped.":"Verificar se o v\xEDdeo est\xE1 em repeti\xE7\xE3o.","_PARAM0_ is looped":"_PARAM0_ est\xE1 em repeti\xE7\xE3o","Volume":"Volume","Compare the current volume of a video object.":"Comparar o volume atual de um object de v\xEDdeo.","Is muted":"Est\xE1 sem som","Check if a video is muted.":"Verificar se um v\xEDdeo est\xE1 sem som.","_PARAM0_ is muted":"_PARAM0_ est\xE1 sem som","Get current time":"Obter o tempo atual","Return the current time of a video object (in seconds).":"Retorna o tempo atual de um object de v\xEDdeo (em segundos).","Get the duration":"Obter a dura\xE7\xE3o","Return the duration of a video object (in seconds).":"Retorna a dura\xE7\xE3o de um object de v\xEDdeo (em segundos).","Compare the duration of a video object":"Comparar a dura\xE7\xE3o de um object de v\xEDdeo","the duration (in seconds)":"the duration (in seconds)","Current time":"Hora actual","Compare the current time of a video object":"Comparar o tempo atual de um object de v\xEDdeo","the current time (in seconds)":"the current time (in seconds)","Is ended":"Terminou","Check if a video is ended":"Verificar se um v\xEDdeo terminou","_PARAM0_ is ended":"_PARAM0_ terminou","Set opacity":"Definir opacidade","Set opacity of the specified video object, between 0 (fully transparent) and 255 (opaque).":"Definir a opacidade do object de v\xEDdeo especificado, entre 0 (totalmente transparente) e 255 (opaco).","Compare the opacity of a video object":"Comparar a opacidade de um object de v\xEDdeo","Get current opacity":"Obter opacidade atual","Return the opacity of a video object":"Retornar a opacidade de um object de v\xEDdeo","Set playback speed":"Definir velocidade de reprodu\xE7\xE3o","Set playback speed of the specified video object, (1 = the default speed, >1 = faster and <1 = slower).":"Defina a velocidade de reprodu\xE7\xE3o do object de v\xEDdeo especificado, (1 = a velocidade padr\xE3o, >1 = mais r\xE1pida e <1 = mais lenta).","the playback speed":"the playback speed","Playback speed ":"Velocidade de reprodu\xE7\xE3o ","Compare the playback speed of a video object":"Comparar a velocidade de reprodu\xE7\xE3o de um object de v\xEDdeo","Get current playback speed":"Obter a velocidade de reprodu\xE7\xE3o atual","Return the playback speed of a video object":"Retorna a velocidade de reprodu\xE7\xE3o de um object de v\xEDdeo","Advanced window management":"Advanced window management","Provides advanced features related to the game window positioning and interaction with the operating system.":"Provides advanced features related to the game window positioning and interaction with the operating system.","Change focus of the window":"Change focus of the window","Make the window gain or lose focus.":"Make the window gain or lose focus.","Focus the window: _PARAM0_":"Focus the window: _PARAM0_","Advanced window management/Windows, Linux, macOS":"Advanced window management/Windows, Linux, macOS","Focus the window?":"Focus the window?","Window focused":"Window focused","Checks if the window is focused.":"Checks if the window is focused.","The window is focused":"The window is focused","Change visibility of the window":"Change visibility of the window","Make the window visible or invisible.":"Make the window visible or invisible.","Window visible: _PARAM0_":"Window visible: _PARAM0_","Show window?":"Show window?","Window visible":"Window visible","Checks if the window is visible.":"Checks if the window is visible.","The window is visible":"The window is visible","Maximize the window":"Maximize the window","Maximize or unmaximize the window.":"Maximize or unmaximize the window.","Maximize window: _PARAM0_":"Maximize window: _PARAM0_","Maximize window?":"Maximize window?","Window maximized":"Window maximized","Checks if the window is maximized.":"Checks if the window is maximized.","The window is maximized":"The window is maximized","Minimize the window":"Minimize the window","Minimize or unminimize the window.":"Minimize or unminimize the window.","Minimize window: _PARAM0_":"Minimize window: _PARAM0_","Minimize window?":"Minimize window?","Window minimized":"Window minimized","Checks if the window is minimized.":"Checks if the window is minimized.","The window is minimized":"The window is minimized","Enable the window":"Enable the window","Enables or disables the window.":"Enables or disables the window.","Enable window: _PARAM0_":"Enable window: _PARAM0_","Enable window?":"Enable window?","Window enabled":"Window enabled","Checks if the window is enabled.":"Checks if the window is enabled.","The window is enabled":"The window is enabled","Allow resizing":"Allow resizing","Enables or disables resizing of the window by the user.":"Enables or disables resizing of the window by the user.","Enable window resizing: _PARAM0_":"Enable window resizing: _PARAM0_","Allow resizing?":"Allow resizing?","Window resizable":"Window resizable","Checks if the window can be resized.":"Checks if the window can be resized.","The window can be resized":"The window can be resized","Allow moving":"Allow moving","Enables or disables moving of the window by the user.":"Enables or disables moving of the window by the user.","Enable window moving: _PARAM0_":"Enable window moving: _PARAM0_","Allow moving?":"Allow moving?","Window movable":"Window movable","Checks if the window can be moved.":"Checks if the window can be moved.","The window can be moved":"The window can be moved","Allow maximizing":"Allow maximizing","Enables or disables maximizing of the window by the user.":"Enables or disables maximizing of the window by the user.","Enable window maximizing: _PARAM0_":"Enable window maximizing: _PARAM0_","Allow maximizing?":"Allow maximizing?","Window maximizable":"Window maximizable","Checks if the window can be maximized.":"Checks if the window can be maximized.","The window can be maximized":"The window can be maximized","Allow mimizing":"Allow mimizing","Enables or disables minimizing of the window by the user.":"Enables or disables minimizing of the window by the user.","Enable window minimizing: _PARAM0_":"Enable window minimizing: _PARAM0_","Allow minimizing?":"Allow minimizing?","Window minimizable":"Window minimizable","Checks if the window can be minimized.":"Checks if the window can be minimized.","The window can be minimized":"The window can be minimized","Allow full-screening":"Allow full-screening","Enables or disables full-screening of the window by the user.":"Enables or disables full-screening of the window by the user.","Enable window full-screening: _PARAM0_":"Enable window full-screening: _PARAM0_","Allow full-screening?":"Allow full-screening?","Window full-screenable":"Window full-screenable","Checks if the window can be full-screened.":"Checks if the window can be full-screened.","The window can be set in fullscreen":"The window can be set in fullscreen","Allow closing":"Allow closing","Enables or disables closing of the window by the user.":"Enables or disables closing of the window by the user.","Enable window closing: _PARAM0_":"Enable window closing: _PARAM0_","Allow closing?":"Allow closing?","Window closable":"Window closable","Checks if the window can be closed.":"Checks if the window can be closed.","The window can be closed":"The window can be closed","Make the windows always on top":"Make the windows always on top","Puts the window constantly above all other windows.":"Puts the window constantly above all other windows.","Make window always on top: _PARAM0_, level: _PARAM1_":"Make window always on top: _PARAM0_, level: _PARAM1_","Enable always on top?":"Enable always on top?","Level":"Level","Window always on top":"Window always on top","Checks if the window is always on top.":"Checks if the window is always on top.","The window is always on top":"The window is always on top","Enable kiosk mode":"Enable kiosk mode","Puts the window in kiosk mode. This prevents the user from exiting fullscreen.":"Puts the window in kiosk mode. This prevents the user from exiting fullscreen.","Enable kiosk mode: _PARAM0_":"Enable kiosk mode: _PARAM0_","Enable kiosk mode?":"Enable kiosk mode?","Kiosk mode":"Kiosk mode","Checks if the window is currently in kiosk mode.":"Checks if the window is currently in kiosk mode.","The window is in kiosk mode":"The window is in kiosk mode","Enable window shadow":"Enable window shadow","Enables or disables the window shadow.":"Enables or disables the window shadow.","Enable window shadow: _PARAM0_":"Enable window shadow: _PARAM0_","Enable shadow?":"Enable shadow?","Shadow enabled":"Shadow enabled","Checks if the window currently has it's shadow enabled.":"Checks if the window currently has it's shadow enabled.","The window has a shadow":"The window has a shadow","Enable content protection":"Enable content protection","Enables or disables the content protection mode. This should prevent screenshots of the game from being taken.":"Enables or disables the content protection mode. This should prevent screenshots of the game from being taken.","Enable content protection: _PARAM0_":"Enable content protection: _PARAM0_","Enable content protection?":"Enable content protection?","Allow focusing":"Allow focusing","Allow or disallow the user to focus the window.":"Allow or disallow the user to focus the window.","Allow to focus the window: _PARAM0_":"Allow to focus the window: _PARAM0_","Allow focus?":"Allow focus?","Flash the window":"Flash the window","Make the window flash or end flashing.":"Make the window flash or end flashing.","Make the window flash: _PARAM0_":"Make the window flash: _PARAM0_","Flash the window?":"Flash the window?","Set window opacity":"Set window opacity","Changes the window opacity.":"Changes the window opacity.","Set the window opacity to _PARAM0_":"Set the window opacity to _PARAM0_","New opacity":"New opacity","Set window position":"Set window position","Changes the window position.":"Changes the window position.","Set the window position to _PARAM0_;_PARAM1_":"Set the window position to _PARAM0_;_PARAM1_","Window X position":"Window X position","Returns the current window X position.":"Returns the current window X position.","Window Y position":"Window Y position","Returns the current window Y position.":"Returns the current window Y position.","Window opacity":"Window opacity","Returns the current window opacity (a number from 0 to 1, 1 being fully opaque).":"Returns the current window opacity (a number from 0 to 1, 1 being fully opaque).","BBCode Text Object":"BBCode Text Object","BBCode text":"BBCode text","Base color":"Base color","Base size":"Base size","Base alignment":"Base alignment","Base font family":"Base font family","Visible on start":"Visible on start","BBText":"BBText","Displays a rich text label using BBCode markup (allowing to set parts of the text as bold, italic, use different colors and shadows).":"Displays a rich text label using BBCode markup (allowing to set parts of the text as bold, italic, use different colors and shadows).","Compare the value of the BBCode text.":"Compare the value of the BBCode text.","the BBCode text":"the BBCode text","Set BBCode text":"Set BBCode text","Get BBCode text":"Get BBCode text","Set base color":"Set base color","Set base color of _PARAM0_ to _PARAM1_":"Set base color of _PARAM0_ to _PARAM1_","Compare the value of the base opacity of the text.":"Compare the value of the base opacity of the text.","the base opacity":"the base opacity","Set base opacity":"Set base opacity","Get the base opacity":"Get the base opacity","Compare the base font size of the text.":"Compare the base font size of the text.","the base font size":"the base font size","Set base font size":"Set base font size","Get the base font size":"Get the base font size","Font family":"Font family","Compare the value of font family":"Compare the value of font family","the base font family":"the base font family","Set font family":"Set font family","Get the base font family":"Get the base font family","Check the current text alignment.":"Check the current text alignment.","The text alignment of _PARAM0_ is _PARAM1_":"The text alignment of _PARAM0_ is _PARAM1_","Change the alignment of the text.":"Change the alignment of the text.","Set text alignment of _PARAM0_ to _PARAM1_":"Set text alignment of _PARAM0_ to _PARAM1_","Get the text alignment":"Get the text alignment","Word wrap is enabled":"Word wrap is enabled","Set word wrap":"Set word wrap","Activate word wrap for _PARAM0_: _PARAM1_":"Activate word wrap for _PARAM0_: _PARAM1_","Compare the width, in pixels, after which the text is wrapped on next line.":"Compare the width, in pixels, after which the text is wrapped on next line.","Change the width, in pixels, after which the text is wrapped on next line.":"Change the width, in pixels, after which the text is wrapped on next line.","Get the wrapping width":"Get the wrapping width","Dialogue Tree (Experimental)":"Dialogue Tree (Experimental)","Load dialogue Tree from a scene variable":"Load dialogue Tree from a scene variable","Load a dialogue data object - Yarn json format, stored in a scene variable. Use this command to load all the Dialogue data at the beginning of the game.":"Load a dialogue data object - Yarn json format, stored in a scene variable. Use this command to load all the Dialogue data at the beginning of the game.","Load dialogue data from Scene variable _PARAM1_":"Load dialogue data from Scene variable _PARAM1_","Dialogue Tree (experimental)":"Dialogue Tree (experimental)","Scene variable that holds the Yarn Json data":"Scene variable that holds the Yarn Json data","Load dialogue Tree from a Json File":"Load dialogue Tree from a Json File","Load a dialogue data object - Yarn json format, stored in a Json file. Use this command to load all the Dialogue data at the beginning of the game.":"Load a dialogue data object - Yarn json format, stored in a Json file. Use this command to load all the Dialogue data at the beginning of the game.","Load dialogue data from json file _PARAM1_":"Load dialogue data from json file _PARAM1_","Json file that holds the Yarn Json data":"Json file that holds the Yarn Json data","Start dialogue from branch":"Start dialogue from branch","Start dialogue from branch. Use this to initiate the dialogue from a specified branch.":"Start dialogue from branch. Use this to initiate the dialogue from a specified branch.","Start dialogue from branch _PARAM0_":"Start dialogue from branch _PARAM0_","Dialogue branch":"Dialogue branch","Stop running dialogue":"Stop running dialogue","Stop the running dialogue. Use this to interrupt dialogue parsing.":"Stop the running dialogue. Use this to interrupt dialogue parsing.","Go to the next dialogue line":"Go to the next dialogue line","Go to the next dialogue line. Use this to advance to the next dialogue line when the player presses a button.":"Go to the next dialogue line. Use this to advance to the next dialogue line when the player presses a button.","Confirm selected Option":"Confirm selected Option","Set the selected option as confirmed, which will validate it and go forward to the next node. Use other actions to select options (see \"select next option\" and \"Select previous option\").":"Set the selected option as confirmed, which will validate it and go forward to the next node. Use other actions to select options (see \"select next option\" and \"Select previous option\").","Select next Option":"Select next Option","Select next Option (add 1 to selected option number). Use this when the dialogue line is of type \"options\" and the player has pressed a button to change selected option.":"Select next Option (add 1 to selected option number). Use this when the dialogue line is of type \"options\" and the player has pressed a button to change selected option.","Select previous Option":"Select previous Option","Select previous Option (subtract 1 from selected option number). Use this when the dialogue line is of type \"options\" and the player has pressed a button to change selected option.":"Select previous Option (subtract 1 from selected option number). Use this when the dialogue line is of type \"options\" and the player has pressed a button to change selected option.","Select option by number":"Select option by number","Select option by number. Use this when the dialogue line is of type \"options\" and the player has pressed a button to change selected option.":"Select option by number. Use this when the dialogue line is of type \"options\" and the player has pressed a button to change selected option.","Select option at index _PARAM0_":"Selecione a op\xE7\xE3o no \xEDndice _PARAM0_","Option index number":"Option index number","Scroll clipped text":"Scroll clipped text","Scroll clipped text. Use this with a timer and \"get clipped text\" when you want to create a typewriter effect. Every time the action runs, a new character appears from the text.":"Scroll clipped text. Use this with a timer and \"get clipped text\" when you want to create a typewriter effect. Every time the action runs, a new character appears from the text.","Complete clipped text scrolling":"Complete clipped text scrolling","Complete the clipped text scrolling. Use this action whenever you want to skip scrolling.":"Complete the clipped text scrolling. Use this action whenever you want to skip scrolling.","Set dialogue state string variable":"Definir o estado do di\xE1logo da vari\xE1vel de string","Set dialogue state string variable. Use this to set a variable that the dialogue data is using.":"Definir o estado da vari\xE1vel de string. Use isto para definir uma vari\xE1vel que o di\xE1logo de dados est\xE1 a usar.","Set dialogue state string variable _PARAM0_ to _PARAM1_":"Definir o estado do di\xE1logo da vari\xE1vel de string _PARAM0_ to _PARAM1_","State Variable Name":"State Variable Name","Variable string value":"Valor da vari\xE1vel de string","Set dialogue state number variable":"Definir o estado do di\xE1logo da vari\xE1vel de n\xFAmero","Set dialogue state number variable. Use this to set a variable that the dialogue data is using.":"Set dialogue state number variable. Use this to set a variable that the dialogue data is using.","Set dialogue state number variable _PARAM0_ to _PARAM1_":"Set dialogue state number variable _PARAM0_ to _PARAM1_","Variable number value":"Variable number value","Set dialogue state boolean variable":"Set dialogue state boolean variable","Set dialogue state boolean variable. Use this to set a variable that the dialogue data is using.":"Set dialogue state boolean variable. Use this to set a variable that the dialogue data is using.","Set dialogue state boolean variable _PARAM0_ to _PARAM1_":"Set dialogue state boolean variable _PARAM0_ to _PARAM1_","Variable boolean value":"Variable boolean value","Save dialogue state":"Save dialogue state","Save dialogue state. Use this to store the dialogue state into a variable, which can later be used for saving the game. That way player choices can become part of the game save.":"Save dialogue state. Use this to store the dialogue state into a variable, which can later be used for saving the game. That way player choices can become part of the game save.","Save dialogue state to _PARAM0_":"Save dialogue state to _PARAM0_","Global Variable":"Global Variable","Load dialogue state":"Load dialogue state","Load dialogue state. Use this to restore dialogue state, if you have stored in a variable before with the \"Save state\" action.":"Load dialogue state. Use this to restore dialogue state, if you have stored in a variable before with the \"Save state\" action.","Load dialogue state from _PARAM0_":"Load dialogue state from _PARAM0_","Clear dialogue state":"Clear dialogue state","Clear dialogue state. This resets all dialogue state accumulated by the player choices. Useful when the player is starting a new game.":"Clear dialogue state. This resets all dialogue state accumulated by the player choices. Useful when the player is starting a new game.","Get the current dialogue line text":"Get the current dialogue line text","Returns the current dialogue line text":"Returns the current dialogue line text","Get the number of options in an options line type":"Get the number of options in an options line type","Get the text of an option from an Options line type":"Get the text of an option from an Options line type","Get the text of an option from an Options line type, using the option's Number. The numbers start from 0.":"Get the text of an option from an Options line type, using the option's Number. The numbers start from 0.","Option Index Number":"Option Index Number","Get a Horizontal list of options from the Options line type":"Get a Horizontal list of options from the Options line type","Get the text of all available options from an Options line type as a horizontal list. You can also pass the selected option's cursor string, which by default is ->":"Get the text of all available options from an Options line type as a horizontal list. You can also pass the selected option's cursor string, which by default is ->","Options Selection Cursor":"Options Selection Cursor","Get a Vertical list of options from the Options line type":"Get a Vertical list of options from the Options line type","Get the text of all available options from an Options line type as a vertical list. You can also pass the selected option's cursor string, which by default is ->":"Get the text of all available options from an Options line type as a vertical list. You can also pass the selected option's cursor string, which by default is ->","Get the number of the currently selected option":"Get the number of the currently selected option","Get the number of the currently selected option. Use this to help you render the option selection marker at the right place.":"Get the number of the currently selected option. Use this to help you render the option selection marker at the right place.","Get dialogue line text clipped":"Get dialogue line text clipped","Get dialogue line text clipped by the typewriter effect. Use the \"Scroll clipped text\" action to control the typewriter effect.":"Get dialogue line text clipped by the typewriter effect. Use the \"Scroll clipped text\" action to control the typewriter effect.","Get the title of the current branch of the running dialogue":"Get the title of the current branch of the running dialogue","Get the tags of the current branch of the running dialogue":"Get the tags of the current branch of the running dialogue","Get a tag of the current branch of the running dialogue via its index":"Get a tag of the current branch of the running dialogue via its index","Tag Index Number":"Tag Index Number","Get the parameters of a command call":"Get the parameters of a command call","Get the parameters of a command call - <<command withParameter anotherParameter>>":"Get the parameters of a command call - <<command withParameter anotherParameter>>","parameter Index Number":"parameter Index Number","Get the number of parameters in the currently passed command":"Get the number of parameters in the currently passed command","Get parameter from a Tag found by the branch contains tag condition":"Get parameter from a Tag found by the branch contains tag condition","Get a list of all visited branches":"Get a list of all visited branches","Get the full raw text of the current branch":"Get the full raw text of the current branch","Get dialogue state value":"Get dialogue state value","Variable Name":"Variable Name","Command is called":"Command is called","Check if a specific Command is called. If it is a <<command withParameter>>, you can even get the parameter with the CommandParameter expression.":"Check if a specific Command is called. If it is a <<command withParameter>>, you can even get the parameter with the CommandParameter expression.","Command <<_PARAM0_>> is called":"Command <<_PARAM0_>> is called","Command String":"Command String","Dialogue line type":"Dialogue line type","Check if the the current dialogue line line is one of the three existing types. Use this to set what logic is executed for each type.\nThe three types are as follows:\n- text: when displaying dialogue text.\n- options: when displaying [[branching/options]] for dialogue choices.\n-command: when <<commands>> are triggered by the dialogue data.":"Check if the the current dialogue line line is one of the three existing types. Use this to set what logic is executed for each type.\nThe three types are as follows:\n- text: when displaying dialogue text.\n- options: when displaying [[branching/options]] for dialogue choices.\n-command: when <<commands>> are triggered by the dialogue data.","The dialogue line is _PARAM0_":"The dialogue line is _PARAM0_","type":"type","Dialogue is running":"Dialogue is running","Check if the dialogue is running. Use this to for things like locking the player movement while speaking with a non player character.":"Check if the dialogue is running. Use this to for things like locking the player movement while speaking with a non player character.","Dialogue has branch":"Dialogue has branch","Check if the dialogue has a branch with specified name. Use this to check if a dialogue branch exists in the loaded dialogue data.":"Check if the dialogue has a branch with specified name. Use this to check if a dialogue branch exists in the loaded dialogue data.","Dialogue has a branch named _PARAM0_":"Dialogue has a branch named _PARAM0_","Branch name":"Branch name","Has selected option changed":"Has selected option changed","Check if a selected option has changed when the current dialogue line type is options. Use this to detect when the player has selected another option, so you can re-draw where the selection arrow is.":"Check if a selected option has changed when the current dialogue line type is options. Use this to detect when the player has selected another option, so you can re-draw where the selection arrow is.","Selected option has changed":"Selected option has changed","Current dialogue branch title":"Current dialogue branch title","Check if the current dialogue branch title is equal to a string. Use this to trigger game events when the player has visited a specific dialogue branch.":"Check if the current dialogue branch title is equal to a string. Use this to trigger game events when the player has visited a specific dialogue branch.","The current dialogue branch title is _PARAM0_":"The current dialogue branch title is _PARAM0_","title name":"title name","Current dialogue branch contains a tag":"Current dialogue branch contains a tag","Check if the current dialogue branch contains a specific tag. Tags are an alternative useful way to <<commands>> to drive game logic with the dialogue data.":"Check if the current dialogue branch contains a specific tag. Tags are an alternative useful way to <<commands>> to drive game logic with the dialogue data.","The current dialogue branch contains a _PARAM0_ tag":"The current dialogue branch contains a _PARAM0_ tag","tag name":"tag name","Branch title has been visited":"Branch title has been visited","Check if a branch has been visited":"Check if a branch has been visited","Branch title _PARAM0_ has been visited":"Branch title _PARAM0_ has been visited","branch title":"branch title","Compare dialogue state string variable":"Compare dialogue state string variable","Compare dialogue state string variable. Use this to trigger game events via dialogue variables.":"Compare dialogue state string variable. Use this to trigger game events via dialogue variables.","Dialogue state string variable _PARAM0_ is equal to _PARAM1_":"Dialogue state string variable _PARAM0_ is equal to _PARAM1_","State variable":"State variable","Equal to":"Equal to","Compare dialogue state number variable":"Compare dialogue state number variable","Compare dialogue state number variable. Use this to trigger game events via dialogue variables.":"Compare dialogue state number variable. Use this to trigger game events via dialogue variables.","Dialogue state number variable _PARAM0_ is equal to _PARAM1_":"Dialogue state number variable _PARAM0_ is equal to _PARAM1_","Compare dialogue state boolean variable":"Compare dialogue state boolean variable","Compare dialogue state variable. Use this to trigger game events via dialogue variables.":"Compare dialogue state variable. Use this to trigger game events via dialogue variables.","Dialogue state boolean variable _PARAM0_ is equal to _PARAM1_":"Dialogue state boolean variable _PARAM0_ is equal to _PARAM1_","Clipped text has completed scrolling":"Clipped text has completed scrolling","Check if the clipped text scrolling has completed. Use this to prevent the player from going to the next dialogue line before the typing effect has revealed the entire text.":"Check if the clipped text scrolling has completed. Use this to prevent the player from going to the next dialogue line before the typing effect has revealed the entire text.","Firebase":"Firebase","Use Google Firebase services (database, functions, storage...) in your game.":"Use Google Firebase services (database, functions, storage...) in your game.","Firebase configuration string":"Firebase configuration string","Enable analytics":"Enable analytics","Enables Analytics for that project.":"Enables Analytics for that project.","Firebase/Analytics":"Firebase/Analytics","Log an Event":"Log an Event","Triggers an Event/Conversion for the current user on the Analytics.Can also pass additional data to the Analytics":"Triggers an Event/Conversion for the current user on the Analytics.Can also pass additional data to the Analytics","Trigger Event _PARAM0_ with argument _PARAM1_":"Trigger Event _PARAM0_ with argument _PARAM1_","Event Name":"Event Name","Additional Data":"Additional Data","Change user UID":"Change user UID","Changes the current user's analytics identifier. This is what let Analytics differienciate user, so it should always be unique for each user. For advanced usage only.":"Changes the current user's analytics identifier. This is what let Analytics differienciate user, so it should always be unique for each user. For advanced usage only.","Set current user's ID to _PARAM0_":"Set current user's ID to _PARAM0_","New Unique ID":"New Unique ID","Set a user's property":"Set a user's property","Sets an user's properties.Can be used to classify user in Analytics.":"Sets an user's properties.Can be used to classify user in Analytics.","Set property _PARAM0_ of the current user to _PARAM1_":"Set property _PARAM0_ of the current user to _PARAM1_","Property Name":"Property Name","Property Data":"Property Data","Get Remote setting as String":"Get Remote setting as String","Get a setting from Firebase Remote Config as a string.":"Get a setting from Firebase Remote Config as a string.","Firebase/Remote Config":"Firebase/Remote Config","Setting Name":"Setting Name","Get Remote setting as Number":"Get Remote setting as Number","Get a setting from Firebase Remote Config as Number.":"Get a setting from Firebase Remote Config as Number.","Set Remote Config Auto Update Inteval":"Set Remote Config Auto Update Inteval","Sets Remote Config Auto Update Inteval.":"Sets Remote Config Auto Update Inteval.","Set Remote Config Auto Update Inteval to _PARAM0_":"Set Remote Config Auto Update Inteval to _PARAM0_","Update Interval in ms":"Update Interval in ms","Set the default configuration":"Set the default configuration","As the Remote Config is stored online, you need to set default values or the Remote Config expressions to return while there is no internet or the config is still loading.":"As the Remote Config is stored online, you need to set default values or the Remote Config expressions to return while there is no internet or the config is still loading.","Set default config to _PARAM0_":"Set default config to _PARAM0_","Structure with defaults":"Structure with defaults","Force sync the configuration":"Force sync the configuration","Use this to sync the Remote Config with the client at any time.":"Use this to sync the Remote Config with the client at any time.","Synchronize Remote Config":"Synchronize Remote Config","Create account with with email":"Create account with with email","Create an account with email and password as credentials.":"Create an account with email and password as credentials.","Create account with email _PARAM0_ and password _PARAM1_":"Create account with email _PARAM0_ and password _PARAM1_","Firebase/Authentication":"Firebase/Authentication","Callback variable with state (ok or error)":"Callback variable with state (ok or error)","Sign into an account with email":"Sign into an account with email","Sign into an account with email and password as credentials. ":"Sign into an account with email and password as credentials. ","Connect to account with email _PARAM0_ and password _PARAM1_":"Connect to account with email _PARAM0_ and password _PARAM1_","Log out of the account":"Log out of the account","Logs out of the current account. ":"Logs out of the current account. ","Log out from the account":"Log out from the account","Sign into an account with auth from provider":"Sign into an account with auth from provider","Sign into an account via an external provider. The available providers are: \"google\", \"facebook\", \"github\" and \"twitter\".\nProvider authentication only works in the browser! Not on previews or pc/mobile exports.":"Sign into an account via an external provider. The available providers are: \"google\", \"facebook\", \"github\" and \"twitter\".\nProvider authentication only works in the browser! Not on previews or pc/mobile exports.","Connect to account with Provider _PARAM0_":"Connect to account with Provider _PARAM0_","Provider":"Provider","Sign In as an anonymous guest":"Sign In as an anonymous guest","Sign into a temporary anonymous account.":"Sign into a temporary anonymous account.","Authenticate anonymously":"Authenticate anonymously","Is the user signed in?":"Is the user signed in?","Checks if the user is signed in. \nYou should always use this before actions requiring authentications.":"Checks if the user is signed in. \nYou should always use this before actions requiring authentications.","Check for authentication":"Check for authentication","Get the user authentififcation token":"Get the user authentififcation token","Get the user authentififcation token. The token is the proof of authentication.":"Get the user authentififcation token. The token is the proof of authentication.","Is the user email address verified":"Is the user email address verified","Checks if the email address of the user got verified.":"Checks if the email address of the user got verified.","The email of the user is verified":"The email of the user is verified","Firebase/Authentication/User Management":"Firebase/Authentication/User Management","Get the user email address":"Get the user email address","Gets the user email address.":"Gets the user email address.","Get the accounts creation time":"Get the accounts creation time","Gets the accounts creation time.":"Gets the accounts creation time.","Get the user last login time":"Get the user last login time","Gets the user last login time.":"Gets the user last login time.","Get the user display name":"Get the user display name","Gets the user display name.":"Gets the user display name.","Get the user phone number":"Get the user phone number","Gets the user phone number.":"Gets the user phone number.","Get the user UID":"Get the user UID","Gets the user Unique IDentifier. Use that to link data to an user instead of the name or email.":"Gets the user Unique IDentifier. Use that to link data to an user instead of the name or email.","Get the user tenant ID":"Get the user tenant ID","Gets the user tenant ID. For advanced usage only.":"Gets the user tenant ID. For advanced usage only.","Get the user refresh token":"Get the user refresh token","Gets the user refresh token. For advanced usage only.":"Gets the user refresh token. For advanced usage only.","Get the user profile picture URL":"Get the user profile picture URL","Gets an URL to the user profile picture.":"Gets an URL to the user profile picture.","Send a verification email":"Send a verification email","Send a link per email to verify the user email.":"Send a link per email to verify the user email.","Send verification email":"Send verification email","Set display name":"Set display name","Sets the user display name.":"Sets the user display name.","Set the user's display name to _PARAM0_":"Set the user's display name to _PARAM0_","New display name":"New display name","Set the user profile picture":"Set the user profile picture","Sets the user profile picture URL to a new one.":"Sets the user profile picture URL to a new one.","Set the user's profile picture URL to _PARAM0_":"Set the user's profile picture URL to _PARAM0_","New profile picture URL":"New profile picture URL","Change the user email":"Change the user email","This action is dangerous so it requires reauthentication.\nChanges the user's email address.":"This action is dangerous so it requires reauthentication.\nChanges the user's email address.","Change the user's email to _PARAM0_ and store result in _PARAM4_ (send verification email: _PARAM3_)":"Change the user's email to _PARAM0_ and store result in _PARAM4_ (send verification email: _PARAM3_)","Firebase/Authentication/User Management/Advanced":"Firebase/Authentication/User Management/Advanced","Old email":"Old email","New email":"New email","Send a verification email before doing the change?":"Send a verification email before doing the change?","Change the user email (Provider)":"Change the user email (Provider)","This action is dangerous so it requires reauthentication.\nChanges the user's email address.\nThis is the same as Change the user email but reauthenticates via an external provider.":"This action is dangerous so it requires reauthentication.\nChanges the user's email address.\nThis is the same as Change the user email but reauthenticates via an external provider.","Change the user's email to _PARAM0_ and store result in _PARAM2_ (send verification email: _PARAM1_)":"Change the user's email to _PARAM0_ and store result in _PARAM2_ (send verification email: _PARAM1_)","Change the user password":"Change the user password","This action is dangerous so it requires reauthentication.\nChanges the user password.":"This action is dangerous so it requires reauthentication.\nChanges the user password.","Change the user password to _PARAM2_ and store result in _PARAM4_ (send verification email: _PARAM3_)":"Change the user password to _PARAM2_ and store result in _PARAM4_ (send verification email: _PARAM3_)","Old password":"Old password","New password":"New password","Change the user password (Provider)":"Change the user password (Provider)","This action is dangerous so it requires reauthentication.\nChanges the user password.\nThis is the same as \"Change the user password\" but reauthenticates via an external provider.":"This action is dangerous so it requires reauthentication.\nChanges the user password.\nThis is the same as \"Change the user password\" but reauthenticates via an external provider.","Change the user password to _PARAM0_ and store result in _PARAM2_ (send verification email: _PARAM1_)":"Change the user password to _PARAM0_ and store result in _PARAM2_ (send verification email: _PARAM1_)","New Password":"New Password","Delete the user account":"Delete the user account","This action is dangerous so it requires reauthentication.\nDeletes the user account.":"This action is dangerous so it requires reauthentication.\nDeletes the user account.","Delete the user account and store result in _PARAM2_":"Delete the user account and store result in _PARAM2_","Delete the user account (Provider)":"Delete the user account (Provider)","This action is dangerous so it requires reauthentication.\nDeletes the user account.\nThis is the same as \"Delete the user account\" but reauthenticates via an external provider.":"This action is dangerous so it requires reauthentication.\nDeletes the user account.\nThis is the same as \"Delete the user account\" but reauthenticates via an external provider.","Delete the user account and store result in _PARAM0_":"Delete the user account and store result in _PARAM0_","Enable performance measuring":"Enable performance measuring","Enables performance measuring.":"Enables performance measuring.","Firebase/Performance Measuring":"Firebase/Performance Measuring","Create a custom performance tracker":"Create a custom performance tracker","Creates a new custom performance tracker (If it doesn't already exists). They are used to measure performance of custom events.":"Creates a new custom performance tracker (If it doesn't already exists). They are used to measure performance of custom events.","Create performance tracker: _PARAM0_":"Create performance tracker: _PARAM0_","Tracker Name":"Tracker Name","Start a tracer":"Start a tracer","Start measuring performance for that tracer":"Start measuring performance for that tracer","Start performance measuring on tracer _PARAM0_":"Start performance measuring on tracer _PARAM0_","Stop a tracer":"Stop a tracer","Stop measuring performance for that tracer":"Stop measuring performance for that tracer","Stop performance measuring on tracer _PARAM0_":"Stop performance measuring on tracer _PARAM0_","Record performance":"Record performance","Record performance for a delimited period of time. Use this if you want to measure the performance for a specified duration.":"Record performance for a delimited period of time. Use this if you want to measure the performance for a specified duration.","Record performance for _PARAM1_ms with a delay of _PARAM2_ms (store in tracker _PARAM0_)":"Record performance for _PARAM1_ms with a delay of _PARAM2_ms (store in tracker _PARAM0_)","Delay before measuring start (in ms)":"Delay before measuring start (in ms)","Measuring duration (in ms)":"Measuring duration (in ms)","Call a HTTP function":"Call a HTTP function","Calls a HTTP function by name, and store the result in a variable.":"Calls a HTTP function by name, and store the result in a variable.","Call HTTP Function _PARAM0_ with parameter(s) _PARAM1_ (Callback variables: Value: _PARAM2_ State: _PARAM3_)":"Call HTTP Function _PARAM0_ with parameter(s) _PARAM1_ (Callback variables: Value: _PARAM2_ State: _PARAM3_)","Firebase/Functions":"Firebase/Functions","HTTP Function Name":"HTTP Function Name","Parameter(s) as JSON or string.":"Parameter(s) as JSON or string.","Callback variable with returned value":"Callback variable with returned value","Get server timestamp":"Get server timestamp","Set a field to the timstamp on the server when the request arrives there":"Set a field to the timstamp on the server when the request arrives there","Firebase/Cloud Firestore":"Firebase/Cloud Firestore","Start a query":"Start a query","Start a query on a collection. A query allows to get a filtered and ordered list of documents in a collection.":"Start a query on a collection. A query allows to get a filtered and ordered list of documents in a collection.","Create a query named _PARAM0_ for collection _PARAM1_":"Create a query named _PARAM0_ for collection _PARAM1_","Firebase/Cloud Firestore/Queries/Initialize":"Firebase/Cloud Firestore/Queries/Initialize","Query name":"Query name","Collection":"Collection","Start a query from another query":"Start a query from another query","Start a query with the same collection and filters as another one.":"Start a query with the same collection and filters as another one.","Create a query named _PARAM0_ from query _PARAM1_":"Create a query named _PARAM0_ from query _PARAM1_","Source query name":"Source query name","Filter by field value":"Filter by field value","Only match the documents that have a field passing a check.":"Only match the documents that have a field passing a check.","Filter query _PARAM0_ to remove documents whose field _PARAM1_ is not _PARAM2__PARAM3_":"Filter query _PARAM0_ to remove documents whose field _PARAM1_ is not _PARAM2__PARAM3_","Firebase/Cloud Firestore/Queries/Filters":"Firebase/Cloud Firestore/Queries/Filters","Field to check":"Field to check","Check type":"Check type","Value to check":"Value to check","Filter by field text":"Filter by field text","Text to check":"Text to check","Order by field value":"Order by field value","Orders all documents in the query by a the value of a field.":"Orders all documents in the query by a the value of a field.","Order query _PARAM0_ by field _PARAM1_ (direction: _PARAM2_)":"Order query _PARAM0_ by field _PARAM1_ (direction: _PARAM2_)","Field to order by":"Field to order by","Direction (ascending or descending)":"Direction (ascending or descending)","Limit amount of documents":"Limit amount of documents","Limits the amount of documents returned by the query. Can only be used after an order filter.":"Limits the amount of documents returned by the query. Can only be used after an order filter.","Limit query _PARAM0_ to _PARAM1_ documents (begin from the end: _PARAM2_)":"Limit query _PARAM0_ to _PARAM1_ documents (begin from the end: _PARAM2_)","Amount to limit by":"Amount to limit by","Begin from the end":"Begin from the end","Skip some documents":"Skip some documents","Removes documents before or after a certain value on the field ordered by in a query. Can only be used after an order filter.":"Removes documents before or after a certain value on the field ordered by in a query. Can only be used after an order filter.","Skip documents with fields (before: _PARAM2_) value _PARAM1_ in query _PARAM0_ (include documents at that value: _PARAM3_)":"Skip documents with fields (before: _PARAM2_) value _PARAM1_ in query _PARAM0_ (include documents at that value: _PARAM3_)","The value of the field ordered by to skip after":"The value of the field ordered by to skip after","Skip documents before?":"Skip documents before?","Include documents which field value equals the value to skip after?":"Include documents which field value equals the value to skip after?","Execute a query":"Execute a query","Execute the query and store results in a scene variable.":"Execute the query and store results in a scene variable.","Execute query _PARAM0_ and store results into _PARAM1_ (store result state in _PARAM2_)":"Execute query _PARAM0_ and store results into _PARAM1_ (store result state in _PARAM2_)","Firebase/Cloud Firestore/Queries/Execute":"Firebase/Cloud Firestore/Queries/Execute","Callback variable where to load the results":"Callback variable where to load the results","Callback variable with state (ok or error message)":"Callback variable with state (ok or error message)","Watch a query":"Watch a query","Executes the query every time a new documents starts or stops matching the query, or a document that matches the query has been changed.":"Executes the query every time a new documents starts or stops matching the query, or a document that matches the query has been changed.","Watch and automatically execute query _PARAM0_ and store results into _PARAM1_ (store result state in _PARAM2_)":"Watch and automatically execute query _PARAM0_ and store results into _PARAM1_ (store result state in _PARAM2_)","Enable persistence":"Enable persistence","When persistence is enabled, all data that is fetched from the database is being automatically stored to allow to continue accessing the data if cut off from the network, instead of waiting for reconnection.\nThis needs to be called before any other firestore operation, otherwise it will fail.":"When persistence is enabled, all data that is fetched from the database is being automatically stored to allow to continue accessing the data if cut off from the network, instead of waiting for reconnection.\nThis needs to be called before any other firestore operation, otherwise it will fail.","Disable persistence":"Disable persistence","Disables the storing of fetched data and clear all the data that has been stored.\nThis needs to be called before any other firestore operation, otherwise it will fail.":"Disables the storing of fetched data and clear all the data that has been stored.\nThis needs to be called before any other firestore operation, otherwise it will fail.","Re-enable network":"Re-enable network","Re-enables the connection to the database after disabling it.":"Re-enables the connection to the database after disabling it.","Disable network":"Disable network","Disables the connection to the database.\nWhile the network is disabled, any read operations will return results from cache, and any write operations will be queued until the network is restored.":"Disables the connection to the database.\nWhile the network is disabled, any read operations will return results from cache, and any write operations will be queued until the network is restored.","Write a document to firestore":"Write a document to firestore","Writes a document (variable) to cloud firestore.":"Writes a document (variable) to cloud firestore.","Write _PARAM2_ to firestore in document _PARAM1_ of collection _PARAM0_ (store result state in _PARAM3_)":"Write _PARAM2_ to firestore in document _PARAM1_ of collection _PARAM0_ (store result state in _PARAM3_)","Firebase/Cloud Firestore/Documents":"Firebase/Cloud Firestore/Documents","Document":"Document","Variable to write":"Variable to write","Add a document to firestore":"Add a document to firestore","Adds a document (variable) to cloud firestore with a unique name.":"Adds a document (variable) to cloud firestore with a unique name.","Add _PARAM1_ to firestore collection _PARAM0_ (store result state in _PARAM2_)":"Add _PARAM1_ to firestore collection _PARAM0_ (store result state in _PARAM2_)","Write a field in firestore":"Write a field in firestore","Writes a field of a firestore document.":"Writes a field of a firestore document.","Write _PARAM3_ to firestore in field _PARAM2_ of document _PARAM1_ in collection _PARAM0_ (store result state in _PARAM4_, Merge: _PARAM5_)":"Write _PARAM3_ to firestore in field _PARAM2_ of document _PARAM1_ in collection _PARAM0_ (store result state in _PARAM4_, Merge: _PARAM5_)","Firebase/Cloud Firestore/Fields":"Firebase/Cloud Firestore/Fields","Field to write":"Field to write","Value to write":"Value to write","Merge Document?":"Merge Document?","Update a document in firestore":"Update a document in firestore","Updates a firestore document (variable).":"Updates a firestore document (variable).","Update firestore document _PARAM1_ in collection _PARAM0_ with _PARAM2_ (store result state in _PARAM3_)":"Update firestore document _PARAM1_ in collection _PARAM0_ with _PARAM2_ (store result state in _PARAM3_)","Variable to update with":"Variable to update with","Update a field of a document":"Update a field of a document","Updates a field of a firestore document.":"Updates a field of a firestore document.","Update field _PARAM2_ of firestore document _PARAM1_ in collection _PARAM0_ with _PARAM3_ (store result state in _PARAM4_)":"Update field _PARAM2_ of firestore document _PARAM1_ in collection _PARAM0_ with _PARAM3_ (store result state in _PARAM4_)","Field to update":"Field to update","Delete a document in firestore":"Delete a document in firestore","Deletes a firestore document (variable).":"Deletes a firestore document (variable).","Delete firestore document _PARAM1_ in collection _PARAM0_ (store result state in _PARAM2_)":"Delete firestore document _PARAM1_ in collection _PARAM0_ (store result state in _PARAM2_)","Delete a field of a document":"Delete a field of a document","Deletes a field of a firestore document.":"Deletes a field of a firestore document.","Delete field _PARAM2_ of firestore document _PARAM1_ in collection _PARAM0_ with (store result state in _PARAM3_)":"Delete field _PARAM2_ of firestore document _PARAM1_ in collection _PARAM0_ with (store result state in _PARAM3_)","Field to delete":"Field to delete","Get a document from firestore":"Get a document from firestore","Gets a firestore document and store it in a variable.":"Gets a firestore document and store it in a variable.","Load firestore document _PARAM1_ from collection _PARAM0_ into _PARAM2_ (store result state in _PARAM3_)":"Load firestore document _PARAM1_ from collection _PARAM0_ into _PARAM2_ (store result state in _PARAM3_)","Callback variable where to load the document":"Callback variable where to load the document","Get a field of a document":"Get a field of a document","Gets the value of a field in a firestore document.":"Gets the value of a field in a firestore document.","Load field _PARAM2_ of firestore document _PARAM1_ in collection _PARAM0_ into _PARAM3_ (store result state in _PARAM4_)":"Load field _PARAM2_ of firestore document _PARAM1_ in collection _PARAM0_ into _PARAM3_ (store result state in _PARAM4_)","Field to get":"Field to get","Callback variable where to store the field's value":"Callback variable where to store the field's value","Check for a document's existence":"Check for a document's existence","Checks for the existence of a document. Sets the result variable to 1 if it exists else to 2.":"Checks for the existence of a document. Sets the result variable to 1 if it exists else to 2.","Check for existence of _PARAM1_ in collection _PARAM0_ and store result in _PARAM2_ (store result state in _PARAM3_)":"Check for existence of _PARAM1_ in collection _PARAM0_ and store result in _PARAM2_ (store result state in _PARAM3_)","Callback variable where to store the result":"Callback variable where to store the result","Check for existence of a document's field":"Check for existence of a document's field","Checks for the existence of a field in a document. Sets the result variable to 1 if it exists else to 2.":"Checks for the existence of a field in a document. Sets the result variable to 1 if it exists else to 2.","Check for existence of _PARAM2_ in document _PARAM1_ of collection _PARAM0_ and store result in _PARAM3_ (store result state in _PARAM4_)":"Check for existence of _PARAM2_ in document _PARAM1_ of collection _PARAM0_ and store result in _PARAM3_ (store result state in _PARAM4_)","Callback Variable where to store the result":"Callback Variable where to store the result","List all documents of a collection":"List all documents of a collection","Generates a list of all document names in a collection, and stores it as a structure.":"Generates a list of all document names in a collection, and stores it as a structure.","List all documents in _PARAM0_ and store result in _PARAM1_ (store result state in _PARAM2_)":"List all documents in _PARAM0_ and store result in _PARAM1_ (store result state in _PARAM2_)","Upload a file":"Upload a file","Upload a file to firebase Storage.":"Upload a file to firebase Storage.","Save _PARAM0_ in location _PARAM1_ to Firebase storage and store access URL in _PARAM3_ (Format: _PARAM2_, Store result state in _PARAM4_)":"Save _PARAM0_ in location _PARAM1_ to Firebase storage and store access URL in _PARAM3_ (Format: _PARAM2_, Store result state in _PARAM4_)","Firebase/Storage":"Firebase/Storage","Upload ID":"Upload ID","File content":"File content","Storage path":"Storage path","File content format":"File content format","Callback variable with the url to the uploaded file":"Callback variable with the url to the uploaded file","Get Download URL":"Get Download URL","Get a unique download URL for a file.":"Get a unique download URL for a file.","Get a download url for _PARAM0_ and store it in _PARAM1_ (store result state in _PARAM2_)":"Get a download url for _PARAM0_ and store it in _PARAM1_ (store result state in _PARAM2_)","Storage path to the file":"Storage path to the file","Write a variable to Database":"Write a variable to Database","Writes a variable to Database.":"Writes a variable to Database.","Write _PARAM1_ to Database in _PARAM0_ (store result state in _PARAM2_)":"Write _PARAM1_ to Database in _PARAM0_ (store result state in _PARAM2_)","Firebase/Realtime Database":"Firebase/Realtime Database","Path":"Caminho","Write a field in Database":"Write a field in Database","Writes a field of a Database document.":"Writes a field of a Database document.","Write _PARAM2_ in field _PARAM1_ of _PARAM0_ (store result state in _PARAM3_)":"Write _PARAM2_ in field _PARAM1_ of _PARAM0_ (store result state in _PARAM3_)","Update a document in Database":"Update a document in Database","Updates a variable on the database.":"Updates a variable on the database.","Update varable _PARAM0_ with _PARAM1_ (store result state in _PARAM2_)":"Update varable _PARAM0_ with _PARAM1_ (store result state in _PARAM2_)","Updates a field of a Database document.":"Updates a field of a Database document.","Update field _PARAM1_ of _PARAM0_ with _PARAM2_ (store result state in _PARAM3_)":"Update field _PARAM1_ of _PARAM0_ with _PARAM2_ (store result state in _PARAM3_)","Delete a database variable":"Delete a database variable","Deletes a variable from the database.":"Deletes a variable from the database.","Delete variable _PARAM0_ from database (store result state in _PARAM1_)":"Delete variable _PARAM0_ from database (store result state in _PARAM1_)","Delete a field of a variable":"Delete a field of a variable","Deletes a field of a variable on the database.":"Deletes a field of a variable on the database.","Delete field _PARAM1_ of variable _PARAM0_ on the database (store result state in _PARAM2_)":"Delete field _PARAM1_ of variable _PARAM0_ on the database (store result state in _PARAM2_)","Get a variable from the database":"Get a variable from the database","Gets a variable from the database and store it in a Scene variable.":"Gets a variable from the database and store it in a Scene variable.","Load database variable _PARAM0_ into _PARAM1_ (store result state in _PARAM2_)":"Load database variable _PARAM0_ into _PARAM1_ (store result state in _PARAM2_)","Callback variable where to store the data":"Callback variable where to store the data","Get a field of a variable":"Get a field of a variable","Gets the value of a field in a variable from the database and store it in a scene variable.":"Gets the value of a field in a variable from the database and store it in a scene variable.","Load field _PARAM1_ of database variable _PARAM0_ into _PARAM2_ (store result state in _PARAM3_)":"Load field _PARAM1_ of database variable _PARAM0_ into _PARAM2_ (store result state in _PARAM3_)","Check for a variable's existence":"Check for a variable's existence","Checks for the existence of a variable. Sets the result variable to 1 if it exists else to 2.":"Checks for the existence of a variable. Sets the result variable to 1 if it exists else to 2.","Check for existence of _PARAM0_ and store result in _PARAM1_ (store result state in _PARAM2_)":"Check for existence of _PARAM0_ and store result in _PARAM1_ (store result state in _PARAM2_)","Check for existence of a variable's field":"Check for existence of a variable's field","Checks for the existence of a field in a variable. Sets the result variable to 1 if it exists else to 2.":"Checks for the existence of a field in a variable. Sets the result variable to 1 if it exists else to 2.","Check for existence of _PARAM1_ in database variable _PARAM0_ and store result in _PARAM2_ (store result state in _PARAM3_)":"Check for existence of _PARAM1_ in database variable _PARAM0_ and store result in _PARAM2_ (store result state in _PARAM3_)","storage":"storage","Debugger Tools":"Debugger Tools","Allow to interact with the editor debugger from the game.":"Allow to interact with the editor debugger from the game.","Pause game execution":"Pause game execution","This pauses the game, useful for inspecting the game state through the debugger. Note that events will be still executed until the end before the game is paused.":"This pauses the game, useful for inspecting the game state through the debugger. Note that events will be still executed until the end before the game is paused.","Draw collisions hitboxes and points":"Draw collisions hitboxes and points","This activates the display of rectangles and information on screen showing the objects bounding boxes (blue), the hitboxes (red) and some points of objects.":"This activates the display of rectangles and information on screen showing the objects bounding boxes (blue), the hitboxes (red) and some points of objects.","Enable debugging view of bounding boxes/collision masks: _PARAM1_ (include invisible objects: _PARAM2_, point names: _PARAM3_, custom points: _PARAM4_)":"Enable debugging view of bounding boxes/collision masks: _PARAM1_ (include invisible objects: _PARAM2_, point names: _PARAM3_, custom points: _PARAM4_)","Enable debug draw":"Enable debug draw","Show collisions for hidden objects":"Show collisions for hidden objects","Show points names":"Show points names","Show custom points":"Show custom points","Log a message to the console":"Log a message to the console","Logs a message to the debugger's console.":"Logs a message to the debugger's console.","Log message _PARAM0_ of type _PARAM1_ to the console in group _PARAM2_":"Log message _PARAM0_ of type _PARAM1_ to the console in group _PARAM2_","Screenshot":"Captura de ecr\xE3","Take screenshot":"Tirar captura de ecr\xE3","Take a screenshot of the game, and save it to a png file (supported only when running on Windows/Linux/macOS).":"Tire uma captura de tela do jogo e salve-a num ficheiro png (suportado apenas quando executado no Windows / Linux / macOS).","Take a screenshot and save at _PARAM1_":"Tire uma captura de ecr\xE3 e salve em _PARAM1_","Physics Engine 2.0":"Motor de F\xEDsica 2.0","Simulate realistic object physics, with gravity, forces, joints, etc.":"Simular a f\xEDsica de object realista, com gravidade, for\xE7as, jun\xE7\xF5es, etc.","World gravity on X axis":"World gravity on X axis","Compare the world gravity on X axis.":"Compare the world gravity on X axis.","the world gravity on X axis":"the world gravity on X axis","Global":"Global","World gravity on Y axis":"World gravity on Y axis","Compare the world gravity on Y axis.":"Compare the world gravity on Y axis.","the world gravity on Y axis":"the world gravity on Y axis","World gravity":"World gravity","Modify the world gravity.":"Modificar a gravidade do mundo.","While an object is needed, this will apply to all objects using the behavior.":"While an object is needed, this will apply to all objects using the behavior.","Set the world gravity of _PARAM0_ to _PARAM2_;_PARAM3_":"Set the world gravity of _PARAM0_ to _PARAM2_;_PARAM3_","Gravity X":"Gravidade X","Gravity Y":"Gravidade Y","World time scale":"World time scale","Compare the world time scale.":"Compare the world time scale.","the world time scale":"the world time scale","Modify the world time scale.":"Modificar a escala de tempo do mundo.","Set the world time scale of _PARAM0_ to _PARAM2_":"Set the world time scale of _PARAM0_ to _PARAM2_","Is dynamic":"\xC9 din\xE2mico","Test if an object is dynamic.":"Testar se um object \xE9 din\xE2mico.","Dynamics":"Din\xE2mica","Set as dynamic":"Definir como din\xE2mico","Set an object as dynamic. Is affected by gravity, forces and velocities.":"Definir um object como din\xE2mico. \xC9 afetado pela gravidade, for\xE7as e velocidades.","Set _PARAM0_ as dynamic":"Definir _PARAM0_ como din\xE2mico","Is static":"\xC9 est\xE1tico","Test if an object is static.":"Testar se um object \xE9 est\xE1tico.","_PARAM0_ is static":"_PARAM0_ \xE9 est\xE1tico","Set as static":"Definir como est\xE1tico","Set an object as static. Is not affected by gravity, and can't be moved by forces or velocities at all.":"Definir um object como est\xE1tico. N\xE3o \xE9 afetado pela gravidade e n\xE3o pode ser movido por for\xE7as ou velocidades.","Set _PARAM0_ as static":"Definir _PARAM0_ como est\xE1tico","Is kinematic":"\xC9 cinem\xE1tico","Test if an object is kinematic.":"Testar se um object \xE9 cinem\xE1tico.","_PARAM0_ is kinematic":"_PARAM0_ \xE9 cinem\xE1tico","Set as kinematic":"Definir como cinem\xE1tico","Set an object as kinematic. Is like a static body but can be moved through its velocity.":"Definir um object como cinem\xE1tico. \xC9 como um corpo est\xE1tico, mas pode ser movido atrav\xE9s da sua velocidade.","Set _PARAM0_ as kinematic":"Definir _PARAM0_ como cinem\xE1tico","Is treat as bullet":"\xC9 tratado como bala","Test if an object is being treat as a bullet.":"Testar se um object est\xE1 a ser tratado como uma bala.","_PARAM0_ is bullet":"_PARAM0_ \xE9 bala","Treat as bullet":"Tratar como bala","Treat the object as a bullet. Better collision handling on high speeds at cost of some performance.":"Tratar o object como uma bala. Melhor manuseio de colis\xE3o em altas velocidades a custo de algum desempenho.","Treat _PARAM0_ as bullet: _PARAM2_":"Tratar _PARAM0_ como bala: _PARAM2_","Treat as bullet?":"Tratar como bala?","Has fixed rotation":"Tem rota\xE7\xE3o fixa","Test if an object has fixed rotation.":"Testar se um object tem rota\xE7\xE3o fixa.","_PARAM0_ has fixed rotation":"_PARAM0_ tem rota\xE7\xE3o fixa","Enable or disable an object fixed rotation. If enabled the object won't be able to rotate.":"Ativar ou desativar a rota\xE7\xE3o fixa de um object. Se ativado, o object n\xE3o poder\xE1 girar.","Set _PARAM0_ fixed rotation: _PARAM2_":"Definir _PARAM0_ rota\xE7\xE3o fixa: _PARAM2_","Fixed rotation?":"Rota\xE7\xE3o fixa?","Is sleeping allowed":"\xC9 permitido dormir","Test if an object can sleep.":"Testar se um object pode dormir.","_PARAM0_ can sleep":"_PARAM0_ pode dormir","Sleeping allowed":"Dormir \xE9 permitido","Allow or not an object to sleep. If enabled the object will be able to sleep, improving performance for non-currently-moving objects.":"Permitir ou n\xE3o um object para dormir. Se ativado, o object poder\xE1 adormecer, melhorando o desempenho de objects que atualmente n\xE3o se movem.","Allow _PARAM0_ to sleep: _PARAM2_":"Permitir _PARAM0_ dormir: _PARAM2_","Can sleep?":"Pode dormir?","Is sleeping":"Est\xE1 a dormir","Test if an object is sleeping.":"Testar se um object est\xE1 a dormir.","_PARAM0_ is sleeping":"_PARAM0_ est\xE1 a dormir","Shape scale":"Escala de forma","Modify an object shape scale. It affects custom shape dimensions and shape offset, if custom dimensions are not set the body will be scaled automatically to the object size.":"Modificar uma escala de forma de um object. Isso afeta as dimens\xF5es da forma personalizada e o deslocamento da forma. Se as dimens\xF5es personalizadas n\xE3o forem definidas, o corpo ser\xE1 redimensionado automaticamente para o tamanho do object.","the shape scale":"the shape scale","Body settings":"Configura\xE7\xF5es do corpo","Density":"Densidade","Test an object density.":"Testar a densidade de um object.","the _PARAM0_ density":"the _PARAM0_ density","Modify an object density. The body's density and volume determine its mass.":"Modificar a densidade de um object. A densidade e o volume do corpo determinam a sua massa.","the density":"the density","Density of the object":"Densidade do object","Get the density of an object.":"Obter a densidade de um object.","Test an object friction.":"Testar a fric\xE7\xE3o de um object.","the _PARAM0_ friction":"the _PARAM0_ friction","Modify an object friction. How much energy is lost from the movement of one object over another. The combined friction from two bodies is calculated as 'sqrt(bodyA.friction * bodyB.friction)'.":"Modificar a fric\xE7\xE3o de um object. Quanta energia \xE9 perdida do movimento de um object sobre outro. O fric\xE7\xE3o combinada de dois corpos \xE9 calculada como 'sqrt(bodyA.friction * bodyB.friction)'.","the friction":"the friction","Friction of the object":"Fric\xE7\xE3o do object","Get the friction of an object.":"Obter a fric\xE7\xE3o de um object.","Restitution":"Restitui\xE7\xE3o","Test an object restitution.":"Testar a restitui\xE7\xE3o de um object.","the _PARAM0_ restitution":"the _PARAM0_ restitution","Modify an object restitution. Energy conservation on collision. The combined restitution from two bodies is calculated as 'max(bodyA.restitution, bodyB.restitution)'.":"Modificar uma restitui\xE7\xE3o de object. Conserva\xE7\xE3o de energia em caso de colis\xE3o. A restitui\xE7\xE3o combinada de dois corpos \xE9 calculada como \"max(bodyA.restitution, bodyB.restitution)\".","the restitution":"the restitution","Restitution of the object":"Restitui\xE7\xE3o do object","Get the restitution of an object.":"Obter a restitui\xE7\xE3o de um object.","Test an object linear damping.":"Testar um object linear de amortecimento.","the _PARAM0_ linear damping":"the _PARAM0_ linear damping","Modify an object linear damping. How much movement speed is lost across the time.":"Modificar o amortecimento linear de um object. Quanta velocidade de movimento \xE9 perdida ao longo do tempo.","Linear damping of the object":"Amortecimento linear do object","Get the linear damping of an object.":"Obter o amortecimento linear de um object.","Test an object angular damping.":"Testar o amortecimento angular de um object.","the _PARAM0_ angular damping":"the _PARAM0_ angular damping","Modify an object angular damping. How much angular speed is lost across the time.":"Modificar um amortecimento angular de um object. Quanta velocidade angular se perde ao longo do tempo.","Angular damping of the object":"Amortecimento angular do object","Get the angular damping of an object.":"Obter o amortecimento angular de um object.","Gravity scale":"Escala de gravidade","Test an object gravity scale.":"Testar a escala de gravidade de um object.","the _PARAM0_ gravity scale":"the _PARAM0_ gravity scale","Modify an object gravity scale. The gravity applied to an object is the world gravity multiplied by the object gravity scale.":"Modificar a escala de gravidade de um object. A gravidade aplicada a um object \xE9 a gravidade do mundo multiplicada pela escala de gravidade do object.","the gravity scale":"the gravity scale","Gravity scale of the object":"Escala de gravidade do object","Get the gravity scale of an object.":"Obter a escala de gravidade de um object.","Layer enabled":"Camada ativada","Test if an object has a specific layer enabled.":"Testar se um object tem uma camada espec\xEDfica habilitada.","_PARAM0_ has layer _PARAM2_ enabled":"_PARAM0_ tem a camada _PARAM2_ activada","Filtering":"Filtragem","Layer (1 - 16)":"Camada (1 - 16)","Enable layer":"Habilitar camada","Enable or disable a layer for an object. Two objects collide if any layer of the first object matches any mask of the second one and vice versa.":"Ativar ou desativar uma camada para um object. Dois objects colidem se qualquer camada do primeiro object corresponder a qualquer m\xE1scara do segundo e vice-versa.","Enable layer _PARAM2_ for _PARAM0_: _PARAM3_":"Habilitar a camada _PARAM2_ para _PARAM0_: _PARAM3_","Enable?":"Habilitar?","Mask enabled":"M\xE1scara activada","Test if an object has a specific mask enabled.":"Testar se um object tem uma m\xE1scara espec\xEDfica ativada.","_PARAM0_ has mask _PARAM2_ enabled":"_PARAM0_ tem m\xE1scara _PARAM2_ ativada","Mask (1 - 16)":"M\xE1scara (1 - 16)","Enable mask":"Ativar m\xE1scara","Enable or disable a mask for an object. Two objects collide if any layer of the first object matches any mask of the second one and vice versa.":"Ativar ou desativar uma m\xE1scara para um object. Dois objects colidem se qualquer camada do primeiro object corresponder a qualquer m\xE1scara do segundo e vice-versa.","Enable mask _PARAM2_ for _PARAM0_: _PARAM3_":"Habilitar m\xE1scara _PARAM2_ para _PARAM0_: _PARAM3_","Linear velocity X":"Velocidade linear X","Test an object linear velocity on X.":"Testar a velocidade linear de um object em X.","the linear velocity on X":"the linear velocity on X","Velocity":"Velocidade","Modify an object linear velocity on X.":"Modificar a velocidade linear de um object em X.","Linear velocity on X axis":"Velocidade linear no eixo X","Get the linear velocity of an object on X axis.":"Obter a velocidade linear de um object no eixo X.","Linear velocity Y":"Velocidade linear Y","Test an object linear velocity on Y.":"Testar a velocidade linear de um object em Y.","the linear velocity on Y":"the linear velocity on Y","Modify an object linear velocity on Y.":"Modificar a velocidade linear de um object em Y.","Linear velocity on Y axis":"Velocidade linear no eixo Y","Get the linear velocity of an object on Y axis.":"Obter a velocidade linear de um object no eixo Y.","Test an object linear velocity length.":"Testar o comprimento de velocidade linear de um object.","the linear velocity length":"the linear velocity length","Get the linear velocity of an object.":"Obter a velocidade linear de um object.","Angular velocity":"Velocidade angular","Test an object angular velocity.":"Testar a velocidade angular de um object.","the angular velocity":"the angular velocity","Modify an object angular velocity.":"Modificar a velocidade angular de um object.","Get the angular velocity of an object.":"Obter a velocidade angular de um object.","Apply force":"Aplicar for\xE7a","Apply a force to the object. You need to specify the point of application (you can get the body mass center through expressions).":"Apply a force to the object. You need to specify the point of application (you can get the body mass center through expressions).","Apply to _PARAM0_ a force of _PARAM2_;_PARAM3_":"Aplicar a _PARAM0_ uma for\xE7a de _PARAM2_;_PARAM3_","Forces & impulses":"For\xE7as & impulsos","X component (N)":"Componente X (N)","Y component (N)":"Componente Y (N)","Applying X position":"Aplicando posi\xE7\xE3o X","Applying Y position":"Aplicando posi\xE7\xE3o Y","Apply force (angle)":"Apply force (angle)","Apply a force to the object using polar coordinates. You need to specify the point of application (you can get the body mass center through expressions).":"Apply a force to the object using polar coordinates. You need to specify the point of application (you can get the body mass center through expressions).","Apply to _PARAM0_ a force of angle _PARAM2_ and length _PARAM3_":"Aplicar a _PARAM0_ uma for\xE7a de \xE2ngulo _PARAM2_ e comprimento _PARAM3_","Length (N)":"Comprimento (N)","Apply force toward position":"Aplicar for\xE7a em dire\xE7\xE3o \xE0 posi\xE7\xE3o","Apply a force to the object to move it toward a position. You need to specify the point of application (you can get the body mass center through expressions).":"Apply a force to the object to move it toward a position. You need to specify the point of application (you can get the body mass center through expressions).","Apply to _PARAM0_ a force of length _PARAM2_ towards _PARAM3_;_PARAM4_":"Aplicar a _PARAM0_ uma for\xE7a de comprimento _PARAM2_ em dire\xE7\xE3o a _PARAM3_;_PARAM4_","Apply impulse":"Aplicar impulso","Apply an impulse to the object. You need to specify the point of application (you can get the body mass center through expressions).":"Apply an impulse to the object. You need to specify the point of application (you can get the body mass center through expressions).","Apply to _PARAM0_ an impulse of _PARAM2_;_PARAM3_":"Aplicar a _PARAM0_ um impulso de _PARAM2 _;_ Param3_","X component (N.m)":"Componente X (N.m)","Y component (N.m)":"Componente Y (N.m)","Apply impulse (angle)":"Apply impulse (angle)","Apply an impulse to the object using polar coordinates. You need to specify the point of application (you can get the body mass center through expressions).":"Apply an impulse to the object using polar coordinates. You need to specify the point of application (you can get the body mass center through expressions).","Apply to _PARAM0_ an impulse of angle _PARAM2_ and length _PARAM3_ (applied at _PARAM4_;_PARAM5_)":"Applicar a _PARAM0_ um impulso de \xE2ngulo _PARAM2_ e comprimento _PARAM3_ (aplicado em _PARAM4_;_PARAM5_)","Length (N.m)":"Comprimento (N.m)","Apply impulse toward position":"Aplicar impulso em dire\xE7\xE3o \xE0 posi\xE7\xE3o","Apply an impulse to the object to move it toward a position. You need to specify the point of application (you can get the body mass center through expressions).":"Apply an impulse to the object to move it toward a position. You need to specify the point of application (you can get the body mass center through expressions).","Apply to _PARAM0_ an impulse of length _PARAM2_ towards _PARAM3_;_PARAM4_ (applied at _PARAM5_;_PARAM6_)":"Aplicar a _PARAM0_ um impulso de comprimento _PARAM2_ em dire\xE7\xE3o a _PARAM3_;_PARAM4_ (aplicado em _PARAM5_;_PARAM6_)","Apply torque (rotational force)":"Apply torque (rotational force)","Apply a torque (also called \"rotational force\") to the object. This will make the object rotate without moving it.":"Apply a torque (also called \"rotational force\") to the object. This will make the object rotate without moving it.","Apply to _PARAM0_ a torque of _PARAM2_":"Aplicar a _PARAM0_ um torque de _PARAM2_","Torque (N.m)":"Torque (N.m)","Apply angular impulse (rotational impulse)":"Apply angular impulse (rotational impulse)","Apply an angular impulse (also called a \"rotational impulse\") to the object. This will make the object rotate without moving it.":"Apply an angular impulse (also called a \"rotational impulse\") to the object. This will make the object rotate without moving it.","Apply to _PARAM0_ an angular impulse of _PARAM2_":"Aplicar a _PARAM0_ um impulso angular de _PARAM2_","Angular impulse (N.m.s":"Impulso angular (N.m.s","Mass center X":"Centro de massa X","Mass center Y":"Centro de massa Y","Joint first object":"Primeiro object comum","Test if an object is the first object on a joint.":"Testar se um object \xE9 o primeiro object num conjunto.","_PARAM0_ is the first object for joint _PARAM2_":"_PARAM0_ \xE9 o primeiro object do conjunto _PARAM2_","Joint ID":"ID conjunto","Joint second object":"Segundo object comum","Test if an object is the second object on a joint.":"Testar se um object \xE9 o segundo object num conjunto.","_PARAM0_ is the second object for joint _PARAM2_":"_PARAM0_ \xE9 o segundo object do conjunto _PARAM2_","Joint first anchor X":"Junta da primeira \xE2ncora X","Joint first anchor Y":"Junta da primeira \xE2ncora Y","Joint second anchor X":"Junta da segunda \xE2ncora X","Joint second anchor Y":"Junta da segunda \xE2ncora Y","Joint reaction force":"For\xE7a de reac\xE7\xE3o conjunta","Test a joint reaction force.":"Testar uma for\xE7a de reac\xE7\xE3o conjunta.","the joint _PARAM2_ reaction force":"the joint _PARAM2_ reaction force","Joint reaction torque":"Torque de rea\xE7\xE3o conjunta","Test a joint reaction torque.":"Testar um torque de rea\xE7\xE3o conjunta.","the joint _PARAM2_ reaction torque":"the joint _PARAM2_ reaction torque","Remove joint":"Remover conjunto","Remove a joint from the scene.":"Remover conjunto da scene.","Remove joint _PARAM2_":"Remover conjunto _PARAM2_","Add distance joint":"Adicionar conjunto de dist\xE2ncia","Add a distance joint between two objects. The length is converted to meters using the world scale on X. The frequency and damping ratio are related to the joint speed of oscillation and how fast it stops.":"Adicionar um conjunto de dist\xE2ncia entre dois objects. O comprimento \xE9 convertido em metros usando a escala mundial em X. A frequ\xEAncia e a raz\xE3o de amortecimento est\xE3o relacionadas \xE0 velocidade de oscila\xE7\xE3o do conjunto e \xE0 rapidez com que ela p\xE1ra.","Add a distance joint between _PARAM0_ and _PARAM4_":"Adicionar um conjunto de dist\xE2ncia entre _PARAM0_ e _PARAM4_","Joints/Distance":"Conjuntos/Dist\xE2ncia","First object":"Primeiro object","Anchor X on first body":"\xC2ncora X no primeiro corpo","Anchor Y on first body":"\xC2ncora Y no primeiro corpo","Second object":"Segundo object","Anchor X on second body":"\xC2ncora X no segundo corpo","Anchor Y on second body":"\xC2ncora Y no segundo corpo","Length (-1 to use current objects distance) (default: -1)":"Comprimento (-1 para usar a dist\xE2ncia dos objects atuais) (padr\xE3o: -1)","Frequency (Hz) (non-negative) (default: 0)":"Frequ\xEAncia (Hz) (n\xE3o-negativo) (padr\xE3o: 0)","Damping ratio (non-negative) (default: 1)":"Rela\xE7\xE3o de amortecimento (n\xE3o-negativo) (padr\xE3o: 1)","Allow collision between connected bodies? (default: no)":"Permitir colis\xE3o entre corpos conectados? (padr\xE3o: n\xE3o)","Variable where to store the joint ID (default: none)":"Vari\xE1vel onde armazenar o ID do conjunto (padr\xE3o: nenhum)","Distance joint length":"Comprimento do conjunto de dist\xE2ncia","Modify a distance joint length.":"Modificar o comprimento de um conjunto de dist\xE2ncia.","the length for distance joint _PARAM2_":"the length for distance joint _PARAM2_","Distance joint frequency":"Frequ\xEAncia conjunta de dist\xE2ncia","Modify a distance joint frequency.":"Modificar a frequ\xEAncia conjunta de dist\xE2ncia.","the frequency for distance joint _PARAM2_":"the frequency for distance joint _PARAM2_","Distance joint damping ratio":"Taxa de redu\xE7\xE3o conjunta de dist\xE2ncia","Modify a distance joint damping ratio.":"Modify a distance joint damping ratio.","the damping ratio for distance joint _PARAM2_":"the damping ratio for distance joint _PARAM2_","Add revolute joint":"Add revolute joint","Add a revolute joint to an object at a fixed point. The object is attached as the second object in the joint, so you can use this for gear joints.":"Add a revolute joint to an object at a fixed point. The object is attached as the second object in the joint, so you can use this for gear joints.","Add a revolute joint to _PARAM0_ at _PARAM2_;_PARAM3_":"Add a revolute joint to _PARAM0_ at _PARAM2_;_PARAM3_","Joints/Revolute":"Joints/Revolute","X anchor":"X anchor","Y anchor":"Y anchor","Enable angle limits? (default: no)":"Enable angle limits? (default: no)","Reference angle (default: 0)":"Reference angle (default: 0)","Minimum angle (default: 0)":"Minimum angle (default: 0)","Maximum angle (default: 0)":"Maximum angle (default: 0)","Enable motor? (default: no)":"Enable motor? (default: no)","Motor speed (default: 0)":"Motor speed (default: 0)","Motor maximum torque (default: 0)":"Motor maximum torque (default: 0)","Add revolute joint between two bodies":"Add revolute joint between two bodies","Add a revolute joint between two objects. The reference angle determines what is considered as the base angle at the initial state.":"Add a revolute joint between two objects. The reference angle determines what is considered as the base angle at the initial state.","Add a revolute joint between _PARAM0_ and _PARAM4_":"Add a revolute joint between _PARAM0_ and _PARAM4_","Revolute joint reference angle":"Revolute joint reference angle","Revolute joint current angle":"Revolute joint current angle","Revolute joint angular speed":"Revolute joint angular speed","Revolute joint limits enabled":"Revolute joint limits enabled","Test if a revolute joint limits are enabled.":"Test if a revolute joint limits are enabled.","Limits for revolute joint _PARAM2_ are enabled":"Limits for revolute joint _PARAM2_ are enabled","Enable revolute joint limits":"Enable revolute joint limits","Enable or disable a revolute joint angle limits.":"Enable or disable a revolute joint angle limits.","Enable limits for revolute joint _PARAM2_: _PARAM3_":"Enable limits for revolute joint _PARAM2_: _PARAM3_","Revolute joint limits":"Revolute joint limits","Modify a revolute joint angle limits.":"Modify a revolute joint angle limits.","Set the limits to _PARAM3_;_PARAM4_ for revolute joint _PARAM2_":"Set the limits to _PARAM3_;_PARAM4_ for revolute joint _PARAM2_","Minimum angle":"Minimum angle","Maximum angle":"Maximum angle","Revolute joint minimum angle":"Revolute joint minimum angle","Revolute joint maximum angle":"Revolute joint maximum angle","Revolute joint motor enabled":"Revolute joint motor enabled","Test if a revolute joint motor is enabled.":"Test if a revolute joint motor is enabled.","Motor of revolute joint _PARAM2_ is enabled":"Motor of revolute joint _PARAM2_ is enabled","Enable revolute joint motor":"Enable revolute joint motor","Enable or disable a revolute joint motor.":"Enable or disable a revolute joint motor.","Enable motor for revolute joint _PARAM2_: _PARAM3_":"Enable motor for revolute joint _PARAM2_: _PARAM3_","Revolute joint motor speed":"Revolute joint motor speed","Modify a revolute joint motor speed.":"Modify a revolute joint motor speed.","the motor speed for revolute joint _PARAM2_":"the motor speed for revolute joint _PARAM2_","Revolute joint max motor torque":"Revolute joint max motor torque","Modify a revolute joint maximum motor torque.":"Modify a revolute joint maximum motor torque.","the maximum motor torque for revolute joint _PARAM2_":"the maximum motor torque for revolute joint _PARAM2_","Revolute joint maximum motor torque":"Revolute joint maximum motor torque","Revolute joint motor torque":"Revolute joint motor torque","Add prismatic joint":"Add prismatic joint","Add a prismatic joint between two objects. The translation limits are converted to meters using the world scale on X.":"Adicionar uma jun\xE7\xE3o prism\xE1tica entre dois objects. Os limites de tradu\xE7\xE3o s\xE3o convertidos em medidores usando a escala mundial no X.","Add a prismatic joint between _PARAM0_ and _PARAM4_":"Adicionar um conjunto prism\xE1tico entre _PARAM0_ e _PARAM4_","Joints/Prismatic":"Conjuntos/Prism\xE1tica","Axis angle":"\xC2ngulo do eixo","Enable limits? (default: no)":"Ativar limites? (padr\xE3o: n\xE3o)","Minimum translation (default: 0)":"Tradu\xE7\xE3o m\xEDnima (padr\xE3o: 0)","Maximum translation (default: 0)":"Tradu\xE7\xE3o m\xE1xima (padr\xE3o: 0)","Motor maximum force (default: 0)":"For\xE7a m\xE1xima do motor (padr\xE3o: 0)","Prismatic joint axis angle":"\xC2ngulo do eixo do conjunto prism\xE1tico","Prismatic joint reference angle":"\xC2ngulo de refer\xEAncia do conjunto prism\xE1tico","Prismatic joint current translation":"Tradu\xE7\xE3o atual do conjunto prism\xE1tico","Prismatic joint current speed":"Velocidade atual do conjunto prism\xE1tico","Prismatic joint speed":"Velocidade do conjunto prism\xE1tico","Prismatic joint limits enabled":"Limites dos conjuntos prism\xE1ticos ativados","Test if a prismatic joint limits are enabled.":"Testar se os limites de um conjunto prism\xE1tico est\xE3o ativos.","Limits for prismatic joint _PARAM2_ are enabled":"Limites para conjunto prism\xE1tico _PARAM2_ est\xE3o ativos","Enable prismatic joint limits":"Ativar limites de conjuntos prism\xE1ticos","Enable or disable a prismatic joint limits.":"Ativar ou desativar os limites prism\xE1ticos do conjunto.","Enable limits for prismatic joint _PARAM2_: _PARAM3_":"Ativar limites para conjunto prism\xE1tico _PARAM2_: _PARAM3_","Prismatic joint limits":"Limites de conjuntos prism\xE1ticos","Modify a prismatic joint limits.":"Modificar os limites dos conjuntos prism\xE1ticos.","Set the limits to _PARAM3_;_PARAM4_ for prismatic joint _PARAM2_":"Definir os limites para _PARAM3_;_PARAM4_ para conjunto prism\xE1tico _PARAM2_","Minimum translation":"Tradu\xE7\xE3o m\xEDnima","Maximum translation":"Tradu\xE7\xE3o m\xE1xima","Prismatic joint minimum translation":"Tradu\xE7\xE3o m\xEDnima do conjunto prism\xE1tico","Prismatic joint maximum translation":"Tradu\xE7\xE3o m\xE1xima do conjunto prism\xE1tico","Prismatic joint motor enabled":"Motor do conjunto prism\xE1tico ativado","Test if a prismatic joint motor is enabled.":"Testar se o motor de um conjunto prism\xE1tico est\xE1 ativado.","Motor for prismatic joint _PARAM2_ is enabled":"Motor para conjunto prism\xE1tico _PARAM2_ est\xE1 ativado","Enable prismatic joint motor":"Ativar motor de conjunto prism\xE1tico","Enable or disable a prismatic joint motor.":"Ativar ou desativar motor de um conjunto prism\xE1tico.","Enable motor for prismatic joint _PARAM2_: _PARAM3_":"Ativar motor para conjunto prism\xE1tico _PARAM2_: _PARAM3_","Prismatic joint motor speed":"Velocidade do motor do conjunto prism\xE1tico","Modify a prismatic joint motor speed.":"Modificar a velocidade do motor do conjunto prism\xE1tico.","the motor force for prismatic joint _PARAM2_":"the motor force for prismatic joint _PARAM2_","Prismatic joint max motor force":"For\xE7a motora m\xE1xima do conjunto prism\xE1tico","Modify a prismatic joint maximum motor force.":"Modificar a for\xE7a motora m\xE1xima de um conjunto prism\xE1tico.","the maximum motor force for prismatic joint _PARAM2_":"the maximum motor force for prismatic joint _PARAM2_","Prismatic joint maximum motor force":"For\xE7a motora m\xE1xima do conjunto prism\xE1tico","Prismatic joint motor force":"For\xE7a motora do conjunto prism\xE1tico","Add pulley joint":"Adicionar conjunto de polia","Add a pulley joint between two objects. Lengths are converted to meters using the world scale on X.":"Adicionar um conjunto de polia entre dois objects. Comprimentos s\xE3o convertidos em metros usando a escala mundial no X.","Add a pulley joint between _PARAM0_ and _PARAM4_":"Adicionar um conjunto de polia entre _PARAM0_ e _PARAM4_","Joints/Pulley":"Conjuntos/Polia","Ground anchor X for first object":"\xC2ncora de solo X para o primeiro object","Ground anchor Y for first object":"\xC2ncora de solo Y para o primeiro object","Ground anchor X for second object":"\xC2ncora de solo X para o segundo object","Ground anchor Y for second object":"\xC2ncora de solo Y para o segundo object","Length for first object (-1 to use anchor positions) (default: -1)":"Comprimento para o primeiro object (-1 para usar posi\xE7\xF5es de \xE2ncora) (padr\xE3o: -1)","Length for second object (-1 to use anchor positions) (default: -1)":"Comprimento para o segundo object (-1 para usar posi\xE7\xF5es de \xE2ncora) (padr\xE3o: -1)","Ratio (non-negative) (default: 1":"Ratio (non-negative) (default: 1","Pulley joint first ground anchor X":"Pulley joint first ground anchor X","Pulley joint first ground anchor Y":"Pulley joint first ground anchor Y","Pulley joint second ground anchor X":"Pulley joint second ground anchor X","Pulley joint second ground anchor Y":"Pulley joint second ground anchor Y","Pulley joint first length":"Pulley joint first length","Pulley joint second length":"Pulley joint second length","Pulley joint ratio":"Pulley joint ratio","Add gear joint":"Add gear joint","Add a gear joint between two joints. Attention: Gear joints require the joints to be revolute or prismatic, and both of them to be attached to a static body as first object.":"Add a gear joint between two joints. Attention: Gear joints require the joints to be revolute or prismatic, and both of them to be attached to a static body as first object.","Add a gear joint between joints _PARAM2_ and _PARAM3_":"Add a gear joint between joints _PARAM2_ and _PARAM3_","Joints/Gear":"Joints/Gear","First joint ID":"First joint ID","Second joint ID":"Second joint ID","Ratio (non-zero) (default: 1)":"Ratio (non-zero) (default: 1)","Gear joint first joint":"Gear joint first joint","Gear joint second joint":"Gear joint second joint","Gear joint ratio":"Gear joint ratio","Modify a Gear joint ratio.":"Modify a Gear joint ratio.","the ratio for gear joint _PARAM2_":"the ratio for gear joint _PARAM2_","Add mouse joint":"Add mouse joint","Add a mouse joint to an object (makes the object move towards a specific point).":"Add a mouse joint to an object (makes the object move towards a specific point).","Add a mouse joint to _PARAM0_":"Add a mouse joint to _PARAM0_","Joints/Mouse":"Joints/Mouse","Target X":"Target X","Target Y":"Target Y","Maximum force (N) (non-negative) (default: 500)":"Maximum force (N) (non-negative) (default: 500)","Frequency (Hz) (positive) (default: 10)":"Frequency (Hz) (positive) (default: 10)","Mouse joint target":"Mouse joint target","Set a mouse joint target.":"Set a mouse joint target.","Set the target position of mouse joint _PARAM2_ of _PARAM0_ to _PARAM3_;_PARAM4_":"Set the target position of mouse joint _PARAM2_ of _PARAM0_ to _PARAM3_;_PARAM4_","Mouse joint target X":"Mouse joint target X","Mouse joint target Y":"Mouse joint target Y","Mouse joint max force":"Mouse joint max force","Set a mouse joint maximum force.":"Set a mouse joint maximum force.","the maximum force for mouse joint _PARAM2_":"the maximum force for mouse joint _PARAM2_","Mouse joint maximum force":"Mouse joint maximum force","Mouse joint frequency":"Mouse joint frequency","Set a mouse joint frequency.":"Set a mouse joint frequency.","the frequency for mouse joint _PARAM2_":"the frequency for mouse joint _PARAM2_","Mouse joint damping ratio":"Mouse joint damping ratio","Set a mouse joint damping ratio.":"Set a mouse joint damping ratio.","the damping ratio for mouse joint _PARAM2_":"the damping ratio for mouse joint _PARAM2_","Add wheel joint":"Add wheel joint","Add a wheel joint between two objects. Higher frequencies means higher suspensions. Damping determines oscillations, critical damping of 1 means no oscillations.":"Add a wheel joint between two objects. Higher frequencies means higher suspensions. Damping determines oscillations, critical damping of 1 means no oscillations.","Add a wheel joint between _PARAM0_ and _PARAM4_":"Add a wheel joint between _PARAM0_ and _PARAM4_","Joints/Wheel":"Joints/Wheel","Frequency (Hz) (non-negative) (default: 10)":"Frequency (Hz) (non-negative) (default: 10)","Wheel joint axis angle":"Wheel joint axis angle","Wheel joint current translation":"Wheel joint current translation","Wheel joint current speed":"Velocidade atual do conjunto da roda","Wheel joint speed":"Velocidade do conjunto da roda","Wheel joint motor enabled":"Motor do conjunto da roda ativado","Test if a wheel joint motor is enabled.":"Testar se o motor de um conjunto de roda est\xE1 ativado.","Motor for wheel joint _PARAM2_ is enabled":"Motor para o conjunto da roda _PARAM2_ est\xE1 ativado","Enable wheel joint motor":"Ativar motor do conjunto da roda","Enable or disable a wheel joint motor.":"Ativar ou desativar o motor do conjunto da roda.","Enable motor for wheel joint _PARAM2_: _PARAM3_":"Ativar motor para conjunto de roda _PARAM2_: _PARAM3_","Wheel joint motor speed":"Velocidade do motor do conjunto da roda","Modify a wheel joint motor speed.":"Modificar a velocidade do motor de um conjunto de roda.","the motor speed for wheel joint _PARAM2_":"the motor speed for wheel joint _PARAM2_","Wheel joint max motor torque":"Torque m\xE1ximo do motor do conjunto da roda","Modify a wheel joint maximum motor torque.":"Modificar o torque m\xE1ximo do motor do conjunto da roda.","the maximum motor torque for wheel joint _PARAM2_":"the maximum motor torque for wheel joint _PARAM2_","Wheel joint maximum motor torque":"Torque m\xE1ximo do motor do conjunto da roda","Wheel joint motor torque":"Torque do motor do conjunto de roda","Wheel joint frequency":"Frequ\xEAncia do conjunto da roda","Modify a wheel joint frequency.":"Modificar a frequ\xEAncia do conjunto da roda.","the frequency for wheel joint _PARAM2_":"the frequency for wheel joint _PARAM2_","Wheel joint damping ratio":"Wheel joint damping ratio","Modify a wheel joint damping ratio.":"Modify a wheel joint damping ratio.","the damping ratio for wheel joint _PARAM2_":"the damping ratio for wheel joint _PARAM2_","Add weld joint":"Add weld joint","Add a weld joint between two objects.":"Add a weld joint between two objects.","Add a weld joint between _PARAM0_ and _PARAM4_":"Add a weld joint between _PARAM0_ and _PARAM4_","Joints/Weld":"Joints/Weld","Weld joint reference angle":"Weld joint reference angle","Weld joint frequency":"Weld joint frequency","Modify a weld joint frequency.":"Modify a weld joint frequency.","the frequency for weld joint _PARAM2_":"the frequency for weld joint _PARAM2_","Weld joint damping ratio":"Weld joint damping ratio","Modify a weld joint damping ratio.":"Modify a weld joint damping ratio.","the damping ratio for weld joint _PARAM2_":"the damping ratio for weld joint _PARAM2_","Add rope joint":"Add rope joint","Add a rope joint between two objects. The maximum length is converted to meters using the world scale on X.":"Add a rope joint between two objects. The maximum length is converted to meters using the world scale on X.","Add a rope joint between _PARAM0_ and _PARAM4_":"Add a rope joint between _PARAM0_ and _PARAM4_","Joints/Rope":"Joints/Rope","Maximum length (-1 to use current objects distance) (default: -1)":"Maximum length (-1 to use current objects distance) (default: -1)","Rope joint max length":"Rope joint max length","Modify a rope joint maximum length.":"Modify a rope joint maximum length.","the maximum length for rope joint _PARAM2_":"the maximum length for rope joint _PARAM2_","Rope joint maximum length":"Rope joint maximum length","Add friction joint":"Add friction joint","Add a friction joint between two objects.":"Add a friction joint between two objects.","Add a friction joint between _PARAM0_ and _PARAM4_":"Add a friction joint between _PARAM0_ and _PARAM4_","Joints/Friction":"Joints/Friction","Maximum force (non-negative)":"Maximum force (non-negative)","Maximum torque (non-negative)":"Maximum torque (non-negative)","Friction joint max force":"Friction joint max force","Modify a friction joint maximum force.":"Modify a friction joint maximum force.","the maximum force for friction joint _PARAM2_":"the maximum force for friction joint _PARAM2_","Friction joint maximum force":"Friction joint maximum force","Friction joint max torque":"Friction joint max torque","Modify a friction joint maximum torque.":"Modify a friction joint maximum torque.","the maximum torque for friction joint _PARAM2_":"the maximum torque for friction joint _PARAM2_","Friction joint maximum torque":"Friction joint maximum torque","Add motor joint":"Add motor joint","Add a motor joint between two objects. The position and angle offsets are relative to the first object.":"Add a motor joint between two objects. The position and angle offsets are relative to the first object.","Add a motor joint between _PARAM0_ and _PARAM2_":"Add a motor joint between _PARAM0_ and _PARAM2_","Joints/Motor":"Joints/Motor","Offset X position":"Offset X position","Offset Y position":"Offset Y position","Offset Angle":"Offset Angle","Correction factor (default: 1)":"Correction factor (default: 1)","Motor joint offset":"Motor joint offset","Modify a motor joint offset.":"Modify a motor joint offset.","Set offset to _PARAM3_;_PARAM4_ for motor joint _PARAM2_":"Set offset to _PARAM3_;_PARAM4_ for motor joint _PARAM2_","Offset X":"Offset X","Offset Y":"Offset Y","Motor joint offset X":"Motor joint offset X","Motor joint offset Y":"Motor joint offset Y","Motor joint angular offset":"Motor joint angular offset","Modify a motor joint angular offset.":"Modify a motor joint angular offset.","the angular offset for motor joint _PARAM2_":"the angular offset for motor joint _PARAM2_","Motor joint max force":"Motor joint max force","Modify a motor joint maximum force.":"Modify a motor joint maximum force.","the maximum force for motor joint _PARAM2_":"the maximum force for motor joint _PARAM2_","Motor joint maximum force":"Motor joint maximum force","Motor joint max torque":"Motor joint max torque","Modify a motor joint maximum torque.":"Modify a motor joint maximum torque.","the maximum torque for motor joint _PARAM2_":"the maximum torque for motor joint _PARAM2_","Motor joint maximum torque":"Motor joint maximum torque","Motor joint correction factor":"Motor joint correction factor","Modify a motor joint correction factor.":"Modify a motor joint correction factor.","the correction factor for motor joint _PARAM2_":"the correction factor for motor joint _PARAM2_","Test if two objects collide.":"Test if two objects collide.","_PARAM0_ is colliding with _PARAM2_":"_PARAM0_ is colliding with _PARAM2_","Lights":"Lights","Light Obstacle Behavior":"Light Obstacle Behavior","This behavior makes the object an obstacle to the light. The light emitted by light objects will be stopped by the object.":"This behavior makes the object an obstacle to the light. The light emitted by light objects will be stopped by the object.","Radius":"Radius","Debug mode":"Debug mode","When activated, display the lines used to render the light - useful to understand how the light is rendered on screen.":"When activated, display the lines used to render the light - useful to understand how the light is rendered on screen.","Light texture (optional)":"Light texture (optional)","A texture to be used to display the light. If you don't specify a texture, the light is rendered as fading from bright, in its center, to dark.":"A texture to be used to display the light. If you don't specify a texture, the light is rendered as fading from bright, in its center, to dark.","Light":"Light","Displays a light on the scene, with a customizable radius and color. Add then the Light Obstacle behavior to the objects that must act as obstacle to the lights.":"Displays a light on the scene, with a customizable radius and color. Add then the Light Obstacle behavior to the objects that must act as obstacle to the lights.","Set the radius of light object":"Set the radius of light object","Set the radius of _PARAM0_ to: _PARAM1_":"Set the radius of _PARAM0_ to: _PARAM1_","Set the color of light object":"Set the color of light object","Set the color of light object in format \"R;G;B\" string.":"Set the color of light object in format \"R;G;B\" string.","Set the color of _PARAM0_ to: _PARAM1_":"Set the color of _PARAM0_ to: _PARAM1_","Tweening":"Tweening","Animate object properties over time. This allows smooth transitions, animations or movement of objects to specified positions.":"Animate object properties over time. This allows smooth transitions, animations or movement of objects to specified positions.","Tween":"Interpola\xE7\xE3o","Smoothly animate position, angle, scale and other properties of the object.":"Smoothly animate position, angle, scale and other properties of the object.","Add object variable tween":"Adicionar interpola\xE7\xE3o vari\xE1vel de object","Add a tween animation for an object variable.":"Adicionar uma interpola\xE7\xE3o de anima\xE7\xE3o para uma vari\xE1vel de object.","Tween the variable _PARAM3_ of _PARAM0_ from _PARAM4_ to _PARAM5_ with easing _PARAM6_ over _PARAM7_ms as _PARAM2_":"Interpolar a vari\xE1vel _PARAM3_ do _PARAM0_ de _PARAM4_ para _PARAM5_ com flexibiliza\xE7\xE3o _PARAM6_ sobre _PARAM7_ms como _PARAM2_","Variables":"Vari\xE1veis","Tween Identifier":"Identificador de interpola\xE7\xE3o","From value":"Do valor","To value":"Para valor","Easing":"Flexibiliza\xE7\xE3o","Destroy this object when tween finishes":"Destruir este object quando a interpola\xE7\xE3o terminar","Add object position tween":"Adicionar posi\xE7\xE3o do object interpolado","Add a tween animation for the object position.":"Adicionar uma anima\xE7\xE3o interpolada para a posi\xE7\xE3o do object.","Tween the position of _PARAM0_ to x: _PARAM3_, y: _PARAM4_ with easing _PARAM5_ over _PARAM6_ms as _PARAM2_":"Interpolar a posi\xE7\xE3o de _PARAM0_ para x: _PARAM3_, y: _PARAM4_ com flexibiliza\xE7\xE3o _PARAM5_ sobre _PARAM6_ms como _PARAM2_","To X":"Para X","To Y":"Para Y","Add object position X tween":"Adicionar posi\xE7\xE3o do object X interpolado","Add a tween animation for the object X position.":"Adicionar uma anima\xE7\xE3o interpolada para a posi\xE7\xE3o X do object.","Tween the X position of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Interpolar a posi\xE7\xE3o X de _PARAM0_ at\xE9 _PARAM3_ com flexibiliza\xE7\xE3o _PARAM4_ sobre _PARAM5_ms como _PARAM2_","Add object width tween":"Add object width tween","Add a tween animation for the object width.":"Add a tween animation for the object width.","Tween the width of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Tween the width of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_","To width":"To width","Add object height tween":"Add object height tween","Add a tween animation for the object height.":"Add a tween animation for the object height.","Tween the height of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Tween the height of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_","To height":"To height","Add object position Y tween":"Adicionar posi\xE7\xE3o do object Y interpolado","Add a tween animation for the object Y position.":"Adicionar uma anima\xE7\xE3o interpolada para a posi\xE7\xE3o Y do object.","Tween the Y position of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Interpolar a posi\xE7\xE3o Y de _PARAM0_ para _PARAM3_ com flexibiliza\xE7\xE3o _PARAM4_ sobre _PARAM5_ms como _PARAM2_","Add object angle tween":"Adicionar \xE2ngulo de object interpolado","Add a tween animation for the object angle.":"Adicionar uma anima\xE7\xE3o interpolada para o \xE2ngulo do object.","Tween the angle of _PARAM0_ to _PARAM3_\xB0 with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Interpolar o \xE2ngulo de _PARAM0_ para _PARAM3_\xB0 com flexibiliza\xE7\xE3o _PARAM4_ sobre _PARAM5_ms como _PARAM2_","To angle (in degrees)":"Para \xE2ngulo (em graus)","Add object scale tween":"Adicionar escala de object interpolado","Add a tween animation for the object scale (Note: the scale can never be less than 0).":"Adicionar uma anima\xE7\xE3o interpolada para a escala de object (Nota: a escala nunca pode ser menor que 0).","Tween the scale of _PARAM0_ to X-scale: _PARAM3_, Y-scale: _PARAM4_ (from center: _PARAM8_) with easing _PARAM5_ over _PARAM6_ms as _PARAM2_":"Tween the scale of _PARAM0_ to X-scale: _PARAM3_, Y-scale: _PARAM4_ (from center: _PARAM8_) with easing _PARAM5_ over _PARAM6_ms as _PARAM2_","To scale X":"Para escala X","To scale Y":"Para escala Y","Scale from center of object":"Scale from center of object","Add object X-scale tween":"Adicionar object escala-X interpolado","Add a tween animation for the object X-scale (Note: the scale can never be less than 0).":"Adicionar uma anima\xE7\xE3o interpolada para o object escala-X (Nota: a escala nunca pode ser menor que 0).","Tween the X-scale of _PARAM0_ to _PARAM3_ (from center: _PARAM7_) with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Tween the X-scale of _PARAM0_ to _PARAM3_ (from center: _PARAM7_) with easing _PARAM4_ over _PARAM5_ms as _PARAM2_","Add object Y-scale tween":"Adicionar object escala-Y interpolado","Add a tween animation for the object Y-scale (Note: the scale can never be less than 0).":"Adicionar uma anima\xE7\xE3o interpolada para o objeto escala-Y (Nota: a escala nunca pode ser menor que 0).","Tween the Y-scale of _PARAM0_ to _PARAM3_ (from center: _PARAM7_) with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Tween the Y-scale of _PARAM0_ to _PARAM3_ (from center: _PARAM7_) with easing _PARAM4_ over _PARAM5_ms as _PARAM2_","Add text size tween":"Adicionar tamanho do texto interpolado","Add a tween animation for the text object character size (Note: the size can never be less than 1).":"Adicionar uma anima\xE7\xE3o interpolada para o tamanho do caractere do object de texto (Nota: o tamanho nunca pode ser menor que 1).","Tween the character size of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Interpolar o tamanho da personagem de _PARAM0_ para _PARAM3_ com flexibiliza\xE7\xE3o _PARAM4_ sobre _PARAM5_ms como _PARAM2_","To character size":"Para o tamanho da personagem","Add object opacity tween":"Adicionar interpola\xE7\xE3o da opacidade do object","Add a tween animation for the object opacity (Value between 0 and 255).":"Adicionar uma interpola\xE7\xE3o de anima\xE7\xE3o para a opacidade do object (valor entre 0 e 255).","Tween the opacity of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Interpolar a opacidade de _PARAM0_ para _PARAM3_ com flexibiliza\xE7\xE3o _PARAM4_ sobre _PARAM5_ms como _PARAM2_","To opacity":"Para opacidade","Add object color tween":"Adicionar interpola\xE7\xE3o da cor do object","Add a tween animation for the object color. Format: \"128;200;255\" with values between 0 and 255 for red, green and blue":"Adicionar uma interpola\xE7\xE3o de anima\xE7\xE3o para a cor do object. Formato: \"128; 200; 255\" com valores entre 0 e 255 para vermelho, verde e azul","Tween the color of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_":"Interpolar a cor de _PARAM0_ para _PARAM3_ com flexibiliza\xE7\xE3o _PARAM4_ sobre _PARAM5_ms como _PARAM2_","To color":"Para cor","Tween on the Hue/Saturation/Lightness (HSL)":"Tween on the Hue/Saturation/Lightness (HSL)","Useful to have a more natural change between colors.":"Useful to have a more natural change between colors.","Add object HSL color tween":"Add object HSL color tween","Add a tween animation for the object color using Hue/Saturation/Lightness. Hue can be any number, Saturation and Lightness are between 0 and 100. Use -1 for Saturation and Lightness to let them unchanged.":"Add a tween animation for the object color using Hue/Saturation/Lightness. Hue can be any number, Saturation and Lightness are between 0 and 100. Use -1 for Saturation and Lightness to let them unchanged.","Tween the color of _PARAM0_ using HSL to H: _PARAM3_ (_PARAM4_), S: _PARAM5_, L: _PARAM6_ with easing _PARAM7_ over _PARAM8_ms as _PARAM2_":"Tween the color of _PARAM0_ using HSL to H: _PARAM3_ (_PARAM4_), S: _PARAM5_, L: _PARAM6_ with easing _PARAM7_ over _PARAM8_ms as _PARAM2_","To Hue":"To Hue","Animate Hue":"Animate Hue","To Saturation (-1 to ignore)":"To Saturation (-1 to ignore)","To Lightness (-1 to ignore)":"To Lightness (-1 to ignore)","Tween exists":"Existe interpola\xE7\xE3o","Check if the tween animation exists.":"Verificar se a interpola\xE7\xE3o da anima\xE7\xE3o existe.","Tween _PARAM2_ on _PARAM0_ exists":"Interpola\xE7\xE3o _PARAM2_ no _PARAM0_ existe","Tween is playing":"Interpola\xE7\xE3o est\xE1 a reproduzir","Check if the tween animation is currently playing.":"Verificar se a anima\xE7\xE3o de interpola\xE7\xE3o est\xE1 neste momento a ser reproduzida.","Tween _PARAM2_ on _PARAM0_ is playing":"Interpola\xE7\xE3o _PARAM2_ no _PARAM0_ est\xE1 a ser reproduzida","Tween finished playing":"Interpola\xE7\xE3o terminou a reprodu\xE7\xE3o","Check if the tween animation has finished playing.":"Verificar se a anima\xE7\xE3o de interpola\xE7\xE3o terminou de reproduzir.","Tween _PARAM2_ on _PARAM0_ has finished playing":"Interpola\xE7\xE3o _PARAM2_ no _PARAM0_ terminou de reproduzir","Pause a tween":"Pausar a interpola\xE7\xE3o","Pause the running tween animation.":"Pausar a anima\xE7\xE3o de interpola\xE7\xE3o em execu\xE7\xE3o.","Pause the tween _PARAM2_ on _PARAM0_":"Pausar a interpola\xE7\xE3o _PARAM2_ no _PARAM0_","Stop a tween":"Parar uma interpola\xE7\xE3o","Stop the running tween animation.":"Parar a anima\xE7\xE3o de interpola\xE7\xE3o em execu\xE7\xE3o.","Stop the tween _PARAM2_ on _PARAM0_":"Parar a interpola\xE7\xE3o _PARAM2_ no _PARAM0_","Jump to end":"Saltar para o fim","Resume a tween":"Retomar uma interpola\xE7\xE3o","Resume the tween animation.":"Retomar a anima\xE7\xE3o de interpola\xE7\xE3o.","Resume the tween _PARAM2_ on _PARAM0_":"Retomar a interpola\xE7\xE3o _PARAM2_ no _PARAM0_","Remove a tween":"Remover uma interpola\xE7\xE3o","Remove the tween animation from the object.":"Remover a anima\xE7\xE3o de interpola\xE7\xE3o do object.","Remove the tween _PARAM2_ from _PARAM0_":"Remover a interpola\xE7\xE3o _PARAM2_ de _PARAM0_","Progress of a tween":"Progresso de uma interpola\xE7\xE3o","Progress of a tween (between 0.0 and 1.0)":"Progresso de uma interpola\xE7\xE3o (entre 0.0 e 1.0)","Adjustment":"Adjustment","Adjust gamma, contrast, saturation, brightness, alpha or color-channel shift.":"Adjust gamma, contrast, saturation, brightness, alpha or color-channel shift.","Gamma (between 0 and 5)":"Gamma (between 0 and 5)","Saturation (between 0 and 5)":"Saturation (between 0 and 5)","Contrast (between 0 and 5)":"Contrast (between 0 and 5)","Brightness (between 0 and 5)":"Brightness (between 0 and 5)","Red (between 0 and 5)":"Red (between 0 and 5)","Green (between 0 and 5)":"Green (between 0 and 5)","Blue (between 0 and 5)":"Blue (between 0 and 5)","Alpha (between 0 and 1, 0 is transparent)":"Alpha (between 0 and 1, 0 is transparent)","Advanced bloom":"Advanced bloom","Applies a bloom effect.":"Applies a bloom effect.","Threshold (between 0 and 1)":"Threshold (between 0 and 1)","Bloom Scale (between 0 and 2)":"Bloom Scale (between 0 and 2)","Brightness (between 0 and 2)":"Brightness (between 0 and 2)","Blur (between 0 and 20)":"Blur (between 0 and 20)","Quality (between 0 and 20)":"Quality (between 0 and 20)","Padding for the visual effect area":"Padding for the visual effect area","ASCII":"ASCII","Render the image with ASCII characters only.":"Render the image with ASCII characters only.","Size (between 2 and 20)":"Size (between 2 and 20)","Beveled edges":"Beveled edges","Add beveled edges around the rendered image.":"Add beveled edges around the rendered image.","Rotation (between 0 and 360)":"Rotation (between 0 and 360)","Outer strength (between 0 and 5)":"Outer strength (between 0 and 5)","Distance (between 10 and 20)":"Distance (between 10 and 20)","Light alpha (between 0 and 1)":"Light alpha (between 0 and 1)","Light color (color of the outline)":"Light color (color of the outline)","Shadow color (color of the outline)":"Shadow color (color of the outline)","Shadow alpha (between 0 and 1)":"Shadow alpha (between 0 and 1)","Black and White":"Black and White","Alter the colors to make the image black and white":"Alter the colors to make the image black and white","Opacity (between 0 and 1)":"Opacity (between 0 and 1)","Blending mode":"Blending mode","Alter the rendered image with the specified blend mode.":"Alter the rendered image with the specified blend mode.","Mode (0: Normal, 1: Add, 2: Multiply, 3: Screen)":"Mode (0: Normal, 1: Add, 2: Multiply, 3: Screen)","Blur (Gaussian, slow - prefer to use Kawase blur)":"Blur (Gaussian, slow - prefer to use Kawase blur)","Blur the rendered image. This is slow, so prefer to use Kawase blur in most cases.":"Blur the rendered image. This is slow, so prefer to use Kawase blur in most cases.","Blur intensity":"Blur intensity","Number of render passes. An high value will cause lags/poor performance.":"Number of render passes. An high value will cause lags/poor performance.","Resolution":"Resolution","Kernel size (one of these values: 5, 7, 9, 11, 13, 15)":"Kernel size (one of these values: 5, 7, 9, 11, 13, 15)","Brightness":"Brightness","Make the image brighter.":"Make the image brighter.","Brightness (between 0 and 1)":"Brightness (between 0 and 1)","Bulge Pinch":"Bulge Pinch","Bulges or pinches the image in a circle.":"Bulges or pinches the image in a circle.","Center X (between 0 and 1, 0.5 is image middle)":"Center X (between 0 and 1, 0.5 is image middle)","Center Y (between 0 and 1, 0.5 is image middle)":"Center Y (between 0 and 1, 0.5 is image middle)","strength (between -1 and 1)":"strength (between -1 and 1)","-1 is strong pinch, 0 is no effect, 1 is strong bulge":"-1 is strong pinch, 0 is no effect, 1 is strong bulge","Color Map":"Color Map","Change the color rendered on screen.":"Change the color rendered on screen.","Color map texture for the effect":"Color map texture for the effect","You can change colors of pixels by modifing a reference color image, containing each colors, called the *Color Map Texture*. To get started, **download** [a default color map texture here](http://wiki.compilgames.net/doku.php/gdevelop5/interface/scene-editor/layer-effects).":"You can change colors of pixels by modifing a reference color image, containing each colors, called the *Color Map Texture*. To get started, **download** [a default color map texture here](http://wiki.compilgames.net/doku.php/gdevelop5/interface/scene-editor/layer-effects).","Disable anti-aliasing (\"nearest\" pixel rounding)":"Disable anti-aliasing (\"nearest\" pixel rounding)","Mix":"Mix","Mix value of the effect on the layer (in percent)":"Mix value of the effect on the layer (in percent)","Color Replace":"Color Replace","Effect replacing a color (or similar) by another.":"Effect replacing a color (or similar) by another.","Original Color":"Original Color","New Color":"New Color","Epsilon (between 0 and 1)":"Epsilon (between 0 and 1)","Tolerance/sensitivity of the floating-point comparison between colors (lower = more exact, higher = more inclusive)":"Tolerance/sensitivity of the floating-point comparison between colors (lower = more exact, higher = more inclusive)","CRT":"CRT","Apply an effect resembling old CRT monitors.":"Apply an effect resembling old CRT monitors.","Line width (between 0 and 5)":"Line width (between 0 and 5)","Line contrast (between 0 and 1)":"Line contrast (between 0 and 1)","Noise (between 0 and 1)":"Noise (between 0 and 1)","Curvature (between 0 and 10)":"Curvature (between 0 and 10)","Show vertical lines":"Show vertical lines","Noise size (between 0 and 10)":"Noise size (between 0 and 10)","Vignetting (between 0 and 1)":"Vignetting (between 0 and 1)","Vignetting alpha (between 0 and 1)":"Vignetting alpha (between 0 and 1)","Vignetting blur (between 0 and 1)":"Vignetting blur (between 0 and 1)","Interlaced Lines Speed":"Interlaced Lines Speed","0: Pause, 0.5: Half speed, 1: Normal speed, 2: Double speed, etc...":"0: Pause, 0.5: Half speed, 1: Normal speed, 2: Double speed, etc...","Noise Frequency":"Noise Frequency","Uses the pixel values from the specified texture (called the displacement map) to perform a displacement of an object.":"Uses the pixel values from the specified texture (called the displacement map) to perform a displacement of an object.","Displacement map texture":"Displacement map texture","Displacement map texture for the effect. To get started, **download** [a default displacement map texture here](http://wiki.compilgames.net/doku.php/gdevelop5/interface/scene-editor/layer-effects).":"Displacement map texture for the effect. To get started, **download** [a default displacement map texture here](http://wiki.compilgames.net/doku.php/gdevelop5/interface/scene-editor/layer-effects).","Dot":"Dot","Applies a dotscreen effect making objects appear to be made out of black and white halftone dots like an old printer.":"Applies a dotscreen effect making objects appear to be made out of black and white halftone dots like an old printer.","Scale (between 0.3 and 1)":"Scale (between 0.3 and 1)","Angle (between 0 and 5)":"Angle (between 0 and 5)","Drop shadow":"Drop shadow","Add a shadow around the rendered image.":"Add a shadow around the rendered image.","Quality (between 1 and 20)":"Quality (between 1 and 20)","Alpha (between 0 and 1)":"Alpha (between 0 and 1)","Distance (between 0 and 50)":"Distance (between 0 and 50)","Color of the shadow":"Color of the shadow","Shadow only (shows only the shadow when enabled)":"Shadow only (shows only the shadow when enabled)","Glitch":"Glitch","Applies a glitch effect to an object.":"Applies a glitch effect to an object.","Slices (between 2 and infinite)":"Slices (between 2 and infinite)","Offset (between -400 and 400)":"Offset (between -400 and 400)","Direction (between -180 and 180)":"Direction (between -180 and 180)","Fill Mode (between 0 and 4)":"Fill Mode (between 0 and 4)","The fill mode of the space after the offset.(0: TRANSPARENT, 1: ORIGINAL, 2: LOOP, 3: CLAMP, 4: MIRROR)":"The fill mode of the space after the offset.(0: TRANSPARENT, 1: ORIGINAL, 2: LOOP, 3: CLAMP, 4: MIRROR)","Average":"Average","Min Size":"Min Size","Sample Size":"Sample Size","Animation Frequency":"Animation Frequency","Red X offset (between -50 and 50)":"Red X offset (between -50 and 50)","Red Y offset (between -50 and 50)":"Red Y offset (between -50 and 50)","Green X offset (between -50 and 50)":"Green X offset (between -50 and 50)","Green Y offset (between -50 and 50)":"Green Y offset (between -50 and 50)","Blue X offset (between -50 and 50)":"Blue X offset (between -50 and 50)","Blue Y offset (between -50 and 50)":"Blue Y offset (between -50 and 50)","Glow":"Glow","Add a glow effect around the rendered image.":"Add a glow effect around the rendered image.","Inner strength (between 0 and 20)":"Inner strength (between 0 and 20)","Outer strength (between 0 and 20)":"Outer strength (between 0 and 20)","Color (color of the outline)":"Color (color of the outline)","Godray":"Godray","Apply and animate atmospheric light rays.":"Apply and animate atmospheric light rays.","Parallel (parallel rays)":"Parallel (parallel rays)","Animation Speed":"Animation Speed","Lacunarity (between 0 and 5)":"Lacunarity (between 0 and 5)","Angle (between -60 and 60)":"Angle (between -60 and 60)","Gain (between 0 and 1)":"Gain (between 0 and 1)","Light (between 0 and 60)":"Light (between 0 and 60)","Center X (between 100 and 1000)":"Center X (between 100 and 1000)","Center Y (between -1000 and 100)":"Center Y (between -1000 and 100)","Blur (Kawase, fast)":"Blur (Kawase, fast)","Blur the rendered image, with much better performance than Gaussian blur.":"Blur the rendered image, with much better performance than Gaussian blur.","Pixelize X (between 0 and 10)":"Pixelize X (between 0 and 10)","Pixelize Y (between 0 and 10)":"Pixelize Y (between 0 and 10)","Light Night":"Light Night","Alter the colors to simulate night.":"Alter the colors to simulate night.","Dark Night":"Dark Night","Alter the colors to simulate a dark night.":"Alter the colors to simulate a dark night.","Intensity (between 0 and 1)":"Intensity (between 0 and 1)","Noise":"Noise","Add some noise on the rendered image.":"Add some noise on the rendered image.","Noise intensity (between 0 and 1)":"Noise intensity (between 0 and 1)","Old Film":"Old Film","Add a Old film effect around the rendered image.":"Add a Old film effect around the rendered image.","Sepia (between 0 and 1)":"Sepia (between 0 and 1)","The amount of saturation of sepia effect, a value of 1 is more saturation and closer to 0 is less, and a value of 0 produces no sepia effect":"The amount of saturation of sepia effect, a value of 1 is more saturation and closer to 0 is less, and a value of 0 produces no sepia effect","Noise Size (between 0 and 10)":"Noise Size (between 0 and 10)","Scratch (between -1 and 1)":"Scratch (between -1 and 1)","Scratch Density (between 0 and 1)":"Scratch Density (between 0 and 1)","Scratch Width (between 1 and 20)":"Scratch Width (between 1 and 20)","Vignetting Alpha (between 0 and 1)":"Vignetting Alpha (between 0 and 1)","Vignetting Blur (between 0 and 1)":"Vignetting Blur (between 0 and 1)","Draws an outline around the rendered image.":"Draws an outline around the rendered image.","Thickness (between 0 and 20)":"Thickness (between 0 and 20)","Color of the outline":"Color of the outline","Pixelate":"Pixelate","Applies a pixelate effect, making display objects appear 'blocky'.":"Applies a pixelate effect, making display objects appear 'blocky'.","Size of the pixels (10 pixels by default)":"Size of the pixels (10 pixels by default)","Radial Blur":"Radial Blur","Applies a Motion blur to an object.":"Applies a Motion blur to an object.","The maximum size of the blur radius, -1 is infinite":"The maximum size of the blur radius, -1 is infinite","Angle (between -180 and 180)":"Angle (between -180 and 180)","The angle in degree of the motion for blur effect":"The angle in degree of the motion for blur effect","Kernel Size (between 3 and 25)":"Kernel Size (between 3 and 25)","The kernel size of the blur filter (Odd number)":"The kernel size of the blur filter (Odd number)","Reflection":"Reflection","Applies a reflection effect to simulate the reflection on water with waves.":"Applies a reflection effect to simulate the reflection on water with waves.","Reflect the image on the waves":"Reflect the image on the waves","Vertical position of the reflection point":"Vertical position of the reflection point","Default is 50% (middle). Smaller numbers produce a larger reflection, larger numbers produce a smaller reflection.":"Default is 50% (middle). Smaller numbers produce a larger reflection, larger numbers produce a smaller reflection.","Amplitude start":"Amplitude start","Starting amplitude of waves (0 by default)":"Starting amplitude of waves (0 by default)","Amplitude ending":"Amplitude ending","Ending amplitude of waves (20 by default)":"Ending amplitude of waves (20 by default)","Wave length start":"Wave length start","Starting wave length (30 by default)":"Starting wave length (30 by default)","Wave length ending":"Wave length ending","Ending wave length (100 by default)":"Ending wave length (100 by default)","Alpha start":"Alpha start","Starting alpha (1 by default)":"Starting alpha (1 by default)","Alpha ending":"Alpha ending","Ending alpha (1 by default)":"Ending alpha (1 by default)","RGB split (chromatic aberration)":"RGB split (chromatic aberration)","Applies a RGB split effect also known as chromatic aberration.":"Applies a RGB split effect also known as chromatic aberration.","Red X offset (between -20 and 20)":"Red X offset (between -20 and 20)","Red Y offset (between -20 and 20)":"Red Y offset (between -20 and 20)","Green X offset (between -20 and 20)":"Green X offset (between -20 and 20)","Green Y offset (between -20 and 20)":"Green Y offset (between -20 and 20)","Blue X offset (between -20 and 20)":"Blue X offset (between -20 and 20)","Blue Y offset (between -20 and 20)":"Blue Y offset (between -20 and 20)","Sepia":"Sepia","Alter the colors to sepia.":"Alter the colors to sepia.","Tilt shift":"Tilt shift","Render a tilt-shift-like camera effect.":"Render a tilt-shift-like camera effect.","Blur (between 0 and 200)":"Blur (between 0 and 200)","Gradient blur (between 0 and 2000)":"Gradient blur (between 0 and 2000)","Twist":"Twist","Applies a twist effect making objects appear twisted in the given direction.":"Applies a twist effect making objects appear twisted in the given direction.","The radius of the twist":"The radius of the twist","Angle (between -10 and 10)":"Angle (between -10 and 10)","The angle in degree of the twist":"The angle in degree of the twist","Offset X (between 0 and 1, 0.5 is image middle)":"Offset X (between 0 and 1, 0.5 is image middle)","Offset Y (between 0 and 1, 0.5 is image middle)":"Offset Y (between 0 and 1, 0.5 is image middle)","Zoom blur":"Zoom blur","Applies a Zoom blur.":"Applies a Zoom blur.","Inner radius":"Inner radius","strength (between 0 and 5)":"strength (between 0 and 5)","Peer-to-Peer communication (experimental)":"Peer-to-Peer communication (experimental)","Event triggered by peer":"Event triggered by peer","Triggers once when a connected client sends the event":"Triggers once when a connected client sends the event","Event _PARAM0_ received from other client (data loss: _PARAM1_)":"Event _PARAM0_ received from other client (data loss: _PARAM1_)","P2P (experimental)":"P2P (experimental)","Event name":"Event name","Data loss allowed?":"Data loss allowed?","Is P2P ready":"Is P2P ready","True if the peer-to-peer extension initialized and is ready to use.":"True if the peer-to-peer extension initialized and is ready to use.","Is P2P ready?":"Is P2P ready?","An error occurred":"An error occurred","Triggers once when an error occurs. Use P2P::GetLastError() expression to get the content of the error if you want to analyse it or display it to the user.":"Triggers once when an error occurs. Use P2P::GetLastError() expression to get the content of the error if you want to analyse it or display it to the user.","P2P error occurred":"P2P error occurred","Peer disconnected":"Peer disconnected","Triggers once when a peer disconnects.":"Triggers once when a peer disconnects.","P2P peer disconnected":"P2P peer disconnected","Peer Connected":"Peer Connected","Triggers once when a remote peer initiates a connection.":"Triggers once when a remote peer initiates a connection.","P2P peer connected":"P2P peer connected","Connect to another client":"Connect to another client","Connects the current client to another client using its id.":"Connects the current client to another client using its id.","Connect to P2P client _PARAM0_":"Connect to P2P client _PARAM0_","ID of the other client":"ID of the other client","Connect to a broker server":"Connect to a broker server","Connects the extension to a broker server.":"Connects the extension to a broker server.","Connect to the broker server at http://_PARAM0_:_PARAM1_/":"Connect to the broker server at http://_PARAM0_:_PARAM1_/","Host":"Host","Port":"Port","SSl enabled?":"SSl enabled?","Connect to the default broker server":"Connect to the default broker server","Connects to the default broker server.":"Connects to the default broker server.","Override the client ID":"Override the client ID","Overrides the client ID of the current game instance with a specified ID. Must be called BEFORE connecting to a broker.":"Overrides the client ID of the current game instance with a specified ID. Must be called BEFORE connecting to a broker.","Override the client ID with _PARAM0_":"Override the client ID with _PARAM0_","ID":"ID","Trigger event on all connected clients":"Trigger event on all connected clients","Triggers an event on all connected clients":"Triggers an event on all connected clients","Trigger event _PARAM0_ on all connected clients (extra data: _PARAM1_)":"Trigger event _PARAM0_ on all connected clients (extra data: _PARAM1_)","Extra data (optional)":"Extra data (optional)","Trigger event on a specific client":"Trigger event on a specific client","Triggers an event on a specific connected client":"Triggers an event on a specific connected client","Trigger event _PARAM1_ on client _PARAM0_ (extra data: _PARAM2_)":"Trigger event _PARAM1_ on client _PARAM0_ (extra data: _PARAM2_)","Trigger event on all connected clients (variable)":"Trigger event on all connected clients (variable)","Variable containing the extra data":"Variable containing the extra data","Trigger event on a specific client (variable)":"Trigger event on a specific client (variable)","Get event data (variable)":"Get event data (variable)","Store the data of the specified event in a variable. Check in the conditions that the event was received using the \"Event received\" condition.":"Store the data of the specified event in a variable. Check in the conditions that the event was received using the \"Event received\" condition.","Overwrite _PARAM1_ with variable sent with last trigger of _PARAM0_":"Overwrite _PARAM1_ with variable sent with last trigger of _PARAM0_","Variable where to store the received data":"Variable where to store the received data","Disconnect from a peer":"Disconnect from a peer","Disconnects this client from another client.":"Disconnects this client from another client.","Disconnect from client _PARAM0_":"Disconnect from client _PARAM0_","Disconnect from all peers":"Disconnect from all peers","Disconnects this client from all other clients.":"Disconnects this client from all other clients.","Disconnect from all clients":"Disconnect from all clients","Disconnect from broker":"Disconnect from broker","Disconnects the client from the broker server.":"Disconnects the client from the broker server.","Disconnect the client from the broker":"Disconnect the client from the broker","Disconnect from all":"Disconnect from all","Disconnects the client from the broker server and all other clients.":"Disconnects the client from the broker server and all other clients.","Disconnect the client from the broker and other clients":"Disconnect the client from the broker and other clients","Get event data":"Get event data","Returns the data received when the specified event was last triggered":"Returns the data received when the specified event was last triggered","Get event sender":"Get event sender","Returns the id of the peer that triggered the event":"Returns the id of the peer that triggered the event","Get client ID":"Get client ID","Gets the client ID of the current game instance":"Gets the client ID of the current game instance","Get last error":"Get last error","Gets the description of the last P2P error":"Gets the description of the last P2P error","Get last disconnected peer":"Get last disconnected peer","Gets the ID of the latest peer that has disconnected.":"Gets the ID of the latest peer that has disconnected.","Get ID of the connected peer":"Get ID of the connected peer","Gets the ID of the newly connected peer.":"Gets the ID of the newly connected peer.","Allow your game to send scores and interact with the Facebook Instant Games platform.":"Allow your game to send scores and interact with the Facebook Instant Games platform.","Save player data":"Salvar dados do jogador","Save the content of the given scene variable in the player data, stored on Facebook Instant Games servers":"Save the content of the given scene variable in the player data, stored on Facebook Instant Games servers","Save the content of _PARAM1_ in key _PARAM0_ of player data (store success message in _PARAM2_ or error in _PARAM3_)":"Salvar o conte\xFAdo de _PARAM1_ na chave _PARAM0_ dos dados do jogador (armazenar a mensagem de sucesso em _PARAM2_ ou erro em _PARAM3_)","Facebook Instant Games/Player data":"Jogos instant\xE2neos do Facebook/Dados do jogador","Variable where to store the success message (optional)":"Vari\xE1vel onde armazenar a mensagem de sucesso (opcional)","Variable where to store the error message (optional, if an error occurs)":"Variable where to store the error message (optional, if an error occurs)","Load player data":"Carregar dados do jogador","Load the player data with the given key in a variable":"Carregar os dados do jogador com a chave dada numa vari\xE1vel","Load player data with key _PARAM0_ in _PARAM1_ (or error in _PARAM2_)":"Carregar os dados do jogador com a chave _PARAM0_ em _PARAM1_ (ou erro em _PARAM2_)","Data key name (e.g: \"Lives\")":"Nome da chave de dados (por exemplo, \"Vidas\")","Variable where to store loaded data":"Vari\xE1vel onde armazenar dados carregados","Save player score":"Salvar pontua\xE7\xE3o do jogador","Save the score, and optionally the content of the given variable in the player score, for the given metadata.":"Salvar a pontua\xE7\xE3o, e opcionalmente o conte\xFAdo da vari\xE1vel fornecida na pontua\xE7\xE3o do jogador, para os metadados fornecidos.","In leaderboard _PARAM0_, save score _PARAM1_ for the player and extra data from _PARAM2_ (store success message in _PARAM3_ or error in _PARAM4_)":"No quadro de l\xEDderes _PARAM 0_, salvar pontua\xE7\xE3o _PARAM 1_ para o jogador e dados extra de _PARAM2_ (armazenar mensagem de sucesso em _PARAM3_ ou o erro em _PARAM4_)","Facebook Instant Games/Leaderboards":"Jogos Instant\xE2neos do Facebook/Quadros de lideran\xE7a","Optional variable with metadata to save":"Vari\xE1vel opcional com metadados para salvar","Load player entry":"Carregar entrada do jogador","Load the player entry in the given leaderboard":"Carregar a entrada do jogador no quadro de l\xEDderes escolhido","Load player entry from leaderboard _PARAM0_. Set rank in _PARAM1_, score in _PARAM2_ (extra data if any in _PARAM3_ and error in _PARAM4_)":"Carregar a entrada do jogador do quadro de l\xEDderes _PARAM0_. Definir classifica\xE7\xE3o em _PARAM1_, pontua\xE7\xE3o em _PARAM2_ (dados extra se houver em _PARAM3_ e erro em _PARAM4_)","Leaderboard name (e.g: \"PlayersBestTimes\")":"Nome do Quadro de lideran\xE7a (ex: PlayersBestTimes\")","Variable where to store the player rank (of -1 if not ranked)":"Vari\xE1vel onde armazenar a classifica\xE7\xE3o do jogador (de -1 se n\xE3o for classificado)","Variable where to store the player score (of -1 if no score)":"Vari\xE1vel onde armazenar a pontua\xE7\xE3o do jogador (de -1 se n\xE3o houver pontua\xE7\xE3o)","Variable where to store extra data (if any)":"Vari\xE1vel onde armazenar dados extra (se houver)","Check if ads are supported":"Verificar se os an\xFAncios s\xE3o suportados","Check if showing ads is supported on this device (only mobile phones can show ads)":"Verificar se a exibi\xE7\xE3o de an\xFAncios \xE9 suportada neste dispositivo (somente telem\xF3veis podem exibir an\xFAncios)","Ads can be shown on this device":"An\xFAncios podem ser exibidos neste dispositivo","Facebook Instant Games/Ads":"Jogos Instant\xE2neos do Facebook/An\xFAncios","Is the interstitial ad ready":"O an\xFAncio intersticial est\xE1 pronto","Check if the interstitial ad requested from Facebook is loaded and ready to be shown.":"Verificar se o an\xFAncio intersticial solicitado do Facebook est\xE1 carregado e pronto para ser exibido.","The interstitial ad is loaded and ready to be shown":"O an\xFAncio intersticial est\xE1 carregado e pronto para ser exibido","Load and prepare an interstitial ad":"Carregar e preparar um an\xFAncio intersticial","Request and load an interstitial ad from Facebook, so that it is ready to be shown.":"Solicitar e carregar um an\xFAncio intersticial do Facebook para que esteja pronto para ser exibido.","Request and load an interstitial ad from Facebook (ad placement id: _PARAM0_, error in _PARAM1_)":"Solicitar e carregar um an\xFAncio intersticial do Facebook (c\xF3digo de posicionamento do an\xFAncio: _PARAM0_, erro em _PARAM1_)","The Ad Placement id (can be found while setting up the ad on Facebook)":"O c\xF3digo de posicionamento do an\xFAncio (pode ser encontrado enquanto configura o an\xFAncio no Facebook)","Show the loaded interstitial ad":"Mostrar o an\xFAncio intersticial carregado","Show the interstitial ad previously loaded in memory. This won't work if you did not load the interstitial before.":"Mostrar o an\xFAncio intersticial carregado anteriormente na mem\xF3ria. Isto n\xE3o vai funcionar se voc\xEA n\xE3o carregou o intersticial antes.","Show the interstitial ad previously loaded in memory (if any error, store it in _PARAM0_)":"Mostrar o an\xFAncio intersticial carregado anteriormente na mem\xF3ria (se houver algum erro, armazene-o em _PARAM0_)","Is the rewarded video ready":"O v\xEDdeo premiado est\xE1 pronto","Check if the rewarded video requested from Facebook is loaded and ready to be shown.":"Verificar se o v\xEDdeo premiado solicitado pelo Facebook est\xE1 carregado e pronto para ser exibido.","The rewarded video is loaded and ready to be shown":"O v\xEDdeo premiado est\xE1 carregado e pronto para ser exibido","Load and prepare a rewarded video":"Carregar e preparar um v\xEDdeo premiado","Request and load a rewarded video from Facebook, so that it is ready to be shown.":"Solicitar e carregar um v\xEDdeo premiado do Facebook, para que esteja pronto para ser exibido.","Request and load a rewarded video from Facebook (ad placement id: _PARAM0_, error in _PARAM1_)":"Solicitar e carregar um v\xEDdeo premiado do Facebook (c\xF3digo de posicionamento do an\xFAncio: _PARAM0_, erro em _PARAM1_)","Show the loaded rewarded video":"Mostrar o v\xEDdeo premiado carregado","Show the rewarded video previously loaded in memory. This won't work if you did not load the video before.":"Mostrar o v\xEDdeo premiado carregado anteriormente na mem\xF3ria. Isto n\xE3o funcionar\xE1 se voc\xEA n\xE3o tiver carregado o v\xEDdeo antes.","Show the rewarded video previously loaded in memory (if any error, store it in _PARAM0_)":"Mostrar o v\xEDdeo premiado carregado anteriormente na mem\xF3ria (se houver algum erro, guarde-o em _PARAM0__)","Player identifier":"Identificador do jogador","Get the player unique identifier":"Obter o identificador \xFAnico do jogador","Player name":"Nome do jogador","Get the player name":"Obter o nome do jogador","Return <subject>.":"Return <subject>.","Compare <subject>.":"Compare <subject>.","Change <subject>.":"Change <subject>.","Modification's sign":"Sinal de modifica\xE7\xE3o","Change <subject> of _PARAM0_: <operator> <value>":"Change <subject> of _PARAM0_: <operator> <value>","Change <subject>: <operator> <value>":"Change <subject>: <operator> <value>","Value to compare":"Valor para comparar","<subject> of _PARAM0_ <operator> <value>":"<subject> of _PARAM0_ <operator> <value>","<subject> <operator> <value>":"<subject> <operator> <value>","Advanced control features":"Caracter\xEDsticas de controle avan\xE7ado","Advanced control features to be used in events.":"Advanced control features to be used in events.","Always":"Sempre","This condition always returns true (or always false, if the condition is inverted).":"This condition always returns true (or always false, if the condition is inverted).","Set number return value":"Set number return value","Set the return value of the events function to the specified number (to be used with \"Expression\" functions).":"Set the return value of the events function to the specified number (to be used with \"Expression\" functions).","Set return value to number _PARAM0_":"Set return value to number _PARAM0_","Set text return value":"Set text return value","Set the return value of the events function to the specified text (to be used with \"String Expression\" functions).":"Set the return value of the events function to the specified text (to be used with \"String Expression\" functions).","Set return value to text _PARAM0_":"Set return value to text _PARAM0_","Set condition return value":"Set condition return value","Set the return value of the Condition events function to either true (condition will pass) or false.":"Set the return value of the Condition events function to either true (condition will pass) or false.","Set return value of the condition to _PARAM0_":"Set return value of the condition to _PARAM0_","Check if a function parameter is set to true (or yes)":"Check if a function parameter is set to true (or yes)","Check if the specified function parameter (also called \"argument\") is set to True or Yes. If the argument is a string, an empty string is considered as \"false\". If it's a number, 0 is considered as \"false\".":"Check if the specified function parameter (also called \"argument\") is set to True or Yes. If the argument is a string, an empty string is considered as \"false\". If it's a number, 0 is considered as \"false\".","Parameter _PARAM0_ is true":"Parameter _PARAM0_ is true","Get function parameter value":"Get function parameter value","Get function parameter (also called \"argument\") value":"Get function parameter (also called \"argument\") value","Get function parameter text":"Get function parameter text","Get function parameter (also called \"argument\") text ":"Get function parameter (also called \"argument\") text ","Scene management features":"Recursos de gerenciamento de cena","Actions and conditions to manipulate the scenes during the game.":"Actions and conditions to manipulate the scenes during the game.","Random integer":"Random integer","Random":"Aleat\xF3rio","Maximum value":"Valor m\xE1ximo","Random integer in range":"Random integer in range","Minimum value":"Minimum value","Random float":"Random float","Random float in range":"Random float in range","Random value in steps":"Random value in steps","Step":"Step","Current scene name":"Nome da cena atual","Name of the current scene":"Nome da cena atual","At the beginning of the scene":"No in\xEDcio da cena","Is true only when scene just begins.":"S\xF3 \xE9 verdade (true) quando cena apenas come\xE7ar.","Scene just resumed":"Scene just resumed","The scene has just resumed after being paused.":"The scene has just resumed after being paused.","Change the scene":"Mudar a cena","Stop this scene and start the specified one instead.":"Interrompa esta cena e comece a especificada no lugar.","Change to scene _PARAM1_":"Change to scene _PARAM1_","Name of the new scene":"Nome da nova cena","Stop any other paused scenes?":"Parar quaisquer outras cenas em pausa?","Pause and start a new scene":"Pausar e iniciar uma nova cena","Pause this scene and start the specified one.\nLater, you can use the \"Stop and go back to previous scene\" action to go back to this scene.":"Pause this scene and start the specified one.\nLater, you can use the \"Stop and go back to previous scene\" action to go back to this scene.","Pause the scene and start _PARAM1_":"Pausar a cena e come\xE7ar _PARAM1_","Stop and go back to previous scene":"Parar e voltar \xE0 cena anterior","Stop this scene and go back to the previous paused one.\nTo pause a scene, use the \"Pause and start a new scene\" action.":"Stop this scene and go back to the previous paused one.\nTo pause a scene, use the \"Pause and start a new scene\" action.","Stop the scene and go back to the previous paused one":"Pare esta cena e volte para a cena anterior pausada","Quit the game":"Sair do jogo","Change background color":"Alterar a cor do fundo","Change the background color of the scene.":"Altere a cor do fundo da cena.","Set background color to _PARAM1_":"Cor do fundo definida para _PARAM1_","Disable input when focus is lost":"Desativar a entrada quando o foco for perdido","mouse buttons must be taken into account even\nif the window is not active.":"mouse buttons must be taken into account even\nif the window is not active.","Disable input when focus is lost: _PARAM1_":"Desactivar o input quando se perde o focus: _PARAM1_","Deactivate input when focus is lost":"Desativar a entrada quando o foco \xE9 perdido","Compare two numbers":"Compare two numbers","Compare the two numbers.":"Compare the two numbers.","_PARAM0_ _PARAM1_ _PARAM2_":"_PARAM0_ _PARAM1_ _PARAM2_","First expression":"Primeira express\xE3o","Second expression":"Segunda express\xE3o","Compare two strings":"Compare two strings","Compare the two strings.":"Compare the two strings.","First string expression":"First string expression","Second string expression":"Second string expression","Cameras and layers features":"Caracter\xEDsticas das c\xE2meras e camadas","Camera center X position":"Posi\xE7\xE3o X do centro da c\xE2mera","the X position of the center of a camera":"the X position of the center of a camera","the X position of camera _PARAM4_ (layer: _PARAM3_)":"the X position of camera _PARAM4_ (layer: _PARAM3_)","Layers and cameras":"Camadas e c\xE2meras","Layer (base layer if empty)":"Camada (camada de base, se estiver vazia)","Camera number (default : 0)":"N\xFAmero de c\xE2mera (padr\xE3o: 0)","Camera center Y position":"Posi\xE7\xE3o Y do centro da c\xE2mera","the Y position of the center of a camera":"the Y position of the center of a camera","the Y position of camera _PARAM4_ (layer: _PARAM3_)":"the Y position of camera _PARAM4_ (layer: _PARAM3_)","Width of a camera":"Largura de uma c\xE2mera","the width of a camera of a layer":"the width of a camera of a layer","the width of camera _PARAM2_ of layer _PARAM1_":"the width of camera _PARAM2_ of layer _PARAM1_","Camera number":"N\xFAmero da c\xE2mera","Height of a camera":"Altura de uma c\xE2mera","the height of a camera of a layer":"the height of a camera of a layer","the height of camera _PARAM2_ of layer _PARAM1_":"the height of camera _PARAM2_ of layer _PARAM1_","Angle of a camera of a layer":"\xC2ngulo de uma c\xE2mera de uma camada","the angle of rotation of a camera":"the angle of rotation of a camera","the angle of camera (layer: _PARAM3_, camera: _PARAM4_)":"the angle of camera (layer: _PARAM3_, camera: _PARAM4_)","Add a camera to a layer":"Adicione uma c\xE2mera a uma camada","This action adds a camera to a layer":"This action adds a camera to a layer","Add a camera to layer _PARAM1_":"Adicionar uma c\xE2mera \xE1 camada _PARAM1_","Render zone: Top left side: X Position (between 0 and 1)":"Zona de renderiza\xE7\xE3o: Parte superior do lado esquerdo: posi\xE7\xE3o X (entre 0 e 1)","Render zone: Top left side: Y Position (between 0 and 1)":"Zona de renderiza\xE7\xE3o: Parte superior do lado esquerdo: posi\xE7\xE3o Y (entre 0 e 1)","Render zone: Bottom right side: X Position (between 0 and 1)":"Zona de renderiza\xE7\xE3o: Parte inferior do lado direito: posi\xE7\xE3o X (entre 0 e 1)","Render zone: Bottom right side: Y Position (between 0 and 1)":"Zona de renderiza\xE7\xE3o: Parte inferior do lado direito: posi\xE7\xE3o Y (entre 0 e 1)","Delete a camera of a layer":"Apagar uma c\xE2mera de uma camada","Remove the specified camera from a layer":"Remover a c\xE2mera especificada de uma camada","Delete camera _PARAM2_ from layer _PARAM1_":"Apagar _PARAM2_ c\xE2mera de camada _PARAM1_","Modify the size of a camera":"Modificar o tamanho de uma c\xE2mera","This action modifies the size of a camera of the specified layer. The zoom will be reset.":"This action modifies the size of a camera of the specified layer. The zoom will be reset.","Change the size of camera _PARAM2_ of _PARAM1_ to _PARAM3_*_PARAM4_":"Alterar o tamanho da c\xE2mera _PARAM2_ de _PARAM1_ de _PARAM3_ * _PARAM4_","Modify the render zone of a camera":"Modificar a zona de render de uma c\xE2mera","This action modifies the render zone of a camera of the specified layer.":"This action modifies the render zone of a camera of the specified layer.","Set the render zone of camera _PARAM2_ from layer _PARAM1_ to _PARAM3_;_PARAM4_ _PARAM5_;_PARAM6_":"Defina a zona de renderiza\xE7\xE3o da c\xE2mera _PARAM2_ da camada de _PARAM1_ para PARAM3_; _PARAM4_ _PARAM5_; _PARAM6_","Change camera zoom":"Change camera zoom","Change camera zoom.":"Mudar zoom da c\xE2mera.","Change camera zoom to _PARAM1_ (layer: _PARAM2_, camera: _PARAM3_)":"Change camera zoom to _PARAM1_ (layer: _PARAM2_, camera: _PARAM3_)","Value (1:Initial zoom, 2:Zoom x2, 0.5:Unzoom x2...)":"Valor ( 1: Zoom inicial, 2: Zoom x 2, 0,5: Unzoom X2...)","Center the camera on an object within limits":"Centar a c\xE2mera em um objeto dentro dos limites","Center the camera on the specified object, without leaving the specified limits.":"Centrar a c\xE2mera no objeto especificado, sem deixar os limites especificados.","Center the camera on _PARAM1_ (limit : from _PARAM2_;_PARAM3_ to _PARAM4_;_PARAM5_) (layer: _PARAM7_, camera: _PARAM8_)":"Centralizar a c\xE2mera em _PARAM1_ (limite: de _PARAM2_; _PARAM3_ para _PARAM4_; _PARAM5_) (camada: _PARAM7_, c\xE2mera: _PARAM8_)","Top left side of the boundary: X Position":"Lado superior esquerdo das bordas: Posi\xE7\xE3o X","Top left side of the boundary: Y Position":"Lado superior esquerdo das bordas: Posi\xE7\xE3o Y","Bottom right side of the boundary: X Position":"Parte inferior direita das bordas: Posi\xE7\xE3o X","Bottom right side of the boundary: Y Position":"Parte inferior direita das bordas: Posi\xE7\xE3o Y","Anticipate the movement of the object (yes by default)":"Antecipar o movimento do objeto (sim por padr\xE3o)","Center the camera on an object":"Centro da c\xE2mera em um objeto","Center the camera on the specified object.":"Centro da c\xE2mera no objeto especifico.","Center camera on _PARAM1_ (layer: _PARAM3_, camera: _PARAM4_)":"Centralizar a c\xE2mera _PARAM1_ (camada: _PARAM3_, c\xE2mera: _PARAM4_)","Show a layer":"Mostrar uma camada","Show a layer.":"Mostrar uma camada.","Show layer _PARAM1_":"Mostrar a camada _PARAM1_","Hide a layer":"Ocultar uma camada","Hide a layer.":"Ocultar uma camada.","Hide layer _PARAM1_":"Ocultar a camada _PARAM1_","Visibility of a layer":"Visibilidade de uma camada","Test if a layer is set as visible.":"Test if a layer is set as visible.","Layer _PARAM1_ is visible":"_PARAM1_ camada \xE9 vis\xEDvel","Effect parameter (number)":"Effect parameter (number)","Change the value of a parameter of an effect.":"Change the value of a parameter of an effect.","You can find the parameter names (and change the effect names) in the effects window.":"You can find the parameter names (and change the effect names) in the effects window.","Set _PARAM3_ to _PARAM4_ for effect _PARAM2_ of layer _PARAM1_":"Set _PARAM3_ to _PARAM4_ for effect _PARAM2_ of layer _PARAM1_","Layers and cameras/Effects":"Layers and cameras/Effects","Effect name":"Effect name","Parameter name":"Nome do par\xE2metro","Effect parameter (string)":"Effect parameter (string)","Change the value (string) of a parameter of an effect.":"Change the value (string) of a parameter of an effect.","Effect parameter (enable or disable)":"Effect parameter (enable or disable)","Enable or disable a parameter of an effect.":"Enable or disable a parameter of an effect.","Enable _PARAM3_ for effect _PARAM2_ of layer _PARAM1_: _PARAM4_":"Enable _PARAM3_ for effect _PARAM2_ of layer _PARAM1_: _PARAM4_","Enable this parameter":"Enable this parameter","Layer effect is enabled":"Layer effect is enabled","The effect on a layer is enabled":"The effect on a layer is enabled","Effect _PARAM2_ on layer _PARAM1_ is enabled":"Effect _PARAM2_ on layer _PARAM1_ is enabled","Enable layer effect":"Enable layer effect","Enable an effect on a layer":"Enable an effect on a layer","Enable effect _PARAM2_ on layer _PARAM1_: _PARAM3_":"Enable effect _PARAM2_ on layer _PARAM1_: _PARAM3_","Enable":"Enable","Layer time scale":"Layer time scale","Compare the time scale applied to the objects of the layer.":"Compare the time scale applied to the objects of the layer.","the time scale of layer _PARAM1_":"the time scale of layer _PARAM1_","Layers and cameras/Time":"Layers and cameras/Time","Change layer time scale":"Change layer time scale","Change the time scale applied to the objects of the layer.":"Change the time scale applied to the objects of the layer.","Set time scale of layer _PARAM1_ to _PARAM2_":"Set time scale of layer _PARAM1_ to _PARAM2_","Scale (1: Default, 2: 2x faster, 0.5: 2x slower...)":"Scale (1: Default, 2: 2x faster, 0.5: 2x slower...)","Layer default Z order":"Layer default Z order","Compare the default Z order set to objects when they are created on a layer.":"Compare the default Z order set to objects when they are created on a layer.","the default Z order of objects created on _PARAM1_":"the default Z order of objects created on _PARAM1_","Change layer default Z order":"Change layer default Z order","Change the default Z order set to objects when they are created on a layer.":"Change the default Z order set to objects when they are created on a layer.","Set the default Z order of objects created on _PARAM1_ to _PARAM2_":"Set the default Z order of objects created on _PARAM1_ to _PARAM2_","New default Z order":"New default Z order","Set the ambient light color":"Set the ambient light color","Set the ambient light color of the lighting layer in format \"R;G;B\" string.":"Set the ambient light color of the lighting layer in format \"R;G;B\" string.","Set the ambient color of the lighting layer _PARAM1_ to _PARAM2_":"Set the ambient color of the lighting layer _PARAM1_ to _PARAM2_","Layers and cameras/Lighting":"Layers and cameras/Lighting","X position of the top left side point of a render zone":"Posi\xE7\xE3o X do ponto superior esquerdo de uma zona de renderiza\xE7\xE3o","Y position of the top left side point of a render zone":"Posi\xE7\xE3o Y do ponto superior esquerdo de uma zona de renderiza\xE7\xE3o","X position of the bottom right side point of a render zone":"Posi\xE7\xE3o X do ponto inferior direito de uma zona de renderiza\xE7\xE3o","Y position of the bottom right side point of a render zone":"Posi\xE7\xE3o Y do ponto inferior direito de uma zona de renderiza\xE7\xE3o","Zoom of a camera of a layer":"Zoom of a camera of a layer","Time scale":"Escala de tempo","Default Z Order for a layer":"Default Z Order for a layer","Builtin events":"Builtin events","Or":"Ou","Check if one of the sub conditions is true":"Check if one of the sub conditions is true","If one of these conditions is true:":"Se uma destas condi\xE7\xF5es for verdadeira:","And":"E","Check if all sub conditions are true":"Check if all sub conditions are true","If all of these conditions are true:":"Se todas essas condi\xE7\xF5es forem verdadeiras:","Not":"N\xE3o","Return the contrary of the result of the sub conditions":"Retornar o contr\xE1rio do resultado das sub-condi\xE7\xF5es","Invert the logical result of these conditions:":"Inverta o resultado l\xF3gico destas condi\xE7\xF5es:","Trigger once while true":"Gatilho (trigger) uma vez condi\xE7\xE3o verdadeira","Run actions only once, for each time the conditions have been met.":"Execute a\xE7\xF5es apenas uma vez, para cada vez que as condi\xE7\xF5es foram atendidas.","Trigger once":"Gatilho (trigger) uma vez","Standard event":"Evento padr\xE3o","Standard event: Actions are run if conditions are fulfilled.":"Evento padr\xE3o: as a\xE7\xF5es s\xE3o executadas, se as condi\xE7\xF5es forem satisfeitas.","Link":"Liga\xE7\xE3o (Link)","Link to some external events":"Liga\xE7\xE3o para alguns eventos externos","Comment":"Comentario","Event displaying a text in the events editor":"Evento que exibe um texto no editor de eventos","While":"Sempre que","The event is repeated while the conditions are true":"O evento \xE9 repetido enquanto as condi\xE7\xF5es forem verdadeiras","Repeat":"Repetir","Event repeated a number of times":"Evento \xE9 repetido v\xE1rias vezes","For each object":"Para cada objeto","Repeat the event for each specified object.":"Repita o evento para cada objeto especificado.","For each child variable (of a structure or array)":"For each child variable (of a structure or array)","Repeat the event for each child variable of a structure or array.":"Repeat the event for each child variable of a structure or array.","Group":"Grupo","Group containing events":"Grupo que cont\xE9m eventos","Window features":"Caracter\xEDsticas de janela","De/activate fullscreen":"Des/ativar tela cheia","This action activates or deactivates fullscreen.":"This action activates or deactivates fullscreen.","Activate fullscreen: _PARAM1_ (keep aspect ratio: _PARAM2_)":"Ativar tela cheia: _PARAM1_ (manter taxa de propor\xE7\xE3o: _PARAM2_)","Game's window and resolution":"Game's window and resolution","Activate fullscreen":"Ativar tela cheia","Keep aspect ratio (HTML5 games only, yes by default)":"Manter propor\xE7\xE3o (HTML5 jogos apenas, sim por padr\xE3o)","Fullscreen activated?":"Fullscreen activated?","Check if the game is currently in fullscreen.":"Check if the game is currently in fullscreen.","The game is in fullscreen":"The game is in fullscreen","Change the window's margins":"Change the window's margins","This action changes the margins, in pixels, between the game frame and the window borders.":"This action changes the margins, in pixels, between the game frame and the window borders.","Set margins of game window to _PARAM1_;_PARAM2_;_PARAM3_;_PARAM4_":"Definir as margens da janela do jogo para _PARAM1_; _PARAM2_; _PARAM3_; _PARAM4_","Top":"Em Cima","Right":"Direita","Bottom":"Em baixo","Left":"Esquerda","Change the resolution of the game":"Change the resolution of the game","Changes the resolution of the game, effectively changing the game area size. This won't change the size of the window in which the game is running.":"Changes the resolution of the game, effectively changing the game area size. This won't change the size of the window in which the game is running.","Set game resolution to _PARAM1_x_PARAM2_":"Set game resolution to _PARAM1_x_PARAM2_","Change the size of the game window":"Change the size of the game window","This action changes the size of the game window. Note that this will only work on platform supporting this operation: games running in browsers or on mobile phones can not update their window size. Game resolution can still be updated.":"This action changes the size of the game window. Note that this will only work on platform supporting this operation: games running in browsers or on mobile phones can not update their window size. Game resolution can still be updated.","Set game window size to _PARAM1_x_PARAM2_ (also update game resolution: _PARAM3_)":"Set game window size to _PARAM1_x_PARAM2_ (also update game resolution: _PARAM3_)","Also update the game resolution? If not, the game will be stretched or reduced to fit in the window.":"Also update the game resolution? If not, the game will be stretched or reduced to fit in the window.","Center the game window on the screen":"Centralize a janela do jogo no ecr\xE3","This action centers the game window on the screen. This only works on Windows, macOS and Linux (not when the game is executed in a web-browser or on iOS/Android).":"Esta ac\xE7\xE3o centraliza a janela do jogo no ecr\xE3. Isto s\xF3 funciona no Windows, macOS e Linux (n\xE3o quando o jogo \xE9 executado num navegador web ou no iOS/Android).","Center the game window":"Centralizar a janela do jogo","Change the game resolution resize mode":"Change the game resolution resize mode","Set if the width or the height of the game resolution should be changed to fit the game window - or if the game resolution should not be updated automatically.":"Set if the width or the height of the game resolution should be changed to fit the game window - or if the game resolution should not be updated automatically.","Set game resolution resize mode to _PARAM1_":"Set game resolution resize mode to _PARAM1_","Resize mode":"Resize mode","Empty to disable resizing. \"adaptWidth\" will update the game width to fit in the window or screen. \"adaptHeight\" will do the same but with the game height.":"Empty to disable resizing. \"adaptWidth\" will update the game width to fit in the window or screen. \"adaptHeight\" will do the same but with the game height.","Automatically adapt the game resolution":"Automatically adapt the game resolution","Set if the game resolution should be automatically adapted when the game window or screen size change. This will only be the case if the game resolution resize mode is configured to adapt the width or the height of the game.":"Set if the game resolution should be automatically adapted when the game window or screen size change. This will only be the case if the game resolution resize mode is configured to adapt the width or the height of the game.","Automatically adapt the game resolution: _PARAM1_":"Automatically adapt the game resolution: _PARAM1_","Update resolution during the game to fit the screen or window size?":"Update resolution during the game to fit the screen or window size?","Change the window's icon":"Change the window's icon","This action changes the icon of the game's window.":"This action changes the icon of the game's window.","Use _PARAM1_ as the icon for the game's window.":"Use _PARAM1_ as the icon for the game's window.","Name of the image to be used as the icon":"Nome da imagem a ser usada como o \xEDcone","Change the window's title":"Change the window's title","This action changes the title of the game's window.":"This action changes the title of the game's window.","Change window title to _PARAM1_":"Alterar o t\xEDtulo da janela para _PARAM1_","New title":"Novo t\xEDtulo","Width of the scene window":"Largura da janela da cena","Width of the scene window (or scene canvas for HTML5 games)":"Largura da janela de cena (ou canvas da cena para HTML5 jogos)","Screen":"Ecr\xE3","Height of the scene window":"Altura da janela da cena","Height of the scene window (or scene canvas for HTML5 games)":"Altura da janela de cena (ou canvas da cena para HTML5 jogos)","Width of the screen/page":"Largura do ecr\xE3/p\xE1gina","Width of the screen (or the page for HTML5 games in browser)":"Largura do ecr\xE3 (ou a p\xE1gina HTML5 do navegador para jogar)","Height of the screen/page":"Altura do ecr\xE3/p\xE1gina","Height of the screen (or the page for HTML5 games in browser)":"Altura do ecr\xE3 (ou a p\xE1gina HTML5 do navegador para jogar)","Color depth":"Profundidade da Cor","Window's title":"T\xEDtulo da janela","Time":"Tempo","Value of a scene timer":"Value of a scene timer","Test the elapsed time of a scene timer.":"Test the elapsed time of a scene timer.","The timer _PARAM2_ is greater than _PARAM1_ seconds":"O temporizador _PARAM2_ \xE9 maior do que _PARAM1_ segundos","Timers and time":"Cron\xF3metros e tempo","Time in seconds":"Tempo em segundos","Timer's name":"Nome do cron\xF3metro","Test the time scale.":"Teste a escala do tempo.","the time scale":"the time scale","Scene timer paused":"Scene timer paused","Test if the specified scene timer is paused.":"Testar se o temporizador de scene especificado est\xE1 pausado.","The timer _PARAM1_ is paused":"_PARAM1_ o temporizador est\xE1 em pausa","Start (or reset) a scene timer":"Iniciar (ou redefinir) um temporizador de scene","Reset the specified scene timer, if the timer doesn't exist it's created and started.":"Reset the specified scene timer, if the timer doesn't exist it's created and started.","Reset the timer _PARAM1_":"Reset o cron\xF3metro _PARAM1_","Pause a scene timer":"Pause a scene timer","Pause a scene timer.":"Pause a scene timer.","Pause timer _PARAM1_":"Pausar o temporizador _PARAM1_","Unpause a scene timer":"Unpause a scene timer","Unpause a scene timer.":"Unpause a scene timer.","Unpause timer _PARAM1_":"Retomar o temporizador _PARAM1_","Delete a scene timer":"Delete a scene timer","Delete a scene timer from memory.":"Delete a scene timer from memory.","Delete timer _PARAM1_ from memory":"Apagar o temporizador _PARAM1_ da mem\xF3ria","Change time scale":"Alterar a escala do tempo","Change the time scale of the game.":"Altere a escala de tempo do jogo.","Set time scale to _PARAM1_":"Definir a escala de tempo para _PARAM1_","Time elapsed since the last frame":"Tempo decorrido desde o \xFAltimo frame","Time elapsed since the last frame rendered on screen":"Tempo decorrido desde o \xFAltimo frame renderizado no ecr\xE3","Scene timer value":"Scene timer value","Time elapsed since the beginning of the scene":"Tempo decorrido desde o come\xE7o da cena","Hour: hour - Minutes: min - Seconds: sec - Day of month: mday - Months since January: mon - Year since 1900: year - Days since Sunday: wday - Days since Jan 1st: yday - Timestamp (ms): timestamp\"":"Hour: hour - Minutes: min - Seconds: sec - Day of month: mday - Months since January: mon - Year since 1900: year - Days since Sunday: wday - Days since Jan 1st: yday - Timestamp (ms): timestamp\"","Variable features":"Caracter\xEDsticas vari\xE1veis","Value of a scene variable":"Value of a scene variable","Compare the value of a scene variable.":"Compare o valor de uma vari\xE1vel local.","the scene variable _PARAM0_":"the scene variable _PARAM0_","Variable":"Vari\xE1vel","Text of a scene variable":"Texto de uma vari\xE1vel de cena","Compare the text of a scene variable.":"Compare o texto de uma vari\xE1vel de cena.","the text of scene variable _PARAM0_":"the text of scene variable _PARAM0_","Boolean value of a scene variable":"Boolean value of a scene variable","Compare the boolean value of a scene variable.":"Compare the boolean value of a scene variable.","The boolean value of scene variable _PARAM0_ is _PARAM1_":"The boolean value of scene variable _PARAM0_ is _PARAM1_","Check if the value is":"Check if the value is","Child existence":"Exist\xEAncia de crian\xE7a","Check if the specified child of the scene variable exists.":"Check if the specified child of the scene variable exists.","Child _PARAM1_ of scene variable _PARAM0_ exists":"Child _PARAM1_ of scene variable _PARAM0_ exists","Variables/Collections/Structures":"Variables/Collections/Structures","Name of the child":"Nome da crian\xE7a","Check if the specified child of the global variable exists.":"Check if the specified child of the global variable exists.","Child _PARAM1_ of global variable _PARAM0_ exists":"Vari\xE1vel _PARAM1_, filha de vari\xE1vel global _PARAM0_ existe","Variables/Global variables/Collections/Structures":"Variables/Global variables/Collections/Structures","Value of a global variable":"Valor de uma vari\xE1vel global","Compare the value of a global variable.":"Compare o valor de uma vari\xE1vel global.","the global variable _PARAM0_":"the global variable _PARAM0_","Variables/Global variables":"Vari\xE1veis Globais/Vol\xFAveis","Text of a global variable":"Texto de uma vari\xE1vel global","Compare the text of a global variable.":"Compare o texto de uma vari\xE1vel global.","the text of the global variable _PARAM0_":"the text of the global variable _PARAM0_","Boolean value of a global variable":"Boolean value of a global variable","Compare the boolean value of a global variable.":"Compare the boolean value of a global variable.","The boolean value of global variable _PARAM0_ is _PARAM1_":"The boolean value of global variable _PARAM0_ is _PARAM1_","Change the value of a scene variable.":"Change the value of a scene variable.","String of a scene variable":"String of a scene variable","Modify the text of a scene variable.":"Modifica o texto de uma vari\xE1vel de cena.","Modify the boolean value of a scene variable.":"Modify the boolean value of a scene variable.","Set the boolean value of scene variable _PARAM0_ to _PARAM1_":"Set the boolean value of scene variable _PARAM0_ to _PARAM1_","New Value:":"New Value:","Toggle boolean value of a scene variable":"Toggle boolean value of a scene variable","Toggle the boolean value of a scene variable.":"Toggle the boolean value of a scene variable.","If it was true, it will become false, and if it was false it will become true.":"If it was true, it will become false, and if it was false it will become true.","Toggle the boolean value of scene variable _PARAM0_":"Toggle the boolean value of scene variable _PARAM0_","Change the value of a global variable":"Change the value of a global variable","String of a global variable":"Caracteres de uma vari\xE1vel global","Modify the text of a global variable.":"Modifica o texto de uma vari\xE1vel global.","the text of global variable _PARAM0_":"the text of global variable _PARAM0_","Modify the boolean value of a global variable.":"Modify the boolean value of a global variable.","Set the boolean value of global variable _PARAM0_ to _PARAM1_":"Set the boolean value of global variable _PARAM0_ to _PARAM1_","Toggle boolean value of a global variable":"Toggle boolean value of a global variable","Toggle the boolean value of a global variable.":"Toggle the boolean value of a global variable.","Toggle the boolean value of global variable _PARAM0_":"Toggle the boolean value of global variable _PARAM0_","Remove a child":"Remover uma crian\xE7a","Remove a child from a scene variable.":"Remove a child from a scene variable.","Remove child _PARAM1_ from scene variable _PARAM0_":"Remove child _PARAM1_ from scene variable _PARAM0_","Child's name":"Nome da crian\xE7a","Remove a child from a global variable.":"Remover um filho de uma vari\xE1vel global.","Remove child _PARAM1_ from global variable _PARAM0_":"Remover o filho _PARAM1_ da vari\xE1vel global _PARAM0_","Clear scene variable":"Clear scene variable","Remove all the children from the scene variable.":"Remove all the children from the scene variable.","Clear children from scene variable _PARAM0_":"Clear children from scene variable _PARAM0_","Variables/Collections":"Variables/Collections","Clear global variable":"Clear global variable","Remove all the children from the global variable.":"Remove all the children from the global variable.","Clear children from global variable _PARAM0_":"Clear children from global variable _PARAM0_","Variables/Global variables/Collections":"Variables/Global variables/Collections","Append variable to a scene array":"Append variable to a scene array","Appends a variable at the end of a scene array variable.":"Appends a variable at the end of a scene array variable.","Append variable _PARAM1_ to array variable _PARAM0_":"Append variable _PARAM1_ to array variable _PARAM0_","Variables/Collections/Arrays":"Variables/Collections/Arrays","Array variable":"Array variable","Scene variable with the content to append":"Scene variable with the content to append","The content of the variable will *be copied* and appended at the end of the array.":"The content of the variable will *be copied* and appended at the end of the array.","Append a string to a scene array":"Append a string to a scene array","Appends a string at the end of a scene array variable.":"Appends a string at the end of a scene array variable.","Append string _PARAM1_ to array variable _PARAM0_":"Append string _PARAM1_ to array variable _PARAM0_","String to append":"String to append","Append a number to a scene array":"Append a number to a scene array","Appends a number at the end of a scene array variable.":"Appends a number at the end of a scene array variable.","Append number _PARAM1_ to array variable _PARAM0_":"Append number _PARAM1_ to array variable _PARAM0_","Number to append":"Number to append","Append a boolean to a scene array":"Append a boolean to a scene array","Appends a boolean at the end of a scene array variable.":"Appends a boolean at the end of a scene array variable.","Append boolean _PARAM1_ to array variable _PARAM0_":"Append boolean _PARAM1_ to array variable _PARAM0_","Boolean to append":"Boolean to append","Remove variable from a scene array (by index)":"Remove variable from a scene array (by index)","Removes a variable at the specified index of a scene array variable.":"Removes a variable at the specified index of a scene array variable.","Remove variable at index _PARAM1_ from scene array variable _PARAM0_":"Remove variable at index _PARAM1_ from scene array variable _PARAM0_","Index to remove":"Index to remove","Append variable to a global array":"Append variable to a global array","Appends a variable at the end of a global array variable.":"Appends a variable at the end of a global array variable.","Variables/Global variables/Collections/Arrays":"Variables/Global variables/Collections/Arrays","Remove variable from a global array (by index)":"Remove variable from a global array (by index)","Removes a variable at the specified index of a global array variable.":"Removes a variable at the specified index of a global array variable.","Remove variable at index _PARAM1_ from global array variable _PARAM0_":"Remove variable at index _PARAM1_ from global array variable _PARAM0_","Append a string to a global array":"Append a string to a global array","Appends a string at the end of a global array variable.":"Appends a string at the end of a global array variable.","Append a number to a global array":"Append a number to a global array","Appends a number at the end of a global array variable.":"Appends a number at the end of a global array variable.","Append a boolean to a global array":"Append a boolean to a global array","Appends a boolean at the end of a global array variable.":"Appends a boolean at the end of a global array variable.","Number of children of a global variable":"Number of children of a global variable","Number of children of a scene variable":"Number of children of a scene variable","Name of the global variable":"Nome da vari\xE1vel global","Text manipulation":"Manipula\xE7\xE3o de texto","Insert a new line":"Inserir uma nova linha","Manipulation of text":"Manipulation of text","Get character from code point":"Obter o caractere de ponto de c\xF3digo","Code point":"Ponto de c\xF3digo","Uppercase a text":"Deixar um texto em mai\xFAsculo","Lowercase a text":"Deixar um texto em min\xFAsculo","Get a portion of a text":"Obter uma por\xE7\xE3o de um texto","Start position of the portion (the first letter is at position 0)":"Posi\xE7\xE3o inicial da parte (a primeira letra \xE9 na posi\xE7\xE3o 0)","Length of the portion":"Comprimento da por\xE7\xE3o","Get a character from a text":"Obter um caractere a partir de um texto","Position of the character (the first letter is at position 0)":"Posi\xE7\xE3o do caractere (a primeira letra \xE9 na posi\xE7\xE3o 0)","Repeat a text":"Repeat a text","Text to repeat":"Text to repeat","Repetition count":"Repetition count","Length of a text":"Comprimento de um texto","Search in a text":"Procurar num texto","Search in a text (return the position of the result or -1 if not found)":"Procurar num texto (retorna a posi\xE7\xE3o do resultado ou -1 se n\xE3o for encontrada nenhuma)","Text to search for":"Texto para pesquisar","Search the last occurence in a text":"Search the last occurence in a text","Search the last occurence in a string (return the position of the result, from the beginning of the string, or -1 if not found)":"Search the last occurence in a string (return the position of the result, from the beginning of the string, or -1 if not found)","Search in a text, starting from a position":"Procurar num texto, a partir de uma posi\xE7\xE3o","Search in a text, starting from a position (return the position of the result or -1 if not found)":"Search in a text, starting from a position (return the position of the result or -1 if not found)","Position of the first character in the string to be considered in the search":"Posi\xE7\xE3o do primeiro caractere na sequ\xEAncia de carateres (string) a ser considerado na busca","Search the last occurence in a text, starting from a position":"Search the last occurence in a text, starting from a position","Search in a text the last occurence, starting from a position (return the position of the result, from the beginning of the string, or -1 if not found)":"Search in a text the last occurence, starting from a position (return the position of the result, from the beginning of the string, or -1 if not found)","Position of the last character in the string to be considered in the search":"Posi\xE7\xE3o do ultimo caractere na sequ\xEAncia de caracteres (string) a ser considerado na busca","Animate even if hidden or far from the screen":"Animate even if hidden or far from the screen","Sprite":"Sprite","Sprite are animated object which can be used for most elements of a game.":"Sprite are animated object which can be used for most elements of a game.","Animated object which can be used for most elements of a game":"Objecto animado que pode ser usado para a maior parte dos elementos de um jogo","Change sprite opacity":"Change sprite opacity","Change the opacity of a Sprite. 0 is fully transparent, 255 is opaque (default).":"Change the opacity of a Sprite. 0 is fully transparent, 255 is opaque (default).","Change the animation":"Alterar a anima\xE7\xE3o","Change the animation of the object, using the animation number in the animations list.":"Change the animation of the object, using the animation number in the animations list.","the number of the animation":"the number of the animation","Animations and images":"Anima\xE7\xF5es e imagens","Change the animation (by name)":"Change the animation (by name)","Change the animation of the object, using the name of the animation.":"Change the animation of the object, using the name of the animation.","Set animation of _PARAM0_ to _PARAM1_":"Set animation of _PARAM0_ to _PARAM1_","Animation name":"Animation name","Change the direction":"Mudar a dire\xE7\xE3o","Change the direction of the object.\nIf the object is set to automatically rotate, the direction is its angle.\nIf the object is in 8 directions mode, the valid directions are 0..7":"Muda a direc\xE7\xE3o de um objecto.\nSe o objecto esta preparado para rodar automaticamente, a direc\xE7\xE3o ser\xE1 o seu \xE2ngulo.\nSe o objecto est\xE1 no modo de 8 direc\xE7\xF5es, as direc\xE7\xF5es validas s\xE3o 0..7","the direction":"the direction","Current frame":"Quadro atual","Modify the current frame of the object":"Modificar o quadro actual do objecto","the animation frame":"the animation frame","Pause the animation":"Pausar a anima\xE7\xE3o","Pause the animation of the object":"Pause the animation of the object","Pause the animation of _PARAM0_":"Pause the animation of _PARAM0_","Play the animation":"Reproduzir a anima\xE7\xE3o","Play the animation of the object":"Play the animation of the object","Play the animation of _PARAM0_":"Play the animation of _PARAM0_","Modify the animation speed scale (1 = the default speed, >1 = faster and <1 = slower).":"Modificar a escala da velocidade de anima\xE7\xE3o (1 = a velocidade padr\xE3o, > 1 = mais r\xE1pido e < 1 = mais devagar).","Object to be rotated":"Objeto a ser rodado","Angular speed (degrees per second)":"Velocidade angular (graus por segundo)","Modify the scale of the specified object.":"Modifica a escala do objeto especificado.","Modify the scale of the width of an object.":"Modifica a escala da largura de um objeto.","the width's scale":"the width's scale","Modify the scale of the height of an object.":"Modifica a escala da altura de um objeto.","the height's scale":"the height's scale","Change the width of a Sprite object.":"Change the width of a Sprite object.","Change the height of a Sprite object.":"Change the height of a Sprite object.","Current animation":"Anima\xE7\xE3o atual","Compare the number of the animation played by the object.":"Compare the number of the animation played by the object.","Current animation name":"Current animation name","Check the animation by played by the object.":"Check the animation by played by the object.","The animation of _PARAM0_ is _PARAM1_":"The animation of _PARAM0_ is _PARAM1_","Current direction":"Dire\xE7\xE3o atual","Compare the direction of the object. If 8 direction mode is activated for the sprite, the value taken for direction will be from 0 to 7. Otherwise, the direction is in degrees.":"Compara a dire\xE7\xE3o do objecto. Se o modo de 8-way est\xE1 habilitado para o sprite, o valor necess\xE1rio para endere\xE7os ser\xE1 entre 0 e 7. Caso contr\xE1rio, o endere\xE7o \xE9 em \xE2ngulos.","Compare the index of the current frame in the animation displayed by the specified object. The first frame in an animation starts at index 0.":"Compare the index of the current frame in the animation displayed by the specified object. The first frame in an animation starts at index 0.","Animation paused":"Anima\xE7\xE3o em pausa","Check if the animation of an object is paused.":"Check if the animation of an object is paused.","The animation of _PARAM0_ is paused":"A anima\xE7\xE3o da _PARAM0_ est\xE1 em pausa","Animation finished":"Anima\xE7\xE3o finalizada","Check if the animation being played by the Sprite object is finished.":"Verifique se a anima\xE7\xE3o \xE9 reproduzida atrav\xE9s do objeto Sprite e foi conclu\xEDda.","The animation of _PARAM0_ is finished":"A anima\xE7\xE3o de _PARAM0_ terminou","Compare the scale of the width of an object.":"Compare a escala da largura de um objeto.","Compare the scale of the height of an object.":"Compare a escala da altura de um objeto.","Compare the opacity of a Sprite, between 0 (fully transparent) to 255 (opaque).":"Compare the opacity of a Sprite, between 0 (fully transparent) to 255 (opaque).","Blend mode":"Modo de mesclagem","Compare the number of the blend mode currently used by an object":"Comparar o n\xFAmero do modo de blend usado atualmente por um objeto","the number of the current blend mode":"the number of the current blend mode","Change the tint of an object. The default color is white.":"Change the tint of an object. The default color is white.","Change the number of the blend mode of an object.\nThe default blend mode is 0 (Normal).":"Change the number of the blend mode of an object.\nThe default blend mode is 0 (Normal).","Change Blend mode of _PARAM0_ to _PARAM1_":"Mude o modo de mistura de _PARAM0_ para _PARAM1_","Flip the object horizontally":"Inverter o objeto horizontalmente","Flip horizontally _PARAM0_ : _PARAM1_":"Inverter horizontalmente _PARAM0_: _PARAM1_","Activate flipping":"Ativar invers\xE3o","Flip the object vertically":"Inverter o objeto verticalmente","Flip vertically _PARAM0_ : _PARAM1_":"Inverter verticalmente _PARAM0_: _PARAM1_","Horizontally flipped":"Espelhar horizontalmente","Check if the object is horizontally flipped":"Check if the object is horizontally flipped","_PARAM0_ is horizontally flipped":"_PARAM0_ \xE9 invertido horizontalmente","Vertically flipped":"Verticalmente invertida","Check if the object is vertically flipped":"Check if the object is vertically flipped","_PARAM0_ is vertically flipped":"_PARAM0_ \xE9 invertida verticalmente","X position of a point":"Posi\xE7\xE3o X de um ponto","Name of the point":"Nome do ponto","Y position of a point":"Posi\xE7\xE3o Y de um ponto","Direction of the object":"Dire\xE7\xE3o do objeto","Animation of the object":"Anima\xE7\xE3o do objeto","Name of the animation of the object":"Name of the animation of the object","Animation frame of the object":"Quadro de anima\xE7\xE3o do objeto","Scale of the width of an object":"Escala de um objeto em largura","Scale of the height of an object":"Escala de um objeto em altura","Collision (Pixel perfect)":"Colis\xE3o (Pixel perfeito)","The condition is true if there is a collision between the two objects.\nThe test is pixel-perfect.":"A condi\xE7\xE3o \xE9 verdadeira se houver que uma colis\xE3o entre dois objetos. \nO teste \xE9 pixel-perfeito.","_PARAM0_ is in collision with _PARAM1_ (pixel perfect)":"_PARAM0_ est\xE1 em colis\xE3o com _PARAM1_ (pixel-perfeito)","Audio":"\xC1UDIO","GDevelop provides several conditions and actions to play audio files. They can be either long musics or short sound effects.":"GDevelop provides several conditions and actions to play audio files. They can be either long musics or short sound effects.","Play a sound on a channel":"Tocar um som num canal","Play a sound (small audio file) on a specific channel,\nso you'll be able to manipulate it.":"Play a sound (small audio file) on a specific channel,\nso you'll be able to manipulate it.","Play the sound _PARAM1_ on the channel _PARAM2_, vol.: _PARAM4_, loop: _PARAM3_":"Play the sound _PARAM1_ on the channel _PARAM2_, vol.: _PARAM4_, loop: _PARAM3_","Audio/Sounds on channels":"\xC1udio/sons em canais","Audio file (or audio resource name)":"Arquivo de \xE1udio (ou nome do recurso de \xE1udio)","Channel identifier":"Identificador de canal","Repeat the sound":"Repetir o som","From 0 to 100, 100 by default.":"From 0 to 100, 100 by default.","Pitch (speed)":"Pitch (speed)","1 by default.":"1 by default.","Stop the sound of a channel":"Interromper o som de um canal","Stop the sound on the specified channel.":"Pare o som no canal especificado.","Stop the sound of channel _PARAM1_":"Parar o som do canal _PARAM1_","Pause the sound of a channel":"Pausar o som de um canal","Pause the sound played on the specified channel.":"Pause o som tocado no canal especificado.","Pause the sound of channel _PARAM1_":"Pausar o som do canal _PARAM1_","Play the sound of a channel":"Reproduzir o som de um canal","Play the sound of the channel.":"Reproduzir o som do canal.","Play the sound of channel _PARAM1_":"Reproduzir o som do canal _PARAM1_","Play a music file on a channel":"Reproduzir um ficheiro de m\xFAsica num canal","Play a music file on a specific channel,\nso you'll be able to interact with it later.":"Reproduzir um ficheiro de m\xFAsica num canal espec\xEDfico,\npara que possa manipulado mais tarde.","Play the music _PARAM1_ on channel _PARAM2_, vol.: _PARAM4_, loop: _PARAM3_":"Play the music _PARAM1_ on channel _PARAM2_, vol.: _PARAM4_, loop: _PARAM3_","Audio/Music on channels":"\xC1udio/M\xFAsica nos canais","Stop the music on a channel":"Parar a m\xFAsica em um canal","Stop the music on the specified channel":"Parar a m\xFAsica no canal especificado","Stop the music of channel _PARAM1_":"Parar a m\xFAsica do canal _PARAM1_","Pause the music of a channel":"Pausar a m\xFAsica de um canal","Pause the music on the specified channel.":"Pausar a m\xFAsica no canal especificado.","Pause the music of channel _PARAM1_":"Pausar a m\xFAsica do canal _PARAM1_","Play the music of a channel":"Tocar a m\xFAsica de um canal","Play the music of the channel.":"Toca a m\xFAsica do canal.","Play the music of channel _PARAM1_":"Tocar a m\xFAsica do canal _PARAM1_","Volume of the sound on a channel":"Volume do som em um canal","This action modifies the volume of the sound on the specified channel. The volume is between 0 and 100.":"Esta a\xE7\xE3o altera o volume de som no canal especificado. O volume define-se entre 0 e 100.","the volume of the sound on channel _PARAM1_":"the volume of the sound on channel _PARAM1_","Volume of the music on a channel":"Volume da m\xFAsica em um canal","This action modifies the volume of the music on the specified channel. The volume is between 0 and 100.":"This action modifies the volume of the music on the specified channel. The volume is between 0 and 100.","the volume of the music on channel _PARAM1_":"the volume of the music on channel _PARAM1_","Game global volume":"Volume global do jogo","This action modifies the global volume of the game. The volume is between 0 and 100.":"This action modifies the global volume of the game. The volume is between 0 and 100.","the global sound level":"the global sound level","Pitch of the sound of a channel":"Tom do som de um canal","This action modifies the pitch (speed) of the sound on a channel.\n1 is the default pitch.":"This action modifies the pitch (speed) of the sound on a channel.\n1 is the default pitch.","the pitch of the sound on channel _PARAM1_":"the pitch of the sound on channel _PARAM1_","Pitch of the music on a channel":"Tom da m\xFAsica em um canal","This action modifies the pitch of the music on the specified channel. 1 is the default pitch":"This action modifies the pitch of the music on the specified channel. 1 is the default pitch","the pitch of the music on channel _PARAM1_":"the pitch of the music on channel _PARAM1_","Playing offset of the sound on a channel":"Deslocamento de reprodu\xE7\xE3o do som em um canal","This action modifies the playing offset of the sound on a channel":"This action modifies the playing offset of the sound on a channel","the playing offset of the sound on channel _PARAM1_":"the playing offset of the sound on channel _PARAM1_","Playing offset of the music on a channel":"Deslocamento de reprodu\xE7\xE3o da m\xFAsica em um canal","This action modifies the playing offset of the music on the specified channel":"This action modifies the playing offset of the music on the specified channel","the playing offset of the music on channel _PARAM1_":"the playing offset of the music on channel _PARAM1_","Play a sound":"Tocar um som","Play a sound.":"Tocar um som.","Play the sound _PARAM1_, vol.: _PARAM3_, loop: _PARAM2_":"Play the sound _PARAM1_, vol.: _PARAM3_, loop: _PARAM2_","Play a music file":"Reproduzir um arquivo de m\xFAsica","Play a music file.":"Reproduzir um arquivo de m\xFAsica.","Play the music _PARAM1_, vol.: _PARAM3_, loop: _PARAM2_":"Play the music _PARAM1_, vol.: _PARAM3_, loop: _PARAM2_","Preload a music file":"Preload a music file","Preload a music file in memory.":"Preload a music file in memory.","Preload the music file _PARAM1_":"Preload the music file _PARAM1_","Audio/Loading":"Audio/Loading","Preload a sound file":"Preload a sound file","Preload a sound file in memory.":"Preload a sound file in memory.","Preload the sound file _PARAM1_":"Preload the sound file _PARAM1_","Sound file (or sound resource name)":"Sound file (or sound resource name)","Unload a music file":"Unload a music file","Unload a music file from memory. Unloading a music file will cause any music playing it to stop.":"Unload a music file from memory. Unloading a music file will cause any music playing it to stop.","Unload the music file _PARAM1_":"Unload the music file _PARAM1_","Unload a sound file":"Unload a sound file","Unload a sound file from memory. Unloading a sound file will cause any sounds playing it to stop.":"Unload a sound file from memory. Unloading a sound file will cause any sounds playing it to stop.","Unload the sound file _PARAM1_":"Unload the sound file _PARAM1_","Unload all audio":"Unload all audio","Unload all the audio in memory. This will cause every sound and music of the game to stop.":"Unload all the audio in memory. This will cause every sound and music of the game to stop.","Unload all audio files":"Unload all audio files","A music file is being played":"Um arquivo de m\xFAsica est\xE1 sendo tocado","Test if the music on a channel is being played":"Teste se a m\xFAsica est\xE1 sendo tocada em um canal","Music on channel _PARAM1_ is being played":"M\xFAsica no canal _PARAM1_ est\xE1 tocada","A music file is paused":"Um arquivo de m\xFAsica est\xE1 em pausa","Test if the music on the specified channel is paused.":"Teste se a m\xFAsica no canal especificado est\xE1 em pausa.","Music on channel _PARAM1_ is paused":"M\xFAsica no canal _PARAM1_ est\xE1 em pausa","A music file is stopped":"Um arquivo de m\xFAsica \xE9 interrompido","Test if the music on the specified channel is stopped.":"Teste se a m\xFAsica no canal especificado foi parada.","Music on channel _PARAM1_ is stopped":"M\xFAsica no canal _PARAM1_ est\xE1 parada","A sound is being played":"Um som est\xE1 a ser tocado","Test if the sound on a channel is being played.":"Teste se o som em um canal est\xE1 sendo tocado.","Sound on channel _PARAM1_ is being played":"Som no canal _PARAM1_ est\xE1 sendo tocado","A sound is paused":"O som est\xE1 em pausa","Test if the sound on the specified channel is paused.":"Teste se o som no canal especificado est\xE1 em pausa.","Sound on channel _PARAM1_ is paused":"Som no canal _PARAM1_ est\xE1 em pausa","A sound is stopped":"Um som foi interrompido","Test if the sound on the specified channel is stopped.":"Teste se o som no canal especificado for interrompido.","Sound on channel _PARAM1_ is stopped":"Som no canal _PARAM1_ foi interrompido","Test the volume of the sound on the specified channel. The volume is between 0 and 100.":"Teste o volume do som no canal especificado. O volume est\xE1 entre 0 e 100.","Test the volume of the music on a specified channel. The volume is between 0 and 100.":"Teste o volume da m\xFAsica no canal especificado. O volume est\xE1 entre 0 e 100.","Global volume":"Volume global","Test the global sound level. The volume is between 0 and 100.":"Teste o n\xEDvel global do som. O volume est\xE1 entre 0 e 100.","the global game volume":"the global game volume","Test the pitch of the sound on the specified channel. 1 is the default pitch.":"Teste o Tom do som no canal especificado. 1 \xE9 o Tom de padr\xE3o.","Test the pitch (speed) of the music on a specified channel. 1 is the default pitch.":"Test the pitch (speed) of the music on a specified channel. 1 is the default pitch.","Test the playing offset of the sound on the specified channel.":"Teste o deslocamento do som no canal especificado do jogo.","Test the playing offset of the music on the specified channel.":"Teste o deslocamento de reprodu\xE7\xE3o da m\xFAsica no canal especificado.","Sound playing offset":"Posi\xE7\xE3o de leitura de um som","Sounds":"Sons","Music playing offset":"Posi\xE7\xE3o de leitura da m\xFAsica","Music":"M\xFAsica","Sound volume":"Volume do som","Music volume":"Volume da m\xFAsica","Sound's pitch":"Tom do som","Music's pitch":"Tom da m\xFAsica","Global volume value":"Valor de volume global","Sound level":"Volume","Features for all objects":"Funcionalidades para todos os objectos","Common features that can be used for all objects in GDevelop.":"Funcionalidades comuns que podem ser utilizadas para todos os objectos no GDevelop.","Base object":"Objeto base","Compare the X position of the object.":"Compare a posi\xE7\xE3o X do objeto.","the X position":"the X position","Change the X position of an object.":"Altere a posi\xE7\xE3o X de um objeto.","Compare the Y position of an object.":"Comparar a posi\xE7\xE3o Y de um objeto.","the Y position":"the Y position","Change the Y position of an object.":"Alterar a posi\xE7\xE3o Y de um objecto.","Change the position of an object.":"Alterar a posi\xE7\xE3o de um objecto.","Change the position of _PARAM0_: _PARAM1_ _PARAM2_ (x axis), _PARAM3_ _PARAM4_ (y axis)":"Change the position of _PARAM0_: _PARAM1_ _PARAM2_ (x axis), _PARAM3_ _PARAM4_ (y axis)","Center position":"Center position","Change the position of an object, using its center.":"Change the position of an object, using its center.","Change the position of the center of _PARAM0_: _PARAM1_ _PARAM2_ (x axis), _PARAM3_ _PARAM4_ (y axis)":"Change the position of the center of _PARAM0_: _PARAM1_ _PARAM2_ (x axis), _PARAM3_ _PARAM4_ (y axis)","Position/Center":"Position/Center","Center X position":"Center X position","the X position of the center":"the X position of the center","Center Y position":"Center Y position","the Y position of the center":"the Y position of the center","Put around a position":"Put around a position","Position the center of the given object around a position, using the specified angle and distance.":"Position the center of the given object around a position, using the specified angle and distance.","Put _PARAM0_ around _PARAM1_;_PARAM2_, with an angle of _PARAM4_ degrees and _PARAM3_ pixels distance.":"Colocar _PARAM0_ em torno de _PARAM1_; _PARAM2_, com um \xE2ngulo de _PARAM4_ graus e dist\xE2ncia de _PARAM3_ pixels.","Change the angle of rotation of an object.":"Mude o \xE2ngulo de rota\xE7\xE3o de um objeto.","Rotate":"Rodar","Rotate an object, clockwise if the speed is positive, counterclockwise otherwise.":"Gire um objeto, no sentido hor\xE1rio, se a velocidade for positiva, no sentido anti-hor\xE1rio, caso contr\xE1rio.","Rotate _PARAM0_ at speed _PARAM1_deg/second":"Girar _PARAM0_ na velocidade de _PARAM1_graus/segundo","Angular speed (in degrees per second)":"Velocidade angular (graus por segundo)","Rotate toward angle":"Girar na dire\xE7\xE3o do \xE2ngulo","Rotate an object towards an angle with the specified speed.":"Gire um objeto na dire\xE7\xE3o do \xE2ngulo com a velocidade especificada.","Rotate _PARAM0_ towards _PARAM1_ at speed _PARAM2_deg/second":"_PARAM0_ girar no sentido _PARAM1_ a velocidade _PARAM2_deg/segundo","Angle to rotate towards (in degrees)":"\xC2ngulo a girar na dire\xE7\xE3o (em graus)","Enter 0 for an immediate rotation.":"Enter 0 for an immediate rotation.","Rotate toward position":"Rodar para a posi\xE7\xE3o","Rotate an object towards a position, with the specified speed.":"Rodar um objeto para uma posi\xE7\xE3o, com a velocidade especificada.","Rotate _PARAM0_ towards _PARAM1_;_PARAM2_ at speed _PARAM3_deg/second":"Rode o _PARAM0_ para _PARAM1_; _PARAM2_ a velocidade _PARAM3_deg/segundo","Add a force to an object. The object will move according to all of the forces it has.":"Add a force to an object. The object will move according to all of the forces it has.","Add to _PARAM0_ _PARAM3_ force of _PARAM1_ p/s on X axis and _PARAM2_ p/s on Y axis":"Add to _PARAM0_ _PARAM3_ force of _PARAM1_ p/s on X axis and _PARAM2_ p/s on Y axis","Movement using forces":"Movement using forces","Speed on X axis (in pixels per second)":"Velocidade no eixo X (em pixels por segundo)","Speed on Y axis (in pixels per second)":"Velocidade no eixo Y (em pixels por segundo)","Force multiplier":"Force multiplier","Add a force (angle)":"Adicionar uma for\xE7a (\xE2ngulo)","Add a force to an object. The object will move according to all of the forces it has. This action creates the force using the specified angle and length.":"Add a force to an object. The object will move according to all of the forces it has. This action creates the force using the specified angle and length.","Add to _PARAM0_ _PARAM3_ force, angle: _PARAM1_ degrees and length: _PARAM2_ pixels":"Add to _PARAM0_ _PARAM3_ force, angle: _PARAM1_ degrees and length: _PARAM2_ pixels","Speed (in pixels per second)":"Velocidade (em pixels por segundo)","Add a force to move toward a position":"Adicionar uma for\xE7a para se mover para uma posi\xE7\xE3o","Add a force to an object to make it move toward a position.":"Adicione uma for\xE7a a um objeto parafaz\xEA-lo se mover em dire\xE7\xE3o a uma posi\xE7\xE3o.","Move _PARAM0_ toward _PARAM1_;_PARAM2_ with _PARAM4_ force of _PARAM3_ pixels":"Move _PARAM0_ toward _PARAM1_;_PARAM2_ with _PARAM4_ force of _PARAM3_ pixels","Stop the object":"Parar o objeto","Stop the object by deleting all of its forces.":"Stop the object by deleting all of its forces.","Stop _PARAM0_ (remove all forces)":"Stop _PARAM0_ (remove all forces)","Delete the object":"Delete the object","Delete the specified object.":"Apagar o objeto especificado.","Delete _PARAM0_":"Delete _PARAM0_","Z order":"Posi\xE7\xE3o Z","Modify the Z-order of an object":"Modify the Z-order of an object","the z-order":"the z-order","Move the object to a different layer.":"Move the object to a different layer.","Put _PARAM0_ on the layer _PARAM1_":"Colocar _PARAM0_ na camada _PARAM1_","Move it to this layer (base layer if empty)":"Move it to this layer (base layer if empty)","Value of an object variable":"Value of an object variable","Change the value of an object variable.":"Change the value of an object variable.","the variable _PARAM1_":"the variable _PARAM1_","Text of an object variable":"Text of an object variable","Change the text of an object variable.":"Change the text of an object variable.","the text of variable _PARAM1_":"the text of variable _PARAM1_","Boolean value of an object variable":"Boolean value of an object variable","Change the boolean value of an object variable.":"Change the boolean value of an object variable.","Set the boolean value of variable _PARAM1_ of _PARAM0_ to _PARAM2_":"Set the boolean value of variable _PARAM1_ of _PARAM0_ to _PARAM2_","Toggle the boolean value of an object variable":"Toggle the boolean value of an object variable","Toggles the boolean value of an object variable.":"Toggles the boolean value of an object variable.","Toggle the boolean value of variable _PARAM1_ of _PARAM0_":"Toggle the boolean value of variable _PARAM1_ of _PARAM0_","Check if the specified child of the variable exists.":"Check if the specified child of the variable exists.","Child _PARAM2_ of variable _PARAM1_ of _PARAM0_ exists":"_PARAM2_ filho de _PARAM1_ vari\xE1vel de _PARAM0_ existe","Remove a child from an object variable.":"Remove a child from an object variable.","Remove child _PARAM2_ from variable _PARAM1_ of _PARAM0_":"Remover a crian\xE7a _PARAM2_ de vari\xE1vel _PARAM1_ de _PARAM0_","Clear variable":"Clear variable","Remove all the children from the object variable.":"Remove all the children from the object variable.","Clear children from variable _PARAM1_ of _PARAM0_":"Clear children from variable _PARAM1_ of _PARAM0_","Hide the specified object.":"Esconda o objeto especificado.","Hide _PARAM0_":"Hide _PARAM0_","Show":"Mostrar","Show the specified object.":"Show the specified object.","Show _PARAM0_":"Show _PARAM0_","Compare the angle of the specified object.":"Compare the angle of the specified object.","the angle (in degrees)":"the angle (in degrees)","Z-order":"Z-order","Compare the Z-order of the specified object.":"Compare the Z-order of the specified object.","the Z-order":"the Z-order","Current layer":"Current layer","Check if the object is on the specified layer.":"Check if the object is on the specified layer.","_PARAM0_ is on layer _PARAM1_":"_PARAM0_ est\xE1 na camada _PARAM1_","Check if an object is visible.":"Check if an object is visible.","_PARAM0_ is visible (not marked as hidden)":"_PARAM0_ is visible (not marked as hidden)","Object is stopped (no forces applied on it)":"Object is stopped (no forces applied on it)","Check if an object is not moving":"Check if an object is not moving","_PARAM0_ is stopped":"_PARAM0_ est\xE1 parado","Speed (from forces)":"Speed (from forces)","Compare the overall speed of an object":"Comparar a velocidade total de um objeto","the overall speed":"the overall speed","Angle of movement (using forces)":"Angle of movement (using forces)","Compare the angle of movement of an object according to the forces applied on it.":"Compare the angle of movement of an object according to the forces applied on it.","Angle of movement of _PARAM0_ is _PARAM1_ (tolerance: _PARAM2_ degrees)":"Angle of movement of _PARAM0_ is _PARAM1_ (tolerance: _PARAM2_ degrees)","Compare the value of an object variable.":"Compare the value of an object variable.","Compare the text of an object variable.":"Compare the text of an object variable.","Compare the boolean value of an object variable.":"Compare the boolean value of an object variable.","The boolean value of variable _PARAM1_ of object _PARAM0_ is _PARAM2_":"The boolean value of variable _PARAM1_ of object _PARAM0_ is _PARAM2_","Append variable to an object array":"Append variable to an object array","Appends a variable to the end of an object array variable.":"Appends a variable to the end of an object array variable.","Append variable _PARAM2_ to array variable _PARAM1_ of _PARAM0_":"Append variable _PARAM2_ to array variable _PARAM1_ of _PARAM0_","Append a string to an object array":"Append a string to an object array","Appends a string to the end of an object array variable.":"Appends a string to the end of an object array variable.","Append string _PARAM2_ to array variable _PARAM1_ of _PARAM0_":"Append string _PARAM2_ to array variable _PARAM1_ of _PARAM0_","Append a number to an object array":"Append a number to an object array","Appends a number to the end of an object array variable.":"Appends a number to the end of an object array variable.","Append number _PARAM2_ to array variable _PARAM1_ of _PARAM0_":"Append number _PARAM2_ to array variable _PARAM1_ of _PARAM0_","Append a boolean to an object array":"Append a boolean to an object array","Appends a boolean to the end of an object array variable.":"Appends a boolean to the end of an object array variable.","Append boolean _PARAM2_ to array variable _PARAM1_ of _PARAM0_":"Append boolean _PARAM2_ to array variable _PARAM1_ of _PARAM0_","Remove variable from an object array (by index)":"Remove variable from an object array (by index)","Removes a variable at the specified index of an object array variable.":"Removes a variable at the specified index of an object array variable.","Remove variable at index _PARAM2_ from array variable _PARAM1_ of _PARAM0_":"Remove variable at index _PARAM2_ from array variable _PARAM1_ of _PARAM0_","Behavior activated":"Automatismo ativado","Check if the behavior is activated for the object.":"Check if the behavior is activated for the object.","Behavior _PARAM1_ of _PARAM0_ is activated":"Automatismo _PARAM1_ de _PARAM0_ est\xE1 ativado","De/activate a behavior":"De/ativar um automatismo","De/activate the behavior for the object.":"De/ativar o automatismo do objeto.","Activate behavior _PARAM1_ of _PARAM0_: _PARAM2_":"Ativar o automatismo _PARAM1_ de _PARAM0_: _PARAM2_","Activate?":"Ativar?","Add a force to move toward an object":"Adicionar uma for\xE7a para se mover em dire\xE7\xE3o a um objeto","Add a force to an object to make it move toward another.":"Adicionar uma for\xE7a a um objeto para fazer ele se mover de dire\xE7\xE3o a outra.","Move _PARAM0_ toward _PARAM1_ with _PARAM3_ force of _PARAM2_ pixels":"Move _PARAM0_ toward _PARAM1_ with _PARAM3_ force of _PARAM2_ pixels","Target Object":"Objeto de destino","Add a force to move around an object":"Adicionar uma for\xE7a para mover ao redor de um objeto","Add a force to an object to make it rotate around another.\nNote that the movement is not precise, especially if the speed is high.\nTo position an object around a position more precisely, use the actions in category \"Position\".":"Add a force to an object to make it rotate around another.\nNote that the movement is not precise, especially if the speed is high.\nTo position an object around a position more precisely, use the actions in category \"Position\".","Rotate _PARAM0_ around _PARAM1_ at _PARAM2_ deg/sec and _PARAM3_ pixels away":"Rotacionar _PARAM0_ em torno de _PARAM1_ com _PARAM2_ graus/s e _PARAM3_ pixels de dist\xE2ncia","Rotate around this object":"Rodar em torno deste objeto","Speed (in degrees per second)":"Velocidade (em graus por segundo)","Distance (in pixels)":"Dist\xE2ncia (em pixels)","Put the object around another":"Put the object around another","Position an object around another, with the specified angle and distance. The center of the objects are used for positioning them.":"Position an object around another, with the specified angle and distance. The center of the objects are used for positioning them.","Put _PARAM0_ around _PARAM1_, with an angle of _PARAM3_ degrees and _PARAM2_ pixels distance.":"Coloca _PARAM0_ em torno de _PARAM1_, com um \xE2ngulo de _PARAM3_ graus e dist\xE2ncia de _PARAM2_ pixels.","\"Center\" Object":"Objeto \"Centrar\"","Separate objects":"Separate objects","Move an object away from another using their collision masks.\nBe sure to call this action on a reasonable number of objects\nto avoid slowing down the game.":"Move an object away from another using their collision masks.\nBe sure to call this action on a reasonable number of objects\nto avoid slowing down the game.","Move _PARAM0_ away from _PARAM1_ (only _PARAM0_ will move)":"Move _PARAM0_ away from _PARAM1_ (only _PARAM0_ will move)","Objects (won't move)":"Objects (won't move)","Ignore objects that are touching each other on their edges, but are not overlapping (default: no)":"Ignore objects that are touching each other on their edges, but are not overlapping (default: no)","Point inside object":"Point inside object","Test if a point is inside the object collision masks.":"Test if a point is inside the object collision masks.","_PARAM1_;_PARAM2_ is inside _PARAM0_":"_PARAM1_;_PARAM2_ is inside _PARAM0_","X position of the point":"X position of the point","Y position of the point":"Y position of the point","The cursor/touch is on an object":"O cursor/toque est\xE1 sobre um objeto","Test if the cursor is over an object, or if the object is being touched.":"Teste se o cursor est\xE1 sobre um objeto, ou se o objeto est\xE1 sendo tocado.","The cursor/touch is on _PARAM0_":"O cursor/toque est\xE1 sobre _PARAM0_","Mouse and touch":"Mouse e toque","Accurate test (yes by default)":"Teste exato (Sim, por padr\xE3o)","Value of an object timer":"Value of an object timer","Test the elapsed time of an object timer.":"Test the elapsed time of an object timer.","The timer _PARAM1_ of _PARAM0_ is greater than _PARAM2_ seconds":"The timer _PARAM1_ of _PARAM0_ is greater than _PARAM2_ seconds","Timers":"Timers","Object timer paused":"Object timer paused","Test if specified object timer is paused.":"Test if specified object timer is paused.","The timer _PARAM1_ of _PARAM0_ is paused":"The timer _PARAM1_ of _PARAM0_ is paused","Start (or reset) an object timer":"Start (or reset) an object timer","Reset the specified object timer, if the timer doesn't exist it's created and started.":"Reset the specified object timer, if the timer doesn't exist it's created and started.","Reset the timer _PARAM1_ of _PARAM0_":"Reset the timer _PARAM1_ of _PARAM0_","Pause an object timer":"Pause an object timer","Pause an object timer.":"Pause an object timer.","Pause timer _PARAM1_ of _PARAM0_":"Pause timer _PARAM1_ of _PARAM0_","Unpause an object timer":"Unpause an object timer","Unpause an object timer.":"Unpause an object timer.","Unpause timer _PARAM1_ of _PARAM0_":"Unpause timer _PARAM1_ of _PARAM0_","Delete an object timer":"Delete an object timer","Delete an object timer from memory.":"Delete an object timer from memory.","Delete timer _PARAM1_ of _PARAM0_ from memory":"Delete timer _PARAM1_ of _PARAM0_ from memory","X position of the object":"Posi\xE7\xE3o X do objeto","Y position of the object":"Posi\xE7\xE3o Y do objeto","Current angle, in degrees, of the object":"\xC2ngulo atual do objeto em graus","X coordinate of the sum of forces":"X coordinate of the sum of forces","Y coordinate of the sum of forces":"Y coordinate of the sum of forces","Angle of the sum of forces":"Angle of the sum of forces","Length of the sum of forces":"Length of the sum of forces","Width of the object":"Largura do objeto","Height of the object":"Altura do objeto","Z-order of an object":"Z-order of an object","Distance between two objects":"Dist\xE2ncia entre dois objetos","Square distance between two objects":"Quadrado da dist\xE2ncia (D\xB2) entre dois objetos","Distance between an object and a position":"Distance between an object and a position","Target X position":"Target X position","Target Y position":"Target Y position","Square distance between an object and a position":"Square distance between an object and a position","Number of children of an object variable":"Number of children of an object variable","Object timer value":"Object timer value","Object timers":"Object timers","Angle between two objects":"Angle between two objects","Compute the angle between two objects. If you need the angle to an arbitrary position, use AngleToPosition.":"Compute the angle between two objects. If you need the angle to an arbitrary position, use AngleToPosition.","X position from angle and distance":"X position from angle and distance","Compute the X position when given an angle and distance relative to the starting object. This is also known as getting the cartesian coordinates of a 2D vector, using its polar coordinates.":"Compute the X position when given an angle and distance relative to the starting object. This is also known as getting the cartesian coordinates of a 2D vector, using its polar coordinates.","Y position from angle and distance":"Y position from angle and distance","Compute the Y position when given an angle and distance relative to the starting object. This is also known as getting the cartesian coordinates of a 2D vector, using its polar coordinates.":"Compute the Y position when given an angle and distance relative to the starting object. This is also known as getting the cartesian coordinates of a 2D vector, using its polar coordinates.","Angle between an object and a position":"Angle between an object and a position","Compute the angle between the object center and a \"target\" position. If you need the angle between two objects, use AngleToObject.":"Compute the angle between the object center and a \"target\" position. If you need the angle between two objects, use AngleToObject.","Enable an object effect":"Enable an object effect","Enable an effect on the object":"Enable an effect on the object","Enable effect _PARAM1_ on _PARAM0_: _PARAM2_":"Enable effect _PARAM1_ on _PARAM0_: _PARAM2_","Set _PARAM2_ to _PARAM3_ for effect _PARAM1_ of _PARAM0_":"Set _PARAM2_ to _PARAM3_ for effect _PARAM1_ of _PARAM0_","Enable _PARAM2_ for effect _PARAM1_ of _PARAM0_: _PARAM3_":"Enable _PARAM2_ for effect _PARAM1_ of _PARAM0_: _PARAM3_","Effect is enabled":"Effect is enabled","Check if the effect on an object is enabled.":"Check if the effect on an object is enabled.","Effect _PARAM1_ of _PARAM0_ is enabled":"Effect _PARAM1_ of _PARAM0_ is enabled","Create an object":"Criar um objeto","Create an object at specified position":"Criar um objeto na posi\xE7\xE3o especificada","Create object _PARAM1_ at position _PARAM2_;_PARAM3_":"Criar o objeto _PARAM1_ na posi\xE7\xE3o _PARAM2_; _PARAM3_","Object to create":"Objeto a criar","Create an object from its name":"Criar um objeto a partir do seu nome","Among the objects of the specified group, this action will create the object with the specified name.":"Among the objects of the specified group, this action will create the object with the specified name.","Among objects _PARAM1_, create object named _PARAM2_ at position _PARAM3_;_PARAM4_":"Entre os objetos _PARAM1_, criar objeto chamado _PARAM2_ na posi\xE7\xE3o _PARAM3_; _PARAM4_","Group of potential objects":"Group of potential objects","Group containing objects that can be created by the action.":"Group containing objects that can be created by the action.","Name of the object to create":"Name of the object to create","Text representing the name of the object to create. If no objects with this name are found in the group, no object will be created.":"Text representing the name of the object to create. If no objects with this name are found in the group, no object will be created.","Pick all instances":"Pick all instances","Pick all instances of the specified object(s). When you pick all instances, the next conditions and actions of this event work on all of them.":"Pick all instances of the specified object(s). When you pick all instances, the next conditions and actions of this event work on all of them.","Pick all instances of _PARAM1_":"Pick all instances of _PARAM1_","Pick a random object":"Escolha um objeto aleat\xF3rio","Pick one object from all the specified objects. When an object is picked, the next conditions and actions of this event work only on that object.":"Escolher um object de todos os objects especificados. Quando um object \xE9 selecionado, as pr\xF3ximas condi\xE7\xF5es e a\xE7\xF5es desse evento funcionam apenas nesse object.","Pick a random _PARAM1_":"Escolher um _PARAM1_ aleat\xF3rio","Apply movement to all objects":"Apply movement to all objects","Moves all objects according to the forces they have. GDevelop calls this action at the end of the events by default.":"Moves all objects according to the forces they have. GDevelop calls this action at the end of the events by default.","An object is moving toward another (using forces)":"An object is moving toward another (using forces)","Check if an object moves toward another.\nThe first object must move.":"Verificar se um objeto se move em dire\xE7\xE3o a outro. \nO primeiro objeto deve se mover.","_PARAM0_ is moving toward _PARAM1_":"_PARAM0_ est\xE1 se movendo em dire\xE7\xE3o a _PARAM1_","Compare the distance between two objects.\nIf condition is inverted, only objects that have a distance greater than specified to any other object will be picked.":"Comparar a dist\xE2ncia entre dois objetos. \nse a condi\xE7\xE3o \xE9 invertida, ser\xE3o escolhidos apenas os objetos que t\xEAm uma dist\xE2ncia maior do que o especificado para qualquer outro objeto.","_PARAM0_ distance to _PARAM1_ is below _PARAM2_ pixels":"Dist\xE2ncia de _PARAM0_ a _PARAM1_ est\xE1 abaixo de _PARAM2_ pixels","Pick all objects":"Pegue todos os objetos","Pick all the specified objects. When you pick all objects, the next conditions and actions of this event work on all of them.":"Pick all the specified objects. When you pick all objects, the next conditions and actions of this event work on all of them.","Pick all _PARAM1_ objects":"Pick all _PARAM1_ objects","Pick nearest object":"Escolha o objeto mais pr\xF3ximo","Pick the object of this type that is nearest to the specified position. If the condition is inverted, the object farthest from the specified position is picked instead.":"Pick the object of this type that is nearest to the specified position. If the condition is inverted, the object farthest from the specified position is picked instead.","Pick the _PARAM0_ that is nearest to _PARAM1_;_PARAM2_":"Pick the _PARAM0_ that is nearest to _PARAM1_;_PARAM2_","Number of objects":"N\xFAmero de objetos","Count how many of the specified objects are currently picked, and compare that number to a value. If previous conditions on the objects have not been used, this condition counts how many of these objects exist in the current scene.":"Count how many of the specified objects are currently picked, and compare that number to a value. If previous conditions on the objects have not been used, this condition counts how many of these objects exist in the current scene.","the number of _PARAM0_ objects":"o n\xFAmero de objectos _PARAMO_","Test the collision between two objects using their collision masks.\nNote that some objects may not have collision masks.\nSome others, like Sprite objects, also provide more precise collision conditions.":"Test the collision between two objects using their collision masks.\nNote that some objects may not have collision masks.\nSome others, like Sprite objects, also provide more precise collision conditions.","_PARAM0_ is in collision with _PARAM1_":"_PARAM0_ est\xE1 em colis\xE3o com _PARAM1_","An object is turned toward another":"Um objeto \xE9 rotacionado em dire\xE7\xE3o a outro","Check if an object is turned toward another":"Check if an object is turned toward another","_PARAM0_ is rotated towards _PARAM1_":"_PARAM0_ \xE9 rotacionado no sentido de _PARAM1_","Name of the object":"Nome do objeto","Name of the second object":"Nome do segundo objeto","Angle of tolerance, in degrees (0: minimum tolerance)":"\xC2ngulo de toler\xE2ncia, em graus (0: toler\xE2ncia m\xEDnima)","Raycast":"Raycast","Sends a ray from the given source position and angle, intersecting the closest object.\nThe instersected object will become the only one taken into account.\nIf the condition is inverted, the object to be intersected will be the farthest one within the ray radius.":"Enviar um raio da posi\xE7\xE3o e do \xE2ngulo de origem dados, intersectando o object mais pr\xF3ximo.\nO object interceptado tornar-se-\xE1 o \xFAnico considerado.\nSe a condi\xE7\xE3o estiver invertida, o object a ser interceptado ser\xE1 o mais distante dentro do raio de raio.","Cast a ray from _PARAM1_;_PARAM2_, angle: _PARAM3_ and max distance: _PARAM4_px, against _PARAM0_, and save the result in _PARAM5_, _PARAM6_":"Cast a ray from _PARAM1_;_PARAM2_, angle: _PARAM3_ and max distance: _PARAM4_px, against _PARAM0_, and save the result in _PARAM5_, _PARAM6_","Objects to test against the ray":"Objects para testar contra o raio","Ray source X position":"Posi\xE7\xE3o X da fonte de raio","Ray source Y position":"Posi\xE7\xE3o Y da fonte de raio","Ray angle (in degrees)":"\xC2ngulo de raio (em graus)","Ray maximum distance (in pixels)":"Dist\xE2ncia m\xE1xima de raio (em p\xEDxeis)","Result X position scene variable":"Result X position scene variable","Scene variable where to store the X position of the intersection. If no intersection is found, the variable won't be changed.":"Scene variable where to store the X position of the intersection. If no intersection is found, the variable won't be changed.","Result Y position scene variable":"Result Y position scene variable","Scene variable where to store the Y position of the intersection. If no intersection is found, the variable won't be changed.":"Scene variable where to store the Y position of the intersection. If no intersection is found, the variable won't be changed.","Raycast to position":"Raycast para posi\xE7\xE3o","Sends a ray from the given source position to the final point, intersecting the closest object.\nThe instersected object will become the only one taken into account.\nIf the condition is inverted, the object to be intersected will be the farthest one within the ray radius.":"Enviar um raio da posi\xE7\xE3o de origem para o ponto final, intersectando o object mais pr\xF3ximo.\nO object interceptado tornar-se-\xE1 o \xFAnico a ser levado em considera\xE7\xE3o.\nSe a condi\xE7\xE3o estiver invertida, o object a ser interceptado ser\xE1 o mais distante dentro do raio de raio.","Cast a ray from from _PARAM1_;_PARAM2_ to _PARAM3_;_PARAM4_ against _PARAM0_, and save the result in _PARAM5_, _PARAM6_":"Cast a ray from from _PARAM1_;_PARAM2_ to _PARAM3_;_PARAM4_ against _PARAM0_, and save the result in _PARAM5_, _PARAM6_","Ray target X position":"Posi\xE7\xE3o X do alvo do raio","Ray target Y position":"Posi\xE7\xE3o Y do alvo do raio","Count the number of the specified objects being currently picked in the event":"Contar o n\xFAmero dos objects especificados que est\xE3o sendo atualmente selecionados no evento","Return the name of the object":"Retorna o nome do object","Object layer":"Camada de object","Return the name of the layer the object is on":"Retorna o nome da camada na qual o object est\xE1","Existence of a group":"Exist\xEAncia de um grupo","Check if an element (example : PlayerState/CurrentLevel) exists in the stored data.\nSpaces are forbidden in element names.":"Check if an element (example : PlayerState/CurrentLevel) exists in the stored data.\nSpaces are forbidden in element names.","_PARAM1_ exists in storage _PARAM0_":"_PARAM1_ exists in storage _PARAM0_","Storage name":"Storage name","Load a storage in memory":"Load a storage in memory","This action loads the specified storage in memory, so you can write and read it.\nYou can open and write without using this action, but it will be slower.\nIf you use this action, do not forget to unload the storage from memory.":"This action loads the specified storage in memory, so you can write and read it.\nYou can open and write without using this action, but it will be slower.\nIf you use this action, do not forget to unload the storage from memory.","Load storage _PARAM0_ in memory":"Load storage _PARAM0_ in memory","Close a storage":"Close a storage","This action closes the structured data previously loaded in memory, saving all changes made.":"This action closes the structured data previously loaded in memory, saving all changes made.","Close structured data _PARAM0_":"Close structured data _PARAM0_","Write a value":"Escreva um valor","Write the result of the expression in the stored data, in the specified element.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.":"Write the result of the expression in the stored data, in the specified element.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.","Write _PARAM2_ in _PARAM1_ of storage _PARAM0_":"Write _PARAM2_ in _PARAM1_ of storage _PARAM0_","Write a text":"Escreva um texto","Write the text in the specified storage, in the specified element.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.":"Write the text in the specified storage, in the specified element.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.","Read a value":"Ler um valor","Read the value saved in the specified element and store it in a scene variable.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.":"Read the value saved in the specified element and store it in a scene variable.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.","Read _PARAM1_ from storage _PARAM0_ and store value in _PARAM3_":"Read _PARAM1_ from storage _PARAM0_ and store value in _PARAM3_","Scene variables":"Vari\xE1veis de cena","Read a text":"Ler um texto","Read the text saved in the specified element and store it in a scene variable.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.":"Read the text saved in the specified element and store it in a scene variable.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.","Read _PARAM1_ from storage _PARAM0_ and store as text in _PARAM3_":"Read _PARAM1_ from storage _PARAM0_ and store as text in _PARAM3_","Delete an element":"Excluir um elemento","This action deletes the specified element from the specified storage.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.":"This action deletes the specified element from the specified storage.\nSpecify the structure leading to the element using / (example : Root/Level/Current)\nSpaces are forbidden in element names.","Delete _PARAM1_ from storage _PARAM0_":"Delete _PARAM1_ from storage _PARAM0_","Clear a storage":"Clear a storage","Clear the specified storage, removing all data saved in it.":"Clear the specified storage, removing all data saved in it.","Delete storage _PARAM0_":"Delete storage _PARAM0_","A storage exists":"A storage exists","Test if the specified storage exists.":"Test if the specified storage exists.","Storage _PARAM0_ exists":"Storage _PARAM0_ exists","Open a URL or a file":"Open a URL or a file","This action launches the specified file or URL, in a browser (or in a new tab if the game is using the Web platform and is launched inside a browser).":"This action launches the specified file or URL, in a browser (or in a new tab if the game is using the Web platform and is launched inside a browser).","Open URL (or file) _PARAM0_":"_PARAM0_ aberto de URL (ou arquivo)","Files":"Arquivos","URL (or filename)":"URL (ou o nome do arquivo)","Execute a command":"Executar um comando","This action executes the specified command.":"This action executes the specified command.","Execute _PARAM0_":"Executar _PARAM0_","Command":"Comando","Create objects from an external layout":"Criar objetos a partir de um layout externo","Create objects from an external layout.":"Criar objetos a partir de um layout externo.","Create objects from the external layout named _PARAM1_":"Create objects from the external layout named _PARAM1_","Name of the external layout":"Nome do layout externo","X position of the origin":"Posi\xE7\xE3o X da origem","Y position of the origin":"Posi\xE7\xE3o Y da origem","Keyboard features":"Fun\xE7\xF5es do teclado","Allows your game to respond to keyboard input. Note that this does not work with on-screen keyboard on touch devices: use instead conditions related to touch when making a game for mobile/touchscreen devices.":"Allows your game to respond to keyboard input. Note that this does not work with on-screen keyboard on touch devices: use instead conditions related to touch when making a game for mobile/touchscreen devices.","Key pressed":"Tecla pressionada","Check if a key is pressed":"Check if a key is pressed","_PARAM1_ key is pressed":"_PARAM1_ tecla \xE9 pressionada","Keyboard":"Teclado","Key released":"Tecla libertada","Check if a key was just released":"Check if a key was just released","_PARAM1_ key is released":"Tecla _PARAM1_ foi solta","Key pressed (text expression)":"Tecla pressionada (express\xE3o de texto)","Check if a key, retrieved from the result of the expression, is pressed":"Check if a key, retrieved from the result of the expression, is pressed","Expression generating the key to check":"Expression generating the key to check","Key released (text expression)":"Tecla liberada (express\xE3o de texto)","Check if a key, retrieved from the result of the expression, was just released":"Check if a key, retrieved from the result of the expression, was just released","Any key pressed":"Qualquer tecla pressionada","Check if any key is pressed":"Check if any key is pressed","Any key is pressed":"Qualquer tecla \xE9 pressionada","Any key released":"Any key released","Check if any key is released":"Check if any key is released","Any key is released":"Any key is released","Last pressed key":"\xDAltima tecla pressionada","Get the name of the latest key pressed on the keyboard":"Obter o nome da \xFAltima tecla pressionada no teclado","Mathematical tools":"Ferramentas matem\xE1ticas","Normalize a value between `min` and `max` to a value between 0 and 1.":"Normalize a value between `min` and `max` to a value between 0 and 1.","Remap a value between 0 and 1.":"Remap a value between 0 and 1.","Min":"Min","Max":"Max","Clamp (restrict a value to a given range)":"Clamp (restrict a value to a given range)","Restrict a value to a given range":"Restrict a value to a given range","Difference between two angles":"Diferen\xE7a entre dois \xE2ngulos","First angle":"Primeiro \xE2ngulo","Second angle":"Segundo \xE2ngulo","Angle between two positions":"Angle between two positions","Compute the angle between two positions.":"Compute the angle between two positions.","First point X position":"First point X position","First point Y position":"First point Y position","Second point X position":"Second point X position","Second point Y position":"Second point Y position","Distance between two positions":"Distance between two positions","Compute the distance between two positions.":"Compute the distance between two positions.","Modulo":"M\xF3dulo","x mod y":"x mod y","x (as in x mod y)":"x (como em x mod y)","y (as in x mod y)":"y (como em x mod y)","Minimum of two numbers":"M\xEDnimo de dois n\xFAmeros","Maximum of two numbers":"M\xE1ximo de dois n\xFAmeros","Absolute value":"Valor absoluto","Arccosine":"Arco cosseno","Hyperbolic arccosine":"Arco cosseno hiperb\xF3lico","Arcsine":"Arco seno","Arctangent":"Arco tangente","2 argument arctangent":"Arco tangente de 2 argumentos","2 argument arctangent (atan2)":"Arco tangente de 2 argumentos (atan2)","Hyperbolic arctangent":"Arco tangente hiperb\xF3lica","Cube root":"Raiz c\xFAbica","Ceil (round up)":"Ceil (arredondar para mais)","Round number up to an integer":"Arredonda um n\xFAmero para cima at\xE9 um inteiro","Floor (round down)":"Floor (arredonda para menos)","Round number down to an integer":"Arredonda um n\xFAmero para baixo at\xE9 um inteiro","Cosine":"Cosseno","Cosine of a number":"Cosseno de um n\xFAmero","Hyperbolic cosine":"Cosseno hiperb\xF3lico","Cotangent":"Cotangente","Cotangent of a number":"Cotangente de um n\xFAmero","Cosecant":"Cossecante","Cosecant of a number":"Cossecante de um n\xFAmero","Round":"Arredondar","Round a number":"Arredondar um n\xFAmero","Exponential":"Exponencial","Exponential of a number":"Exponencial de um n\xFAmero","Logarithm":"Logaritmo","Base-2 logarithm":"Logaritmo de base 2","Base 2 Logarithm":"Logaritmo de base 2","Base-10 logarithm":"Logaritmo de base 10","Nth root":"Raiz en\xE9sima","Nth root of a number":"Raiz en\xE9sima de um n\xFAmero","N":"N","Power":"Pot\xEAncia","Raise a number to power n":"Elevar um n\xFAmero \xE0 pot\xEAncia n","The exponent (n in x^n)":"O expoente (n em x ^ n)","Secant":"Secante","Sign of a number":"Sinal de um n\xFAmero","Return the sign of a number (1,-1 or 0)":"Retornar o sinal de um n\xFAmero (1, -1 ou 0)","Sine":"Seno","Sine of a number":"Seno de um n\xFAmero","Hyperbolic sine":"Seno hiperb\xF3lico","Square root":"Raiz quadrada","Square root of a number":"Raiz quadrada de um n\xFAmero","Tangent":"Tangente","Tangent of a number":"Tangente de um n\xFAmero","Hyperbolic tangent":"Tangente hiperb\xF3lica","Truncation":"Truncamento","Truncate a number":"Truncate a number","Lerp (Linear interpolation)":"Lerp (interpola\xE7\xE3o Linear)","Linearly interpolate a to b by x":"Interpolar linearmente a para b por x","a (in a+(b-a)*x)":"a (em a+(b-a)*x)","b (in a+(b-a)*x)":"b (em a+(b-a)*x)","x (in a+(b-a)*x)":"x (em a+(b-a)*x)","Compute the X position when given an angle and distance relative to the origin (0;0). This is also known as getting the cartesian coordinates of a 2D vector, using its polar coordinates.":"Compute the X position when given an angle and distance relative to the origin (0;0). This is also known as getting the cartesian coordinates of a 2D vector, using its polar coordinates.","Compute the Y position when given an angle and distance relative to the origin (0;0). This is also known as getting the cartesian coordinates of a 2D vector, using its polar coordinates.":"Compute the Y position when given an angle and distance relative to the origin (0;0). This is also known as getting the cartesian coordinates of a 2D vector, using its polar coordinates.","Standard Conversions":"Convers\xF5es padr\xE3o","Text > Number":"Texto > N\xFAmero","Convert the text to a number":"Converter o texto num n\xFAmero","Conversion":"Convers\xE3o","Text to convert to a number":"Text to convert to a number","Number > Text":"N\xFAmero > Texto","Convert the result of the expression to text":"Convert the result of the expression to text","Expression to be converted to text":"Expression to be converted to text","Number > Text ( without scientific notation )":"N\xFAmero > Texto (sem nota\xE7\xE3o cient\xEDfica)","Convert the result of the expression to text, without using the scientific notation":"Convert the result of the expression to text, without using the scientific notation","Degrees > Radians":"Graus > Radianos","Converts the angle, expressed in degrees, into radians":"Converte o \xE2ngulo, expressado em graus, em radianos","Radians > Degrees":"Radianos > Graus","Converts the angle, expressed in radians, into degrees":"Converte o \xE2ngulo expressado em radianos, em graus","Angle, in radians":"\xC2ngulo em radianos","Basic internet features":"Recursos b\xE1sicos da internet","Features to send web requests, communicate with external \"APIs\" and other network related tasks.":"Features to send web requests, communicate with external \"APIs\" and other network related tasks.","Network":"Rede","Send a request to a web page":"Enviar uma solicita\xE7\xE3o para uma p\xE1gina da web","Send an asynchronous request to the specified web page.\n\nPlease note that for the web games, the game must be hosted on the same host as specified below, except if the server is configured to answer to all requests (cross-domain requests).":"Send an asynchronous request to the specified web page.\n\nPlease note that for the web games, the game must be hosted on the same host as specified below, except if the server is configured to answer to all requests (cross-domain requests).","Send a _PARAM2_ request to _PARAM0_ with body: _PARAM1_, and store the result in _PARAM4_ (or in _PARAM5_ in case of error)":"Send a _PARAM2_ request to _PARAM0_ with body: _PARAM1_, and store the result in _PARAM4_ (or in _PARAM5_ in case of error)","URL (API or web-page address)":"URL (API or web-page address)","Example: \"https://example.com/user/123\". Using *https* is highly recommended.":"Example: \"https://example.com/user/123\". Using *https* is highly recommended.","Request body content":"Solicitar o conte\xFAdo de corpo","Request method":"Request method","If empty, \"GET\" will be used.":"If empty, \"GET\" will be used.","Content type":"Content type","If empty, \"application/x-www-form-urlencoded\" will be used.":"If empty, \"application/x-www-form-urlencoded\" will be used.","Variable where to store the response":"Variable where to store the response","The response of the server will be stored, as a string, in this variable. If the server returns *JSON*, you may want to use the action \"Convert JSON to a scene variable\" afterwards, to explore the results with a *structure variable*.":"The response of the server will be stored, as a string, in this variable. If the server returns *JSON*, you may want to use the action \"Convert JSON to a scene variable\" afterwards, to explore the results with a *structure variable*.","Variable where to store the error message":"Variable where to store the error message","Optional, only used if an error occurs. This will contain the error message (if request could not be sent) or the [\"status code\"](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes), if the server returns a status >= 400.":"Optional, only used if an error occurs. This will contain the error message (if request could not be sent) or the [\"status code\"](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes), if the server returns a status >= 400.","Download a file":"Download de um arquivo","Download a file from a web site":"Baixar um arquivo de um site da web","Download file _PARAM1_ from _PARAM0_ under the name of _PARAM2_":"Carregar o ficheiro _PARAM1_ de _PARAM0_ sob o nome de _PARAM2_","Host (for example : http://www.website.com)":"Host (Por exemplo: http://www.website.com)","Path to file (for example : /folder/file.txt)":"Caminho para o arquivo (por exemplo: /folder/file.txt)","Save as":"Guardar como","Enable (or disable) metrics collection":"Enable (or disable) metrics collection","Enable, or disable, the sending of anonymous data used to compute the number of sessions and other metrics from your game players.\nBe sure to only send metrics if in accordance with the terms of service of your game and if they player gave their consent, depending on how your game/company handles this.":"Enable, or disable, the sending of anonymous data used to compute the number of sessions and other metrics from your game players.\nBe sure to only send metrics if in accordance with the terms of service of your game and if they player gave their consent, depending on how your game/company handles this.","Enable analytics metrics: _PARAM1_":"Enable analytics metrics: _PARAM1_","Enable the metrics?":"Enable the metrics?","Convert JSON to a scene variable":"Convert JSON to a scene variable","Parse a JSON object and store it into a scene variable":"Parse a JSON object and store it into a scene variable","Parse JSON string _PARAM0_ and store it into variable _PARAM1_":"Analisa a string JASON _PARAM0_ e armazena na vari\xE1vel _PARAM1_","JSON string":"Cadeia de caracteres JSON","Variable where store the JSON object":"Vari\xE1vel onde armazenar o objeto JSON","Convert JSON to global variable":"Convert JSON to global variable","Parse a JSON object and store it into a global variable":"Parse a JSON object and store it into a global variable","Parse JSON string _PARAM0_ and store it into global variable _PARAM1_":"Parse JSON string _PARAM0_ and store it into global variable _PARAM1_","Global variable where store the JSON object":"Global variable where store the JSON object","Convert JSON to object variable":"Convert JSON to object variable","Parse a JSON object and store it into an object variable":"Parse a JSON object and store it into an object variable","Parse JSON string _PARAM0_ and store it into variable _PARAM2_ of _PARAM1_":"Parse JSON string _PARAM0_ and store it into variable _PARAM2_ of _PARAM1_","Object variable where store the JSON object":"Object variable where store the JSON object","Convert scene variable to JSON":"Convert scene variable to JSON","Convert a scene variable to JSON":"Convert a scene variable to JSON","Scene variable to be stringified":"Scene variable to be stringified","Convert global variable to JSON":"Convert global variable to JSON","Convert a global variable to JSON":"Convert a global variable to JSON","The global variable to be stringified":"The global variable to be stringified","Convert object variable to JSON":"Convert object variable to JSON","Convert an object variable to JSON":"Convert an object variable to JSON","The object with the variable":"The object with the variable","The object variable to be stringified":"The object variable to be stringified","The mouse wheel is scrolling up":"The mouse wheel is scrolling up","Check if the mouse wheel is scrolling up. Use MouseWheelDelta expression if you want to know the amount that was scrolled.":"Check if the mouse wheel is scrolling up. Use MouseWheelDelta expression if you want to know the amount that was scrolled.","The mouse wheel is scrolling down":"The mouse wheel is scrolling down","Check if the mouse wheel is scrolling down. Use MouseWheelDelta expression if you want to know the amount that was scrolled.":"Check if the mouse wheel is scrolling down. Use MouseWheelDelta expression if you want to know the amount that was scrolled.","De/activate moving the mouse cursor with touches":"De/activate moving the mouse cursor with touches","When activated, any touch made on a touchscreen will also move the mouse cursor. When deactivated, mouse and touch positions will be completely independent.\nBy default, this is activated so that you can simply use the mouse conditions to also support touchscreens. If you want to have multitouch and differentiate mouse movement and touches, just deactivate it with this action.":"When activated, any touch made on a touchscreen will also move the mouse cursor. When deactivated, mouse and touch positions will be completely independent.\nBy default, this is activated so that you can simply use the mouse conditions to also support touchscreens. If you want to have multitouch and differentiate mouse movement and touches, just deactivate it with this action.","Move mouse cursor when touching screen: _PARAM1_":"Mover o cursor do rato quando tocar no ecr\xE3: _PARAM1_","Activate (yes by default when game is launched)":"Ativar (sim por padr\xE3o quando o jogo for lan\xE7ado)","Center cursor horizontally":"Centrar o cursor horizontalmente","Put the cursor in the middle of the screen horizontally.":"Coloque o cursor horizontalmente no meio da tela.","Center cursor vertically":"Centrar verticalmente o cursor","Put the cursor in the middle of the screen vertically.":"Coloque o cursor verticalmente no meio da tela.","Hide the cursor":"Ocultar o cursor","Hide the cursor.":"Ocultar o cursor.","Show the cursor":"Mostrar o cursor","Show the cursor.":"Mostrar o cursor.","Position the cursor of the mouse":"Posi\xE7\xE3o do cursor do rato","Position the cursor at the given coordinates.":"Posi\xE7\xE3o do cursor nas coordenadas indicadas.","Position cursor at _PARAM1_;_PARAM2_":"Posi\xE7\xE3o do cursor em _PARAM1_;_PARAM2_","Center the cursor":"Centrar o cursor","Center the cursor on the screen.":"Centrar o cursor na tela.","Cursor X position":"Posi\xE7\xE3o X do cursor","the X position of the cursor or of a touch":"the X position of the cursor or of a touch","the cursor (or touch) X position":"the cursor (or touch) X position","Cursor Y position":"Posi\xE7\xE3o Y do cursor","the Y position of the cursor or of a touch":"the Y position of the cursor or of a touch","the cursor (or touch) Y position":"the cursor (or touch) Y position","Mouse button pressed or touch held":"Mouse button pressed or touch held","Check if the specified mouse button is pressed or if a touch is in contact with the screen.":"Check if the specified mouse button is pressed or if a touch is in contact with the screen.","Touch or _PARAM1_ mouse button is down":"Toque ou bot\xE3o _PARAM1_ do mouse est\xE1 pressionado","Button to check":"Button to check","Mouse button released":"Bot\xE3o do mouse libertado","Check if the specified mouse button was released.":"Check if the specified mouse button was released.","_PARAM1_ mouse button was released":"Bot\xE3o _PARAM1_ do mouse foi liberado","Mouse button pressed or touch held (text expression)":"Mouse button pressed or touch held (text expression)","Check if a mouse button, retrieved from the result of the expression, is pressed.":"Check if a mouse button, retrieved from the result of the expression, is pressed.","_PARAM1_ mouse button is pressed":"_PARAM1_ mouse button is pressed","Expression generating the button to check":"Expression generating the button to check","Possible values are Left, Right and Middle.":"Possible values are Left, Right and Middle.","Mouse button released (text expression)":"Mouse button released (text expression)","Check if a mouse button, retrieved from the result of the expression, was just released.":"Check if a mouse button, retrieved from the result of the expression, was just released.","_PARAM1_ mouse button is released":"_PARAM1_ mouse button is released","Expression generating the mouse button to check":"Expression generating the mouse button to check","Touch X position":"Posi\xE7\xE3o X toque","the X position of a specific touch":"the X position of a specific touch","the touch #_PARAM1_ X position":"the touch #_PARAM1_ X position","Mouse and touch/Multitouch":"Mouse e touch/Multitouch","Touch identifier":"Identificador de toque","Touch Y position":"Toque a posi\xE7\xE3o Y","the Y position of a specific touch":"the Y position of a specific touch","the touch #_PARAM1_ Y position":"the touch #_PARAM1_ Y position","A new touch has started":"Come\xE7ou um novo toque","Check if a touch has started. The touch identifier can be accessed using LastTouchId().\nAs more than one touch can be started, this condition is only true once for each touch: the next time you use it, it will be for a new touch, or it will return false if no more touches have just started.":"Check if a touch has started. The touch identifier can be accessed using LastTouchId().\nAs more than one touch can be started, this condition is only true once for each touch: the next time you use it, it will be for a new touch, or it will return false if no more touches have just started.","A touch has ended":"Um toque terminou","Check if a touch has ended. The touch identifier can be accessed using LastEndedTouchId().\nAs more than one touch can be ended, this condition is only true once for each touch: the next time you use it, it will be for a new touch, or it will return false if no more touches have just ended.":"Check if a touch has ended. The touch identifier can be accessed using LastEndedTouchId().\nAs more than one touch can be ended, this condition is only true once for each touch: the next time you use it, it will be for a new touch, or it will return false if no more touches have just ended.","Mouse wheel: Displacement":"Roda do mouse: Deslocamento","Mouse wheel displacement":"Deslocamento daroda do mouse","Identifier of the last touch":"Identificador do \xFAltimo toque","Identifier of the last ended touch":"Identificador do ultimo toque finalizado","Cannot find an expression with this name: ":"N\xE3o \xE9 poss\xEDvel encontrar uma express\xE3o com este nome: ","Double check that you've not made any typo in the name.":"Verificar duplamente se voc\xEA n\xE3o fez nenhum erro de digita\xE7\xE3o no nome.","You tried to use an expression that returns a number, but a string is expected. Use `ToString` if you need to convert a number to a string.":"You tried to use an expression that returns a number, but a string is expected. Use `ToString` if you need to convert a number to a string.","You tried to use an expression that returns a number, but another type is expected:":"You tried to use an expression that returns a number, but another type is expected:","You tried to use an expression that returns a string, but a number is expected. Use `ToNumber` if you need to convert a string to a number.":"You tried to use an expression that returns a string, but a number is expected. Use `ToNumber` if you need to convert a string to a number.","You tried to use an expression that returns a string, but another type is expected:":"You tried to use an expression that returns a string, but another type is expected:","You tried to use an expression with the wrong return type:":"You tried to use an expression with the wrong return type:","The number of parameters must be exactly ":"O n\xFAmero de par\xE2metros deve ser exatamente ","The number of parameters must be: ":"O n\xFAmero de par\xE2metros deve ser: ","A text must start with a double quote (\").":"Um texto deve come\xE7ar com aspas duplas (\").","A text must end with a double quote (\"). Add a double quote to terminate the text.":"Um texto deve terminar com aspas duplas (\"). Adicione uma aspa dupla para terminar o texto.","A number was expected. You must enter a number here.":"Um n\xFAmero era esperado. Voc\xEA deve inserir um n\xFAmero aqui.","Unable to copy \"":"Imposs\xEDvel copiar\"","\" to \"":"\"a\"","\".":"\".","Smooth the image":"Suavizar a imagem","Always loaded in memory":"Sempre carregado na mem\xF3ria","Preload as sound":"Preload as sound","Preload as music":"Preload as music","Disable preloading at game startup":"Disable preloading at game startup","The expression has extra character at the end that should be removed (or completed if your expression is not finished).":"A express\xE3o tem um caractere extra no final que deve ser removido (ou conclu\xEDdo se sua express\xE3o n\xE3o estiver terminada).","You entered a text, but a number was expected.":"Voc\xEA inseriu um texto, mas um n\xFAmero era esperado.","You entered a text, but this type was expected:":"Voc\xEA inseriu um texto, mas este tipo era esperado:","You entered a number, but a text was expected (in quotes).":"Voc\xEA inseriu um n\xFAmero, mas um texto era esperado (entre aspas).","You entered a number, but this type was expected:":"Voc\xEA inseriu um n\xFAmero, mas este tipo era esperado:","Missing a closing parenthesis. Add a closing parenthesis for each opening parenthesis.":"Falta um par\xEAntese fechado. Adicione um par\xEAntese fechado para cada par\xEAntese aberto.","You must wrap your text inside double quotes (example: \"Hello world\").":"Voc\xEA deve envolver seu texto entre aspas duplas (exemplo: \"Hello world\").","You must enter a number.":"Voc\xEA deve inserir um n\xFAmero.","You must enter a number or a text, wrapped inside double quotes (example: \"Hello world\").":"You must enter a number or a text, wrapped inside double quotes (example: \"Hello world\").","You've entered a name, but this type was expected:":"Voc\xEA inseriu um nome, mas este tipo era esperado:","Missing a closing bracket. Add a closing bracket for each opening bracket.":"Falta um colchete fechado. Adicione um colchete fechado para cada colchete aberto.","An opening parenthesis (for an object expression), or double colon (::) was expected (for a behavior expression).":"Um par\xEAntese aberto (para uma express\xE3o de object) ou dois pontos duplos (::) era esperado (para uma express\xE3o de comportamento).","An opening parenthesis was expected here to call a function.":"Um par\xEAntese aberto era esperado aqui para chamar uma fun\xE7\xE3o.","An object name was expected but something else was written. Enter just the name of the object for this parameter.":"An object name was expected but something else was written. Enter just the name of the object for this parameter.","This function is improperly set up. Reach out to the extension developer or a GDevelop maintainer to fix this issue":"Esta fun\xE7\xE3o est\xE1 configurada incorretamente. Entre em contato com o desenvolvedor da extens\xE3o ou com um mantenedor do GDevelop para corrigir esse problema","This parameter was not expected by this expression. Remove it or verify that you've entered the proper expression name.":"Este par\xE2metro n\xE3o foi esperado por esta express\xE3o. Remover ou verificar que voc\xEA digitou o nome da express\xE3o adequada.","The list of parameters is not terminated. Add a closing parenthesis to end the parameters.":"A lista de par\xE2metros n\xE3o est\xE1 finalizada. Adicione um par\xEAntese fechado para finalizar os par\xE2metros.","You've used an operator that is not supported. Operator should be either +, -, / or *.":"Voc\xEA usou um operador que n\xE3o \xE9 suportado. O operador deve ser +, -, / ou *.","You've used an operator that is not supported. Only + can be used to concatenate texts.":"Voc\xEA usou um operador que n\xE3o \xE9 suportado. Somente + pode ser usado para concatenar textos.","Operators (+, -, /, *) can't be used with an object name. Remove the operator.":"Operadores (+, -, /, *) n\xE3o podem ser usados com um object name. Remova o operador.","Operators (+, -, /, *) can't be used in variable names. Remove the operator from the variable name.":"Operadores (+, -, /, *) n\xE3o podem ser usados em nomes de vari\xE1veis. Remova o operador do nome da vari\xE1vel.","You've used an \"unary\" operator that is not supported. Operator should be either + or -.":"Voc\xEA usou um operador \"un\xE1rio\" que n\xE3o \xE9 suportado. Operador deve ser + ou -.","You've used an operator that is not supported. Only + can be used to concatenate texts, and must be placed between two texts (or expressions).":"Voc\xEA usou um operador que n\xE3o \xE9 suportado. Somente + pode ser usado para concatenar textos e deve ser colocado entre dois textos (ou express\xF5es).","Operators (+, -) can't be used with an object name. Remove the operator.":"Operadores (+, -) n\xE3o podem ser usados com um object name. Remover o operador.","Operators (+, -) can't be used in variable names. Remove the operator from the variable name.":"Operadores (+, -) n\xE3o podem ser usados em nomes de vari\xE1veis. Remover o operador do nome da vari\xE1vel.","You must enter a number or a valid expression call.":"Voc\xEA deve inserir um n\xFAmero ou uma chamada de express\xE3o v\xE1lida.","You must enter a text (between quotes) or a valid expression call.":"Voc\xEA deve inserir um texto (entre aspas) ou uma chamada de express\xE3o v\xE1lida.","You must enter a variable name.":"Voc\xEA deve inserir um nome de vari\xE1vel.","You must enter a valid object name.":"Voc\xEA deve inserir um object name v\xE1lido.","You must enter a valid expression.":"Voc\xEA deve inserir uma express\xE3o v\xE1lida."}};
/* * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <config.h> #include "pktbuf.h" #include <inttypes.h> #include <stdlib.h> #include "coverage.h" #include "ofp-util.h" #include "ofpbuf.h" #include "timeval.h" #include "util.h" #include "vconn.h" #include "vlog.h" VLOG_DEFINE_THIS_MODULE(pktbuf); COVERAGE_DEFINE(pktbuf_buffer_unknown); COVERAGE_DEFINE(pktbuf_null_cookie); COVERAGE_DEFINE(pktbuf_retrieved); COVERAGE_DEFINE(pktbuf_reuse_error); /* Buffers are identified by a 32-bit opaque ID. We divide the ID * into a buffer number (low bits) and a cookie (high bits). The buffer number * is an index into an array of buffers. The cookie distinguishes between * different packets that have occupied a single buffer. Thus, the more * buffers we have, the lower-quality the cookie... */ #define PKTBUF_BITS 8 #define PKTBUF_MASK (PKTBUF_CNT - 1) #define PKTBUF_CNT (1u << PKTBUF_BITS) #define COOKIE_BITS (32 - PKTBUF_BITS) #define COOKIE_MAX ((1u << COOKIE_BITS) - 1) #define OVERWRITE_MSECS 5000 struct packet { struct ofpbuf *buffer; uint32_t cookie; long long int timeout; ofp_port_t in_port; }; struct pktbuf { struct packet packets[PKTBUF_CNT]; unsigned int buffer_idx; unsigned int null_idx; }; int pktbuf_capacity(void) { return PKTBUF_CNT; } struct pktbuf * pktbuf_create(void) { return xzalloc(sizeof *pktbuf_create()); } void pktbuf_destroy(struct pktbuf *pb) { if (pb) { size_t i; for (i = 0; i < PKTBUF_CNT; i++) { ofpbuf_delete(pb->packets[i].buffer); } free(pb); } } static unsigned int make_id(unsigned int buffer_idx, unsigned int cookie) { return buffer_idx | (cookie << PKTBUF_BITS); } /* Attempts to allocate an OpenFlow packet buffer id within 'pb'. The packet * buffer will store a copy of 'buffer_size' bytes in 'buffer' and the port * number 'in_port', which should be the OpenFlow port number on which 'buffer' * was received. * * If successful, returns the packet buffer id (a number other than * UINT32_MAX). pktbuf_retrieve() can later be used to retrieve the buffer and * its input port number (buffers do expire after a time, so this is not * guaranteed to be true forever). On failure, returns UINT32_MAX. * * The caller retains ownership of 'buffer'. */ uint32_t pktbuf_save(struct pktbuf *pb, const void *buffer, size_t buffer_size, ofp_port_t in_port) { struct packet *p = &pb->packets[pb->buffer_idx]; pb->buffer_idx = (pb->buffer_idx + 1) & PKTBUF_MASK; if (p->buffer) { if (time_msec() < p->timeout) { return UINT32_MAX; } ofpbuf_delete(p->buffer); } /* Don't use maximum cookie value since all-1-bits ID is special. */ if (++p->cookie >= COOKIE_MAX) { p->cookie = 0; } p->buffer = ofpbuf_clone_data_with_headroom(buffer, buffer_size, sizeof(struct ofp10_packet_in)); p->timeout = time_msec() + OVERWRITE_MSECS; p->in_port = in_port; return make_id(p - pb->packets, p->cookie); } /* * Allocates and returns a "null" packet buffer id. The returned packet buffer * id is considered valid by pktbuf_retrieve(), but it is not associated with * actual buffered data. * * This function is always successful. * * This is useful in one special case: with the current OpenFlow design, the * "fail-open" code cannot always know whether a connection to a controller is * actually valid until it receives a OFPT_PACKET_OUT or OFPT_FLOW_MOD request, * but at that point the packet in question has already been forwarded (since * we are still in "fail-open" mode). If the packet was buffered in the usual * way, then the OFPT_PACKET_OUT or OFPT_FLOW_MOD would cause a duplicate * packet in the network. Null packet buffer ids identify such a packet that * has already been forwarded, so that Open vSwitch can quietly ignore the * request to re-send it. (After that happens, the switch exits fail-open * mode.) * * See the top-level comment in fail-open.c for an overview. */ uint32_t pktbuf_get_null(void) { return make_id(0, COOKIE_MAX); } /* Attempts to retrieve a saved packet with the given 'id' from 'pb'. Returns * 0 if successful, otherwise an OpenFlow error code. * * On success, ordinarily stores the buffered packet in '*bufferp' and the * OpenFlow port number on which the packet was received in '*in_port'. The * caller becomes responsible for freeing the buffer. However, if 'id' * identifies a "null" packet buffer (created with pktbuf_get_null()), stores * NULL in '*bufferp' and OFPP_NONE in '*in_port'. * * 'in_port' may be NULL if the input port is not of interest. * * A returned packet will have at least sizeof(struct ofp10_packet_in) bytes of * headroom. * * On failure, stores NULL in in '*bufferp' and UINT16_MAX in '*in_port'. */ enum ofperr pktbuf_retrieve(struct pktbuf *pb, uint32_t id, struct ofpbuf **bufferp, ofp_port_t *in_port) { static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 20); struct packet *p; enum ofperr error; if (id == UINT32_MAX) { error = 0; goto error; } if (!pb) { VLOG_WARN_RL(&rl, "attempt to send buffered packet via connection " "without buffers"); return OFPERR_OFPBRC_BUFFER_UNKNOWN; } p = &pb->packets[id & PKTBUF_MASK]; if (p->cookie == id >> PKTBUF_BITS) { struct ofpbuf *buffer = p->buffer; if (buffer) { *bufferp = buffer; if (in_port) { *in_port = p->in_port; } p->buffer = NULL; COVERAGE_INC(pktbuf_retrieved); return 0; } else { COVERAGE_INC(pktbuf_reuse_error); VLOG_WARN_RL(&rl, "attempt to reuse buffer %08"PRIx32, id); error = OFPERR_OFPBRC_BUFFER_EMPTY; } } else if (id >> PKTBUF_BITS != COOKIE_MAX) { COVERAGE_INC(pktbuf_buffer_unknown); VLOG_WARN_RL(&rl, "cookie mismatch: %08"PRIx32" != %08"PRIx32, id, (id & PKTBUF_MASK) | (p->cookie << PKTBUF_BITS)); error = OFPERR_OFPBRC_BUFFER_UNKNOWN; } else { COVERAGE_INC(pktbuf_null_cookie); VLOG_INFO_RL(&rl, "Received null cookie %08"PRIx32" (this is normal " "if the switch was recently in fail-open mode)", id); error = 0; } error: *bufferp = NULL; if (in_port) { *in_port = OFPP_NONE; } return error; } void pktbuf_discard(struct pktbuf *pb, uint32_t id) { struct packet *p = &pb->packets[id & PKTBUF_MASK]; if (p->cookie == id >> PKTBUF_BITS) { ofpbuf_delete(p->buffer); p->buffer = NULL; } } /* Returns the number of packets buffered in 'pb'. Returns 0 if 'pb' is * null. */ unsigned int pktbuf_count_packets(const struct pktbuf *pb) { int n = 0; if (pb) { int i; for (i = 0; i < PKTBUF_CNT; i++) { if (pb->packets[i].buffer) { n++; } } } return n; }
# Copyright (c) 2020 The Plankton Authors. # All rights reserved. # # This source code is derived from UUV Simulator # (https://github.com/uuvsimulator/uuv_simulator) # Copyright (c) 2016-2019 The UUV Simulator Authors # licensed under the Apache license, Version 2.0 # cf. 3rd-party-licenses.txt file in the root directory of this source tree. # # 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. """Trajectory generation package.""" from .wp_trajectory_generator import WPTrajectoryGenerator from .trajectory_point import TrajectoryPoint from .trajectory_generator import TrajectoryGenerator from .path_generator import *
/* ISC license. */ #include <string.h> #include <skalibs/sgetopt.h> #include <skalibs/stralloc.h> #include <skalibs/genalloc.h> #include <execline/execline.h> #include "exlsn.h" int exlsn_define (int argc, char const **argv, char const *const *envp, exlsn_t *info) { eltransforminfo_t si = ELTRANSFORMINFO_ZERO ; subgetopt localopt = SUBGETOPT_ZERO ; elsubst_t blah ; blah.var = info->vars.len ; blah.value = info->values.len ; for (;;) { int opt = subgetopt_r(argc, argv, "NnsCcd:", &localopt) ; if (opt < 0) break ; switch (opt) { case 'N' : si.chomp = 0 ; break ; case 'n' : si.chomp = 1 ; break ; case 's' : si.split = 1 ; break ; case 'C' : si.crunch = 1 ; break ; case 'c' : si.crunch = 0 ; break ; case 'd' : si.delim = localopt.arg ; break ; default : return -3 ; } } argc -= localopt.ind ; argv += localopt.ind ; if (argc < 2) return -3 ; if (!*argv[0] || el_vardupl(argv[0], info->vars.s, info->vars.len)) return -2 ; if (!stralloc_catb(&info->vars, argv[0], strlen(argv[0]) + 1)) return -1 ; if (!stralloc_cats(&info->values, argv[1])) goto err ; { int r = el_transform(&info->values, blah.value, &si) ; if (r < 0) goto err ; blah.n = r ; } if (!genalloc_append(elsubst_t, &info->data, &blah)) goto err ; (void)envp ; return localopt.ind + 2 ; err: info->vars.len = blah.var ; info->values.len = blah.value ; return -1 ; }
(function(){var d;window.AmCharts?d=window.AmCharts:(d={},window.AmCharts=d,d.themes={},d.maps={},d.inheriting={},d.charts=[],d.onReadyArray=[],d.useUTC=!1,d.updateRate=30,d.uid=0,d.lang={},d.translations={},d.mapTranslations={},d.windows={},d.initHandlers=[]);d.Class=function(a){var b=function(){arguments[0]!==d.inheriting&&(this.events={},this.construct.apply(this,arguments))};a.inherits?(b.prototype=new a.inherits(d.inheriting),b.base=a.inherits.prototype,delete a.inherits):(b.prototype.createEvents= function(){for(var a=0,b=arguments.length;a<b;a++)this.events[arguments[a]]=[]},b.prototype.listenTo=function(a,b,c){this.removeListener(a,b,c);a.events[b].push({handler:c,scope:this})},b.prototype.addListener=function(a,b,c){this.removeListener(this,a,b);this.events[a].push({handler:b,scope:c})},b.prototype.removeListener=function(a,b,c){if(a&&a.events)for(a=a.events[b],b=a.length-1;0<=b;b--)a[b].handler===c&&a.splice(b,1)},b.prototype.fire=function(a,b){for(var c=this.events[a],d=0,k=c.length;d< k;d++){var l=c[d];l.handler.call(l.scope,b)}});for(var c in a)b.prototype[c]=a[c];return b};d.addChart=function(a){d.updateInt||(d.updateInt=setInterval(function(){d.update()},Math.round(1E3/d.updateRate)));d.charts.push(a)};d.removeChart=function(a){for(var b=d.charts,c=b.length-1;0<=c;c--)b[c]==a&&b.splice(c,1);0===b.length&&d.updateInt&&(clearInterval(d.updateInt),d.updateInt=NaN)};d.isModern=!0;d.getIEVersion=function(){var a=0,b,c;"Microsoft Internet Explorer"==navigator.appName&&(b=navigator.userAgent, c=/MSIE ([0-9]{1,}[.0-9]{0,})/,null!==c.exec(b)&&(a=parseFloat(RegExp.$1)));return a};d.applyLang=function(a,b){var c=d.translations;b.dayNames=d.extend({},d.dayNames);b.shortDayNames=d.extend({},d.shortDayNames);b.monthNames=d.extend({},d.monthNames);b.shortMonthNames=d.extend({},d.shortMonthNames);c&&(c=c[a])&&(d.lang=c,c.monthNames&&(b.dayNames=d.extend({},c.dayNames),b.shortDayNames=d.extend({},c.shortDayNames),b.monthNames=d.extend({},c.monthNames),b.shortMonthNames=d.extend({},c.shortMonthNames)))}; d.IEversion=d.getIEVersion();9>d.IEversion&&0<d.IEversion&&(d.isModern=!1,d.isIE=!0);d.dx=0;d.dy=0;if(document.addEventListener||window.opera)d.isNN=!0,d.isIE=!1,d.dx=.5,d.dy=.5;document.attachEvent&&(d.isNN=!1,d.isIE=!0,d.isModern||(d.dx=0,d.dy=0));window.chrome&&(d.chrome=!0);d.handleMouseUp=function(a){for(var b=d.charts,c=0;c<b.length;c++){var e=b[c];e&&e.handleReleaseOutside&&e.handleReleaseOutside(a)}};d.handleMouseMove=function(a){for(var b=d.charts,c=0;c<b.length;c++){var e=b[c];e&&e.handleMouseMove&& e.handleMouseMove(a)}};d.handleWheel=function(a){for(var b=d.charts,c=0;c<b.length;c++){var e=b[c];if(e&&e.mouseIsOver){e.mouseWheelScrollEnabled||e.mouseWheelZoomEnabled?e.handleWheel&&e.handleWheel(a):a.stopPropagation&&a.stopPropagation();break}}};d.resetMouseOver=function(){for(var a=d.charts,b=0;b<a.length;b++){var c=a[b];c&&(c.mouseIsOver=!1)}};d.ready=function(a){d.onReadyArray.push(a)};d.handleLoad=function(){d.isReady=!0;for(var a=d.onReadyArray,b=0;b<a.length;b++){var c=a[b];isNaN(d.processDelay)? c():setTimeout(c,d.processDelay*b)}};d.addInitHandler=function(a,b){d.initHandlers.push({method:a,types:b})};d.callInitHandler=function(a){var b=d.initHandlers;if(d.initHandlers)for(var c=0;c<b.length;c++){var e=b[c];e.types?d.isInArray(e.types,a.type)&&e.method(a):e.method(a)}};d.getUniqueId=function(){d.uid++;return"AmChartsEl-"+d.uid};d.isNN&&(document.addEventListener("mousemove",d.handleMouseMove,!0),document.addEventListener("mouseup",d.handleMouseUp,!0),window.addEventListener("load",d.handleLoad, !0),window.addEventListener("DOMMouseScroll",d.handleWheel,!0),document.addEventListener("mousewheel",d.handleWheel,!0));d.isIE&&(document.attachEvent("onmousemove",d.handleMouseMove),document.attachEvent("onmouseup",d.handleMouseUp),window.attachEvent("onload",d.handleLoad));d.clear=function(){var a=d.charts;if(a)for(var b=a.length-1;0<=b;b--)a[b].clear();d.updateInt&&clearInterval(d.updateInt);d.charts=[];d.isNN&&(document.removeEventListener("mousemove",d.handleMouseMove,!0),document.removeEventListener("mouseup", d.handleMouseUp,!0),window.removeEventListener("load",d.handleLoad,!0),window.removeEventListener("DOMMouseScroll",d.handleWheel,!0),document.removeEventListener("mousewheel",d.handleWheel,!0));d.isIE&&(document.detachEvent("onmousemove",d.handleMouseMove),document.detachEvent("onmouseup",d.handleMouseUp),window.detachEvent("onload",d.handleLoad))};d.makeChart=function(a,b,c){var e=b.type,h=b.theme;d.isString(h)&&(h=d.themes[h],b.theme=h);var f;switch(e){case "serial":f=new d.AmSerialChart(h);break; case "xy":f=new d.AmXYChart(h);break;case "pie":f=new d.AmPieChart(h);break;case "radar":f=new d.AmRadarChart(h);break;case "gauge":f=new d.AmAngularGauge(h);break;case "funnel":f=new d.AmFunnelChart(h);break;case "map":f=new d.AmMap(h);break;case "stock":f=new d.AmStockChart(h);break;case "gantt":f=new d.AmGanttChart(h)}d.extend(f,b);if(b.listeners)for(var g in b.listeners)e=b.listeners[g],f.addListener(e.event,e.method);d.isReady?isNaN(c)?f.write(a):setTimeout(function(){d.realWrite(f,a)},c):d.ready(function(){isNaN(c)? f.write(a):setTimeout(function(){d.realWrite(f,a)},c)});return f};d.realWrite=function(a,b){a.write(b)};d.updateCount=0;d.validateAt=Math.round(d.updateRate/5);d.update=function(){var a=d.charts;d.updateCount++;var b=!1;d.updateCount==d.validateAt&&(b=!0,d.updateCount=0);if(a)for(var c=0;c<a.length;c++)a[c].update&&a[c].update(),b&&a[c].autoResize&&a[c].validateSize&&a[c].validateSize()};d.bezierX=3;d.bezierY=6})();(function(){var d=window.AmCharts;d.toBoolean=function(a,b){if(void 0===a)return b;switch(String(a).toLowerCase()){case "true":case "yes":case "1":return!0;case "false":case "no":case "0":case null:return!1;default:return Boolean(a)}};d.removeFromArray=function(a,b){var c;if(void 0!==b&&void 0!==a)for(c=a.length-1;0<=c;c--)a[c]==b&&a.splice(c,1)};d.getPath=function(){var a=document.getElementsByTagName("script");if(a)for(var b=0;b<a.length;b++){var c=a[b].src;if(-1!==c.search(/\/(amcharts|ammap)\.js/))return c.replace(/\/(amcharts|ammap)\.js.*/, "/")}};d.normalizeUrl=function(a){return""!==a&&-1===a.search(/\/$/)?a+"/":a};d.isAbsolute=function(a){return 0===a.search(/^http[s]?:|^\//)};d.isInArray=function(a,b){for(var c=0;c<a.length;c++)if(a[c]==b)return!0;return!1};d.getDecimals=function(a){var b=0;isNaN(a)||(a=String(a),-1!=a.indexOf("e-")?b=Number(a.split("-")[1]):-1!=a.indexOf(".")&&(b=a.split(".")[1].length));return b};d.wordwrap=function(a,b,c,e){var h,f,g,k;a+="";if(1>b)return a;h=-1;for(a=(k=a.split(/\r\n|\n|\r/)).length;++h<a;k[h]+= g){g=k[h];for(k[h]="";g.length>b;k[h]+=d.trim(g.slice(0,f))+((g=g.slice(f)).length?c:""))f=2==e||(f=g.slice(0,b+1).match(/\S*(\s)?$/))[1]?b:f.input.length-f[0].length||1==e&&b||f.input.length+(f=g.slice(b).match(/^\S*/))[0].length;g=d.trim(g)}return k.join(e)};d.trim=function(a){return a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};d.wrappedText=function(a,b,c,e,h,f,g,k){var l=d.text(a,b,c,e,h,f,g);if(l){var m=l.getBBox();if(m.width>k){var n="\n";d.isModern||(n="<br>");k=Math.floor(k/(m.width/ b.length));2<k&&(k-=2);b=d.wordwrap(b,k,n,!0);l.remove();l=d.text(a,b,c,e,h,f,g)}}return l};d.getStyle=function(a,b){var c="";document.defaultView&&document.defaultView.getComputedStyle?c=document.defaultView.getComputedStyle(a,"").getPropertyValue(b):a.currentStyle&&(b=b.replace(/\-(\w)/g,function(a,b){return b.toUpperCase()}),c=a.currentStyle[b]);return c};d.removePx=function(a){if(void 0!==a)return Number(a.substring(0,a.length-2))};d.getURL=function(a,b){if(a)if("_self"!=b&&b)if("_top"==b&&window.top)window.top.location.href= a;else if("_parent"==b&&window.parent)window.parent.location.href=a;else if("_blank"==b)window.open(a);else{var c=document.getElementsByName(b)[0];c?c.src=a:(c=d.windows[b])?c.opener&&!c.opener.closed?c.location.href=a:d.windows[b]=window.open(a):d.windows[b]=window.open(a)}else window.location.href=a};d.ifArray=function(a){return a&&"object"==typeof a&&0<a.length?!0:!1};d.callMethod=function(a,b){var c;for(c=0;c<b.length;c++){var e=b[c];if(e){if(e[a])e[a]();var h=e.length;if(0<h){var d;for(d=0;d< h;d++){var g=e[d];if(g&&g[a])g[a]()}}}}};d.toNumber=function(a){return"number"==typeof a?a:Number(String(a).replace(/[^0-9\-.]+/g,""))};d.toColor=function(a){if(""!==a&&void 0!==a)if(-1!=a.indexOf(",")){a=a.split(",");var b;for(b=0;b<a.length;b++){var c=a[b].substring(a[b].length-6,a[b].length);a[b]="#"+c}}else a=a.substring(a.length-6,a.length),a="#"+a;return a};d.toCoordinate=function(a,b,c){var e;void 0!==a&&(a=String(a),c&&c<b&&(b=c),e=Number(a),-1!=a.indexOf("!")&&(e=b-Number(a.substr(1))),-1!= a.indexOf("%")&&(e=b*Number(a.substr(0,a.length-1))/100));return e};d.fitToBounds=function(a,b,c){a<b&&(a=b);a>c&&(a=c);return a};d.isDefined=function(a){return void 0===a?!1:!0};d.stripNumbers=function(a){return a.replace(/[0-9]+/g,"")};d.roundTo=function(a,b){if(0>b)return a;var c=Math.pow(10,b);return Math.round(a*c)/c};d.toFixed=function(a,b){var c=String(Math.round(a*Math.pow(10,b)));if(0<b){var e=c.length;if(e<b){var h;for(h=0;h<b-e;h++)c="0"+c}e=c.substring(0,c.length-b);""===e&&(e=0);return e+ "."+c.substring(c.length-b,c.length)}return String(c)};d.formatDuration=function(a,b,c,e,h,f){var g=d.intervals,k=f.decimalSeparator;if(a>=g[b].contains){var l=a-Math.floor(a/g[b].contains)*g[b].contains;"ss"==b?(l=d.formatNumber(l,f),1==l.split(k)[0].length&&(l="0"+l)):l=d.roundTo(l,f.precision);("mm"==b||"hh"==b)&&10>l&&(l="0"+l);c=l+""+e[b]+""+c;a=Math.floor(a/g[b].contains);b=g[b].nextInterval;return d.formatDuration(a,b,c,e,h,f)}"ss"==b&&(a=d.formatNumber(a,f),1==a.split(k)[0].length&&(a="0"+ a));("mm"==b||"hh"==b)&&10>a&&(a="0"+a);c=a+""+e[b]+""+c;if(g[h].count>g[b].count)for(a=g[b].count;a<g[h].count;a++)b=g[b].nextInterval,"ss"==b||"mm"==b||"hh"==b?c="00"+e[b]+""+c:"DD"==b&&(c="0"+e[b]+""+c);":"==c.charAt(c.length-1)&&(c=c.substring(0,c.length-1));return c};d.formatNumber=function(a,b,c,e,h){a=d.roundTo(a,b.precision);isNaN(c)&&(c=b.precision);var f=b.decimalSeparator;b=b.thousandsSeparator;var g;g=0>a?"-":"";a=Math.abs(a);var k=String(a),l=!1;-1!=k.indexOf("e")&&(l=!0);0<=c&&!l&&(k= d.toFixed(a,c));var m="";if(l)m=k;else{var k=k.split("."),l=String(k[0]),n;for(n=l.length;0<=n;n-=3)m=n!=l.length?0!==n?l.substring(n-3,n)+b+m:l.substring(n-3,n)+m:l.substring(n-3,n);void 0!==k[1]&&(m=m+f+k[1]);void 0!==c&&0<c&&"0"!=m&&(m=d.addZeroes(m,f,c))}m=g+m;""===g&&!0===e&&0!==a&&(m="+"+m);!0===h&&(m+="%");return m};d.addZeroes=function(a,b,c){a=a.split(b);void 0===a[1]&&0<c&&(a[1]="0");return a[1].length<c?(a[1]+="0",d.addZeroes(a[0]+b+a[1],b,c)):void 0!==a[1]?a[0]+b+a[1]:a[0]};d.scientificToNormal= function(a){var b;a=String(a).split("e");var c;if("-"==a[1].substr(0,1)){b="0.";for(c=0;c<Math.abs(Number(a[1]))-1;c++)b+="0";b+=a[0].split(".").join("")}else{var e=0;b=a[0].split(".");b[1]&&(e=b[1].length);b=a[0].split(".").join("");for(c=0;c<Math.abs(Number(a[1]))-e;c++)b+="0"}return b};d.toScientific=function(a,b){if(0===a)return"0";var c=Math.floor(Math.log(Math.abs(a))*Math.LOG10E),e=String(e).split(".").join(b);return String(e)+"e"+c};d.randomColor=function(){return"#"+("00000"+(16777216*Math.random()<< 0).toString(16)).substr(-6)};d.hitTest=function(a,b,c){var e=!1,h=a.x,f=a.x+a.width,g=a.y,k=a.y+a.height,l=d.isInRectangle;e||(e=l(h,g,b));e||(e=l(h,k,b));e||(e=l(f,g,b));e||(e=l(f,k,b));e||!0===c||(e=d.hitTest(b,a,!0));return e};d.isInRectangle=function(a,b,c){return a>=c.x-5&&a<=c.x+c.width+5&&b>=c.y-5&&b<=c.y+c.height+5?!0:!1};d.isPercents=function(a){if(-1!=String(a).indexOf("%"))return!0};d.findPosX=function(a){var b=a,c=a.offsetLeft;if(a.offsetParent){for(;a=a.offsetParent;)c+=a.offsetLeft; for(;(b=b.parentNode)&&b!=document.body;)c-=b.scrollLeft||0}return c};d.findPosY=function(a){var b=a,c=a.offsetTop;if(a.offsetParent){for(;a=a.offsetParent;)c+=a.offsetTop;for(;(b=b.parentNode)&&b!=document.body;)c-=b.scrollTop||0}return c};d.findIfFixed=function(a){if(a.offsetParent)for(;a=a.offsetParent;)if("fixed"==d.getStyle(a,"position"))return!0;return!1};d.findIfAuto=function(a){return a.style&&"auto"==d.getStyle(a,"overflow")?!0:a.parentNode?d.findIfAuto(a.parentNode):!1};d.findScrollLeft= function(a,b){a.scrollLeft&&(b+=a.scrollLeft);return a.parentNode?d.findScrollLeft(a.parentNode,b):b};d.findScrollTop=function(a,b){a.scrollTop&&(b+=a.scrollTop);return a.parentNode?d.findScrollTop(a.parentNode,b):b};d.formatValue=function(a,b,c,e,h,f,g,k){if(b){void 0===h&&(h="");var l;for(l=0;l<c.length;l++){var m=c[l],n=b[m];void 0!==n&&(n=f?d.addPrefix(n,k,g,e):d.formatNumber(n,e),a=a.replace(new RegExp("\\[\\["+h+""+m+"\\]\\]","g"),n))}}return a};d.formatDataContextValue=function(a,b){if(a){var c= a.match(/\[\[.*?\]\]/g),e;for(e=0;e<c.length;e++){var h=c[e],h=h.substr(2,h.length-4);void 0!==b[h]&&(a=a.replace(new RegExp("\\[\\["+h+"\\]\\]","g"),b[h]))}}return a};d.massReplace=function(a,b){for(var c in b)if(b.hasOwnProperty(c)){var e=b[c];void 0===e&&(e="");a=a.replace(c,e)}return a};d.cleanFromEmpty=function(a){return a.replace(/\[\[[^\]]*\]\]/g,"")};d.addPrefix=function(a,b,c,e,h){var f=d.formatNumber(a,e),g="",k,l,m;if(0===a)return"0";0>a&&(g="-");a=Math.abs(a);if(1<a)for(k=b.length-1;-1< k;k--){if(a>=b[k].number&&(l=a/b[k].number,m=Number(e.precision),1>m&&(m=1),c=d.roundTo(l,m),m=d.formatNumber(c,{precision:-1,decimalSeparator:e.decimalSeparator,thousandsSeparator:e.thousandsSeparator}),!h||l==c)){f=g+""+m+""+b[k].prefix;break}}else for(k=0;k<c.length;k++)if(a<=c[k].number){l=a/c[k].number;m=Math.abs(Math.round(Math.log(l)*Math.LOG10E));l=d.roundTo(l,m);f=g+""+l+""+c[k].prefix;break}return f};d.remove=function(a){a&&a.remove()};d.getEffect=function(a){">"==a&&(a="easeOutSine");"<"== a&&(a="easeInSine");"elastic"==a&&(a="easeOutElastic");return a};d.getObjById=function(a,b){var c,e;for(e=0;e<a.length;e++){var h=a[e];h.id==b&&(c=h)}return c};d.applyTheme=function(a,b,c){b||(b=d.theme);b&&b[c]&&d.extend(a,b[c])};d.isString=function(a){return"string"==typeof a?!0:!1};d.extend=function(a,b,c){var e;a||(a={});for(e in b)c?a.hasOwnProperty(e)||(a[e]=b[e]):a[e]=b[e];return a};d.copyProperties=function(a,b){for(var c in a)a.hasOwnProperty(c)&&"events"!=c&&void 0!==a[c]&&"function"!=typeof a[c]&& "cname"!=c&&(b[c]=a[c])};d.processObject=function(a,b,c,e){if(!1===a instanceof b&&(a=e?d.extend(new b(c),a):d.extend(a,new b(c),!0),a.listeners))for(var h in a.listeners)b=a.listeners[h],a.addListener(b.event,b.method);return a};d.fixNewLines=function(a){var b=RegExp("\\n","g");a&&(a=a.replace(b,"<br />"));return a};d.fixBrakes=function(a){if(d.isModern){var b=RegExp("<br>","g");a&&(a=a.replace(b,"\n"))}else a=d.fixNewLines(a);return a};d.deleteObject=function(a,b){if(a){if(void 0===b||null===b)b= 20;if(0!==b)if("[object Array]"===Object.prototype.toString.call(a))for(var c=0;c<a.length;c++)d.deleteObject(a[c],b-1),a[c]=null;else if(a&&!a.tagName)try{for(c in a)a[c]&&("object"==typeof a[c]&&d.deleteObject(a[c],b-1),"function"!=typeof a[c]&&(a[c]=null))}catch(e){}}};d.bounce=function(a,b,c,e,h){return(b/=h)<1/2.75?7.5625*e*b*b+c:b<2/2.75?e*(7.5625*(b-=1.5/2.75)*b+.75)+c:b<2.5/2.75?e*(7.5625*(b-=2.25/2.75)*b+.9375)+c:e*(7.5625*(b-=2.625/2.75)*b+.984375)+c};d.easeInSine=function(a,b,c,e,h){return-e* Math.cos(b/h*(Math.PI/2))+e+c};d.easeOutSine=function(a,b,c,e,h){return e*Math.sin(b/h*(Math.PI/2))+c};d.easeOutElastic=function(a,b,c,e,h){a=1.70158;var d=0,g=e;if(0===b)return c;if(1==(b/=h))return c+e;d||(d=.3*h);g<Math.abs(e)?(g=e,a=d/4):a=d/(2*Math.PI)*Math.asin(e/g);return g*Math.pow(2,-10*b)*Math.sin(2*(b*h-a)*Math.PI/d)+e+c};d.fixStepE=function(a){a=a.toExponential(0).split("e");var b=Number(a[1]);9==Number(a[0])&&b++;return d.generateNumber(1,b)};d.generateNumber=function(a,b){var c="",e; e=0>b?Math.abs(b)-1:Math.abs(b);var h;for(h=0;h<e;h++)c+="0";return 0>b?Number("0."+c+String(a)):Number(String(a)+c)};d.setCN=function(a,b,c,e){if(a.addClassNames&&b&&(b=b.node)&&c){var h=b.getAttribute("class");a=a.classNamePrefix+"-";e&&(a="");h?b.setAttribute("class",h+" "+a+c):b.setAttribute("class",a+c)}};d.parseDefs=function(a,b){for(var c in a){var e=typeof a[c];if(0<a[c].length&&"object"==e)for(var h=0;h<a[c].length;h++)e=document.createElementNS(d.SVG_NS,c),b.appendChild(e),d.parseDefs(a[c][h], e);else"object"==e?(e=document.createElementNS(d.SVG_NS,c),b.appendChild(e),d.parseDefs(a[c],e)):b.setAttribute(c,a[c])}}})();(function(){var d=window.AmCharts;d.AxisBase=d.Class({construct:function(a){this.createEvents("clickItem","rollOverItem","rollOutItem");this.viY=this.viX=this.titleDY=this.y=this.x=this.dy=this.dx=0;this.axisThickness=1;this.axisColor="#000000";this.axisAlpha=1;this.gridCount=this.tickLength=5;this.gridAlpha=.15;this.gridThickness=1;this.gridColor="#000000";this.dashLength=0;this.labelFrequency=1;this.showLastLabel=this.showFirstLabel=!0;this.fillColor="#FFFFFF";this.fillAlpha=0;this.labelsEnabled= !0;this.labelRotation=0;this.autoGridCount=!0;this.offset=0;this.guides=[];this.visible=!0;this.counter=0;this.guides=[];this.ignoreAxisWidth=this.inside=!1;this.minHorizontalGap=75;this.minVerticalGap=35;this.titleBold=!0;this.minorGridEnabled=!1;this.minorGridAlpha=.07;this.autoWrap=!1;this.titleAlign="middle";this.labelOffset=0;this.bcn="axis-";this.centerLabels=!1;this.periods=[{period:"ss",count:1},{period:"ss",count:5},{period:"ss",count:10},{period:"ss",count:30},{period:"mm",count:1},{period:"mm", count:5},{period:"mm",count:10},{period:"mm",count:30},{period:"hh",count:1},{period:"hh",count:3},{period:"hh",count:6},{period:"hh",count:12},{period:"DD",count:1},{period:"DD",count:2},{period:"DD",count:3},{period:"DD",count:4},{period:"DD",count:5},{period:"WW",count:1},{period:"MM",count:1},{period:"MM",count:2},{period:"MM",count:3},{period:"MM",count:6},{period:"YYYY",count:1},{period:"YYYY",count:2},{period:"YYYY",count:5},{period:"YYYY",count:10},{period:"YYYY",count:50},{period:"YYYY", count:100}];this.dateFormats=[{period:"fff",format:"JJ:NN:SS"},{period:"ss",format:"JJ:NN:SS"},{period:"mm",format:"JJ:NN"},{period:"hh",format:"JJ:NN"},{period:"DD",format:"MMM DD"},{period:"WW",format:"MMM DD"},{period:"MM",format:"MMM"},{period:"YYYY",format:"YYYY"}];this.nextPeriod={fff:"ss",ss:"mm",mm:"hh",hh:"DD",DD:"MM",MM:"YYYY"};d.applyTheme(this,a,"AxisBase")},zoom:function(a,b){this.start=a;this.end=b;this.dataChanged=!0;this.draw()},fixAxisPosition:function(){var a=this.position;"H"== this.orientation?("left"==a&&(a="bottom"),"right"==a&&(a="top")):("bottom"==a&&(a="left"),"top"==a&&(a="right"));this.position=a},draw:function(){var a=this.chart;this.allLabels=[];this.counter=0;this.destroy();this.fixAxisPosition();this.labels=[];var b=a.container,c=b.set();a.gridSet.push(c);this.set=c;b=b.set();a.axesLabelsSet.push(b);this.labelsSet=b;this.axisLine=new this.axisRenderer(this);this.autoGridCount?("V"==this.orientation?(a=this.height/this.minVerticalGap,3>a&&(a=3)):a=this.width/ this.minHorizontalGap,this.gridCountR=Math.max(a,1)):this.gridCountR=this.gridCount;this.axisWidth=this.axisLine.axisWidth;this.addTitle()},setOrientation:function(a){this.orientation=a?"H":"V"},addTitle:function(){var a=this.title;this.titleLabel=null;if(a){var b=this.chart,c=this.titleColor;void 0===c&&(c=b.color);var e=this.titleFontSize;isNaN(e)&&(e=b.fontSize+1);a=d.text(b.container,a,c,b.fontFamily,e,this.titleAlign,this.titleBold);d.setCN(b,a,this.bcn+"title");this.titleLabel=a}},positionTitle:function(){var a= this.titleLabel;if(a){var b,c,e=this.labelsSet,h={};0<e.length()?h=e.getBBox():(h.x=0,h.y=0,h.width=this.viW,h.height=this.viH,d.VML&&(h.y+=this.y,h.x+=this.x));e.push(a);var e=h.x,f=h.y;d.VML&&(this.rotate?e-=this.x:f-=this.y);var g=h.width,h=h.height,k=this.viW,l=this.viH,m=0,n=a.getBBox().height/2,p=this.inside,q=this.titleAlign;switch(this.position){case "top":b="left"==q?-1:"right"==q?k:k/2;c=f-10-n;break;case "bottom":b="left"==q?-1:"right"==q?k:k/2;c=f+h+10+n;break;case "left":b=e-10-n;p&& (b-=5);m=-90;c=("left"==q?l+1:"right"==q?-1:l/2)+this.titleDY;break;case "right":b=e+g+10+n,p&&(b+=7),c=("left"==q?l+2:"right"==q?-2:l/2)+this.titleDY,m=-90}this.marginsChanged?(a.translate(b,c),this.tx=b,this.ty=c):a.translate(this.tx,this.ty);this.marginsChanged=!1;isNaN(this.titleRotation)||(m=this.titleRotation);0!==m&&a.rotate(m)}},pushAxisItem:function(a,b){var c=this,e=a.graphics();0<e.length()&&(b?c.labelsSet.push(e):c.set.push(e));if(e=a.getLabel())this.labelsSet.push(e),e.click(function(b){c.handleMouse(b, a,"clickItem")}).mouseover(function(b){c.handleMouse(b,a,"rollOverItem")}).mouseout(function(b){c.handleMouse(b,a,"rollOutItem")})},handleMouse:function(a,b,c){this.fire(c,{type:c,value:b.value,serialDataItem:b.serialDataItem,axis:this,target:b.label,chart:this.chart,event:a})},addGuide:function(a){for(var b=this.guides,c=!1,e=b.length,h=0;h<b.length;h++)b[h]==a&&(c=!0,e=h);a=d.processObject(a,d.Guide,this.theme);a.id||(a.id="guideAuto"+e+"_"+(new Date).getTime());c||b.push(a)},removeGuide:function(a){var b= this.guides,c;for(c=0;c<b.length;c++)b[c]==a&&b.splice(c,1)},handleGuideOver:function(a){clearTimeout(this.chart.hoverInt);var b=a.graphics.getBBox(),c=b.x+b.width/2,b=b.y+b.height/2,e=a.fillColor;void 0===e&&(e=a.lineColor);this.chart.showBalloon(a.balloonText,e,!0,c,b)},handleGuideOut:function(){this.chart.hideBalloon()},addEventListeners:function(a,b){var c=this;a.mouseover(function(){c.handleGuideOver(b)});a.touchstart(function(){c.handleGuideOver(b)});a.mouseout(function(){c.handleGuideOut(b)})}, getBBox:function(){var a=this.labelsSet.getBBox();d.VML||(a={x:a.x+this.x,y:a.y+this.y,width:a.width,height:a.height});return a},destroy:function(){d.remove(this.set);d.remove(this.labelsSet);var a=this.axisLine;a&&d.remove(a.set);d.remove(this.grid0)},chooseMinorFrequency:function(a){for(var b=10;0<b;b--)if(a/b==Math.round(a/b))return a/b},parseDatesDraw:function(){var a,b=this.chart,c=this.showFirstLabel,e=this.showLastLabel,h,f="",g=d.extractPeriod(this.minPeriod),k=d.getPeriodDuration(g.period, g.count),l,m,n,p,q,r=this.firstDayOfWeek,u=this.boldPeriodBeginning;a=this.minorGridEnabled;var t,z=this.gridAlpha,y,v=this.choosePeriod(0),w=v.period,v=v.count,A=d.getPeriodDuration(w,v);A<k&&(w=g.period,v=g.count,A=k);g=w;"WW"==g&&(g="DD");this.stepWidth=this.getStepWidth(this.timeDifference);var B=Math.ceil(this.timeDifference/A)+5,C=l=d.resetDateToMin(new Date(this.startTime-A),w,v,r).getTime();if(g==w&&1==v&&this.centerLabelOnFullPeriod||this.autoWrap||this.centerLabels)n=A*this.stepWidth,this.autoWrap&& !this.centerLabels&&(n=-n);this.cellWidth=k*this.stepWidth;p=Math.round(l/A);k=-1;p/2==Math.round(p/2)&&(k=-2,l-=A);p=this.firstTime;var D=0,J=0;a&&1<v&&(t=this.chooseMinorFrequency(v),y=d.getPeriodDuration(w,t));if(0<this.gridCountR)for(B-5-k>this.autoRotateCount&&!isNaN(this.autoRotateAngle)&&(this.labelRotationR=this.autoRotateAngle),a=k;a<=B;a++){q=p+A*(a+Math.floor((C-p)/A))-D;"DD"==w&&(q+=36E5);q=d.resetDateToMin(new Date(q),w,v,r).getTime();"MM"==w&&(h=(q-l)/A,1.5<=(q-l)/A&&(q=q-(h-1)*A+d.getPeriodDuration("DD", 3),q=d.resetDateToMin(new Date(q),w,1).getTime(),D+=A));h=(q-this.startTime)*this.stepWidth;if("radar"==b.type){if(0>h||h>this.axisWidth)continue;h=this.y+(this.axisWidth-h)}else this.rotate?(h+=this.x-this.viX,"date"==this.type&&"middle"==this.gridPosition&&(J=-A*this.stepWidth/2)):h="date"==this.type?this.axisWidth-h+(this.y-this.viY):h+(this.y-this.viY);f=!1;this.nextPeriod[g]&&(f=this.checkPeriodChange(this.nextPeriod[g],1,q,l,g));l=!1;f&&this.markPeriodChange?(f=this.dateFormatsObject[this.nextPeriod[g]], this.twoLineMode&&(f=this.dateFormatsObject[g]+"\n"+f,f=d.fixBrakes(f)),l=!0):f=this.dateFormatsObject[g];u||(l=!1);this.currentDateFormat=f;f=d.formatDate(new Date(q),f,b);if(a==k&&!c||a==B&&!e)f=" ";this.labelFunction&&(f=this.labelFunction(f,new Date(q),this,w,v,m).toString());this.boldLabels&&(l=!0);m=new this.axisItemRenderer(this,h,f,!1,n,J,!1,l);this.pushAxisItem(m);m=l=q;if(!isNaN(t))for(h=1;h<v;h+=t)this.gridAlpha=this.minorGridAlpha,f=q+y*h,f=d.resetDateToMin(new Date(f),w,t,r).getTime(), f=new this.axisItemRenderer(this,(f-this.startTime)*this.stepWidth,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0),this.pushAxisItem(f);this.gridAlpha=z}},choosePeriod:function(a){var b=d.getPeriodDuration(this.periods[a].period,this.periods[a].count),c=Math.ceil(this.timeDifference/b),e=this.periods;return this.timeDifference<b&&0<a?e[a-1]:c<=this.gridCountR?e[a]:a+1<e.length?this.choosePeriod(a+1):e[a]},getStepWidth:function(a){var b;this.startOnAxis?(b=this.axisWidth/(a-1),1==a&&(b=this.axisWidth)): b=this.axisWidth/a;return b},timeZoom:function(a,b){this.startTime=a;this.endTime=b},minDuration:function(){var a=d.extractPeriod(this.minPeriod);return d.getPeriodDuration(a.period,a.count)},checkPeriodChange:function(a,b,c,e,h){c=new Date(c);var f=new Date(e),g=this.firstDayOfWeek;e=b;"DD"==a&&(b=1);c=d.resetDateToMin(c,a,b,g).getTime();b=d.resetDateToMin(f,a,b,g).getTime();return"DD"==a&&"hh"!=h&&c-b<d.getPeriodDuration(a,e)?!1:c!=b?!0:!1},generateDFObject:function(){this.dateFormatsObject={}; var a;for(a=0;a<this.dateFormats.length;a++){var b=this.dateFormats[a];this.dateFormatsObject[b.period]=b.format}}})})();(function(){var d=window.AmCharts;d.ValueAxis=d.Class({inherits:d.AxisBase,construct:function(a){this.cname="ValueAxis";this.createEvents("axisChanged","logarithmicAxisFailed","axisSelfZoomed","axisZoomed");d.ValueAxis.base.construct.call(this,a);this.dataChanged=!0;this.stackType="none";this.position="left";this.unitPosition="right";this.includeAllValues=this.recalculateToPercents=this.includeHidden=this.includeGuidesInMinMax=this.integersOnly=!1;this.durationUnits={DD:"d. ",hh:":",mm:":",ss:""}; this.scrollbar=!1;this.baseValue=0;this.radarCategoriesEnabled=!0;this.gridType="polygons";this.useScientificNotation=!1;this.axisTitleOffset=10;this.pointPosition="axis";this.minMaxMultiplier=1;this.logGridLimit=2;this.totalTextOffset=this.treatZeroAs=0;this.minPeriod="ss";d.applyTheme(this,a,this.cname)},updateData:function(){0>=this.gridCountR&&(this.gridCountR=1);this.totals=[];this.data=this.chart.chartData;var a=this.chart;"xy"!=a.type&&(this.stackGraphs("smoothedLine"),this.stackGraphs("line"), this.stackGraphs("column"),this.stackGraphs("step"));this.recalculateToPercents&&this.recalculate();this.synchronizationMultiplier&&this.synchronizeWith?(d.isString(this.synchronizeWith)&&(this.synchronizeWith=a.getValueAxisById(this.synchronizeWith)),this.synchronizeWith&&(this.synchronizeWithAxis(this.synchronizeWith),this.foundGraphs=!0)):(this.foundGraphs=!1,this.getMinMax())},draw:function(){d.ValueAxis.base.draw.call(this);var a=this.chart,b=this.set;this.labelRotationR=this.labelRotation;d.setCN(a, this.set,"value-axis value-axis-"+this.id);d.setCN(a,this.labelsSet,"value-axis value-axis-"+this.id);d.setCN(a,this.axisLine.axisSet,"value-axis value-axis-"+this.id);var c=this.type;"duration"==c&&(this.duration="ss");!0===this.dataChanged&&(this.updateData(),this.dataChanged=!1);"date"==c&&(this.logarithmic=!1,this.min=this.minRR,this.max=this.maxRR,this.getDateMinMax());if(this.logarithmic){var e=this.treatZeroAs,h=this.getMin(0,this.data.length-1);this.minReal<h&&(this.minReal=h);isNaN(this.minReal)&& (this.minReal=h);0<e&&0===h&&(this.minReal=h=e);if(0>=h||0>=this.minimum){this.fire("logarithmicAxisFailed",{type:"logarithmicAxisFailed",chart:a});return}}this.grid0=null;var f,g,k=a.dx,l=a.dy,e=!1,h=this.logarithmic;if(isNaN(this.min)||isNaN(this.max)||!this.foundGraphs||Infinity==this.min||-Infinity==this.max)e=!0;else{var m=this.labelFrequency,n=this.showFirstLabel,p=this.showLastLabel,q=1;f=0;this.minCalc=this.min;this.maxCalc=this.max;this.strictMinMax&&(isNaN(this.minimum)||(this.min=this.minimum), isNaN(this.maximum)||(this.max=this.maximum));isNaN(this.minZoom)||(this.min=this.minZoom);isNaN(this.maxZoom)||(this.max=this.maxZoom);var r=Math.round((this.maxCalc-this.minCalc)/this.step)+1,u;!0===h?(u=Math.log(this.max)*Math.LOG10E-Math.log(this.minReal)*Math.LOG10E,this.stepWidth=this.axisWidth/u,u>this.logGridLimit&&(r=Math.ceil(Math.log(this.max)*Math.LOG10E)+1,f=Math.round(Math.log(this.minReal)*Math.LOG10E),r>this.gridCountR&&(q=Math.ceil(r/this.gridCountR)))):this.stepWidth=this.axisWidth/ (this.max-this.min);var t=0;1>this.step&&-1<this.step&&(t=d.getDecimals(this.step));this.integersOnly&&(t=0);t>this.maxDecCount&&(t=this.maxDecCount);var z=this.precision;isNaN(z)||(t=z);this.max=d.roundTo(this.max,this.maxDecCount);this.min=d.roundTo(this.min,this.maxDecCount);g={};g.precision=t;g.decimalSeparator=a.nf.decimalSeparator;g.thousandsSeparator=a.nf.thousandsSeparator;this.numberFormatter=g;var y,v=this.guides,w=v.length;if(0<w){var A=this.fillAlpha;for(g=this.fillAlpha=0;g<w;g++){var B= v[g],C=NaN,D=B.above;isNaN(B.toValue)||(C=this.getCoordinate(B.toValue),y=new this.axisItemRenderer(this,C,"",!0,NaN,NaN,B),this.pushAxisItem(y,D));var J=NaN;isNaN(B.value)||(J=this.getCoordinate(B.value),y=new this.axisItemRenderer(this,J,B.label,!0,NaN,(C-J)/2,B),this.pushAxisItem(y,D));isNaN(C-J)||(y=new this.guideFillRenderer(this,J,C,B),this.pushAxisItem(y,D),y=y.graphics(),B.graphics=y,B.balloonText&&this.addEventListeners(y,B))}this.fillAlpha=A}this.exponential=!1;for(g=f;g<r;g+=q)v=d.roundTo(this.step* g+this.min,t),-1!=String(v).indexOf("e")&&(this.exponential=!0);this.duration&&(this.maxInterval=d.getMaxInterval(this.max,this.duration));var t=this.step,E,v=this.minorGridAlpha;this.minorGridEnabled&&(E=this.getMinorGridStep(t,this.stepWidth*t));if("date"==c)this.generateDFObject(),this.timeDifference=this.max-this.min,this.maxTime=this.lastTime=this.max,this.startTime=this.firstTime=this.min,this.parseDatesDraw();else for(r>=this.autoRotateCount&&!isNaN(this.autoRotateAngle)&&(this.labelRotationR= this.autoRotateAngle),g=f;g<r;g+=q)if(c=t*g+this.minCalc,h&&this.max-this.min>10*this.min&&(c-=this.min),c=d.roundTo(c,this.maxDecCount+1),!this.integersOnly||Math.round(c)==c)if(isNaN(z)||Number(d.toFixed(c,z))==c){!0===h&&(0===c&&(c=this.minReal),u>this.logGridLimit&&(c=Math.pow(10,g)));y=this.formatValue(c,!1,g);Math.round(g/m)!=g/m&&(y=void 0);if(0===g&&!n||g==r-1&&!p)y=" ";f=this.getCoordinate(c);var O;this.rotate&&this.autoWrap&&(O=this.stepWidth*t-10);y=new this.axisItemRenderer(this,f,y,void 0, O,void 0,void 0,this.boldLabels);this.pushAxisItem(y);if(c==this.baseValue&&"radar"!=a.type){var I,W,A=this.viW,B=this.viH;y=this.viX;w=this.viY;"H"==this.orientation?0<=f&&f<=A+1&&(I=[f,f,f+k],W=[B,0,l]):0<=f&&f<=B+1&&(I=[0,A,A+k],W=[f,f,f+l]);I&&(f=d.fitToBounds(2*this.gridAlpha,0,1),f=d.line(a.container,I,W,this.gridColor,f,1,this.dashLength),f.translate(y,w),this.grid0=f,a.axesSet.push(f),f.toBack(),d.setCN(a,f,this.bcn+"zero-grid-"+this.id),d.setCN(a,f,this.bcn+"zero-grid"))}if(!isNaN(E)&&0< v&&g<r-1){f=this.gridAlpha;this.gridAlpha=this.minorGridAlpha;for(y=1;y<t/E;y++)w=this.getCoordinate(c+E*y),w=new this.axisItemRenderer(this,w,"",!1,0,0,!1,!1,0,!0),this.pushAxisItem(w);this.gridAlpha=f}}u=this.baseValue;this.min>this.baseValue&&this.max>this.baseValue&&(u=this.min);this.min<this.baseValue&&this.max<this.baseValue&&(u=this.max);h&&u<this.minReal&&(u=this.minReal);this.baseCoord=this.getCoordinate(u);u={type:"axisChanged",target:this,chart:a};u.min=h?this.minReal:this.min;u.max=this.max; this.fire("axisChanged",u);this.axisCreated=!0}h=this.axisLine.set;u=this.labelsSet;this.positionTitle();"radar"!=a.type?(a=this.viX,E=this.viY,b.translate(a,E),u.translate(a,E)):h.toFront();!this.visible||e?(b.hide(),h.hide(),u.hide()):(b.show(),h.show(),u.show());this.axisY=this.y-this.viY;this.axisX=this.x-this.viX},getDateMinMax:function(){this.minimumDate&&(this.minimumDate instanceof Date||(this.minimumDate=d.getDate(this.minimumDate,this.chart.dataDateFormat,"fff")),this.min=this.minimumDate.getTime()); this.maximumDate&&(this.maximumDate instanceof Date||(this.maximumDate=d.getDate(this.maximumDate,this.chart.dataDateFormat,"fff")),this.max=this.maximumDate.getTime())},formatValue:function(a,b,c){var e=this.exponential,h=this.logarithmic,f=this.numberFormatter,g=this.chart;!0===this.logarithmic&&(e=-1!=String(a).indexOf("e")?!0:!1);this.useScientificNotation&&(e=!0);this.usePrefixes&&(e=!1);e?(c=-1==String(a).indexOf("e")?a.toExponential(15):String(a),e=c.split("e"),c=Number(e[0]),e=Number(e[1]), c=d.roundTo(c,14),10==c&&(c=1,e+=1),c=c+"e"+e,0===a&&(c="0"),1==a&&(c="1")):(h&&(e=String(a).split("."),e[1]?(f.precision=e[1].length,0>c&&(f.precision=Math.abs(c)),b&&1<a&&(f.precision=0)):f.precision=-1),c=this.usePrefixes?d.addPrefix(a,g.prefixesOfBigNumbers,g.prefixesOfSmallNumbers,f,!b):d.formatNumber(a,f,f.precision));this.duration&&(b&&(f.precision=0),c=d.formatDuration(a,this.duration,"",this.durationUnits,this.maxInterval,f));"date"==this.type&&(c=d.formatDate(new Date(a),this.currentDateFormat, g));this.recalculateToPercents?c+="%":(b=this.unit)&&(c="left"==this.unitPosition?b+c:c+b);this.labelFunction&&(c=this.labelFunction(a,c,this).toString());return c},getMinorGridStep:function(a,b){var c=[5,4,2];60>b&&c.shift();for(var e=Math.floor(Math.log(Math.abs(a))*Math.LOG10E),h=0;h<c.length;h++){var d=a/c[h],g=Math.floor(Math.log(Math.abs(d))*Math.LOG10E);if(!(1<Math.abs(e-g)))if(1>a){if(g=Math.pow(10,-g)*d,g==Math.round(g))return d}else if(d==Math.round(d))return d}},stackGraphs:function(a){var b= this.stackType;"stacked"==b&&(b="regular");"line"==b&&(b="none");"100% stacked"==b&&(b="100%");this.stackType=b;var c=[],e=[],h=[],f=[],g,k=this.chart.graphs,l,m,n,p,q=this.baseValue,r=!1;if("line"==a||"step"==a||"smoothedLine"==a)r=!0;if(r&&("regular"==b||"100%"==b))for(p=0;p<k.length;p++)n=k[p],n.hidden||(m=n.type,n.chart==this.chart&&n.valueAxis==this&&a==m&&n.stackable&&(l&&(n.stackGraph=l),l=n));for(l=this.start;l<=this.end;l++){var u=0;for(p=0;p<k.length;p++)if(n=k[p],n.hidden)n.newStack&&(h[l]= NaN,e[l]=NaN);else if(m=n.type,n.chart==this.chart&&n.valueAxis==this&&a==m&&n.stackable)if(m=this.data[l].axes[this.id].graphs[n.id],g=m.values.value,isNaN(g))n.newStack&&(h[l]=NaN,e[l]=NaN);else{var t=d.getDecimals(g);u<t&&(u=t);isNaN(f[l])?f[l]=Math.abs(g):f[l]+=Math.abs(g);f[l]=d.roundTo(f[l],u);t=n.fillToGraph;r&&t&&(t=this.data[l].axes[this.id].graphs[t.id])&&(m.values.open=t.values.value);"regular"==b&&(r&&(isNaN(c[l])?(c[l]=g,m.values.close=g,m.values.open=this.baseValue):(isNaN(g)?m.values.close= c[l]:m.values.close=g+c[l],m.values.open=c[l],c[l]=m.values.close)),"column"==a&&(n.newStack&&(h[l]=NaN,e[l]=NaN),m.values.close=g,0>g?(m.values.close=g,isNaN(e[l])?m.values.open=q:(m.values.close+=e[l],m.values.open=e[l]),e[l]=m.values.close):(m.values.close=g,isNaN(h[l])?m.values.open=q:(m.values.close+=h[l],m.values.open=h[l]),h[l]=m.values.close)))}}for(l=this.start;l<=this.end;l++)for(p=0;p<k.length;p++)(n=k[p],n.hidden)?n.newStack&&(h[l]=NaN,e[l]=NaN):(m=n.type,n.chart==this.chart&&n.valueAxis== this&&a==m&&n.stackable&&(m=this.data[l].axes[this.id].graphs[n.id],g=m.values.value,isNaN(g)||(c=g/f[l]*100,m.values.percents=c,m.values.total=f[l],n.newStack&&(h[l]=NaN,e[l]=NaN),"100%"==b&&(isNaN(e[l])&&(e[l]=0),isNaN(h[l])&&(h[l]=0),0>c?(m.values.close=d.fitToBounds(c+e[l],-100,100),m.values.open=e[l],e[l]=m.values.close):(m.values.close=d.fitToBounds(c+h[l],-100,100),m.values.open=h[l],h[l]=m.values.close)))))},recalculate:function(){var a=this.chart,b=a.graphs,c;for(c=0;c<b.length;c++){var e= b[c];if(e.valueAxis==this){var h="value";if("candlestick"==e.type||"ohlc"==e.type)h="open";var f,g,k=this.end+2,k=d.fitToBounds(this.end+1,0,this.data.length-1),l=this.start;0<l&&l--;var m;g=this.start;e.compareFromStart&&(g=0);if(!isNaN(a.startTime)&&(m=a.categoryAxis)){var n=m.minDuration(),n=new Date(a.startTime+n/2),p=d.resetDateToMin(new Date(a.startTime),m.minPeriod).getTime();d.resetDateToMin(new Date(n),m.minPeriod).getTime()>p&&g++}if(m=a.recalculateFromDate)m=d.getDate(m,a.dataDateFormat, "fff"),g=a.getClosestIndex(a.chartData,"time",m.getTime(),!0,0,a.chartData.length),k=a.chartData.length-1;for(m=g;m<=k&&(g=this.data[m].axes[this.id].graphs[e.id],f=g.values[h],isNaN(f));m++);this.recBaseValue=f;for(h=l;h<=k;h++){g=this.data[h].axes[this.id].graphs[e.id];g.percents={};var l=g.values,q;for(q in l)g.percents[q]="percents"!=q?l[q]/f*100-100:l[q]}}}},getMinMax:function(){var a=!1,b=this.chart,c=b.graphs,e;for(e=0;e<c.length;e++){var h=c[e].type;("line"==h||"step"==h||"smoothedLine"== h)&&this.expandMinMax&&(a=!0)}a&&(0<this.start&&this.start--,this.end<this.data.length-1&&this.end++);"serial"==b.type&&(!0!==b.categoryAxis.parseDates||a||this.end<this.data.length-1&&this.end++);this.includeAllValues&&(this.start=0,this.end=this.data.length-1);a=this.minMaxMultiplier;this.min=this.getMin(this.start,this.end);this.max=this.getMax();this.minRR=this.min;this.maxRR=this.max;a=(this.max-this.min)*(a-1);this.min-=a;this.max+=a;a=this.guides.length;if(this.includeGuidesInMinMax&&0<a)for(b= 0;b<a;b++)c=this.guides[b],c.toValue<this.min&&(this.min=c.toValue),c.value<this.min&&(this.min=c.value),c.toValue>this.max&&(this.max=c.toValue),c.value>this.max&&(this.max=c.value);isNaN(this.minimum)||(this.min=this.minimum);isNaN(this.maximum)||(this.max=this.maximum);"date"==this.type&&this.getDateMinMax();this.min>this.max&&(a=this.max,this.max=this.min,this.min=a);isNaN(this.minTemp)||(this.min=this.minTemp);isNaN(this.maxTemp)||(this.max=this.maxTemp);this.minReal=this.min;this.maxReal=this.max; 0===this.min&&0===this.max&&(this.max=9);this.min>this.max&&(this.min=this.max-1);a=this.min;b=this.max;c=this.max-this.min;e=0===c?Math.pow(10,Math.floor(Math.log(Math.abs(this.max))*Math.LOG10E))/10:Math.pow(10,Math.floor(Math.log(Math.abs(c))*Math.LOG10E))/10;isNaN(this.maximum)&&isNaN(this.maxTemp)&&(this.max=Math.ceil(this.max/e)*e+e);isNaN(this.minimum)&&isNaN(this.minTemp)&&(this.min=Math.floor(this.min/e)*e-e);0>this.min&&0<=a&&(this.min=0);0<this.max&&0>=b&&(this.max=0);"100%"==this.stackType&& (this.min=0>this.min?-100:0,this.max=0>this.max?0:100);c=this.max-this.min;e=Math.pow(10,Math.floor(Math.log(Math.abs(c))*Math.LOG10E))/10;this.step=Math.ceil(c/this.gridCountR/e)*e;c=Math.pow(10,Math.floor(Math.log(Math.abs(this.step))*Math.LOG10E));c=d.fixStepE(c);e=Math.ceil(this.step/c);5<e&&(e=10);5>=e&&2<e&&(e=5);this.step=Math.ceil(this.step/(c*e))*c*e;1>c?(this.maxDecCount=Math.abs(Math.log(Math.abs(c))*Math.LOG10E),this.maxDecCount=Math.round(this.maxDecCount),this.step=d.roundTo(this.step, this.maxDecCount+1)):this.maxDecCount=0;this.min=this.step*Math.floor(this.min/this.step);this.max=this.step*Math.ceil(this.max/this.step);0>this.min&&0<=a&&(this.min=0);0<this.max&&0>=b&&(this.max=0);1<this.minReal&&1<this.max-this.minReal&&(this.minReal=Math.floor(this.minReal));c=Math.pow(10,Math.floor(Math.log(Math.abs(this.minReal))*Math.LOG10E));0===this.min&&(this.minReal=c);0===this.min&&1<this.minReal&&(this.minReal=1);0<this.min&&0<this.minReal-this.step&&(this.minReal=this.min+this.step< this.minReal?this.min+this.step:this.min);this.logarithmic&&(2<Math.log(b)*Math.LOG10E-Math.log(a)*Math.LOG10E?(this.minReal=this.min=Math.pow(10,Math.floor(Math.log(Math.abs(a))*Math.LOG10E)),this.max=Math.pow(10,Math.ceil(Math.log(Math.abs(b))*Math.LOG10E))):(b=Math.pow(10,Math.floor(Math.log(Math.abs(this.min))*Math.LOG10E))/10,a=Math.pow(10,Math.floor(Math.log(Math.abs(a))*Math.LOG10E))/10,b<a&&(this.minReal=this.min=10*a)))},getMin:function(a,b){var c,e;for(e=a;e<=b;e++){var d=this.data[e].axes[this.id].graphs, f;for(f in d)if(d.hasOwnProperty(f)){var g=this.chart.getGraphById(f);if(g.includeInMinMax&&(!g.hidden||this.includeHidden)){isNaN(c)&&(c=Infinity);this.foundGraphs=!0;g=d[f].values;this.recalculateToPercents&&(g=d[f].percents);var k;if(this.minMaxField)k=g[this.minMaxField],k<c&&(c=k);else for(var l in g)g.hasOwnProperty(l)&&"percents"!=l&&"total"!=l&&(k=g[l],k<c&&(c=k))}}}return c},getMax:function(){var a,b;for(b=this.start;b<=this.end;b++){var c=this.data[b].axes[this.id].graphs,e;for(e in c)if(c.hasOwnProperty(e)){var d= this.chart.getGraphById(e);if(d.includeInMinMax&&(!d.hidden||this.includeHidden)){isNaN(a)&&(a=-Infinity);this.foundGraphs=!0;d=c[e].values;this.recalculateToPercents&&(d=c[e].percents);var f;if(this.minMaxField)f=d[this.minMaxField],f>a&&(a=f);else for(var g in d)d.hasOwnProperty(g)&&"percents"!=g&&"total"!=g&&(f=d[g],f>a&&(a=f))}}}return a},dispatchZoomEvent:function(a,b){var c={type:"axisZoomed",startValue:a,endValue:b,target:this,chart:this.chart};this.fire(c.type,c)},zoomOut:function(){var a= this.chart;"xy"!=a.type&&(this.maxZoom=this.minZoom=void 0,a.updateAfterValueZoom())},zoomToValues:function(a,b){var c=this.chart;"xy"==c.type?(b<a&&(c=b,b=a,a=c),a<this.min&&(a=this.min),b>this.max&&(b=this.max),c={type:"axisSelfZoomed"},c.chart=this.chart,c.valueAxis=this,c.multiplier=this.axisWidth/Math.abs(this.getCoordinate(b)-this.getCoordinate(a)),c.startValue=a,c.endValue=b,c.position="V"==this.orientation?this.reversed?this.getCoordinate(a):this.getCoordinate(b):this.reversed?this.getCoordinate(b): this.getCoordinate(a),this.fire(c.type,c)):(this.minZoom=a,this.maxZoom=b,c.updateAfterValueZoom())},coordinateToValue:function(a){if(isNaN(a))return NaN;var b=this.axisWidth,c=this.stepWidth,e=this.reversed,d=this.rotate,f=this.min,g=this.minReal;return!0===this.logarithmic?Math.pow(10,(d?!0===e?(b-a)/c:a/c:!0===e?a/c:(b-a)/c)+Math.log(g)*Math.LOG10E):!0===e?d?f-(a-b)/c:a/c+f:d?a/c+f:f-(a-b)/c},getCoordinate:function(a){if(isNaN(a))return NaN;var b=this.rotate,c=this.reversed,e=this.axisWidth,d= this.stepWidth,f=this.min,g=this.minReal;!0===this.logarithmic?(0===a&&(a=this.treatZeroAs),a=Math.log(a)*Math.LOG10E-Math.log(g)*Math.LOG10E,b=b?!0===c?e-d*a:d*a:!0===c?d*a:e-d*a):b=!0===c?b?e-d*(a-f):d*(a-f):b?d*(a-f):e-d*(a-f);b=this.rotate?b+(this.x-this.viX):b+(this.y-this.viY);1E7<Math.abs(b)&&(b=1E7*(b/Math.abs(b)));return Math.round(b)},synchronizeWithAxis:function(a){this.synchronizeWith=a;this.listenTo(this.synchronizeWith,"axisChanged",this.handleSynchronization)},handleSynchronization:function(){if(this.synchronizeWith){d.isString(this.synchronizeWith)&& (this.synchronizeWith=this.chart.getValueAxisById(this.synchronizeWith));var a=this.synchronizeWith,b=a.min,c=a.max,a=a.step,e=this.synchronizationMultiplier;e&&(this.min=b*e,this.max=c*e,this.step=a*e,b=Math.pow(10,Math.floor(Math.log(Math.abs(this.step))*Math.LOG10E)),b=Math.abs(Math.log(Math.abs(b))*Math.LOG10E),this.maxDecCount=b=Math.round(b),this.draw())}}})})();(function(){var d=window.AmCharts;d.RecAxis=d.Class({construct:function(a){var b=a.chart,c=a.axisThickness,e=a.axisColor,h=a.axisAlpha,f=a.offset,g=a.dx,k=a.dy,l=a.viX,m=a.viY,n=a.viH,p=a.viW,q=b.container;"H"==a.orientation?(e=d.line(q,[0,p],[0,0],e,h,c),this.axisWidth=a.width,"bottom"==a.position?(k=c/2+f+n+m-1,c=l):(k=-c/2-f+m+k,c=g+l)):(this.axisWidth=a.height,"right"==a.position?(e=d.line(q,[0,0,-g],[0,n,n-k],e,h,c),k=m+k,c=c/2+f+g+p+l-1):(e=d.line(q,[0,0],[0,n],e,h,c),k=m,c=-c/2-f+l));e.translate(c, k);c=b.container.set();c.push(e);b.axesSet.push(c);d.setCN(b,e,a.bcn+"line");this.axisSet=c;this.set=e}})})();(function(){var d=window.AmCharts;d.RecItem=d.Class({construct:function(a,b,c,e,h,f,g,k,l,m,n,p){b=Math.round(b);var q=a.chart;this.value=c;void 0==c&&(c="");l||(l=0);void 0==e&&(e=!0);var r=q.fontFamily,u=a.fontSize;void 0==u&&(u=q.fontSize);var t=a.color;void 0==t&&(t=q.color);void 0!==n&&(t=n);var z=a.chart.container,y=z.set();this.set=y;var v=a.axisThickness,w=a.axisColor,A=a.axisAlpha,B=a.tickLength,C=a.gridAlpha,D=a.gridThickness,J=a.gridColor,E=a.dashLength,O=a.fillColor,I=a.fillAlpha,W=a.labelsEnabled; n=a.labelRotationR;var ea=a.counter,P=a.inside,oa=a.labelOffset,qa=a.dx,ka=a.dy,Qa=a.orientation,ca=a.position,aa=a.previousCoord,V=a.viH,sa=a.viW,ba=a.offset,da,ta;g?(void 0!==g.id&&(p=q.classNamePrefix+"-guide-"+g.id),W=!0,isNaN(g.tickLength)||(B=g.tickLength),void 0!=g.lineColor&&(J=g.lineColor),void 0!=g.color&&(t=g.color),isNaN(g.lineAlpha)||(C=g.lineAlpha),isNaN(g.dashLength)||(E=g.dashLength),isNaN(g.lineThickness)||(D=g.lineThickness),!0===g.inside&&(P=!0,0<ba&&(ba=0)),isNaN(g.labelRotation)|| (n=g.labelRotation),isNaN(g.fontSize)||(u=g.fontSize),g.position&&(ca=g.position),void 0!==g.boldLabel&&(k=g.boldLabel),isNaN(g.labelOffset)||(oa=g.labelOffset)):""===c&&(B=0);m&&!isNaN(a.minorTickLength)&&(B=a.minorTickLength);var fa="start";0<h&&(fa="middle");a.centerLabels&&(fa="middle");var R=n*Math.PI/180,X,wa,H=0,x=0,la=0,ga=X=0,Ja=0;"V"==Qa&&(n=0);var Z;W&&""!==c&&(Z=a.autoWrap&&0===n?d.wrappedText(z,c,t,r,u,fa,k,Math.abs(h),0):d.text(z,c,t,r,u,fa,k),fa=Z.getBBox(),ga=fa.width,Ja=fa.height); if("H"==Qa){if(0<=b&&b<=sa+1&&(0<B&&0<A&&b+l<=sa+1&&(da=d.line(z,[b+l,b+l],[0,B],w,A,D),y.push(da)),0<C&&(ta=d.line(z,[b,b+qa,b+qa],[V,V+ka,ka],J,C,D,E),y.push(ta))),x=0,H=b,g&&90==n&&P&&(H-=u),!1===e?(fa="start",x="bottom"==ca?P?x+B:x-B:P?x-B:x+B,H+=3,0<h&&(H+=h/2-3,fa="middle"),0<n&&(fa="middle")):fa="middle",1==ea&&0<I&&!g&&!m&&aa<sa&&(e=d.fitToBounds(b,0,sa),aa=d.fitToBounds(aa,0,sa),X=e-aa,0<X&&(wa=d.rect(z,X,a.height,O,I),wa.translate(e-X+qa,ka),y.push(wa))),"bottom"==ca?(x+=V+u/2+ba,P?(0<n? (x=V-ga/2*Math.sin(R)-B-3,H+=ga/2*Math.cos(R)-4+2):0>n?(x=V+ga*Math.sin(R)-B-3+2,H+=-ga*Math.cos(R)-Ja*Math.sin(R)-4):x-=B+u+3+3,x-=oa):(0<n?(x=V+ga/2*Math.sin(R)+B+3,H-=ga/2*Math.cos(R)):0>n?(x=V+B+3-ga/2*Math.sin(R)+2,H+=ga/2*Math.cos(R)):x+=B+v+3+3,x+=oa)):(x+=ka+u/2-ba,H+=qa,P?(0<n?(x=ga/2*Math.sin(R)+B+3,H-=ga/2*Math.cos(R)):x+=B+3,x+=oa):(0<n?(x=-(ga/2)*Math.sin(R)-B-6,H+=ga/2*Math.cos(R)):x-=B+u+3+v+3,x-=oa)),"bottom"==ca?X=(P?V-B-1:V+v-1)+ba:(la=qa,X=(P?ka:ka-B-v+1)-ba),f&&(H+=f),f=H,0<n&& (f+=ga/2*Math.cos(R)),Z&&(u=0,P&&(u=ga/2*Math.cos(R)),f+u>sa+2||0>f))Z.remove(),Z=null}else{0<=b&&b<=V+1&&(0<B&&0<A&&b+l<=V+1&&(da=d.line(z,[0,B],[b+l,b+l],w,A,D),y.push(da)),0<C&&(ta=d.line(z,[0,qa,sa+qa],[b,b+ka,b+ka],J,C,D,E),y.push(ta)));fa="end";if(!0===P&&"left"==ca||!1===P&&"right"==ca)fa="start";x=b-Ja/2+2;1==ea&&0<I&&!g&&!m&&(e=d.fitToBounds(b,0,V),aa=d.fitToBounds(aa,0,V),R=e-aa,wa=d.polygon(z,[0,a.width,a.width,0],[0,0,R,R],O,I),wa.translate(qa,e-R+ka),y.push(wa));x+=u/2;"right"==ca?(H+= qa+sa+ba,x+=ka,P?(f||(x-=u/2+3),H=H-(B+4)-oa):(H+=B+4+v,x-=2,H+=oa)):P?(H+=B+4-ba,f||(x-=u/2+3),g&&(H+=qa,x+=ka),H+=oa):(H+=-B-v-4-2-ba,x-=2,H-=oa);da&&("right"==ca?(la+=qa+ba+sa,X+=ka,la=P?la-v:la+v):(la-=ba,P||(la-=B+v)));f&&(x+=f);P=-3;"right"==ca&&(P+=ka);Z&&(x>V+1||x<P)&&(Z.remove(),Z=null)}da&&(da.translate(la,X),d.setCN(q,da,a.bcn+"tick"),d.setCN(q,da,p,!0),g&&d.setCN(q,da,"guide"));!1===a.visible&&(da&&da.remove(),Z&&(Z.remove(),Z=null));Z&&(Z.attr({"text-anchor":fa}),Z.translate(H,x),0!== n&&Z.rotate(-n,a.chart.backgroundColor),a.allLabels.push(Z),this.label=Z,d.setCN(q,Z,a.bcn+"label"),d.setCN(q,Z,p,!0),g&&d.setCN(q,Z,"guide"));ta&&(d.setCN(q,ta,a.bcn+"grid"),d.setCN(q,ta,p,!0),g&&d.setCN(q,ta,"guide"));wa&&(d.setCN(q,wa,a.bcn+"fill"),d.setCN(q,wa,p,!0));m?ta&&d.setCN(q,ta,a.bcn+"grid-minor"):(a.counter=0===ea?1:0,a.previousCoord=b);0===this.set.node.childNodes.length&&this.set.remove()},graphics:function(){return this.set},getLabel:function(){return this.label}})})();(function(){var d=window.AmCharts;d.RecFill=d.Class({construct:function(a,b,c,e){var h=a.dx,f=a.dy,g=a.orientation,k=0;if(c<b){var l=b;b=c;c=l}var m=e.fillAlpha;isNaN(m)&&(m=0);var l=a.chart.container,n=e.fillColor;"V"==g?(b=d.fitToBounds(b,0,a.viH),c=d.fitToBounds(c,0,a.viH)):(b=d.fitToBounds(b,0,a.viW),c=d.fitToBounds(c,0,a.viW));c-=b;isNaN(c)&&(c=4,k=2,m=0);0>c&&"object"==typeof n&&(n=n.join(",").split(",").reverse());"V"==g?(g=d.rect(l,a.viW,c,n,m),g.translate(h,b-k+f)):(g=d.rect(l,c,a.viH,n, m),g.translate(b-k+h,f));d.setCN(a.chart,g,"guide-fill");e.id&&d.setCN(a.chart,g,"guide-fill-"+e.id);this.set=l.set([g])},graphics:function(){return this.set},getLabel:function(){}})})();(function(){var d=window.AmCharts;d.AmChart=d.Class({construct:function(a){this.theme=a;this.classNamePrefix="amcharts";this.addClassNames=!1;this.version="3.15.2";d.addChart(this);this.createEvents("dataUpdated","init","rendered","drawn","failed","resized");this.height=this.width="100%";this.dataChanged=!0;this.chartCreated=!1;this.previousWidth=this.previousHeight=0;this.backgroundColor="#FFFFFF";this.borderAlpha=this.backgroundAlpha=0;this.color=this.borderColor="#000000";this.fontFamily="Verdana"; this.fontSize=11;this.usePrefixes=!1;this.addCodeCredits=this.autoResize=!0;this.precision=-1;this.percentPrecision=2;this.decimalSeparator=".";this.thousandsSeparator=",";this.labels=[];this.allLabels=[];this.titles=[];this.marginRight=this.marginLeft=this.autoMarginOffset=0;this.timeOuts=[];this.creditsPosition="top-left";var b=document.createElement("div"),c=b.style;c.overflow="hidden";c.position="relative";c.textAlign="left";this.chartDiv=b;b=document.createElement("div");c=b.style;c.overflow= "hidden";c.position="relative";c.textAlign="left";this.legendDiv=b;this.titleHeight=0;this.hideBalloonTime=150;this.handDrawScatter=2;this.handDrawThickness=1;this.prefixesOfBigNumbers=[{number:1E3,prefix:"k"},{number:1E6,prefix:"M"},{number:1E9,prefix:"G"},{number:1E12,prefix:"T"},{number:1E15,prefix:"P"},{number:1E18,prefix:"E"},{number:1E21,prefix:"Z"},{number:1E24,prefix:"Y"}];this.prefixesOfSmallNumbers=[{number:1E-24,prefix:"y"},{number:1E-21,prefix:"z"},{number:1E-18,prefix:"a"},{number:1E-15, prefix:"f"},{number:1E-12,prefix:"p"},{number:1E-9,prefix:"n"},{number:1E-6,prefix:"\u03bc"},{number:.001,prefix:"m"}];this.panEventsEnabled=!0;this.product="amcharts";this.animations=[];this.balloon=new d.AmBalloon(this.theme);this.balloon.chart=this;d.applyTheme(this,a,"AmChart")},drawChart:function(){0<this.realWidth&&0<this.realHeight&&(this.drawBackground(),this.redrawLabels(),this.drawTitles(),this.brr(),this.renderFix())},drawBackground:function(){d.remove(this.background);var a=this.container, b=this.backgroundColor,c=this.backgroundAlpha,e=this.set;d.isModern||0!==c||(c=.001);var h=this.updateWidth();this.realWidth=h;var f=this.updateHeight();this.realHeight=f;b=d.polygon(a,[0,h-1,h-1,0],[0,0,f-1,f-1],b,c,1,this.borderColor,this.borderAlpha);d.setCN(this,b,"bg");this.background=b;e.push(b);if(b=this.backgroundImage)a=a.image(b,0,0,h,f),d.setCN(this,b,"bg-image"),this.bgImg=a,e.push(a)},drawTitles:function(a){var b=this.titles;this.titleHeight=0;if(d.ifArray(b)){var c=20,e;for(e=0;e<b.length;e++){var h= b[e],h=d.processObject(h,d.Title,this.theme);if(!1!==h.enabled){var f=h.color;void 0===f&&(f=this.color);var g=h.size;isNaN(g)&&(g=this.fontSize+2);isNaN(h.alpha);var k=this.marginLeft,f=d.wrappedText(this.container,h.text,f,this.fontFamily,g,"middle",!0,this.divRealWidth-20);f.translate(k+(this.realWidth-this.marginRight-k)/2,c);f.node.style.pointerEvents="none";h.sprite=f;d.setCN(this,f,"title");h.id&&d.setCN(this,f,"title-"+h.id);k=!0;void 0!==h.bold&&(k=h.bold);k&&f.attr({"font-weight":"bold"}); f.attr({opacity:h.alpha});c+=f.getBBox().height+5;a?f.remove():this.freeLabelsSet.push(f)}}this.titleHeight=c-10}},write:function(a){if(a="object"!=typeof a?document.getElementById(a):a){for(;a.firstChild;)a.removeChild(a.firstChild);this.div=a;a.style.overflow="hidden";a.style.textAlign="left";var b=this.chartDiv,c=this.legendDiv,e=this.legend,h=c.style,f=b.style;this.measure();this.previousHeight=this.divRealHeight;this.previousWidth=this.divRealWidth;var g,k=document.createElement("div");g=k.style; g.position="relative";this.containerDiv=k;k.className=this.classNamePrefix+"-main-div";b.className=this.classNamePrefix+"-chart-div";a.appendChild(k);var l=this.exportConfig;l&&d.AmExport&&!this.AmExport&&(this.AmExport=new d.AmExport(this,l));this.amExport&&d.AmExport&&(this.AmExport=d.extend(this.amExport,new d.AmExport(this),!0));this.AmExport&&this.AmExport.init&&this.AmExport.init();if(e)if(e=this.addLegend(e,e.divId),e.enabled)switch(e.position){case "bottom":k.appendChild(b);k.appendChild(c); break;case "top":k.appendChild(c);k.appendChild(b);break;case "absolute":g.width=a.style.width;g.height=a.style.height;h.position="absolute";f.position="absolute";void 0!==e.left&&(h.left=e.left+"px");void 0!==e.right&&(h.right=e.right+"px");void 0!==e.top&&(h.top=e.top+"px");void 0!==e.bottom&&(h.bottom=e.bottom+"px");e.marginLeft=0;e.marginRight=0;k.appendChild(b);k.appendChild(c);break;case "right":g.width=a.style.width;g.height=a.style.height;h.position="relative";f.position="absolute";k.appendChild(b); k.appendChild(c);break;case "left":g.width=a.style.width;g.height=a.style.height;h.position="absolute";f.position="relative";k.appendChild(b);k.appendChild(c);break;case "outside":k.appendChild(b)}else k.appendChild(b);else k.appendChild(b);this.listenersAdded||(this.addListeners(),this.listenersAdded=!0);this.initChart()}},createLabelsSet:function(){d.remove(this.labelsSet);this.labelsSet=this.container.set();this.freeLabelsSet.push(this.labelsSet)},initChart:function(){window.AmCharts_path&&(this.path= window.AmCharts_path);void 0===this.path&&(this.path=d.getPath());void 0===this.path&&(this.path="amcharts/");this.path=d.normalizeUrl(this.path);void 0===this.pathToImages&&(this.pathToImages=this.path+"images/");this.initHC||(d.callInitHandler(this),this.initHC=!0);d.applyLang(this.language,this);var a=this.numberFormatter;a&&(isNaN(a.precision)||(this.precision=a.precision),void 0!==a.thousandsSeparator&&(this.thousandsSeparator=a.thousandsSeparator),void 0!==a.decimalSeparator&&(this.decimalSeparator= a.decimalSeparator));(a=this.percentFormatter)&&!isNaN(a.precision)&&(this.percentPrecision=a.precision);this.nf={precision:this.precision,thousandsSeparator:this.thousandsSeparator,decimalSeparator:this.decimalSeparator};this.pf={precision:this.percentPrecision,thousandsSeparator:this.thousandsSeparator,decimalSeparator:this.decimalSeparator};this.destroy();(a=this.container)?(a.container.innerHTML="",a.width=this.realWidth,a.height=this.realHeight,a.addDefs(this),this.chartDiv.appendChild(a.container)): a=new d.AmDraw(this.chartDiv,this.realWidth,this.realHeight,this);this.container=a;this.checkDisplay();a.chart=this;d.VML||d.SVG?(a.handDrawn=this.handDrawn,a.handDrawScatter=this.handDrawScatter,a.handDrawThickness=this.handDrawThickness,this.set&&this.set.remove(),this.set=a.set(),this.gridSet&&this.gridSet.remove(),this.gridSet=a.set(),this.cursorLineSet&&this.cursorLineSet.remove(),this.cursorLineSet=a.set(),this.graphsBehindSet&&this.graphsBehindSet.remove(),this.graphsBehindSet=a.set(),this.bulletBehindSet&& this.bulletBehindSet.remove(),this.bulletBehindSet=a.set(),this.columnSet&&this.columnSet.remove(),this.columnSet=a.set(),this.graphsSet&&this.graphsSet.remove(),this.graphsSet=a.set(),this.trendLinesSet&&this.trendLinesSet.remove(),this.trendLinesSet=a.set(),this.axesSet&&this.axesSet.remove(),this.axesSet=a.set(),this.cursorSet&&this.cursorSet.remove(),this.cursorSet=a.set(),this.scrollbarsSet&&this.scrollbarsSet.remove(),this.scrollbarsSet=a.set(),this.bulletSet&&this.bulletSet.remove(),this.bulletSet= a.set(),this.freeLabelsSet&&this.freeLabelsSet.remove(),this.axesLabelsSet&&this.axesLabelsSet.remove(),this.axesLabelsSet=a.set(),this.freeLabelsSet=a.set(),this.balloonsSet&&this.balloonsSet.remove(),this.balloonsSet=a.set(),this.zoomButtonSet&&this.zoomButtonSet.remove(),this.zbSet&&(this.zbSet.remove(),this.zbSet=null),this.zoomButtonSet=a.set(),this.linkSet&&this.linkSet.remove(),this.linkSet=a.set()):this.fire("failed",{type:"failed",chart:this})},premeasure:function(){var a=this.div;if(a){this.boundingRect= this.chartDiv.getBoundingClientRect();var b=a.offsetWidth,c=a.offsetHeight;a.clientHeight&&(b=a.clientWidth,c=a.clientHeight);if(b!=this.mw||c!=this.mh)this.mw=b,this.mh=c,this.measure()}},measure:function(){var a=this.div;if(a){var b=this.chartDiv,c=a.offsetWidth,e=a.offsetHeight,h=this.container;a.clientHeight&&(c=a.clientWidth,e=a.clientHeight);var f=d.removePx(d.getStyle(a,"padding-left")),g=d.removePx(d.getStyle(a,"padding-right")),k=d.removePx(d.getStyle(a,"padding-top")),l=d.removePx(d.getStyle(a, "padding-bottom"));isNaN(f)||(c-=f);isNaN(g)||(c-=g);isNaN(k)||(e-=k);isNaN(l)||(e-=l);f=a.style;a=f.width;f=f.height;-1!=a.indexOf("px")&&(c=d.removePx(a));-1!=f.indexOf("px")&&(e=d.removePx(f));e=Math.round(e);c=Math.round(c);a=Math.round(d.toCoordinate(this.width,c));f=Math.round(d.toCoordinate(this.height,e));(c!=this.previousWidth||e!=this.previousHeight)&&0<a&&0<f&&(b.style.width=a+"px",b.style.height=f+"px",b.style.padding=0,h&&h.setSize(a,f),this.balloon=d.processObject(this.balloon,d.AmBalloon, this.theme),this.balloon.setBounds(2,2,a-2,f));this.balloon.chart=this;this.realWidth=a;this.realHeight=f;this.divRealWidth=c;this.divRealHeight=e}},checkDisplay:function(){if(this.container){var a=d.rect(this.container,10,10),b=a.getBBox();0===b.width&&0===b.height&&(this.divRealHeight=this.divRealWidth=this.realHeight=this.realWidth=0,this.previousWidth=this.previousHeight=NaN);a.remove()}},destroy:function(){this.chartDiv.innerHTML="";this.clearTimeOuts();this.legend&&this.legend.destroy()},clearTimeOuts:function(){var a= this.timeOuts;if(a){var b;for(b=0;b<a.length;b++)clearTimeout(a[b])}this.timeOuts=[]},clear:function(a){d.callMethod("clear",[this.chartScrollbar,this.scrollbarV,this.scrollbarH,this.chartCursor]);this.chartCursor=this.scrollbarH=this.scrollbarV=this.chartScrollbar=null;this.clearTimeOuts();this.container&&(this.container.remove(this.chartDiv),this.container.remove(this.legendDiv));a||d.removeChart(this);if(a=this.div)for(;a.firstChild;)a.removeChild(a.firstChild);this.legend&&this.legend.destroy()}, setMouseCursor:function(a){"auto"==a&&d.isNN&&(a="default");this.chartDiv.style.cursor=a;this.legendDiv.style.cursor=a},redrawLabels:function(){this.labels=[];var a=this.allLabels;this.createLabelsSet();var b;for(b=0;b<a.length;b++)this.drawLabel(a[b])},drawLabel:function(a){if(this.container&&!1!==a.enabled){a=d.processObject(a,d.Label,this.theme);var b=a.y,c=a.text,e=a.align,h=a.size,f=a.color,g=a.rotation,k=a.alpha,l=a.bold,m=d.toCoordinate(a.x,this.realWidth),b=d.toCoordinate(b,this.realHeight); m||(m=0);b||(b=0);void 0===f&&(f=this.color);isNaN(h)&&(h=this.fontSize);e||(e="start");"left"==e&&(e="start");"right"==e&&(e="end");"center"==e&&(e="middle",g?b=this.realHeight-b+b/2:m=this.realWidth/2-m);void 0===k&&(k=1);void 0===g&&(g=0);b+=h/2;c=d.text(this.container,c,f,this.fontFamily,h,e,l,k);c.translate(m,b);d.setCN(this,c,"label");a.id&&d.setCN(this,c,"label-"+a.id);0!==g&&c.rotate(g);a.url?(c.setAttr("cursor","pointer"),c.click(function(){d.getURL(a.url)})):c.node.style.pointerEvents="none"; this.labelsSet.push(c);this.labels.push(c)}},addLabel:function(a,b,c,e,d,f,g,k,l,m){a={x:a,y:b,text:c,align:e,size:d,color:f,alpha:k,rotation:g,bold:l,url:m,enabled:!0};this.container&&this.drawLabel(a);this.allLabels.push(a)},clearLabels:function(){var a=this.labels,b;for(b=a.length-1;0<=b;b--)a[b].remove();this.labels=[];this.allLabels=[]},updateHeight:function(){var a=this.divRealHeight,b=this.legend;if(b){var c=this.legendDiv.offsetHeight,b=b.position;if("top"==b||"bottom"==b){a-=c;if(0>a||isNaN(a))a= 0;this.chartDiv.style.height=a+"px"}}return a},updateWidth:function(){var a=this.divRealWidth,b=this.divRealHeight,c=this.legend;if(c){var e=this.legendDiv,d=e.offsetWidth;isNaN(c.width)||(d=c.width);c.ieW&&(d=c.ieW);var f=e.offsetHeight,e=e.style,g=this.chartDiv.style,c=c.position;if("right"==c||"left"==c){a-=d;if(0>a||isNaN(a))a=0;g.width=a+"px";"left"==c?(g.left=d+"px",e.left="0px"):(g.left="0px",e.left=a+"px");b>f&&(e.top=(b-f)/2+"px")}}return a},getTitleHeight:function(){this.drawTitles(!0); return this.titleHeight},addTitle:function(a,b,c,e,d){isNaN(b)&&(b=this.fontSize+2);a={text:a,size:b,color:c,alpha:e,bold:d,enabled:!0};this.titles.push(a);return a},handleWheel:function(a){var b=0;a||(a=window.event);a.wheelDelta?b=a.wheelDelta/120:a.detail&&(b=-a.detail/3);b&&this.handleWheelReal(b,a.shiftKey);a.preventDefault&&a.preventDefault()},handleWheelReal:function(){},addListeners:function(){var a=this,b=a.chartDiv;document.addEventListener?(a.panEventsEnabled&&(b.style.msTouchAction="none"), "ontouchstart"in document.documentElement&&(b.addEventListener("touchstart",function(b){a.handleTouchStart.call(a,b)},!0),b.addEventListener("touchmove",function(b){a.handleMouseMove.call(a,b)},!0),b.addEventListener("touchend",function(b){a.handleTouchEnd.call(a,b)},!0)),b.addEventListener("mousedown",function(b){a.mouseIsOver=!0;a.handleMouseMove.call(a,b);a.handleMouseDown.call(a,b)},!0),b.addEventListener("mouseover",function(b){a.handleMouseOver.call(a,b)},!0),b.addEventListener("mouseout",function(b){a.handleMouseOut.call(a, b)},!0)):(b.attachEvent("onmousedown",function(b){a.handleMouseDown.call(a,b)}),b.attachEvent("onmouseover",function(b){a.handleMouseOver.call(a,b)}),b.attachEvent("onmouseout",function(b){a.handleMouseOut.call(a,b)}))},dispDUpd:function(){if(!this.skipEvents){var a;this.dispatchDataUpdated&&(this.dispatchDataUpdated=!1,a="dataUpdated",this.fire(a,{type:a,chart:this}));this.chartCreated||(this.chartCreated=!0,a="init",this.fire(a,{type:a,chart:this}));this.chartRendered||(a="rendered",this.fire(a, {type:a,chart:this}),this.chartRendered=!0);a="drawn";this.fire(a,{type:a,chart:this})}this.skipEvents=!1},validateSize:function(){var a=this;a.premeasure();a.checkDisplay();if(a.divRealWidth!=a.previousWidth||a.divRealHeight!=a.previousHeight){var b=a.legend;if(0<a.realWidth&&0<a.realHeight){a.sizeChanged=!0;if(b){a.legendInitTO&&clearTimeout(a.legendInitTO);var c=setTimeout(function(){b.invalidateSize()},10);a.timeOuts.push(c);a.legendInitTO=c}"xy"!=a.type?a.marginsUpdated=!1:(a.marginsUpdated= !0,a.selfZoom=!0);clearTimeout(a.initTO);c=setTimeout(function(){a.initChart()},10);a.timeOuts.push(c);a.initTO=c}a.fire("resized",{type:"resized",chart:a});a.renderFix();b&&b.renderFix&&b.renderFix();a.previousHeight=a.divRealHeight;a.previousWidth=a.divRealWidth}},invalidateSize:function(){this.previousHeight=this.previousWidth=NaN;this.invalidateSizeReal()},invalidateSizeReal:function(){var a=this;a.marginsUpdated=!1;clearTimeout(a.validateTO);var b=setTimeout(function(){a.validateSize()},5);a.timeOuts.push(b); a.validateTO=b},validateData:function(a){this.chartCreated&&(this.dataChanged=!0,this.marginsUpdated=!1,this.initChart(a))},validateNow:function(a,b){this.initTO&&clearTimeout(this.initTO);a&&(this.dataChanged=!0);this.skipEvents=b;this.chartRendered=!1;this.write(this.div)},showItem:function(a){a.hidden=!1;this.initChart()},hideItem:function(a){a.hidden=!0;this.initChart()},hideBalloon:function(){var a=this;clearTimeout(a.hoverInt);clearTimeout(a.balloonTO);a.hoverInt=setTimeout(function(){a.hideBalloonReal.call(a)}, a.hideBalloonTime)},cleanChart:function(){},hideBalloonReal:function(){var a=this.balloon;a&&a.hide()},showBalloon:function(a,b,c,e,d){var f=this;clearTimeout(f.balloonTO);clearTimeout(f.hoverInt);f.balloonTO=setTimeout(function(){f.showBalloonReal.call(f,a,b,c,e,d)},1)},showBalloonReal:function(a,b,c,e,d){this.handleMouseMove();var f=this.balloon;f.enabled&&(f.followCursor(!1),f.changeColor(b),!c||f.fixedPosition?(f.setPosition(e,d),f.followCursor(!1)):f.followCursor(!0),a&&f.showBalloon(a))},handleMouseOver:function(){this.outTO&& clearTimeout(this.outTO);d.resetMouseOver();this.mouseIsOver=!0},handleMouseOut:function(){var a=this;a.outTO&&clearTimeout(a.outTO);a.outTO=setTimeout(function(){a.handleMouseOutReal()},10)},handleMouseOutReal:function(){d.resetMouseOver();this.mouseIsOver=!1},handleMouseMove:function(a){a||(a=window.event);if(a){if(a.touches&&(a=a.touches.item(0),!a))return;this.boundingRect&&a.clientX&&(this.mouseX=a.clientX-this.boundingRect.left,this.mouseY=a.clientY-this.boundingRect.top)}},handleTouchStart:function(a){this.handleMouseMove(a); this.handleMouseDown(a)},handleTouchEnd:function(a){this.handleMouseMove(a);d.resetMouseOver();this.handleReleaseOutside(a)},handleReleaseOutside:function(){},handleMouseDown:function(a){d.resetMouseOver();this.mouseIsOver=!0;a&&a.preventDefault&&(this.panEventsEnabled?a.preventDefault():a.touches||a.preventDefault())},addLegend:function(a,b){a=d.processObject(a,d.AmLegend,this.theme);a.divId=b;a.ieW=0;var c;c="object"!=typeof b&&b?document.getElementById(b):b;this.legend=a;a.chart=this;c?(a.div= c,a.position="outside",a.autoMargins=!1):a.div=this.legendDiv;return a},removeLegend:function(){this.legend=void 0;this.legendDiv.innerHTML=""},handleResize:function(){(d.isPercents(this.width)||d.isPercents(this.height))&&this.invalidateSizeReal();this.renderFix()},renderFix:function(){if(!d.VML){var a=this.container;a&&a.renderFix()}},getSVG:function(){if(d.hasSVG)return this.container},animate:function(a,b,c,e,h,f,g){a["an_"+b]&&d.removeFromArray(this.animations,a["an_"+b]);c={obj:a,frame:0,attribute:b, from:c,to:e,time:h,effect:f,suffix:g};a["an_"+b]=c;this.animations.push(c);return c},setLegendData:function(a){var b=this.legend;b&&b.setData(a)},stopAnim:function(a){d.removeFromArray(this.animations,a)},updateAnimations:function(){var a;this.container&&this.container.update();if(this.animations)for(a=this.animations.length-1;0<=a;a--){var b=this.animations[a],c=1E3*b.time/d.updateRate,e=b.frame+1,h=b.obj,f=b.attribute;if(e<=c){b.frame++;var g=Number(b.from),k=Number(b.to)-g,c=d[b.effect](0,e,g, k,c);0===k?(this.animations.splice(a,1),h.node.style[f]=Number(b.to)+b.suffix):h.node.style[f]=c+b.suffix}else h.node.style[f]=Number(b.to)+b.suffix,this.animations.splice(a,1)}},update:function(){this.updateAnimations()},inIframe:function(){try{return window.self!==window.top}catch(a){return!0}},brr:function(){var a="amcharts.com",b=window.location.hostname.split("."),c;2<=b.length&&(c=b[b.length-2]+"."+b[b.length-1]);this.amLink&&(b=this.amLink.parentNode)&&b.removeChild(this.amLink);b=this.creditsPosition; if(c!=a||!0===this.inIframe()){var a="http://www."+a,e=c=0,d=this.realWidth,f=this.realHeight,g=this.type;if("serial"==g||"xy"==g||"gantt"==g)c=this.marginLeftReal,e=this.marginTopReal,d=c+this.plotAreaWidth,f=e+this.plotAreaHeight;var g=a+"/javascript-charts/",k="JavaScript charts",l="JS chart by amCharts";"ammap"==this.product&&(g=a+"/javascript-maps/",k="Interactive JavaScript maps",l="JS map by amCharts");a=document.createElement("a");l=document.createTextNode(l);a.setAttribute("href",g);a.setAttribute("title", k);a.appendChild(l);this.chartDiv.appendChild(a);this.amLink=a;g=a.style;g.position="absolute";g.textDecoration="none";g.color=this.color;g.fontFamily=this.fontFamily;g.fontSize=this.fontSize+"px";g.opacity=.7;g.display="block";var k=a.offsetWidth,a=a.offsetHeight,l=5+c,m=e+5;"bottom-left"==b&&(l=5+c,m=f-a-3);"bottom-right"==b&&(l=d-k-5,m=f-a-3);"top-right"==b&&(l=d-k-5,m=e+5);g.left=l+"px";g.top=m+"px"}}});d.Slice=d.Class({construct:function(){}});d.SerialDataItem=d.Class({construct:function(){}}); d.GraphDataItem=d.Class({construct:function(){}});d.Guide=d.Class({construct:function(a){this.cname="Guide";d.applyTheme(this,a,this.cname)}});d.Title=d.Class({construct:function(a){this.cname="Title";d.applyTheme(this,a,this.cname)}});d.Label=d.Class({construct:function(a){this.cname="Label";d.applyTheme(this,a,this.cname)}})})();(function(){var d=window.AmCharts;d.AmGraph=d.Class({construct:function(a){this.cname="AmGraph";this.createEvents("rollOverGraphItem","rollOutGraphItem","clickGraphItem","doubleClickGraphItem","rightClickGraphItem","clickGraph","rollOverGraph","rollOutGraph");this.type="line";this.stackable=!0;this.columnCount=1;this.columnIndex=0;this.centerCustomBullets=this.showBalloon=!0;this.maxBulletSize=50;this.minBulletSize=4;this.balloonText="[[value]]";this.hidden=this.scrollbar=this.animationPlayed=!1; this.pointPosition="middle";this.depthCount=1;this.includeInMinMax=!0;this.negativeBase=0;this.visibleInLegend=!0;this.showAllValueLabels=!1;this.showBulletsAt=this.showBalloonAt="close";this.lineThickness=1;this.dashLength=0;this.connect=!0;this.lineAlpha=1;this.bullet="none";this.bulletBorderThickness=2;this.bulletBorderAlpha=0;this.bulletAlpha=1;this.bulletSize=8;this.cornerRadiusTop=this.hideBulletsCount=this.bulletOffset=0;this.cursorBulletAlpha=1;this.gradientOrientation="vertical";this.dy= this.dx=0;this.periodValue="";this.clustered=!0;this.periodSpan=1;this.y=this.x=0;this.switchable=!0;this.tcc=this.minDistance=1;this.labelRotation=0;this.labelAnchor="auto";this.labelOffset=3;this.bcn="graph-";this.dateFormat="MMM DD, YYYY";d.applyTheme(this,a,this.cname)},draw:function(){var a=this.chart,b=a.type;isNaN(this.precision)||(this.numberFormatter?this.numberFormatter.precision=this.precision:this.numberFormatter={precision:this.precision,decimalSeparator:a.decimalSeparator,thousandsSeparator:a.thousandsSeparator}); var c=a.container;this.container=c;this.destroy();var e=c.set(),h=c.set();this.behindColumns?(a.graphsBehindSet.push(e),a.bulletBehindSet.push(h)):(a.graphsSet.push(e),a.bulletSet.push(h));var f=this.bulletAxis;d.isString(f)&&(this.bulletAxis=a.getValueAxisById(f));this.bulletSet=h;if(!this.scrollbar){var f=a.marginLeftReal,g=a.marginTopReal;e.translate(f,g);h.translate(f,g)}c=c.set();d.remove(this.columnsSet);e.push(c);this.set=e;d.setCN(a,e,"graph-"+this.type);d.setCN(a,e,"graph-"+this.id);d.setCN(a, h,"graph-"+this.type);d.setCN(a,h,"graph-"+this.id);this.columnsSet=c;this.columnsArray=[];this.ownColumns=[];this.allBullets=[];this.animationArray=[];e=this.labelPosition;e||(h=this.valueAxis.stackType,e="top","column"==this.type&&(a.rotate&&(e="right"),"100%"==h||"regular"==h)&&(e="middle"),this.labelPosition=e);d.ifArray(this.data)&&(a=!1,"xy"==b?this.xAxis.axisCreated&&this.yAxis.axisCreated&&(a=!0):this.valueAxis.axisCreated&&(a=!0),!this.hidden&&a&&this.createGraph())},createGraph:function(){var a= this,b=a.chart;a.startAlpha=b.startAlpha;a.seqAn=b.sequencedAnimation;a.baseCoord=a.valueAxis.baseCoord;void 0===a.fillAlphas&&(a.fillAlphas=0);a.bulletColorR=a.bulletColor;void 0===a.bulletColorR&&(a.bulletColorR=a.lineColorR,a.bulletColorNegative=a.negativeLineColor);void 0===a.bulletAlpha&&(a.bulletAlpha=a.lineAlpha);b=b.type;"gantt"==b&&(b="serial");clearTimeout(a.playedTO);if(!isNaN(a.valueAxis.min)&&!isNaN(a.valueAxis.max)){switch(b){case "serial":a.categoryAxis&&(a.createSerialGraph(),"candlestick"== a.type&&1>a.valueAxis.minMaxMultiplier&&a.positiveClip(a.set));break;case "radar":a.createRadarGraph();break;case "xy":a.createXYGraph(),a.positiveClip(a.set)}a.playedTO=setTimeout(function(){a.setAnimationPlayed.call(a)},500*a.chart.startDuration)}},setAnimationPlayed:function(){this.animationPlayed=!0},createXYGraph:function(){var a=[],b=[],c=this.xAxis,e=this.yAxis;this.pmh=e.viH+1;this.pmw=c.viW+1;this.pmy=this.pmx=0;var d;for(d=this.start;d<=this.end;d++){var f=this.data[d].axes[c.id].graphs[this.id], g=f.values,k=g.x,l=g.y,g=c.getCoordinate(k),m=e.getCoordinate(l);!isNaN(k)&&!isNaN(l)&&(a.push(g),b.push(m),f.x=g,f.y=m,k=this.createBullet(f,g,m,d),l=this.labelText)&&(f=this.createLabel(f,g,m,l),this.positionLabel(g,m,f,k),this.allBullets.push(f))}this.drawLineGraph(a,b);this.launchAnimation()},createRadarGraph:function(){var a=this.valueAxis.stackType,b=[],c=[],e=[],d=[],f,g,k,l,m;for(m=this.start;m<=this.end;m++){var n=this.data[m].axes[this.valueAxis.id].graphs[this.id],p,q;"none"==a||"3d"== a?p=n.values.value:(p=n.values.close,q=n.values.open);if(isNaN(p))this.connect||(this.drawLineGraph(b,c,e,d),b=[],c=[],e=[],d=[]);else{var r=this.y-(this.valueAxis.getCoordinate(p)-this.height),r=r*this.valueAxis.rMultiplier,u=180-360/(this.end-this.start+1)*m;"middle"==this.valueAxis.pointPosition&&(u-=180/(this.end-this.start+1));p=r*Math.sin(u/180*Math.PI);r*=Math.cos(u/180*Math.PI);b.push(p);c.push(r);if(!isNaN(q)){var t=this.y-(this.valueAxis.getCoordinate(q)-this.height),t=t*this.valueAxis.rMultiplier, z=t*Math.sin(u/180*Math.PI),u=t*Math.cos(u/180*Math.PI);e.push(z);d.push(u);isNaN(k)&&(k=z);isNaN(l)&&(l=u)}u=this.createBullet(n,p,r,m);if(z=this.labelText)n=this.createLabel(n,p,r,z),this.positionLabel(p,r,n,u),this.allBullets.push(n);isNaN(f)&&(f=p);isNaN(g)&&(g=r)}}b.push(f);c.push(g);isNaN(k)||(e.push(k),d.push(l));this.drawLineGraph(b,c,e,d);this.launchAnimation()},positionLabel:function(a,b,c,e){var d="middle",f=!1,g=this.labelPosition,k=c.getBBox();if(e){var l=e.graphDataItem,m=this.chart.rotate, n=l.isNegative,p=this.chart,q=this.valueAxis;b-=k.height/4/2;switch(g){case "top":g=m?"top":n?"bottom":"top";break;case "right":g=m?n?"left":"right":"right";break;case "bottom":g=m?"bottom":n?"top":"bottom";break;case "left":g=m?n?"right":"left":"left"}var r=l.columnGraphics,u=0,t=0;r&&(u=r.x,t=r.y);var z=this.labelOffset;switch(g){case "top":b=q.reversed?b+(e.size/2+k.height/2+z):b-(e.size/2+k.height/2+z);break;case "right":d="start";a+=e.size/2+z;break;case "bottom":b=q.reversed?b-(e.size/2+k.height/ 2+z):b+(e.size/2+k.height/2+z);break;case "left":d="end";a-=e.size/2+z;break;case "inside":"column"==this.type&&(f=!0,m?n?(d="end",a=u-3-z):(d="start",a=u+3+z):b=n?t+7+z:t-10-z);break;case "middle":"column"==this.type&&(f=!0,m?a-=(a-u)/2+z-3:b-=(b-t)/2+z-3)}"auto"!=this.labelAnchor&&(d=this.labelAnchor);c.attr({"text-anchor":d});this.labelRotation&&c.rotate(this.labelRotation);c.translate(a,b);k=c.getBBox();!this.showAllValueLabels&&r&&f&&(k.height>l.columnHeight||k.width>l.columnWidth)&&(c.remove(), c=!1);if(c&&("serial"==p.type||"gantt"==p.type))if(m){if(0>b||b>this.height)c.remove(),c=!1}else if(0>a||a>this.width)c.remove(),c=!1;return c}},getGradRotation:function(){var a=270;"horizontal"==this.gradientOrientation&&(a=0);return this.gradientRotation=a},createSerialGraph:function(){this.dashLengthSwitched=this.fillColorsSwitched=this.lineColorSwitched=void 0;var a=this.chart,b=this.id,c=this.index,e=this.data,h=this.chart.container,f=this.valueAxis,g=this.type,k=this.columnWidthReal,l=this.showBulletsAt; isNaN(this.columnWidth)||(k=this.columnWidth);isNaN(k)&&(k=.8);var m=this.useNegativeColorIfDown,n=this.width,p=this.height,q=this.y,r=this.rotate,u=this.columnCount,t=d.toCoordinate(this.cornerRadiusTop,k/2),z=this.connect,y=[],v=[],w,A,B,C,D=this.chart.graphs.length,J,E=this.dx/this.tcc,O=this.dy/this.tcc,I=f.stackType,W=this.start,ea=this.end,P=this.scrollbar,oa="graph-column-";P&&(oa="scrollbar-graph-column-");var qa=this.categoryAxis,ka=this.baseCoord,Qa=this.negativeBase,ca=this.columnIndex, aa=this.lineThickness,V=this.lineAlpha,sa=this.lineColorR,ba=this.dashLength,da=this.set,ta,fa=this.getGradRotation(),R=this.chart.columnSpacing,X=qa.cellWidth,wa=(X*k-u)/u;R>wa&&(R=wa);var H,x,la,ga=p+1,Ja=n+1,Z=0,qb=0,rb,sb,eb,fb,tb=this.fillColorsR,Ka=this.negativeFillColors,Da=this.negativeLineColor,Wa=this.fillAlphas,Xa=this.negativeFillAlphas;"object"==typeof Wa&&(Wa=Wa[0]);"object"==typeof Xa&&(Xa=Xa[0]);var gb=f.getCoordinate(f.min);f.logarithmic&&(gb=f.getCoordinate(f.minReal));this.minCoord= gb;this.resetBullet&&(this.bullet="none");if(!(P||"line"!=g&&"smoothedLine"!=g&&"step"!=g||(1==e.length&&"step"!=g&&"none"==this.bullet&&(this.bullet="round",this.resetBullet=!0),!Ka&&void 0==Da||m))){var Ra=Qa;Ra>f.max&&(Ra=f.max);Ra<f.min&&(Ra=f.min);f.logarithmic&&(Ra=f.minReal);var Ga=f.getCoordinate(Ra),Ib=f.getCoordinate(f.max);r?(ga=p,Ja=Math.abs(Ib-Ga)+1,rb=p,sb=Math.abs(gb-Ga)+1,fb=qb=0,f.reversed?(Z=0,eb=Ga):(Z=Ga,eb=0)):(Ja=n,ga=Math.abs(Ib-Ga)+1,sb=n,rb=Math.abs(gb-Ga)+1,eb=Z=0,f.reversed? (fb=q,qb=Ga):fb=Ga+1)}var Ha=Math.round;this.pmx=Ha(Z);this.pmy=Ha(qb);this.pmh=Ha(ga);this.pmw=Ha(Ja);this.nmx=Ha(eb);this.nmy=Ha(fb);this.nmh=Ha(rb);this.nmw=Ha(sb);d.isModern||(this.nmy=this.nmx=0,this.nmh=this.height);this.clustered||(u=1);k="column"==g?(X*k-R*(u-1))/u:X*k;1>k&&(k=1);var Jb=this.fixedColumnWidth;isNaN(Jb)||(k=Jb);var K;if("line"==g||"step"==g||"smoothedLine"==g){if(0<W){for(K=W-1;-1<K;K--)if(H=e[K],x=H.axes[f.id].graphs[b],la=x.values.value,!isNaN(la)){W=K;break}if(this.lineColorField)for(K= W;-1<K;K--)if(H=e[K],x=H.axes[f.id].graphs[b],x.lineColor){this.bulletColorSwitched=this.lineColorSwitched=x.lineColor;break}if(this.fillColorsField)for(K=W;-1<K;K--)if(H=e[K],x=H.axes[f.id].graphs[b],x.fillColors){this.fillColorsSwitched=x.fillColors;break}if(this.dashLengthField)for(K=W;-1<K;K--)if(H=e[K],x=H.axes[f.id].graphs[b],!isNaN(x.dashLength)){this.dashLengthSwitched=x.dashLength;break}}if(ea<e.length-1)for(K=ea+1;K<e.length;K++)if(H=e[K],x=H.axes[f.id].graphs[b],la=x.values.value,!isNaN(la)){ea= K;break}}ea<e.length-1&&ea++;var S=[],T=[],La=!1;if("line"==g||"step"==g||"smoothedLine"==g)if(this.stackable&&"regular"==I||"100%"==I||this.fillToGraph)La=!0;var Kb=this.noStepRisers,hb=-1E3,ib=-1E3,jb=this.minDistance,Ma=!0,Ya=!1;for(K=W;K<=ea;K++){H=e[K];x=H.axes[f.id].graphs[b];x.index=K;var Za,Na=NaN;if(m&&void 0==this.openField)for(var ub=K+1;ub<e.length&&(!e[ub]||!(Za=e[K+1].axes[f.id].graphs[b])||!Za.values||(Na=Za.values.value,isNaN(Na)));ub++);var U,Q,M,ha,ma=NaN,G=NaN,F=NaN,N=NaN,L=NaN, Oa=NaN,Ea=NaN,Pa=NaN,Fa=NaN,ya=NaN,za=NaN,ia=NaN,ja=NaN,Y=NaN,vb=NaN,wb=NaN,na=NaN,pa=void 0,Ia=tb,Sa=Wa,Ba=sa,ua,xa,xb=this.proCandlesticks,kb=this.topRadius,$a=this.pattern;void 0!=x.pattern&&($a=x.pattern);isNaN(x.alpha)||(Sa=x.alpha);isNaN(x.dashLength)||(ba=x.dashLength);var Ca=x.values;f.recalculateToPercents&&(Ca=x.percents);if(Ca){Y=this.stackable&&"none"!=I&&"3d"!=I?Ca.close:Ca.value;if("candlestick"==g||"ohlc"==g)Y=Ca.close,wb=Ca.low,Ea=f.getCoordinate(wb),vb=Ca.high,Fa=f.getCoordinate(vb); na=Ca.open;F=f.getCoordinate(Y);isNaN(na)||(L=f.getCoordinate(na),m&&(Na=na,na=L=NaN));m&&(void 0==this.openField?Za&&(Za.isNegative=Na<Y?!0:!1,isNaN(Na)&&(x.isNegative=!Ma)):x.isNegative=Na>Y?!0:!1);if(!P)switch(this.showBalloonAt){case "close":x.y=F;break;case "open":x.y=L;break;case "high":x.y=Fa;break;case "low":x.y=Ea}var ma=H.x[qa.id],Ta=this.periodSpan-1,ra=Math.floor(X/2)+Math.floor(Ta*X/2),Aa=ra,lb=0;"left"==this.stepDirection&&(lb=(2*X+Ta*X)/2,ma-=lb);"center"==this.stepDirection&&(lb=X/ 2,ma-=lb);"start"==this.pointPosition&&(ma-=X/2+Math.floor(Ta*X/2),ra=0,Aa=Math.floor(X)+Math.floor(Ta*X));"end"==this.pointPosition&&(ma+=X/2+Math.floor(Ta*X/2),ra=Math.floor(X)+Math.floor(Ta*X),Aa=0);if(Kb){var yb=this.columnWidth;isNaN(yb)||(ra*=yb,Aa*=yb)}P||(x.x=ma);-1E5>ma&&(ma=-1E5);ma>n+1E5&&(ma=n+1E5);r?(G=F,N=L,L=F=ma,isNaN(na)&&!this.fillToGraph&&(N=ka),Oa=Ea,Pa=Fa):(N=G=ma,isNaN(na)&&!this.fillToGraph&&(L=ka));if(!xb&&Y<na||xb&&Y<ta)x.isNegative=!0,Ka&&(Ia=Ka),Xa&&(Sa=Xa),void 0!=Da&& (Ba=Da);Ya=!1;isNaN(Y)||(m?Y>Na?(Ma&&(Ya=!0),Ma=!1):(Ma||(Ya=!0),Ma=!0):x.isNegative=Y<Qa?!0:!1,ta=Y);var Lb=!1;P&&a.chartScrollbar.ignoreCustomColors&&(Lb=!0);Lb||(void 0!=x.color&&(Ia=x.color),x.fillColors&&(Ia=x.fillColors));switch(g){case "line":if(isNaN(Y))z||(this.drawLineGraph(y,v,S,T),y=[],v=[],S=[],T=[]);else{if(Math.abs(G-hb)>=jb||Math.abs(F-ib)>=jb)y.push(G),v.push(F),hb=G,ib=F;ya=G;za=F;ia=G;ja=F;!La||isNaN(L)||isNaN(N)||(S.push(N),T.push(L));if(Ya||void 0!=x.lineColor||void 0!=x.fillColors|| !isNaN(x.dashLength))this.drawLineGraph(y,v,S,T),y=[G],v=[F],S=[],T=[],!La||isNaN(L)||isNaN(N)||(S.push(N),T.push(L)),m?Ma?(this.lineColorSwitched=sa,this.fillColorsSwitched=tb):(this.lineColorSwitched=Da,this.fillColorsSwitched=Ka):(this.lineColorSwitched=x.lineColor,this.fillColorsSwitched=x.fillColors),this.dashLengthSwitched=x.dashLength;x.gap&&(this.drawLineGraph(y,v,S,T),y=[],v=[],S=[],T=[])}break;case "smoothedLine":if(isNaN(Y))z||(this.drawSmoothedGraph(y,v,S,T),y=[],v=[],S=[],T=[]);else{if(Math.abs(G- hb)>=jb||Math.abs(F-ib)>=jb)y.push(G),v.push(F),hb=G,ib=F;ya=G;za=F;ia=G;ja=F;!La||isNaN(L)||isNaN(N)||(S.push(N),T.push(L));void 0==x.lineColor&&void 0==x.fillColors&&isNaN(x.dashLength)||(this.drawSmoothedGraph(y,v,S,T),y=[G],v=[F],S=[],T=[],!La||isNaN(L)||isNaN(N)||(S.push(N),T.push(L)),this.lineColorSwitched=x.lineColor,this.fillColorsSwitched=x.fillColors,this.dashLengthSwitched=x.dashLength);x.gap&&(this.drawSmoothedGraph(y,v,S,T),y=[],v=[],S=[],T=[])}break;case "step":if(!isNaN(Y)){r?(isNaN(w)|| (y.push(w),v.push(F-ra)),v.push(F-ra),y.push(G),v.push(F+Aa),y.push(G),!La||isNaN(L)||isNaN(N)||(isNaN(B)||(S.push(B),T.push(L-ra)),S.push(N),T.push(L-ra),S.push(N),T.push(L+Aa))):(isNaN(A)||(v.push(A),y.push(G-ra)),y.push(G-ra),v.push(F),y.push(G+Aa),v.push(F),!La||isNaN(L)||isNaN(N)||(isNaN(C)||(S.push(N-ra),T.push(C)),S.push(N-ra),T.push(L),S.push(N+Aa),T.push(L)));w=G;A=F;B=N;C=L;ya=G;za=F;ia=G;ja=F;if(Ya||void 0!=x.lineColor||void 0!=x.fillColors||!isNaN(x.dashLength)){var Zb=y[y.length-2],$b= v[v.length-2];y.pop();v.pop();this.drawLineGraph(y,v,S,T);y=[Zb];v=[$b];r?(v.push(F+Aa),y.push(G)):(y.push(G+Aa),v.push(F));S=[];T=[];this.lineColorSwitched=x.lineColor;this.fillColorsSwitched=x.fillColors;this.dashLengthSwitched=x.dashLength;m&&(Ma?(this.lineColorSwitched=sa,this.fillColorsSwitched=tb):(this.lineColorSwitched=Da,this.fillColorsSwitched=Ka))}if(Kb||x.gap)w=A=NaN,this.drawLineGraph(y,v,S,T),y=[],v=[],S=[],T=[]}else if(!z){if(1>=this.periodSpan||1<this.periodSpan&&G-w>ra+Aa)w=A=NaN; this.drawLineGraph(y,v,S,T);y=[];v=[];S=[];T=[]}break;case "column":ua=Ba;void 0!=x.lineColor&&(ua=x.lineColor);if(!isNaN(Y)){m||(x.isNegative=Y<Qa?!0:!1);x.isNegative&&(Ka&&(Ia=Ka),void 0!=Da&&(ua=Da));var Mb=f.min,Nb=f.max;if(!(Y<Mb&&na<Mb||Y>Nb&&na>Nb)){var va;if(r){"3d"==I?(Q=F-(u/2-this.depthCount+1)*(k+R)+R/2+O*ca,U=N+E*ca,va=ca):(Q=Math.floor(F-(u/2-ca)*(k+R)+R/2),U=N,va=0);M=k;ya=G;za=Q+k/2;isNaN(N)||N>G&&!x.isNegative&&(ya=N);ia=G;ja=Q+k/2;Q+M>p+va*O&&(M=p-Q+va*O);Q<va*O&&(M+=Q,Q=va*O);ha= G-N;var ac=U;U=d.fitToBounds(U,0,n);ha+=ac-U;ha=d.fitToBounds(ha,-U,n-U+E*ca);Q<p&&0<M&&(pa=new d.Cuboid(h,ha,M,E-a.d3x,O-a.d3y,Ia,Sa,aa,ua,V,fa,t,r,ba,$a,kb,oa),x.columnWidth=Math.abs(ha),x.columnHeight=Math.abs(M))}else{"3d"==I?(U=G-(u/2-this.depthCount+1)*(k+R)+R/2+E*ca,Q=L+O*ca,va=ca):(U=G-(u/2-ca)*(k+R)+R/2,Q=L,va=0);M=k;ya=U+k/2;za=F;isNaN(L)||L<F&&!x.isNegative&&!f.reversed&&(za=L);ia=U+k/2;ja=F;U+M>n+va*E&&(M=n-U+va*E);U<va*E&&(M+=U-va*E,U=va*E);ha=F-L;var bc=Q;Q=d.fitToBounds(Q,this.dy,p); ha+=bc-Q;ha=d.fitToBounds(ha,-Q+O*ca,p-Q);U<n+ca*E&&0<M&&(this.showOnAxis&&(Q-=O/2),pa=new d.Cuboid(h,M,ha,E-a.d3x,O-a.d3y,Ia,Sa,aa,ua,this.lineAlpha,fa,t,r,ba,$a,kb,oa),x.columnHeight=Math.abs(ha),x.columnWidth=Math.abs(M))}}if(pa&&(xa=pa.set,d.setCN(a,pa.set,"graph-"+this.type),d.setCN(a,pa.set,"graph-"+this.id),x.className&&d.setCN(a,pa.set,x.className,!0),x.columnGraphics=xa,xa.translate(U,Q),this.columnsSet.push(xa),(x.url||this.showHandOnHover)&&xa.setAttr("cursor","pointer"),!P)){"none"==I&& (J=r?(this.end+1-K)*D-c:D*K+c);"3d"==I&&(r?(J=(this.end+1-K)*D-c-1E3*this.depthCount,ya+=E*this.columnIndex,ia+=E*this.columnIndex,x.y+=E*this.columnIndex):(J=(D-c)*(K+1)+1E3*this.depthCount,za+=O*this.columnIndex,ja+=O*this.columnIndex,x.y+=O*this.columnIndex));if("regular"==I||"100%"==I)J=r?0<Ca.value?(this.end+1-K)*D+c:(this.end+1-K)*D-c:0<Ca.value?D*K+c:D*K-c;this.columnsArray.push({column:pa,depth:J});x.x=r?Q+M/2:U+M/2;this.ownColumns.push(pa);this.animateColumns(pa,K,G,N,F,L);this.addListeners(xa, x)}}break;case "candlestick":if(!isNaN(na)&&!isNaN(Y)){var Ua,ab;ua=Ba;void 0!=x.lineColor&&(ua=x.lineColor);if(r){if(Q=F-k/2,U=N,M=k,Q+M>p&&(M=p-Q),0>Q&&(M+=Q,Q=0),Q<p&&0<M){var zb,Ab;Y>na?(zb=[G,Pa],Ab=[N,Oa]):(zb=[N,Pa],Ab=[G,Oa]);!isNaN(Pa)&&!isNaN(Oa)&&F<p&&0<F&&(Ua=d.line(h,zb,[F,F],ua,V,aa),ab=d.line(h,Ab,[F,F],ua,V,aa));ha=G-N;pa=new d.Cuboid(h,ha,M,E,O,Ia,Wa,aa,ua,V,fa,t,r,ba,$a,kb,oa)}}else if(U=G-k/2,Q=L+aa/2,M=k,U+M>n&&(M=n-U),0>U&&(M+=U,U=0),ha=F-L,U<n&&0<M){xb&&Y>=na&&(Sa=0);var pa= new d.Cuboid(h,M,ha,E,O,Ia,Sa,aa,ua,V,fa,t,r,ba,$a,kb,oa),Bb,Cb;Y>na?(Bb=[F,Fa],Cb=[L,Ea]):(Bb=[L,Fa],Cb=[F,Ea]);!isNaN(Fa)&&!isNaN(Ea)&&G<n&&0<G&&(Ua=d.line(h,[G,G],Bb,ua,V,aa),ab=d.line(h,[G,G],Cb,ua,V,aa),d.setCN(a,Ua,this.bcn+"line-high"),x.className&&d.setCN(a,Ua,x.className,!0),d.setCN(a,ab,this.bcn+"line-low"),x.className&&d.setCN(a,ab,x.className,!0))}pa&&(xa=pa.set,x.columnGraphics=xa,da.push(xa),xa.translate(U,Q-aa/2),(x.url||this.showHandOnHover)&&xa.setAttr("cursor","pointer"),Ua&&(da.push(Ua), da.push(ab)),ya=G,za=F,r?(ja=F,ia=G,"open"==l&&(ia=N),"high"==l&&(ia=Pa),"low"==l&&(ia=Oa)):(ja=F,"open"==l&&(ja=L),"high"==l&&(ja=Fa),"low"==l&&(ja=Ea),ia=G),P||(x.x=r?Q+M/2:U+M/2,this.animateColumns(pa,K,G,N,F,L),this.addListeners(xa,x)))}break;case "ohlc":if(!(isNaN(na)||isNaN(vb)||isNaN(wb)||isNaN(Y))){var Ob=h.set();da.push(Ob);Y<na&&(x.isNegative=!0,void 0!=Da&&(Ba=Da));var mb,nb,ob;if(r){var Db=F-k/2,Db=d.fitToBounds(Db,0,p),Pb=d.fitToBounds(F,0,p),Eb=F+k/2,Eb=d.fitToBounds(Eb,0,p);nb=d.line(h, [N,N],[Db,Pb],Ba,V,aa,ba);0<F&&F<p&&(mb=d.line(h,[Oa,Pa],[F,F],Ba,V,aa,ba));ob=d.line(h,[G,G],[Pb,Eb],Ba,V,aa,ba);ja=F;ia=G;"open"==l&&(ia=N);"high"==l&&(ia=Pa);"low"==l&&(ia=Oa)}else{var Fb=G-k/2,Fb=d.fitToBounds(Fb,0,n),Qb=d.fitToBounds(G,0,n),Gb=G+k/2,Gb=d.fitToBounds(Gb,0,n);nb=d.line(h,[Fb,Qb],[L,L],Ba,V,aa,ba);0<G&&G<n&&(mb=d.line(h,[G,G],[Ea,Fa],Ba,V,aa,ba));ob=d.line(h,[Qb,Gb],[F,F],Ba,V,aa,ba);ja=F;"open"==l&&(ja=L);"high"==l&&(ja=Fa);"low"==l&&(ja=Ea);ia=G}da.push(nb);da.push(mb);da.push(ob); d.setCN(a,nb,this.bcn+"stroke-open");d.setCN(a,ob,this.bcn+"stroke-close");d.setCN(a,mb,this.bcn+"stroke");x.className&&d.setCN(a,Ob,x.className,!0);ya=G;za=F}}if(!P&&!isNaN(Y)){var Rb=this.hideBulletsCount;if(this.end-this.start<=Rb||0===Rb){var Sb=this.createBullet(x,ia,ja,K),Tb=this.labelText;if(Tb&&Sb){var Hb=this.createLabel(x,ia,ja,Tb);(Hb=this.positionLabel(ya,za,Hb,Sb,M,ha))&&this.allBullets.push(Hb)}if("regular"==I||"100%"==I){var Ub=f.totalText;if(Ub){var Va=this.createLabel(x,0,0,Ub,f.totalTextColor); this.allBullets.push(Va);var Vb=Va.getBBox(),Wb=Vb.width,Xb=Vb.height,bb,cb,pb=f.totalTextOffset,Yb=f.totals[K];Yb&&Yb.remove();var db=0;"column"!=g&&(db=this.bulletSize);r?(cb=F,bb=0>Y?G-Wb/2-2-db-pb:G+Wb/2+3+db+pb):(bb=G,cb=0>Y?F+Xb/2+db+pb:F-Xb/2-3-db-pb);Va.translate(bb,cb);f.totals[K]=Va;r?(0>cb||cb>p)&&Va.remove():(0>bb||bb>n)&&Va.remove()}}}}}}if("line"==g||"step"==g||"smoothedLine"==g)"smoothedLine"==g?this.drawSmoothedGraph(y,v,S,T):this.drawLineGraph(y,v,S,T),P||this.launchAnimation();this.bulletsHidden&& this.hideBullets();this.customBulletsHidden&&this.hideCustomBullets()},animateColumns:function(a,b){var c=this,e=c.chart.startDuration;0<e&&!c.animationPlayed&&(c.seqAn?(a.set.hide(),c.animationArray.push(a),e=setTimeout(function(){c.animate.call(c)},e/(c.end-c.start+1)*(b-c.start)*1E3),c.timeOuts.push(e)):c.animate(a))},createLabel:function(a,b,c,e,h){var f=this.chart,g=a.labelColor;g||(g=this.color);g||(g=f.color);h&&(g=h);h=this.fontSize;void 0===h&&(this.fontSize=h=f.fontSize);var k=this.labelFunction; e=f.formatString(e,a);e=d.cleanFromEmpty(e);k&&(e=k(a,e));a=d.text(this.container,e,g,f.fontFamily,h);a.node.style.pointerEvents="none";a.translate(b,c);this.bulletSet.push(a);return a},positiveClip:function(a){a.clipRect(this.pmx,this.pmy,this.pmw,this.pmh)},negativeClip:function(a){a.clipRect(this.nmx,this.nmy,this.nmw,this.nmh)},drawLineGraph:function(a,b,c,e){var h=this;if(1<a.length){var f=h.set,g=h.chart,k=h.container,l=k.set(),m=k.set();f.push(m);f.push(l);var n=h.lineAlpha,p=h.lineThickness, f=h.fillAlphas,q=h.lineColorR,r=h.negativeLineAlpha;isNaN(r)&&(r=n);var u=h.lineColorSwitched;u&&(q=u);var u=h.fillColorsR,t=h.fillColorsSwitched;t&&(u=t);var z=h.dashLength;(t=h.dashLengthSwitched)&&(z=t);var t=h.negativeLineColor,y=h.negativeFillColors,v=h.negativeFillAlphas,w=h.baseCoord;0!==h.negativeBase&&(w=h.valueAxis.getCoordinate(h.negativeBase),w>h.height&&(w=h.height),0>w&&(w=0));n=d.line(k,a,b,q,n,p,z,!1,!0);d.setCN(g,n,h.bcn+"stroke");l.push(n);l.click(function(a){h.handleGraphEvent(a, "clickGraph")}).mouseover(function(a){h.handleGraphEvent(a,"rollOverGraph")}).mouseout(function(a){h.handleGraphEvent(a,"rollOutGraph")});void 0===t||h.useNegativeColorIfDown||(p=d.line(k,a,b,t,r,p,z,!1,!0),d.setCN(g,p,h.bcn+"stroke"),d.setCN(g,p,h.bcn+"stroke-negative"),m.push(p));if(0<f||0<v)if(p=a.join(";").split(";"),r=b.join(";").split(";"),n=g.type,"serial"==n||"radar"==n?0<c.length?(c.reverse(),e.reverse(),p=a.concat(c),r=b.concat(e)):"radar"==n?(r.push(0),p.push(0)):h.rotate?(r.push(r[r.length- 1]),p.push(w),r.push(r[0]),p.push(w),r.push(r[0]),p.push(p[0])):(p.push(p[p.length-1]),r.push(w),p.push(p[0]),r.push(w),p.push(a[0]),r.push(r[0])):"xy"==n&&(b=h.fillToAxis)&&(d.isString(b)&&(b=g.getValueAxisById(b)),"H"==b.orientation?(w="top"==b.position?0:b.viH,p.push(p[p.length-1]),r.push(w),p.push(p[0]),r.push(w),p.push(a[0]),r.push(r[0])):(w="left"==b.position?0:b.viW,r.push(r[r.length-1]),p.push(w),r.push(r[0]),p.push(w),r.push(r[0]),p.push(p[0]))),a=h.gradientRotation,0<f&&(b=d.polygon(k,p, r,u,f,1,"#000",0,a),b.pattern(h.pattern,NaN,g.path),d.setCN(g,b,h.bcn+"fill"),l.push(b)),y||void 0!==t)isNaN(v)&&(v=f),y||(y=t),k=d.polygon(k,p,r,y,v,1,"#000",0,a),d.setCN(g,k,h.bcn+"fill"),d.setCN(g,k,h.bcn+"fill-negative"),k.pattern(h.pattern,NaN,g.path),m.push(k),m.click(function(a){h.handleGraphEvent(a,"clickGraph")}).mouseover(function(a){h.handleGraphEvent(a,"rollOverGraph")}).mouseout(function(a){h.handleGraphEvent(a,"rollOutGraph")});h.applyMask(m,l)}},applyMask:function(a,b){var c=a.length(); "serial"!=this.chart.type||this.scrollbar||(this.positiveClip(b),0<c&&this.negativeClip(a))},drawSmoothedGraph:function(a,b,c,e){if(1<a.length){var h=this.set,f=this.chart,g=this.container,k=g.set(),l=g.set();h.push(l);h.push(k);var m=this.lineAlpha,n=this.lineThickness,h=this.dashLength,p=this.fillAlphas,q=this.lineColorR,r=this.fillColorsR,u=this.negativeLineColor,t=this.negativeFillColors,z=this.negativeFillAlphas,y=this.baseCoord,v=this.lineColorSwitched;v&&(q=v);(v=this.fillColorsSwitched)&& (r=v);v=this.negativeLineAlpha;isNaN(v)&&(v=m);m=new d.Bezier(g,a,b,q,m,n,r,0,h);d.setCN(f,m,this.bcn+"stroke");k.push(m.path);void 0!==u&&(n=new d.Bezier(g,a,b,u,v,n,r,0,h),d.setCN(f,n,this.bcn+"stroke"),d.setCN(f,n,this.bcn+"stroke-negative"),l.push(n.path));0<p&&(m=a.join(";").split(";"),q=b.join(";").split(";"),n="",0<c.length?(c.push("M"),e.push("M"),c.reverse(),e.reverse(),m=a.concat(c),q=b.concat(e)):(this.rotate?(n+=" L"+y+","+b[b.length-1],n+=" L"+y+","+b[0]):(n+=" L"+a[a.length-1]+","+y, n+=" L"+a[0]+","+y),n+=" L"+a[0]+","+b[0]),c=new d.Bezier(g,m,q,NaN,0,0,r,p,h,n),d.setCN(f,c,this.bcn+"fill"),c.path.pattern(this.pattern,NaN,f.path),k.push(c.path),t||void 0!==u)&&(z||(z=p),t||(t=u),a=new d.Bezier(g,a,b,NaN,0,0,t,z,h,n),a.path.pattern(this.pattern,NaN,f.path),d.setCN(f,a,this.bcn+"fill"),d.setCN(f,a,this.bcn+"fill-negative"),l.push(a.path));this.applyMask(l,k)}},launchAnimation:function(){var a=this,b=a.chart.startDuration;if(0<b&&!a.animationPlayed){var c=a.set,e=a.bulletSet;d.VML|| (c.attr({opacity:a.startAlpha}),e.attr({opacity:a.startAlpha}));c.hide();e.hide();a.seqAn?(b=setTimeout(function(){a.animateGraphs.call(a)},a.index*b*1E3),a.timeOuts.push(b)):a.animateGraphs()}},animateGraphs:function(){var a=this.chart,b=this.set,c=this.bulletSet,e=this.x,d=this.y;b.show();c.show();var f=a.startDuration,a=a.startEffect;b&&(this.rotate?(b.translate(-1E3,d),c.translate(-1E3,d)):(b.translate(e,-1E3),c.translate(e,-1E3)),b.animate({opacity:1,translate:e+","+d},f,a),c.animate({opacity:1, translate:e+","+d},f,a))},animate:function(a){var b=this.chart,c=this.animationArray;!a&&0<c.length&&(a=c[0],c.shift());c=d[d.getEffect(b.startEffect)];b=b.startDuration;a&&(this.rotate?a.animateWidth(b,c):a.animateHeight(b,c),a.set.show())},legendKeyColor:function(){var a=this.legendColor,b=this.lineAlpha;void 0===a&&(a=this.lineColorR,0===b&&(b=this.fillColorsR)&&(a="object"==typeof b?b[0]:b));return a},legendKeyAlpha:function(){var a=this.legendAlpha;void 0===a&&(a=this.lineAlpha,this.fillAlphas> a&&(a=this.fillAlphas),0===a&&(a=this.bulletAlpha),0===a&&(a=1));return a},createBullet:function(a,b,c){if(!isNaN(b)&&!isNaN(c)){var e=this.chart,h=this.container,f=this.bulletOffset,g=this.bulletSize;isNaN(a.bulletSize)||(g=a.bulletSize);var k=a.values.value,l=this.maxValue,m=this.minValue,n=this.maxBulletSize,p=this.minBulletSize;isNaN(l)||(isNaN(k)||(g=(k-m)/(l-m)*(n-p)+p),m==l&&(g=n));l=g;this.bulletAxis&&(g=a.values.error,isNaN(g)||(k=g),g=this.bulletAxis.stepWidth*k);g<this.minBulletSize&&(g= this.minBulletSize);this.rotate?b=a.isNegative?b-f:b+f:c=a.isNegative?c+f:c-f;var q,p=this.bulletColorR;a.lineColor&&(this.bulletColorSwitched=a.lineColor);this.bulletColorSwitched&&(p=this.bulletColorSwitched);a.isNegative&&void 0!==this.bulletColorNegative&&(p=this.bulletColorNegative);void 0!==a.color&&(p=a.color);var r;"xy"==e.type&&this.valueField&&(r=this.pattern,a.pattern&&(r=a.pattern));f=this.bullet;a.bullet&&(f=a.bullet);var k=this.bulletBorderThickness,m=this.bulletBorderColorR,n=this.bulletBorderAlpha, u=this.bulletAlpha;m||(m=p);this.useLineColorForBulletBorder&&(m=this.lineColorR,this.lineColorSwitched&&(m=this.lineColorSwitched));var t=a.alpha;isNaN(t)||(u=t);if("none"!=this.bullet||a.bullet)q=d.bullet(h,f,g,p,u,k,m,n,l,0,r,e.path);if(this.customBullet||a.customBullet)r=this.customBullet,a.customBullet&&(r=a.customBullet),r&&(q&&q.remove(),"function"==typeof r?(q=new r,q.chart=e,a.bulletConfig&&(q.availableSpace=c,q.graph=this,q.graphDataItem=a,q.bulletY=c,a.bulletConfig.minCoord=this.minCoord- c,q.bulletConfig=a.bulletConfig),q.write(h),q=q.set):(q=h.set(),h=h.image(r,0,0,g,g),q.push(h),this.centerCustomBullets&&h.translate(-g/2,-g/2)));if(q){(a.url||this.showHandOnHover)&&q.setAttr("cursor","pointer");if("serial"==e.type||"gantt"==e.type)if(-.5>b-0||b-0>this.width||c<-g/2||c-0>this.height)q.remove(),q=null;q&&(this.bulletSet.push(q),q.translate(b,c),this.addListeners(q,a),this.allBullets.push(q));a.bx=b;a.by=c;d.setCN(e,q,this.bcn+"bullet");a.className&&d.setCN(e,q,a.className,!0)}q?(q.size= g||0,a.bulletGraphics=q):q={size:0};q.graphDataItem=a;return q}},showBullets:function(){var a=this.allBullets,b;this.bulletsHidden=!1;for(b=0;b<a.length;b++)a[b].show()},hideBullets:function(){var a=this.allBullets,b;this.bulletsHidden=!0;for(b=0;b<a.length;b++)a[b].hide()},showCustomBullets:function(){var a=this.allBullets,b;this.customBulletsHidden=!1;for(b=0;b<a.length;b++)a[b].graphDataItem.customBullet&&a[b].show()},hideCustomBullets:function(){var a=this.allBullets,b;this.customBulletsHidden= !0;for(b=0;b<a.length;b++)a[b].graphDataItem.customBullet&&a[b].hide()},addListeners:function(a,b){var c=this;a.mouseover(function(a){c.handleRollOver(b,a)}).mouseout(function(a){c.handleRollOut(b,a)}).touchend(function(a){c.handleRollOver(b,a);c.chart.panEventsEnabled&&c.handleClick(b,a)}).touchstart(function(a){c.handleRollOver(b,a)}).click(function(a){c.handleClick(b,a)}).dblclick(function(a){c.handleDoubleClick(b,a)}).contextmenu(function(a){c.handleRightClick(b,a)})},handleRollOver:function(a, b){if(a){var c=this.chart,e={type:"rollOverGraphItem",item:a,index:a.index,graph:this,target:this,chart:this.chart,event:b};this.fire("rollOverGraphItem",e);c.fire("rollOverGraphItem",e);clearTimeout(c.hoverInt);e=this.showBalloon;!c.chartCursor||"serial"!=c.type&&"gantt"!=c.type||(e=!1,!c.chartCursor.valueBalloonsEnabled&&this.showBalloon&&(e=!0));if(e){var e=c.formatString(this.balloonText,a,!0),h=this.balloonFunction;h&&(e=h(a,a.graph));e=d.cleanFromEmpty(e);h=c.getBalloonColor(this,a);c.balloon.showBullet= !1;c.balloon.pointerOrientation="V";var f=a.x,g=a.y;c.rotate&&(f=a.y,g=a.x);""!==e?c.showBalloon(e,h,!0,f+c.marginLeftReal,g+c.marginTopReal):this.chart.hideBalloonReal()}else this.chart.hideBalloonReal()}this.handleGraphEvent(b,"rollOverGraph")},handleRollOut:function(a,b){this.chart.hideBalloon();if(a){var c={type:"rollOutGraphItem",item:a,index:a.index,graph:this,target:this,chart:this.chart,event:b};this.fire("rollOutGraphItem",c);this.chart.fire("rollOutGraphItem",c)}this.handleGraphEvent(b, "rollOutGraph")},handleClick:function(a,b){if(a){var c={type:"clickGraphItem",item:a,index:a.index,graph:this,target:this,chart:this.chart,event:b};this.fire("clickGraphItem",c);this.chart.fire("clickGraphItem",c);d.getURL(a.url,this.urlTarget)}this.handleGraphEvent(b,"clickGraph")},handleGraphEvent:function(a,b){var c={type:b,graph:this,target:this,chart:this.chart,event:a};this.fire(b,c);this.chart.fire(b,c)},handleRightClick:function(a,b){if(a){var c={type:"rightClickGraphItem",item:a,index:a.index, graph:this,target:this,chart:this.chart,event:b};this.fire("rightClickGraphItem",c);this.chart.fire("rightClickGraphItem",c)}},handleDoubleClick:function(a,b){if(a){var c={type:"doubleClickGraphItem",item:a,index:a.index,graph:this,target:this,chart:this.chart,event:b};this.fire("doubleClickGraphItem",c);this.chart.fire("doubleClickGraphItem",c)}},zoom:function(a,b){this.start=a;this.end=b;this.draw()},changeOpacity:function(a){var b=this.set;b&&b.setAttr("opacity",a);if(b=this.ownColumns){var c; for(c=0;c<b.length;c++){var e=b[c].set;e&&e.setAttr("opacity",a)}}(b=this.bulletSet)&&b.setAttr("opacity",a)},destroy:function(){d.remove(this.set);d.remove(this.bulletSet);var a=this.timeOuts;if(a){var b;for(b=0;b<a.length;b++)clearTimeout(a[b])}this.timeOuts=[]}})})();(function(){var d=window.AmCharts;d.ChartCursor=d.Class({construct:function(a){this.cname="ChartCursor";this.createEvents("changed","zoomed","onHideCursor","draw","selected","moved");this.enabled=!0;this.cursorAlpha=1;this.selectionAlpha=.2;this.cursorColor="#CC0000";this.categoryBalloonAlpha=1;this.color="#FFFFFF";this.type="cursor";this.zoomed=!1;this.zoomable=!0;this.pan=!1;this.categoryBalloonDateFormat="MMM DD, YYYY";this.categoryBalloonText="[[category]]";this.categoryBalloonEnabled=this.valueBalloonsEnabled= !0;this.rolledOver=!1;this.cursorPosition="middle";this.bulletsEnabled=this.skipZoomDispatch=!1;this.bulletSize=8;this.selectWithoutZooming=this.oneBalloonOnly=!1;this.graphBulletSize=1.7;this.animationDuration=.3;this.zooming=!1;this.adjustment=0;this.avoidBalloonOverlapping=!0;this.leaveCursor=!1;d.applyTheme(this,a,this.cname)},draw:function(){this.destroy();var a=this.chart,b=a.container;this.rotate=a.rotate;this.container=b;b=b.set();b.translate(this.x,this.y);this.set=b;a.cursorSet.push(b); b=new d.AmBalloon;b.className="category";b.chart=a;this.categoryBalloon=b;d.copyProperties(a.balloon,b);b.cornerRadius=0;b.shadowAlpha=0;b.borderThickness=1;b.borderAlpha=1;b.showBullet=!1;var c=this.categoryBalloonColor;void 0===c&&(c=this.cursorColor);b.fillColor=c;b.balloonColor=c;b.fillAlpha=this.categoryBalloonAlpha;b.borderColor=c;b.color=this.color;c=this.valueLineAxis;d.isString(c)&&(c=a.getValueAxisById(c));c||(c=a.valueAxes[0]);this.valueLineAxis=c;this.valueLineBalloonEnabled&&(this.vaBalloon= c=new d.AmBalloon,d.copyProperties(b,c),c.animationDuration=0,this.rotate||(c.pointerOrientation="H"));this.rotate&&(b.pointerOrientation="H");this.extraWidth=0;this.prevX=[];this.prevY=[];this.prevTX=[];this.prevTY=[];if(this.valueBalloonsEnabled)for(b=0;b<a.graphs.length;b++)c=new d.AmBalloon,c.className=a.graphs[b].id,c.chart=a,d.copyProperties(a.balloon,c),a.graphs[b].valueBalloon=c;"cursor"==this.type?this.createCursor():this.createCrosshair()},updateData:function(){var a=this.chart;this.data= a.chartData;this.firstTime=a.firstTime;this.lastTime=a.lastTime},createCursor:function(){var a=this.chart,b=this.cursorAlpha,c=a.categoryAxis,e=this.categoryBalloon,h,f,g,k;g=a.dx;k=a.dy;var l=this.width,m=this.height,n=a.rotate;e.pointerWidth=c.tickLength;n?(h=[0,l,l+g],f=[0,0,k],g=[g,0,0],k=[k,0,m]):(h=[g,0,0],f=[k,0,m],g=[0,l,l+g],k=[0,0,k]);h=d.line(this.container,h,f,this.cursorColor,b,1);d.setCN(a,h,"cursor-line");this.line=h;h.node.style.pointerEvents="none";(f=this.fullRectSet)?(f.push(h), f.translate(this.x,this.y)):this.set.push(h);this.valueLineEnabled&&(h=this.valueLineAlpha,isNaN(h)||(b=h),b=d.line(this.container,g,k,this.cursorColor,b,1),b.node.style.pointerEvents="none",d.setCN(a,b,"cursor-value-line"),this.vLine=b,this.set.push(b));this.setBalloonBounds(e,c,n);(a=this.vaBalloon)&&this.setBalloonBounds(a,this.valueLineAxis,!n);this.hideCursor()},createCrosshair:function(){var a=this.cursorAlpha,b=this.container,c=d.line(b,[0,0],[0,this.height],this.cursorColor,a,1),a=d.line(b, [0,this.width],[0,0],this.cursorColor,a,1);d.setCN(this.chart,c,"cursor-line");d.setCN(this.chart,a,"cursor-line");this.set.push(c);this.set.push(a);this.vLine=c;this.hLine=a;this.hideCursor()},update:function(){var a=this.chart;if(a)if(a.mouseIsOver){var b=a.mouseX-this.x,c=a.mouseY-this.y;-.5<b&&b<this.width+1&&0<c&&c<this.height?((this.valueLineEnabled||this.valueLineBalloonEnabled)&&this.updateVLine(b,c),this.setPosition(),this.drawing?this.rolledOver||a.setMouseCursor("crosshair"):this.pan&& (this.rolledOver||a.setMouseCursor("move")),this.rolledOver=!0):this.rolledOver&&(this.handleMouseOut(),this.rolledOver=!1)}else this.rolledOver&&(this.handleMouseOut(),this.rolledOver=!1)},updateVLine:function(a,b){var c=this.vLine,e=this.vaBalloon;if((c||e)&&!this.panning&&!this.drawing){c&&c.show();var d=this.valueLineAxis,f,g=this.rotate;g?(c&&c.translate(a,0),d&&(f=d.coordinateToValue(a)),c=a):(c&&c.translate(0,b),d&&(f=d.coordinateToValue(b)),c=b-1);if(e&&!isNaN(f)&&this.prevLineValue!=f){var k= d.formatValue(f,!0);this.setBalloonPosition(e,d,c,!g);e.showBalloon(k)}this.prevLineValue=f}},getMousePosition:function(){var a,b=this.width,c=this.height;a=this.chart;this.rotate?(a=a.mouseY-this.y,0>a&&(a=0),a>c&&(a=c)):(a=a.mouseX-this.x-1,0>a&&(a=0),a>b&&(a=b));return a},updateCrosshair:function(){var a=this.chart,b=a.mouseX-this.x,c=a.mouseY-this.y,e=this.vLine,h=this.hLine,b=d.fitToBounds(b,0,this.width),c=d.fitToBounds(c,0,this.height);e&&0<this.cursorAlpha&&(e.show(),h.show(),e.translate(b, 0),h.translate(0,c));this.zooming&&(a.hideXScrollbar&&(b=NaN),a.hideYScrollbar&&(c=NaN),this.updateSelectionSize(b,c));this.fireMoved();a.mouseIsOver||this.zooming||this.hideCursor()},fireMoved:function(){var a=this.chart,b={type:"moved",target:this};b.chart=a;b.zooming=this.zooming;b.x=a.mouseX-this.x;b.y=a.mouseY-this.y;this.fire("moved",b)},updateSelectionSize:function(a,b){d.remove(this.selection);var c=this.selectionPosX,e=this.selectionPosY,h=0,f=0,g=this.width,k=this.height;isNaN(a)||(c>a&& (h=a,g=c-a),c<a&&(h=c,g=a-c),c==a&&(h=a,g=0),g+=this.extraWidth,h-=this.extraWidth/2);isNaN(b)||(e>b&&(f=b,k=e-b),e<b&&(f=e,k=b-e),e==b&&(f=b,k=0),k+=this.extraWidth,f-=this.extraWidth/2);0<g&&0<k&&(c=d.rect(this.container,g,k,this.cursorColor,this.selectionAlpha),d.setCN(this.chart,c,"cursor-selection"),c.translate(h+this.x,f+this.y),this.selection=c)},arrangeBalloons:function(){var a=this.valueBalloons,b=this.x,c=this.y,e=this.height+c;a.sort(this.compareY);var d;for(d=0;d<a.length;d++){var f=a[d].balloon; f.setBounds(b,c,b+this.width,e);f.prevX=this.prevX[d];f.prevY=this.prevY[d];f.prevTX=this.prevTX[d];f.prevTY=this.prevTY[d];f.draw();e=f.yPos-3}this.arrangeBalloons2()},compareY:function(a,b){return a.yy<b.yy?1:-1},arrangeBalloons2:function(){var a=this.valueBalloons;a.reverse();var b,c=this.x,e,d,f=a.length;for(d=0;d<f;d++){var g=a[d].balloon;b=g.bottom;var k=g.bottom-g.yPos,l=f-d-1;0<d&&b-k<e+3&&(g.setBounds(c,e+3,c+this.width,e+k+3),g.prevX=this.prevX[l],g.prevY=this.prevY[l],g.prevTX=this.prevTX[l], g.prevTY=this.prevTY[l],g.draw());g.set&&g.set.show();this.prevX[l]=g.prevX;this.prevY[l]=g.prevY;this.prevTX[l]=g.prevTX;this.prevTY[l]=g.prevTY;e=g.bottom}},showBullets:function(){d.remove(this.allBullets);var a=this.container,b=a.set();this.set.push(b);this.set.show();this.allBullets=b;var b=this.chart.graphs,c;for(c=0;c<b.length;c++){var e=b[c];if(!e.hidden&&e.balloonText){var h=this.data[this.index].axes[e.valueAxis.id].graphs[e.id],f=h.y;if(!isNaN(f)){var g,k;g=h.x;this.rotate?(k=f,f=g):k=g; e=d.circle(a,this.bulletSize/2,this.chart.getBalloonColor(e,h,!0),e.cursorBulletAlpha);e.translate(k,f);this.allBullets.push(e)}}}},destroy:function(){this.clear();d.remove(this.selection);this.selection=null;var a=this.categoryBalloon;a&&a.destroy();(a=this.vaBalloon)&&a.destroy();this.destroyValueBalloons();d.remove(this.set)},clear:function(){},destroyValueBalloons:function(){var a=this.valueBalloons;if(a){var b;for(b=0;b<a.length;b++)a[b].balloon.hide()}},zoom:function(a,b,c,e){var h=this.chart; this.destroyValueBalloons();this.zooming=!1;var f;this.rotate?this.selectionPosY=f=h.mouseY:this.selectionPosX=f=h.mouseX;this.start=a;this.end=b;this.startTime=c;this.endTime=e;this.zoomed=!0;e=h.categoryAxis;f=this.rotate;b=this.width;c=this.height;a=e.stepWidth;if(this.fullWidth){var g=1;e.parseDates&&!e.equalSpacing&&(g=e.minDuration());f?this.extraWidth=c=a*g:(this.extraWidth=b=a*g,this.categoryBalloon.minWidth=b);this.line&&this.line.remove();this.line=d.rect(this.container,b,c,this.cursorColor, this.cursorAlpha,0);this.line.node.style.pointerEvents="none";d.setCN(h,this.line,"cursor-fill");this.fullRectSet&&this.fullRectSet.push(this.line)}this.stepWidth=a;this.tempVal=this.valueBalloonsEnabled;this.valueBalloonsEnabled=!1;this.setPosition();this.valueBalloonsEnabled=this.tempVal;this.hideCursor()},hideObj:function(a){a&&a.hide()},hideCursor:function(a){void 0===a&&(a=!0);this.leaveCursor||(this.hideObj(this.set),this.hideObj(this.categoryBalloon),this.hideObj(this.line),this.hideObj(this.vLine), this.hideObj(this.hLine),this.hideObj(this.vaBalloon),this.hideObj(this.allBullets),this.destroyValueBalloons(),this.selectWithoutZooming||d.remove(this.selection),this.previousIndex=NaN,a&&this.fire("onHideCursor",{type:"onHideCursor",chart:this.chart,target:this}),this.drawing||this.chart.setMouseCursor("auto"),this.normalizeBulletSize())},setPosition:function(a,b,c){void 0===b&&(b=!0);if("cursor"==this.type){if(this.tempPosition=NaN,d.ifArray(this.data))isNaN(a)&&(a=this.getMousePosition()),(a!= this.previousMousePosition||!0===this.zoomed||this.oneBalloonOnly)&&!isNaN(a)&&("mouse"==this.cursorPosition&&(this.tempPosition=a),isNaN(c)&&(c=this.chart.categoryAxis.xToIndex(a)),c!=this.previousIndex||this.zoomed||"mouse"==this.cursorPosition||this.oneBalloonOnly)&&(this.updateCursor(c,b),this.zoomed=!1),this.previousMousePosition=a}else this.updateCrosshair()},normalizeBulletSize:function(){var a=this.resizedBullets;if(a)for(var b=0;b<a.length;b++){var c=a[b],e=c.bulletGraphics;e&&(e.translate(c.bx, c.by,1),c=c.graph,isNaN(this.graphBulletAlpha)||(e.setAttr("fill-opacity",c.bulletAlpha),e.setAttr("stroke-opacity",c.bulletBorderAlpha)))}},updateCursor:function(a,b){var c=this.chart,e=this.fullWidth,h=c.mouseX-this.x,f=c.mouseY-this.y;this.drawingNow&&(d.remove(this.drawingLine),this.drawingLine=d.line(this.container,[this.x+this.drawStartX,this.x+h],[this.y+this.drawStartY,this.y+f],this.cursorColor,1,1));if(this.enabled){void 0===b&&(b=!0);this.index=a+=this.adjustment;var g=c.categoryAxis,k= c.dx,l=c.dy,m=this.x+1,n=this.y+1,p=this.width,q=this.height,r=this.data[a],u;this.data[a+1]&&(u=this.data[a+1]);this.fireMoved();if(r){var t=r.x[g.id],z=c.rotate,y=this.stepWidth,v=this.categoryBalloon,w=this.firstTime,A=this.lastTime,B=this.cursorPosition,C=this.zooming,D=this.panning,J=c.graphs;if(c.mouseIsOver||C||D||this.forceShow)if(this.forceShow=!1,D){var k=this.panClickPos,c=this.panClickEndTime,C=this.panClickStartTime,E=this.panClickEnd,m=this.panClickStart,h=(z?k-f:k-h)/y;if(!g.parseDates|| g.equalSpacing)h=Math.round(h);0!==h&&(k={type:"zoomed",target:this},k.chart=this.chart,g.parseDates&&!g.equalSpacing?(c+h>A&&(h=A-c),C+h<w&&(h=w-C),k.start=Math.round(C+h),k.end=Math.round(c+h),this.fire(k.type,k)):E+h>=this.data.length||0>m+h||(k.start=m+h,k.end=E+h,this.fire(k.type,k)))}else{"start"==B?t-=g.cellWidth/2:"mouse"==B&&(c.mouseIsOver?t=z?f-2:h-2:isNaN(this.tempPosition)||(t=this.tempPosition-2));if(z){if(0>t)if(C)t=0;else{this.hideCursor();return}if(t>q+1)if(C)t=q+1;else{this.hideCursor(); return}}else{if(0>t)if(C)t=0;else{this.hideCursor();return}if(t>p)if(C)t=p;else{this.hideCursor();return}}w=this.line;0<this.cursorAlpha&&(z?(A=0,y=t+l,e&&(y-=g.cellWidth/2)):(A=t,y=0,e&&(A-=g.cellWidth/2)),B=this.animationDuration,0<B&&!this.zooming?isNaN(this.previousX)?w.translate(A,y):(w.translate(this.previousX,this.previousY),w.animate({translate:A+","+y},B,"easeOutSine")):w.translate(A,y),this.previousX=A,this.previousY=y,w.show());this.linePos=z?t+l:t;C&&(e&&w.hide(),z?this.updateSelectionSize(NaN, t):this.updateSelectionSize(t,NaN));A=!0;C&&(A=!1);this.categoryBalloonEnabled&&A?(this.setBalloonPosition(v,g,t,z),(w=this.categoryBalloonFunction)?v.showBalloon(w(r.category)):(w=t="",g.parseDates?(t=d.formatDate(r.category,this.categoryBalloonDateFormat,c),g=d.changeDate(new Date(r.category),c.categoryAxis.minPeriod,1),w=d.formatDate(g,this.categoryBalloonDateFormat,c),-1!=t.indexOf("fff")&&(t=d.formatMilliseconds(t,r.category),w=d.formatMilliseconds(w,g))):(t=d.fixNewLines(r.category),u&&(w=d.fixNewLines(u.category))), g=this.categoryBalloonText.replace(/\[\[category\]\]/g,String(t)),g=g.replace(/\[\[toCategory\]\]/g,String(w)),v.showBalloon(g))):v.hide();J&&this.bulletsEnabled&&this.showBullets();if(this.oneBalloonOnly){t=Infinity;for(g=0;g<J.length;g++)v=J[g],v.showBalloon&&!v.hidden&&v.balloonText&&(u=r.axes[v.valueAxis.id].graphs[v.id],w=u.y,"top"==v.showBalloonAt&&(w=0),"bottom"==v.showBalloonAt&&(w=this.height),isNaN(w)||(z?Math.abs(h-w)<t&&(t=Math.abs(h-w),E=v):Math.abs(f-w)<t&&(t=Math.abs(f-w),E=v)));this.mostCloseGraph&& (E=this.mostCloseGraph)}if(a!=this.previousIndex||E!=this.previousMostCloseGraph)if(this.normalizeBulletSize(),this.destroyValueBalloons(),this.resizedBullets=[],J&&this.valueBalloonsEnabled&&A&&c.balloon.enabled){this.valueBalloons=A=[];for(g=0;g<J.length;g++)if(v=J[g],w=NaN,(!this.oneBalloonOnly||v==E)&&v.showBalloon&&!v.hidden&&v.balloonText&&("step"==v.type&&"left"==v.stepDirection&&(r=this.data[a+1]),r)){if(u=r.axes[v.valueAxis.id].graphs[v.id])w=u.y;"top"==v.showBalloonAt&&(w=0);"bottom"==v.showBalloonAt&& (w=this.height);if(this.showNextAvailable&&isNaN(w)&&a+1<this.data.length)for(t=a+1;t<this.data.length;t++)if(y=this.data[t])if(u=y.axes[v.valueAxis.id].graphs[v.id],w=u.y,!isNaN(w))break;if(!isNaN(w)){y=u.x;e=!0;if(z){if(t=w,0>y||y>q)e=!1}else if(t=y,y=w,0>t||t>p+k+1)e=!1;e&&(e=this.graphBulletSize,l=this.graphBulletAlpha,1==e&&isNaN(l)||!d.isModern||!(B=u.bulletGraphics)||(B.translate(u.bx,u.by,e),this.resizedBullets.push(u),isNaN(l)||(B.setAttr("fill-opacity",l),B.setAttr("stroke-opacity",l))), e=v.valueBalloon,l=c.getBalloonColor(v,u),e.setBounds(m,n,m+p,n+q),e.pointerOrientation="H",B=this.balloonPointerOrientation,"vertical"==B&&(e.pointerOrientation="V"),"horizontal"==B&&(e.pointerOrientation="H"),e.changeColor(l),void 0!==v.balloonAlpha&&(e.fillAlpha=v.balloonAlpha),void 0!==v.balloonTextColor&&(e.color=v.balloonTextColor),e.setPosition(t+m,y+n),t=c.formatString(v.balloonText,u,!0),(y=v.balloonFunction)&&(t=y(u,v).toString()),""!==t&&(z?e.showBalloon(t):(e.text=t,e.show=!0),A.push({yy:w, balloon:e})),!z&&e.set&&(e.set.hide(),v=e.textDiv)&&(v.style.visibility="hidden"))}}this.avoidBalloonOverlapping&&this.arrangeBalloons()}b?(k={type:"changed"},k.index=a,k.chart=this.chart,k.zooming=C,k.mostCloseGraph=E,k.position=z?f:h,k.target=this,c.fire("changed",k),this.fire("changed",k),this.skipZoomDispatch=!1):(this.skipZoomDispatch=!0,c.updateLegendValues(a));this.previousIndex=a;this.previousMostCloseGraph=E}}}else this.hideCursor()},setBalloonPosition:function(a,b,c,e){var d=b.position, f=b.inside;b=b.axisThickness;var g=this.chart,k=g.dx,g=g.dy,l=this.x,m=this.y,n=this.width,p=this.height;e?(f&&("right"==d?a.setBounds(l,m+g,l+n+k,m+c+g):a.setBounds(l,m+g,l+n+k,m+c)),"right"==d?f?a.setPosition(l+n+k,m+c+g):a.setPosition(l+n+k+b,m+c+g):f?a.setPosition(l,m+c):a.setPosition(l-b,m+c)):"top"==d?f?a.setPosition(l+c+k,m+g):a.setPosition(l+c+k,m+g-b+1):f?a.setPosition(l+c,m+p):a.setPosition(l+c,m+p+b-1)},setBalloonBounds:function(a,b,c){var e=b.position,d=b.inside,f=b.axisThickness,g=b.tickLength, k=this.chart,l=k.dx,k=k.dy,m=this.x,n=this.y,p=this.width,q=this.height;c?(d&&(a.pointerWidth=0),"right"==e?d?a.setBounds(m,n+k,m+p+l,n+q+k):a.setBounds(m+p+l+f,n+k,m+p+1E3,n+q+k):d?a.setBounds(m,n,p+m,q+n):a.setBounds(-1E3,-1E3,m-g-f,n+q+15)):(a.maxWidth=p,b.parseDates&&(g=0,a.pointerWidth=0),"top"==e?d?a.setBounds(m+l,n+k,p+l+m,q+n):a.setBounds(m+l,-1E3,p+l+m,n+k-g-f):d?a.setBounds(m,n,p+m,q+n-g):a.setBounds(m,n+q+g+f-1,m+p,n+q+g+f))},enableDrawing:function(a){this.enabled=!a;this.hideCursor(); this.rolledOver=!1;this.drawing=a},isZooming:function(a){a&&a!=this.zooming&&this.handleMouseDown("fake");a||a==this.zooming||this.handleMouseUp()},handleMouseOut:function(){if(this.enabled)if(this.zooming)this.setPosition();else{this.index=void 0;var a={type:"changed",index:void 0,target:this};a.chart=this.chart;this.fire("changed",a);this.hideCursor()}},handleReleaseOutside:function(){this.handleMouseUp()},handleMouseUp:function(){var a=this.chart,b=this.data,c;if(a){var e=a.mouseX-this.x,h=a.mouseY- this.y;if(this.drawingNow){this.drawingNow=!1;d.remove(this.drawingLine);c=this.drawStartX;var f=this.drawStartY;if(2<Math.abs(c-e)||2<Math.abs(f-h))c={type:"draw",target:this,chart:a,initialX:c,initialY:f,finalX:e,finalY:h},this.fire(c.type,c)}if(this.enabled&&0<b.length){if(this.pan)this.rolledOver=!1;else if(this.zoomable&&this.zooming){c=this.selectWithoutZooming?{type:"selected"}:{type:"zoomed"};c.target=this;c.chart=a;if("cursor"==this.type)this.rotate?this.selectionPosY=h:this.selectionPosX= h=e,4>Math.abs(h-this.initialMouse)&&this.fromIndex==this.index||(this.index<this.fromIndex?(c.end=this.fromIndex,c.start=this.index):(c.end=this.index,c.start=this.fromIndex),h=a.categoryAxis,h.parseDates&&!h.equalSpacing&&(b[c.start]&&(c.start=b[c.start].time),b[c.end]&&(c.end=a.getEndTime(b[c.end].time))),this.skipZoomDispatch||this.fire(c.type,c));else{var g=this.initialMouseX,k=this.initialMouseY;3>Math.abs(e-g)&&3>Math.abs(h-k)||(b=Math.min(g,e),f=Math.min(k,h),e=Math.abs(g-e),h=Math.abs(k- h),a.hideXScrollbar&&(b=0,e=this.width),a.hideYScrollbar&&(f=0,h=this.height),c.selectionHeight=h,c.selectionWidth=e,c.selectionY=f,c.selectionX=b,this.skipZoomDispatch||this.fire(c.type,c))}this.selectWithoutZooming||d.remove(this.selection)}this.skipZoomDispatch=!1}}this.panning=this.zooming=!1},showCursorAt:function(a){var b=this.chart.categoryAxis;a=b.parseDates?b.dateToCoordinate(a):b.categoryToCoordinate(a);this.previousMousePosition=NaN;this.forceShow=!0;this.setPosition(a,!1)},clearSelection:function(){d.remove(this.selection)}, handleMouseDown:function(a){if(this.zoomable||this.pan||this.drawing){var b=this.rotate,c=this.chart,e=c.mouseX-this.x,h=c.mouseY-this.y;if(0<e&&e<this.width&&0<h&&h<this.height||"fake"==a)this.setPosition(),this.selectWithoutZooming&&d.remove(this.selection),this.drawing?(this.drawStartY=h,this.drawStartX=e,this.drawingNow=!0):this.pan?(this.zoomable=!1,c.setMouseCursor("move"),this.panning=!0,this.panClickPos=b?h:e,this.panClickStart=this.start,this.panClickEnd=this.end,this.panClickStartTime=this.startTime, this.panClickEndTime=this.endTime):this.zoomable&&("cursor"==this.type?(this.fromIndex=this.index,b?(this.initialMouse=h,this.selectionPosY=this.linePos):(this.initialMouse=e,this.selectionPosX=this.linePos)):(this.initialMouseX=e,this.initialMouseY=h,this.selectionPosX=e,this.selectionPosY=h),this.zooming=!0)}}})})();(function(){var d=window.AmCharts;d.SimpleChartScrollbar=d.Class({construct:function(a){this.createEvents("zoomed");this.backgroundColor="#D4D4D4";this.backgroundAlpha=1;this.selectedBackgroundColor="#EFEFEF";this.scrollDuration=this.selectedBackgroundAlpha=1;this.resizeEnabled=!0;this.hideResizeGrips=!1;this.scrollbarHeight=20;this.updateOnReleaseOnly=!1;9>document.documentMode&&(this.updateOnReleaseOnly=!0);this.dragIconHeight=this.dragIconWidth=35;this.dragIcon="dragIconRoundBig";d.applyTheme(this, a,"SimpleChartScrollbar")},draw:function(){var a=this;a.destroy();if(a.enabled){var b=a.chart.container,c=a.rotate,e=a.chart,h=b.set();a.set=h;e.scrollbarsSet.push(h);var f,g;c?(f=a.scrollbarHeight,g=e.plotAreaHeight):(g=a.scrollbarHeight,f=e.plotAreaWidth);a.width=f;if((a.height=g)&&f){var k=d.rect(b,f,g,a.backgroundColor,a.backgroundAlpha,1,a.backgroundColor,a.backgroundAlpha);d.setCN(e,k,"scrollbar-bg");a.bg=k;h.push(k);k=d.rect(b,f,g,"#000",.005);h.push(k);a.invisibleBg=k;k.click(function(){a.handleBgClick()}).mouseover(function(){a.handleMouseOver()}).mouseout(function(){a.handleMouseOut()}).touchend(function(){a.handleBgClick()}); k=d.rect(b,f,g,a.selectedBackgroundColor,a.selectedBackgroundAlpha);d.setCN(e,k,"scrollbar-bg-selected");a.selectedBG=k;h.push(k);f=d.rect(b,f,g,"#000",.005);a.dragger=f;h.push(f);f.mousedown(function(b){a.handleDragStart(b)}).mouseup(function(){a.handleDragStop()}).mouseover(function(){a.handleDraggerOver()}).mouseout(function(){a.handleMouseOut()}).touchstart(function(b){a.handleDragStart(b)}).touchend(function(){a.handleDragStop()});f=e.pathToImages;c?(k=f+a.dragIcon+"H.png",f=a.dragIconWidth, c=a.dragIconHeight):(k=f+a.dragIcon+".png",c=a.dragIconWidth,f=a.dragIconHeight);g=b.image(k,0,0,c,f);d.setCN(e,g,"scrollbar-grip-left");k=b.image(k,0,0,c,f);d.setCN(e,k,"scrollbar-grip-right");var l=10,m=20;e.panEventsEnabled&&(l=25,m=a.scrollbarHeight);var n=d.rect(b,l,m,"#000",.005),p=d.rect(b,l,m,"#000",.005);p.translate(-(l-c)/2,-(m-f)/2);n.translate(-(l-c)/2,-(m-f)/2);c=b.set([g,p]);b=b.set([k,n]);a.iconLeft=c;h.push(a.iconLeft);a.iconRight=b;h.push(b);c.mousedown(function(){a.leftDragStart()}).mouseup(function(){a.leftDragStop()}).mouseover(function(){a.iconRollOver()}).mouseout(function(){a.iconRollOut()}).touchstart(function(){a.leftDragStart()}).touchend(function(){a.leftDragStop()}); b.mousedown(function(){a.rightDragStart()}).mouseup(function(){a.rightDragStop()}).mouseover(function(){a.iconRollOver()}).mouseout(function(){a.iconRollOut()}).touchstart(function(){a.rightDragStart()}).touchend(function(){a.rightDragStop()});d.ifArray(e.chartData)?h.show():h.hide();a.hideDragIcons();a.clipDragger(!1)}h.translate(a.x,a.y);h.node.style.msTouchAction="none"}},updateScrollbarSize:function(a,b){a=Math.round(a);b=Math.round(b);var c=this.dragger,e,d,f,g;this.rotate?(e=0,d=a,f=this.width+ 1,g=b-a,c.setAttr("height",b-a),c.setAttr("y",d)):(e=a,d=0,f=b-a,g=this.height+1,c.setAttr("width",b-a),c.setAttr("x",e));this.clipAndUpdate(e,d,f,g)},update:function(){var a,b=!1,c,e,d=this.x,f=this.y,g=this.dragger,k=this.getDBox();if(k){c=k.x+d;e=k.y+f;var l=k.width,k=k.height,m=this.rotate,n=this.chart,p=this.width,q=this.height,r=n.mouseX,u=n.mouseY;a=this.initialMouse;this.forceClip&&this.clipDragger(!0);n.mouseIsOver&&(this.dragging&&(n=this.initialCoord,m?(a=n+(u-a),0>a&&(a=0),n=q-k,a>n&& (a=n),g.setAttr("y",a)):(a=n+(r-a),0>a&&(a=0),n=p-l,a>n&&(a=n),g.setAttr("x",a)),this.clipDragger(!0)),this.resizingRight&&(m?(a=u-e,a+e>q+f&&(a=q-e+f),0>a?(this.resizingRight=!1,b=this.resizingLeft=!0):(0===a&&(a=.1),g.setAttr("height",a))):(a=r-c,a+c>p+d&&(a=p-c+d),0>a?(this.resizingRight=!1,b=this.resizingLeft=!0):(0===a&&(a=.1),g.setAttr("width",a))),this.clipDragger(!0)),this.resizingLeft&&(m?(c=e,e=u,e<f&&(e=f),e>q+f&&(e=q+f),a=!0===b?c-e:k+c-e,0>a?(this.resizingRight=!0,this.resizingLeft=!1, g.setAttr("y",c+k-f)):(0===a&&(a=.1),g.setAttr("y",e-f),g.setAttr("height",a))):(e=r,e<d&&(e=d),e>p+d&&(e=p+d),a=!0===b?c-e:l+c-e,0>a?(this.resizingRight=!0,this.resizingLeft=!1,g.setAttr("x",c+l-d)):(0===a&&(a=.1),g.setAttr("x",e-d),g.setAttr("width",a))),this.clipDragger(!0)))}},stopForceClip:function(){this.forceClip=!1},clipDragger:function(a){var b=this.getDBox();if(b){var c=b.x,e=b.y,d=b.width,b=b.height,f=!1;if(this.rotate){if(c=0,d=this.width+1,this.clipY!=e||this.clipH!=b)f=!0}else if(e= 0,b=this.height+1,this.clipX!=c||this.clipW!=d)f=!0;f&&(this.clipAndUpdate(c,e,d,b),a&&(this.updateOnReleaseOnly||this.dispatchScrollbarEvent()))}},maskGraphs:function(){},clipAndUpdate:function(a,b,c,e){this.clipX=a;this.clipY=b;this.clipW=c;this.clipH=e;this.selectedBG.clipRect(a,b,c,e);this.updateDragIconPositions();this.maskGraphs(a,b,c,e)},dispatchScrollbarEvent:function(){if(this.skipEvent)this.skipEvent=!1;else{var a=this.chart;a.hideBalloon();var b=this.getDBox(),c=b.x,e=b.y,d=b.width,b=b.height; this.rotate?(c=e,d=this.height/b):d=this.width/d;a={type:"zoomed",position:c,chart:a,target:this,multiplier:d};this.fire(a.type,a)}},updateDragIconPositions:function(){var a=this.getDBox(),b=a.x,c=a.y,e=this.iconLeft,d=this.iconRight,f,g,k=this.scrollbarHeight;this.rotate?(f=this.dragIconWidth,g=this.dragIconHeight,e.translate((k-g)/2,c-f/2),d.translate((k-g)/2,c+a.height-f/2)):(f=this.dragIconHeight,g=this.dragIconWidth,e.translate(b-g/2,(k-f)/2),d.translate(b-g/2+a.width,(k-f)/2))},showDragIcons:function(){this.resizeEnabled&& (this.iconLeft.show(),this.iconRight.show())},hideDragIcons:function(){if(!this.resizingLeft&&!this.resizingRight&&!this.dragging){if(this.hideResizeGrips||!this.resizeEnabled)this.iconLeft.hide(),this.iconRight.hide();this.removeCursors()}},removeCursors:function(){this.chart.setMouseCursor("auto")},relativeZoom:function(a,b){this.enabled&&(this.dragger.stop(),this.multiplier=a,this.position=b,this.updateScrollbarSize(b,this.rotate?b+this.height/a:b+this.width/a),this.clipDragger())},destroy:function(){this.clear(); d.remove(this.set);d.remove(this.iconRight);d.remove(this.iconLeft)},clear:function(){},handleDragStart:function(){if(this.enabled){var a=this.chart;this.dragger.stop();this.removeCursors();this.dragging=!0;var b=this.getDBox();this.rotate?(this.initialCoord=b.y,this.initialMouse=a.mouseY):(this.initialCoord=b.x,this.initialMouse=a.mouseX)}},handleDragStop:function(){this.updateOnReleaseOnly&&(this.update(),this.skipEvent=!1,this.dispatchScrollbarEvent());this.dragging=!1;this.mouseIsOver&&this.removeCursors(); this.update()},handleDraggerOver:function(){this.handleMouseOver()},leftDragStart:function(){this.dragger.stop();this.resizingLeft=!0},leftDragStop:function(){this.resizingLeft=!1;this.mouseIsOver||this.removeCursors();this.updateOnRelease()},rightDragStart:function(){this.dragger.stop();this.resizingRight=!0},rightDragStop:function(){this.resizingRight=!1;this.mouseIsOver||this.removeCursors();this.updateOnRelease()},iconRollOut:function(){this.removeCursors()},iconRollOver:function(){this.rotate? this.chart.setMouseCursor("n-resize"):this.chart.setMouseCursor("e-resize");this.handleMouseOver()},getDBox:function(){if(this.dragger)return this.dragger.getBBox()},handleBgClick:function(){var a=this;if(!a.resizingRight&&!a.resizingLeft){a.zooming=!0;var b,c,e=a.scrollDuration,h=a.dragger;b=a.getDBox();var f=b.height,g=b.width;c=a.chart;var k=a.y,l=a.x,m=a.rotate;m?(b="y",c=c.mouseY-f/2-k,c=d.fitToBounds(c,0,a.height-f)):(b="x",c=c.mouseX-g/2-l,c=d.fitToBounds(c,0,a.width-g));a.updateOnReleaseOnly? (a.skipEvent=!1,h.setAttr(b,c),a.dispatchScrollbarEvent(),a.clipDragger()):(c=Math.round(c),m?h.animate({y:c},e,">"):h.animate({x:c},e,">"),a.forceClip=!0,clearTimeout(a.forceTO),a.forceTO=setTimeout(function(){a.stopForceClip.call(a)},5E3*e))}},updateOnRelease:function(){this.updateOnReleaseOnly&&(this.update(),this.skipEvent=!1,this.dispatchScrollbarEvent())},handleReleaseOutside:function(){if(this.set){if(this.resizingLeft||this.resizingRight||this.dragging)this.updateOnRelease(),this.removeCursors(); this.mouseIsOver=this.dragging=this.resizingRight=this.resizingLeft=!1;this.hideDragIcons();this.update()}},handleMouseOver:function(){this.mouseIsOver=!0;this.showDragIcons()},handleMouseOut:function(){this.mouseIsOver=!1;this.hideDragIcons()}})})();(function(){var d=window.AmCharts;d.ChartScrollbar=d.Class({inherits:d.SimpleChartScrollbar,construct:function(a){this.cname="ChartScrollbar";d.ChartScrollbar.base.construct.call(this,a);this.enabled=!0;this.graphLineColor="#BBBBBB";this.graphLineAlpha=0;this.graphFillColor="#BBBBBB";this.graphFillAlpha=1;this.selectedGraphLineColor="#888888";this.selectedGraphLineAlpha=0;this.selectedGraphFillColor="#888888";this.selectedGraphFillAlpha=1;this.gridCount=0;this.gridColor="#FFFFFF";this.gridAlpha=.7; this.skipEvent=this.autoGridCount=!1;this.color="#FFFFFF";this.scrollbarCreated=!1;this.offset=0;this.oppositeAxis=!0;d.applyTheme(this,a,this.cname)},init:function(){var a=this.categoryAxis,b=this.chart;a||(this.categoryAxis=a=new d.CategoryAxis);a.chart=b;a.id="scrollbar";a.dateFormats=b.categoryAxis.dateFormats;a.markPeriodChange=b.categoryAxis.markPeriodChange;a.boldPeriodBeginning=b.categoryAxis.boldPeriodBeginning;a.labelFunction=b.categoryAxis.labelFunction;a.axisItemRenderer=d.RecItem;a.axisRenderer= d.RecAxis;a.guideFillRenderer=d.RecFill;a.inside=!0;a.fontSize=this.fontSize;a.tickLength=0;a.axisAlpha=0;d.isString(this.graph)&&(this.graph=d.getObjById(b.graphs,this.graph));if(a=this.graph){var c=this.valueAxis;c||(this.valueAxis=c=new d.ValueAxis,c.visible=!1,c.scrollbar=!0,c.axisItemRenderer=d.RecItem,c.axisRenderer=d.RecAxis,c.guideFillRenderer=d.RecFill,c.labelsEnabled=!1,c.chart=b);b=this.unselectedGraph;b||(b=new d.AmGraph,b.scrollbar=!0,this.unselectedGraph=b,b.negativeBase=a.negativeBase, b.noStepRisers=a.noStepRisers);b=this.selectedGraph;b||(b=new d.AmGraph,b.scrollbar=!0,this.selectedGraph=b,b.negativeBase=a.negativeBase,b.noStepRisers=a.noStepRisers)}this.scrollbarCreated=!0},draw:function(){var a=this;d.ChartScrollbar.base.draw.call(a);if(a.enabled){a.scrollbarCreated||a.init();var b=a.chart,c=b.chartData,e=a.categoryAxis,h=a.rotate,f=a.x,g=a.y,k=a.width,l=a.height,m=b.categoryAxis,n=a.set;e.setOrientation(!h);e.parseDates=m.parseDates;e.rotate=h;e.equalSpacing=m.equalSpacing; e.minPeriod=m.minPeriod;e.startOnAxis=m.startOnAxis;e.viW=k;e.viH=l;e.width=k;e.height=l;e.gridCount=a.gridCount;e.gridColor=a.gridColor;e.gridAlpha=a.gridAlpha;e.color=a.color;e.tickLength=0;e.axisAlpha=0;e.autoGridCount=a.autoGridCount;e.parseDates&&!e.equalSpacing&&e.timeZoom(b.firstTime,b.lastTime);e.zoom(0,c.length-1);if(m=a.graph){var p=a.valueAxis,q=m.valueAxis;p.id=q.id;p.rotate=h;p.setOrientation(h);p.width=k;p.height=l;p.viW=k;p.viH=l;p.dataProvider=c;p.reversed=q.reversed;p.logarithmic= q.logarithmic;p.gridAlpha=0;p.axisAlpha=0;n.push(p.set);h?(p.y=g,p.x=0):(p.x=f,p.y=0);var f=Infinity,g=-Infinity,r;for(r=0;r<c.length;r++){var u=c[r].axes[q.id].graphs[m.id].values,t;for(t in u)if(u.hasOwnProperty(t)&&"percents"!=t&&"total"!=t){var z=u[t];z<f&&(f=z);z>g&&(g=z)}}Infinity!=f&&(p.minimum=f);-Infinity!=g&&(p.maximum=g+.1*(g-f));f==g&&(--p.minimum,p.maximum+=1);void 0!==a.minimum&&(p.minimum=a.minimum);void 0!==a.maximum&&(p.maximum=a.maximum);p.zoom(0,c.length-1);t=a.unselectedGraph; t.id=m.id;t.bcn="scrollbar-graph-";t.rotate=h;t.chart=b;t.data=c;t.valueAxis=p;t.chart=m.chart;t.categoryAxis=a.categoryAxis;t.periodSpan=m.periodSpan;t.valueField=m.valueField;t.openField=m.openField;t.closeField=m.closeField;t.highField=m.highField;t.lowField=m.lowField;t.lineAlpha=a.graphLineAlpha;t.lineColorR=a.graphLineColor;t.fillAlphas=a.graphFillAlpha;t.fillColorsR=a.graphFillColor;t.connect=m.connect;t.hidden=m.hidden;t.width=k;t.height=l;t.pointPosition=m.pointPosition;t.stepDirection=m.stepDirection; t.periodSpan=m.periodSpan;q=a.selectedGraph;q.id=m.id;q.bcn=t.bcn+"selected-";q.rotate=h;q.chart=b;q.data=c;q.valueAxis=p;q.chart=m.chart;q.categoryAxis=e;q.periodSpan=m.periodSpan;q.valueField=m.valueField;q.openField=m.openField;q.closeField=m.closeField;q.highField=m.highField;q.lowField=m.lowField;q.lineAlpha=a.selectedGraphLineAlpha;q.lineColorR=a.selectedGraphLineColor;q.fillAlphas=a.selectedGraphFillAlpha;q.fillColorsR=a.selectedGraphFillColor;q.connect=m.connect;q.hidden=m.hidden;q.width= k;q.height=l;q.pointPosition=m.pointPosition;q.stepDirection=m.stepDirection;q.periodSpan=m.periodSpan;b=a.graphType;b||(b=m.type);t.type=b;q.type=b;c=c.length-1;t.zoom(0,c);q.zoom(0,c);q.set.click(function(){a.handleBackgroundClick()}).mouseover(function(){a.handleMouseOver()}).mouseout(function(){a.handleMouseOut()});t.set.click(function(){a.handleBackgroundClick()}).mouseover(function(){a.handleMouseOver()}).mouseout(function(){a.handleMouseOut()});n.push(t.set);n.push(q.set)}n.push(e.set);n.push(e.labelsSet); a.bg.toBack();a.invisibleBg.toFront();a.dragger.toFront();a.iconLeft.toFront();a.iconRight.toFront()}},timeZoom:function(a,b,c){this.startTime=a;this.endTime=b;this.timeDifference=b-a;this.skipEvent=!d.toBoolean(c);this.zoomScrollbar();this.skipEvent||this.dispatchScrollbarEvent()},zoom:function(a,b){this.start=a;this.end=b;this.skipEvent=!0;this.zoomScrollbar()},dispatchScrollbarEvent:function(){if(this.skipEvent)this.skipEvent=!1;else{var a=this.chart.chartData,b,c,e=this.dragger.getBBox();b=e.x; var d=e.y,f=e.width,e=e.height,g=this.chart;this.rotate?(b=d,c=e):c=f;f={type:"zoomed",target:this};f.chart=g;var k=this.categoryAxis,l=this.stepWidth,d=g.minSelectedTime,e=!1;if(k.parseDates&&!k.equalSpacing){if(a=g.lastTime,g=g.firstTime,k=Math.round(b/l)+g,b=this.dragging?k+this.timeDifference:Math.round((b+c)/l)+g,k>b&&(k=b),0<d&&b-k<d&&(b=Math.round(k+(b-k)/2),e=Math.round(d/2),k=b-e,b+=e,e=!0),b>a&&(b=a),b-d<k&&(k=b-d),k<g&&(k=g),k+d>b&&(b=k+d),k!=this.startTime||b!=this.endTime)this.startTime= k,this.endTime=b,f.start=k,f.end=b,f.startDate=new Date(k),f.endDate=new Date(b),this.fire(f.type,f)}else if(k.startOnAxis||(b+=l/2),c-=this.stepWidth/2,d=k.xToIndex(b),b=k.xToIndex(b+c),d!=this.start||this.end!=b)k.startOnAxis&&(this.resizingRight&&d==b&&b++,this.resizingLeft&&d==b&&(0<d?d--:b=1)),this.start=d,this.end=this.dragging?this.start+this.difference:b,f.start=this.start,f.end=this.end,k.parseDates&&(a[this.start]&&(f.startDate=new Date(a[this.start].time)),a[this.end]&&(f.endDate=new Date(a[this.end].time))), this.fire(f.type,f);e&&this.zoomScrollbar()}},zoomScrollbar:function(){var a,b;a=this.chart;var c=a.chartData,e=this.categoryAxis;e.parseDates&&!e.equalSpacing?(c=e.stepWidth,e=a.firstTime,a=c*(this.startTime-e),b=c*(this.endTime-e)):(a=c[this.start].x[e.id],b=c[this.end].x[e.id],c=e.stepWidth,e.startOnAxis||(e=c/2,a-=e,b+=e));this.stepWidth=c;this.updateScrollbarSize(a,b)},maskGraphs:function(a,b,c,e){var d=this.selectedGraph;d&&d.set.clipRect(a,b,c,e)},handleDragStart:function(){d.ChartScrollbar.base.handleDragStart.call(this); this.difference=this.end-this.start;this.timeDifference=this.endTime-this.startTime;0>this.timeDifference&&(this.timeDifference=0)},handleBackgroundClick:function(){d.ChartScrollbar.base.handleBackgroundClick.call(this);this.dragging||(this.difference=this.end-this.start,this.timeDifference=this.endTime-this.startTime,0>this.timeDifference&&(this.timeDifference=0))}})})();(function(){var d=window.AmCharts;d.AmBalloon=d.Class({construct:function(a){this.cname="AmBalloon";this.enabled=!0;this.fillColor="#FFFFFF";this.fillAlpha=.8;this.borderThickness=2;this.borderColor="#FFFFFF";this.borderAlpha=1;this.cornerRadius=0;this.maxWidth=220;this.horizontalPadding=8;this.verticalPadding=4;this.pointerWidth=6;this.pointerOrientation="V";this.color="#000000";this.adjustBorderColor=!0;this.show=this.follow=this.showBullet=!1;this.bulletSize=3;this.shadowAlpha=.4;this.shadowColor= "#000000";this.fadeOutDuration=this.animationDuration=.3;this.fixedPosition=!1;this.offsetY=6;this.offsetX=1;this.textAlign="center";this.disableMouseEvents=!0;this.deltaSignX=this.deltaSignY=1;d.isModern||(this.offsetY*=1.5);d.applyTheme(this,a,this.cname)},draw:function(){var a=this.pointToX,b=this.pointToY,c=this.chart;d.VML&&(this.fadeOutDuration=0);this.xAnim&&c.stopAnim(this.xAnim);this.yAnim&&c.stopAnim(this.yAnim);if(!isNaN(a)){var e=this.follow,h=c.container,f=this.set;d.remove(f);this.removeDiv(); f=h.set();f.node.style.pointerEvents="none";this.set=f;c.balloonsSet.push(f);if(this.show){var g=this.l,k=this.t,l=this.r,m=this.b,n=this.balloonColor,p=this.fillColor,q=this.borderColor,r=p;void 0!=n&&(this.adjustBorderColor?r=q=n:p=n);var u=this.horizontalPadding,t=this.verticalPadding,z=this.pointerWidth,y=this.pointerOrientation,v=this.cornerRadius,w=c.fontFamily,A=this.fontSize;void 0==A&&(A=c.fontSize);var n=document.createElement("div"),B=c.classNamePrefix;n.className=B+"-balloon-div";this.className&& (n.className=n.className+" "+B+"-balloon-div-"+this.className);B=n.style;this.disableMouseEvents&&(B.pointerEvents="none");B.position="absolute";var C=this.minWidth,D="";isNaN(C)||(D="min-width:"+(C-2*u)+"px; ");n.innerHTML="<div style='text-align:"+this.textAlign+"; "+D+"max-width:"+this.maxWidth+"px; font-size:"+A+"px; color:"+this.color+"; font-family:"+w+"'>"+this.text+"</div>";c.chartDiv.appendChild(n);this.textDiv=n;A=n.offsetWidth;w=n.offsetHeight;n.clientHeight&&(A=n.clientWidth,w=n.clientHeight); w+=2*t;D=A+2*u;!isNaN(C)&&D<C&&(D=C);window.opera&&(w+=2);var J=!1,A=this.offsetY;c.handDrawn&&(A+=c.handDrawScatter+2);"H"!=y?(C=a-D/2,b<k+w+10&&"down"!=y?(J=!0,e&&(b+=A),A=b+z,this.deltaSignY=-1):(e&&(b-=A),A=b-w-z,this.deltaSignY=1)):(2*z>w&&(z=w/2),A=b-w/2,a<g+(l-g)/2?(C=a+z,this.deltaSignX=-1):(C=a-D-z,this.deltaSignX=1));A+w>=m&&(A=m-w);A<k&&(A=k);C<g&&(C=g);C+D>l&&(C=l-D);var k=A+t,m=C+u,t=this.shadowAlpha,E=this.shadowColor,u=this.borderThickness,O=this.bulletSize,I;0<v||0===z?(0<t&&(a=d.rect(h, D,w,p,0,u+1,E,t,this.cornerRadius),d.isModern?a.translate(1,1):a.translate(4,4),f.push(a)),p=d.rect(h,D,w,p,this.fillAlpha,u,q,this.borderAlpha,this.cornerRadius),this.showBullet&&(I=d.circle(h,O,r,this.fillAlpha),f.push(I))):(r=[],v=[],"H"!=y?(g=a-C,g>D-z&&(g=D-z),g<z&&(g=z),r=[0,g-z,a-C,g+z,D,D,0,0],v=J?[0,0,b-A,0,0,w,w,0]:[w,w,b-A,w,w,0,0,w]):(r=b-A,r>w-z&&(r=w-z),r<z&&(r=z),v=[0,r-z,b-A,r+z,w,w,0,0],r=a<g+(l-g)/2?[0,0,C<a?0:a-C,0,0,D,D,0]:[D,D,C+D>a?D:a-C,D,D,0,0,D]),0<t&&(a=d.polygon(h,r,v,p, 0,u,E,t),a.translate(1,1),f.push(a)),p=d.polygon(h,r,v,p,this.fillAlpha,u,q,this.borderAlpha));this.bg=p;f.push(p);p.toFront();d.setCN(c,p,"balloon-bg");this.className&&d.setCN(c,p,"balloon-bg-"+this.className);h=1*this.deltaSignX;B.left=m+"px";B.top=k+"px";f.translate(C-h,A);p=p.getBBox();this.bottom=A+w+1;this.yPos=p.y+A;I&&I.translate(this.pointToX-C+h,b-A);b=this.animationDuration;0<this.animationDuration&&!e&&!isNaN(this.prevX)&&(f.translate(this.prevX,this.prevY),f.animate({translate:C-h+","+ A},b,"easeOutSine"),n&&(B.left=this.prevTX+"px",B.top=this.prevTY+"px",this.xAnim=c.animate({node:n},"left",this.prevTX,m,b,"easeOutSine","px"),this.yAnim=c.animate({node:n},"top",this.prevTY,k,b,"easeOutSine","px")));this.prevX=C-h;this.prevY=A;this.prevTX=m;this.prevTY=k}}},followMouse:function(){if(this.follow&&this.show){var a=this.chart.mouseX-this.offsetX*this.deltaSignX,b=this.chart.mouseY;this.pointToX=a;this.pointToY=b;if(a!=this.previousX||b!=this.previousY)if(this.previousX=a,this.previousY= b,0===this.cornerRadius)this.draw();else{var c=this.set;if(c){var e=c.getBBox(),a=a-e.width/2,d=b-e.height-10;a<this.l&&(a=this.l);a>this.r-e.width&&(a=this.r-e.width);d<this.t&&(d=b+10);c.translate(a,d);b=this.textDiv.style;b.left=a+this.horizontalPadding+"px";b.top=d+this.verticalPadding+"px"}}}},changeColor:function(a){this.balloonColor=a},setBounds:function(a,b,c,e){this.l=a;this.t=b;this.r=c;this.b=e;this.destroyTO&&clearTimeout(this.destroyTO)},showBalloon:function(a){this.text=a;this.show= !0;this.destroyTO&&clearTimeout(this.destroyTO);a=this.chart;this.fadeAnim1&&a.stopAnim(this.fadeAnim1);this.fadeAnim2&&a.stopAnim(this.fadeAnim2);this.draw()},hide:function(a){var b=this;isNaN(a)&&(a=b.fadeOutDuration);var c=b.chart;if(0<a){b.destroyTO&&clearTimeout(b.destroyTO);b.destroyTO=setTimeout(function(){b.destroy.call(b)},1E3*a);b.follow=!1;b.show=!1;var e=b.set;e&&(e.setAttr("opacity",b.fillAlpha),b.fadeAnim1=e.animate({opacity:0},a,"easeInSine"));b.textDiv&&(b.fadeAnim2=c.animate({node:b.textDiv}, "opacity",1,0,a,"easeInSine",""))}else b.show=!1,b.follow=!1,b.destroy()},setPosition:function(a,b,c){this.pointToX=a;this.pointToY=b;c&&(a==this.previousX&&b==this.previousY||this.draw());this.previousX=a;this.previousY=b},followCursor:function(a){var b=this;(b.follow=a)?(b.pShowBullet=b.showBullet,b.showBullet=!1):void 0!==b.pShowBullet&&(b.showBullet=b.pShowBullet);clearInterval(b.interval);var c=b.chart.mouseX,e=b.chart.mouseY;!isNaN(c)&&a&&(b.pointToX=c-b.offsetX*b.deltaSignX,b.pointToY=e,b.followMouse(), b.interval=setInterval(function(){b.followMouse.call(b)},40))},removeDiv:function(){if(this.textDiv){var a=this.textDiv.parentNode;a&&a.removeChild(this.textDiv)}},destroy:function(){clearInterval(this.interval);d.remove(this.set);this.removeDiv();this.set=null}})})();(function(){var d=window.AmCharts;d.AmCoordinateChart=d.Class({inherits:d.AmChart,construct:function(a){d.AmCoordinateChart.base.construct.call(this,a);this.theme=a;this.createEvents("rollOverGraphItem","rollOutGraphItem","clickGraphItem","doubleClickGraphItem","rightClickGraphItem","clickGraph","rollOverGraph","rollOutGraph");this.startAlpha=1;this.startDuration=0;this.startEffect="elastic";this.sequencedAnimation=!0;this.colors="#FF6600 #FCD202 #B0DE09 #0D8ECF #2A0CD0 #CD0D74 #CC0000 #00CC00 #0000CC #DDDDDD #999999 #333333 #990000".split(" "); this.balloonDateFormat="MMM DD, YYYY";this.valueAxes=[];this.graphs=[];this.guides=[];this.gridAboveGraphs=!1;d.applyTheme(this,a,"AmCoordinateChart")},initChart:function(){d.AmCoordinateChart.base.initChart.call(this);var a=this.categoryAxis;a&&(this.categoryAxis=d.processObject(a,d.CategoryAxis,this.theme));this.processValueAxes();this.createValueAxes();this.processGraphs();this.processGuides();d.VML&&(this.startAlpha=1);this.setLegendData(this.graphs);this.gridAboveGraphs&&this.gridSet.toFront()}, createValueAxes:function(){if(0===this.valueAxes.length){var a=new d.ValueAxis;this.addValueAxis(a)}},parseData:function(){this.processValueAxes();this.processGraphs()},parseSerialData:function(a){var b=this.graphs,c,e={},h=this.seriesIdField;h||(h=this.categoryField);this.chartData=[];if(a){var f=!1,g,k=this.categoryAxis,l,m,n;k&&(f=k.parseDates,l=k.forceShowField,n=k.classNameField,m=k.labelColorField,g=k.categoryFunction);var p,q,r={},u;f&&(c=d.extractPeriod(k.minPeriod),p=c.period,q=c.count,u= d.getPeriodDuration(p,q));var t={};this.lookupTable=t;var z,y=this.dataDateFormat,v={};for(z=0;z<a.length;z++){var w={},A=a[z];c=A[this.categoryField];w.dataContext=A;w.category=g?g(c,A,k):String(c);l&&(w.forceShow=A[l]);n&&(w.className=A[n]);m&&(w.labelColor=A[m]);t[A[h]]=w;if(f&&(k.categoryFunction?c=k.categoryFunction(c,A,k):(!y||c instanceof Date||(c=c.toString()+" |"),c=d.getDate(c,y,k.minPeriod)),c=d.resetDateToMin(c,p,q,k.firstDayOfWeek),w.category=c,w.time=c.getTime(),isNaN(w.time)))continue; var B=this.valueAxes;w.axes={};w.x={};var C;for(C=0;C<B.length;C++){var D=B[C].id;w.axes[D]={};w.axes[D].graphs={};var J;for(J=0;J<b.length;J++){c=b[J];var E=c.id,O=1.1;isNaN(c.gapPeriod)||(O=c.gapPeriod);var I=c.periodValue;if(c.valueAxis.id==D){w.axes[D].graphs[E]={};var W={};W.index=z;var ea=A;c.dataProvider&&(ea=e);W.values=this.processValues(ea,c,I);!c.connect&&v&&v[E]&&0<O&&w.time-r[E]>=u*O&&(v[E].gap=!0);this.processFields(c,W,ea);W.category=w.category;W.serialDataItem=w;W.graph=c;w.axes[D].graphs[E]= W;r[E]=w.time;v[E]=W}}}this.chartData[z]=w}}for(a=0;a<b.length;a++)c=b[a],c.dataProvider&&this.parseGraphData(c)},processValues:function(a,b,c){var e={},h,f=!1;"candlestick"!=b.type&&"ohlc"!=b.type||""===c||(f=!0);for(var g="value error open close low high".split(" "),k=0;k<g.length;k++){var l=g[k];"value"!=l&&"error"!=l&&f&&(c=l.charAt(0).toUpperCase()+l.slice(1));var m=a[b[l+"Field"]+c];null!==m&&(h=Number(m),isNaN(h)||(e[l]=h),"date"==b.valueAxis.type&&void 0!==m&&(h=d.getDate(m,b.chart.dataDateFormat), e[l]=h.getTime()))}return e},parseGraphData:function(a){var b=a.dataProvider,c=a.seriesIdField;c||(c=this.seriesIdField);c||(c=this.categoryField);var e;for(e=0;e<b.length;e++){var d=b[e],f=this.lookupTable[String(d[c])],g=a.valueAxis.id;f&&(g=f.axes[g].graphs[a.id],g.serialDataItem=f,g.values=this.processValues(d,a,a.periodValue),this.processFields(a,g,d))}},addValueAxis:function(a){a.chart=this;this.valueAxes.push(a);this.validateData()},removeValueAxesAndGraphs:function(){var a=this.valueAxes, b;for(b=a.length-1;-1<b;b--)this.removeValueAxis(a[b])},removeValueAxis:function(a){var b=this.graphs,c;for(c=b.length-1;0<=c;c--){var e=b[c];e&&e.valueAxis==a&&this.removeGraph(e)}b=this.valueAxes;for(c=b.length-1;0<=c;c--)b[c]==a&&b.splice(c,1);this.validateData()},addGraph:function(a){this.graphs.push(a);this.chooseGraphColor(a,this.graphs.length-1);this.validateData()},removeGraph:function(a){var b=this.graphs,c;for(c=b.length-1;0<=c;c--)b[c]==a&&(b.splice(c,1),a.destroy());this.validateData()}, processValueAxes:function(){var a=this.valueAxes,b;for(b=0;b<a.length;b++){var c=a[b],c=d.processObject(c,d.ValueAxis,this.theme);a[b]=c;c.chart=this;c.id||(c.id="valueAxisAuto"+b+"_"+(new Date).getTime());void 0===c.usePrefixes&&(c.usePrefixes=this.usePrefixes)}},processGuides:function(){var a=this.guides,b=this.categoryAxis;if(a)for(var c=0;c<a.length;c++){var e=a[c];(void 0!==e.category||void 0!==e.date)&&b&&b.addGuide(e);e.id||(e.id="guideAuto"+c+"_"+(new Date).getTime());var h=e.valueAxis;h? (d.isString(h)&&(h=this.getValueAxisById(h)),h?h.addGuide(e):this.valueAxes[0].addGuide(e)):isNaN(e.value)||this.valueAxes[0].addGuide(e)}},processGraphs:function(){var a=this.graphs,b;for(b=0;b<a.length;b++){var c=a[b],c=d.processObject(c,d.AmGraph,this.theme);a[b]=c;this.chooseGraphColor(c,b);c.chart=this;d.isString(c.valueAxis)&&(c.valueAxis=this.getValueAxisById(c.valueAxis));c.valueAxis||(c.valueAxis=this.valueAxes[0]);c.id||(c.id="graphAuto"+b+"_"+(new Date).getTime())}},formatString:function(a, b,c){var e=b.graph,h=e.valueAxis;h.duration&&b.values.value&&(h=d.formatDuration(b.values.value,h.duration,"",h.durationUnits,h.maxInterval,h.numberFormatter),a=a.split("[[value]]").join(h));a=d.massReplace(a,{"[[title]]":e.title,"[[description]]":b.description});a=c?d.fixNewLines(a):d.fixBrakes(a);return a=d.cleanFromEmpty(a)},getBalloonColor:function(a,b,c){var e=a.lineColor,h=a.balloonColor;c&&(h=e);c=a.fillColorsR;"object"==typeof c?e=c[0]:void 0!==c&&(e=c);b.isNegative&&(c=a.negativeLineColor, a=a.negativeFillColors,"object"==typeof a?c=a[0]:void 0!==a&&(c=a),void 0!==c&&(e=c));void 0!==b.color&&(e=b.color);void 0!==b.lineColor&&(e=b.lineColor);b=b.fillColors;void 0!==b&&(e=b,d.ifArray(b)&&(e=b[0]));void 0===h&&(h=e);return h},getGraphById:function(a){return d.getObjById(this.graphs,a)},getValueAxisById:function(a){return d.getObjById(this.valueAxes,a)},processFields:function(a,b,c){if(a.itemColors){var e=a.itemColors,h=b.index;b.color=h<e.length?e[h]:d.randomColor()}e="lineColor color alpha fillColors description bullet customBullet bulletSize bulletConfig url labelColor dashLength pattern gap className".split(" "); for(h=0;h<e.length;h++){var f=e[h],g=a[f+"Field"];g&&(g=c[g],d.isDefined(g)&&(b[f]=g))}b.dataContext=c},chooseGraphColor:function(a,b){if(a.lineColor)a.lineColorR=a.lineColor;else{var c;c=this.colors.length>b?this.colors[b]:d.randomColor();a.lineColorR=c}a.fillColorsR=a.fillColors?a.fillColors:a.lineColorR;a.bulletBorderColorR=a.bulletBorderColor?a.bulletBorderColor:a.useLineColorForBulletBorder?a.lineColorR:a.bulletColor;a.bulletColorR=a.bulletColor?a.bulletColor:a.lineColorR;if(c=this.patterns)a.pattern= c[b]},handleLegendEvent:function(a){var b=a.type;a=a.dataItem;if(!this.legend.data&&a){var c=a.hidden,e=a.showBalloon;switch(b){case "clickMarker":this.textClickEnabled&&(e?this.hideGraphsBalloon(a):this.showGraphsBalloon(a));break;case "clickLabel":e?this.hideGraphsBalloon(a):this.showGraphsBalloon(a);break;case "rollOverItem":c||this.highlightGraph(a);break;case "rollOutItem":c||this.unhighlightGraph();break;case "hideItem":this.hideGraph(a);break;case "showItem":this.showGraph(a)}}},highlightGraph:function(a){var b= this.graphs,c,e=.2;this.legend&&(e=this.legend.rollOverGraphAlpha);if(1!=e)for(c=0;c<b.length;c++){var d=b[c];d!=a&&d.changeOpacity(e)}},unhighlightGraph:function(){var a;this.legend&&(a=this.legend.rollOverGraphAlpha);if(1!=a){a=this.graphs;var b;for(b=0;b<a.length;b++)a[b].changeOpacity(1)}},showGraph:function(a){a.switchable&&(a.hidden=!1,this.dataChanged=!0,"xy"!=this.type&&(this.marginsUpdated=!1),this.chartCreated&&this.initChart())},hideGraph:function(a){a.switchable&&(this.dataChanged=!0, "xy"!=this.type&&(this.marginsUpdated=!1),a.hidden=!0,this.chartCreated&&this.initChart())},hideGraphsBalloon:function(a){a.showBalloon=!1;this.updateLegend()},showGraphsBalloon:function(a){a.showBalloon=!0;this.updateLegend()},updateLegend:function(){this.legend&&this.legend.invalidateSize()},resetAnimation:function(){var a=this.graphs;if(a){var b;for(b=0;b<a.length;b++)a[b].animationPlayed=!1}},animateAgain:function(){this.resetAnimation();this.validateNow()}})})();(function(){var d=window.AmCharts;d.AmSlicedChart=d.Class({inherits:d.AmChart,construct:function(a){this.createEvents("rollOverSlice","rollOutSlice","clickSlice","pullOutSlice","pullInSlice","rightClickSlice");d.AmSlicedChart.base.construct.call(this,a);this.colors="#FF0F00 #FF6600 #FF9E01 #FCD202 #F8FF01 #B0DE09 #04D215 #0D8ECF #0D52D1 #2A0CD0 #8A0CCF #CD0D74 #754DEB #DDDDDD #999999 #333333 #000000 #57032A #CA9726 #990000 #4B0C25".split(" ");this.alpha=1;this.groupPercent=0;this.groupedTitle="Other"; this.groupedPulled=!1;this.groupedAlpha=1;this.marginLeft=0;this.marginBottom=this.marginTop=10;this.marginRight=0;this.hoverAlpha=1;this.outlineColor="#FFFFFF";this.outlineAlpha=0;this.outlineThickness=1;this.startAlpha=0;this.startDuration=1;this.startEffect="bounce";this.sequencedAnimation=!0;this.pullOutDuration=1;this.pullOutEffect="bounce";this.pullOnHover=this.pullOutOnlyOne=!1;this.labelsEnabled=!0;this.labelTickColor="#000000";this.labelTickAlpha=.2;this.hideLabelsPercent=0;this.urlTarget= "_self";this.autoMarginOffset=10;this.gradientRatio=[];this.maxLabelWidth=200;d.applyTheme(this,a,"AmSlicedChart")},initChart:function(){d.AmSlicedChart.base.initChart.call(this);this.dataChanged&&(this.parseData(),this.dispatchDataUpdated=!0,this.dataChanged=!1,this.setLegendData(this.chartData));this.drawChart()},handleLegendEvent:function(a){var b=a.type,c=a.dataItem,e=this.legend;if(!e.data&&c){var d=c.hidden;a=a.event;switch(b){case "clickMarker":d||e.switchable||this.clickSlice(c,a);break;case "clickLabel":d|| this.clickSlice(c,a,!1);break;case "rollOverItem":d||this.rollOverSlice(c,!1,a);break;case "rollOutItem":d||this.rollOutSlice(c,a);break;case "hideItem":this.hideSlice(c,a);break;case "showItem":this.showSlice(c,a)}}},invalidateVisibility:function(){this.recalculatePercents();this.initChart();var a=this.legend;a&&a.invalidateSize()},addEventListeners:function(a,b){var c=this;a.mouseover(function(a){c.rollOverSlice(b,!0,a)}).mouseout(function(a){c.rollOutSlice(b,a)}).touchend(function(a){c.rollOverSlice(b, a);c.panEventsEnabled&&c.clickSlice(b,a)}).touchstart(function(a){c.rollOverSlice(b,a)}).click(function(a){c.clickSlice(b,a)}).contextmenu(function(a){c.handleRightClick(b,a)})},formatString:function(a,b,c){a=d.formatValue(a,b,["value"],this.nf,"",this.usePrefixes,this.prefixesOfSmallNumbers,this.prefixesOfBigNumbers);var e=this.pf.precision;isNaN(this.tempPrec)||(this.pf.precision=this.tempPrec);a=d.formatValue(a,b,["percents"],this.pf);a=d.massReplace(a,{"[[title]]":b.title,"[[description]]":b.description}); this.pf.precision=e;-1!=a.indexOf("[[")&&(a=d.formatDataContextValue(a,b.dataContext));a=c?d.fixNewLines(a):d.fixBrakes(a);return a=d.cleanFromEmpty(a)},startSlices:function(){var a;for(a=0;a<this.chartData.length;a++)0<this.startDuration&&this.sequencedAnimation?this.setStartTO(a):this.startSlice(this.chartData[a])},setStartTO:function(a){var b=this;a=setTimeout(function(){b.startSequenced.call(b)},b.startDuration/b.chartData.length*500*a);b.timeOuts.push(a)},pullSlices:function(a){var b=this.chartData, c;for(c=0;c<b.length;c++){var e=b[c];e.pulled&&this.pullSlice(e,1,a)}},startSequenced:function(){var a=this.chartData,b;for(b=0;b<a.length;b++)if(!a[b].started){this.startSlice(this.chartData[b]);break}},startSlice:function(a){a.started=!0;var b=a.wedge,c=this.startDuration,e=a.labelSet;b&&0<c&&(0<a.alpha&&b.show(),b.translate(a.startX,a.startY),b.animate({opacity:1,translate:"0,0"},c,this.startEffect));e&&0<c&&(0<a.alpha&&e.show(),e.translate(a.startX,a.startY),e.animate({opacity:1,translate:"0,0"}, c,this.startEffect))},showLabels:function(){var a=this.chartData,b;for(b=0;b<a.length;b++){var c=a[b];if(0<c.alpha){var e=c.label;e&&e.show();(c=c.tick)&&c.show()}}},showSlice:function(a){isNaN(a)?a.hidden=!1:this.chartData[a].hidden=!1;this.invalidateVisibility()},hideSlice:function(a){isNaN(a)?a.hidden=!0:this.chartData[a].hidden=!0;this.hideBalloon();this.invalidateVisibility()},rollOverSlice:function(a,b,c){isNaN(a)||(a=this.chartData[a]);clearTimeout(this.hoverInt);if(!a.hidden){this.pullOnHover&& this.pullSlice(a,1);1>this.hoverAlpha&&a.wedge&&a.wedge.attr({opacity:this.hoverAlpha});var e=a.balloonX,h=a.balloonY;a.pulled&&(e+=a.pullX,h+=a.pullY);var f=this.formatString(this.balloonText,a,!0),g=this.balloonFunction;g&&(f=g(a,f));g=d.adjustLuminosity(a.color,-.15);f?this.showBalloon(f,g,b,e,h):this.hideBalloon();0===a.value&&this.hideBalloon();a={type:"rollOverSlice",dataItem:a,chart:this,event:c};this.fire(a.type,a)}},rollOutSlice:function(a,b){isNaN(a)||(a=this.chartData[a]);a.wedge&&a.wedge.attr({opacity:1}); this.hideBalloon();var c={type:"rollOutSlice",dataItem:a,chart:this,event:b};this.fire(c.type,c)},clickSlice:function(a,b,c){isNaN(a)||(a=this.chartData[a]);a.pulled?this.pullSlice(a,0):this.pullSlice(a,1);d.getURL(a.url,this.urlTarget);c||(a={type:"clickSlice",dataItem:a,chart:this,event:b},this.fire(a.type,a))},handleRightClick:function(a,b){isNaN(a)||(a=this.chartData[a]);var c={type:"rightClickSlice",dataItem:a,chart:this,event:b};this.fire(c.type,c)},drawTicks:function(){var a=this.chartData, b;for(b=0;b<a.length;b++){var c=a[b];if(c.label&&!c.skipTick){var e=c.ty,e=d.line(this.container,[c.tx0,c.tx,c.tx2],[c.ty0,e,e],this.labelTickColor,this.labelTickAlpha);d.setCN(this,e,this.type+"-tick");d.setCN(this,e,c.className,!0);c.tick=e;c.wedge.push(e)}}},initialStart:function(){var a=this,b=a.startDuration,c=setTimeout(function(){a.showLabels.call(a)},1E3*b);a.timeOuts.push(c);a.chartCreated?a.pullSlices(!0):(a.startSlices(),0<b?(b=setTimeout(function(){a.pullSlices.call(a)},1200*b),a.timeOuts.push(b)): a.pullSlices(!0))},pullSlice:function(a,b,c){var e=this.pullOutDuration;!0===c&&(e=0);if(c=a.wedge)0<e?(c.animate({translate:b*a.pullX+","+b*a.pullY},e,this.pullOutEffect),a.labelSet&&a.labelSet.animate({translate:b*a.pullX+","+b*a.pullY},e,this.pullOutEffect)):(a.labelSet&&a.labelSet.translate(b*a.pullX,b*a.pullY),c.translate(b*a.pullX,b*a.pullY));1==b?(a.pulled=!0,this.pullOutOnlyOne&&this.pullInAll(a.index),a={type:"pullOutSlice",dataItem:a,chart:this}):(a.pulled=!1,a={type:"pullInSlice",dataItem:a, chart:this});this.fire(a.type,a)},pullInAll:function(a){var b=this.chartData,c;for(c=0;c<this.chartData.length;c++)c!=a&&b[c].pulled&&this.pullSlice(b[c],0)},pullOutAll:function(){var a=this.chartData,b;for(b=0;b<a.length;b++)a[b].pulled||this.pullSlice(a[b],1)},parseData:function(){var a=[];this.chartData=a;var b=this.dataProvider;isNaN(this.pieAlpha)||(this.alpha=this.pieAlpha);if(void 0!==b){var c=b.length,e=0,h,f,g;for(h=0;h<c;h++){f={};var k=b[h];f.dataContext=k;null!==k[this.valueField]&&(f.value= Number(k[this.valueField]));(g=k[this.titleField])||(g="");f.title=g;f.pulled=d.toBoolean(k[this.pulledField],!1);(g=k[this.descriptionField])||(g="");f.description=g;f.labelRadius=Number(k[this.labelRadiusField]);f.switchable=!0;f.className=k[this.classNameField];f.url=k[this.urlField];g=k[this.patternField];!g&&this.patterns&&(g=this.patterns[h]);f.pattern=g;f.visibleInLegend=d.toBoolean(k[this.visibleInLegendField],!0);g=k[this.alphaField];f.alpha=void 0!==g?Number(g):this.alpha;g=k[this.colorField]; void 0!==g&&(f.color=g);f.labelColor=d.toColor(k[this.labelColorField]);e+=f.value;f.hidden=!1;a[h]=f}for(h=b=0;h<c;h++)f=a[h],f.percents=f.value/e*100,f.percents<this.groupPercent&&b++;1<b&&(this.groupValue=0,this.removeSmallSlices(),a.push({title:this.groupedTitle,value:this.groupValue,percents:this.groupValue/e*100,pulled:this.groupedPulled,color:this.groupedColor,url:this.groupedUrl,description:this.groupedDescription,alpha:this.groupedAlpha,pattern:this.groupedPattern,className:this.groupedClassName, dataContext:{}}));c=this.baseColor;c||(c=this.pieBaseColor);e=this.brightnessStep;e||(e=this.pieBrightnessStep);for(h=0;h<a.length;h++)c?g=d.adjustLuminosity(c,h*e/100):(g=this.colors[h],void 0===g&&(g=d.randomColor())),void 0===a[h].color&&(a[h].color=g);this.recalculatePercents()}},recalculatePercents:function(){var a=this.chartData,b=0,c,e;for(c=0;c<a.length;c++)e=a[c],!e.hidden&&0<e.value&&(b+=e.value);for(c=0;c<a.length;c++)e=this.chartData[c],e.percents=!e.hidden&&0<e.value?100*e.value/b:0}, removeSmallSlices:function(){var a=this.chartData,b;for(b=a.length-1;0<=b;b--)a[b].percents<this.groupPercent&&(this.groupValue+=a[b].value,a.splice(b,1))},animateAgain:function(){var a=this;a.startSlices();for(var b=0;b<a.chartData.length;b++){var c=a.chartData[b];c.started=!1;var e=c.wedge;e&&e.translate(c.startX,c.startY);(e=c.labelSet)&&e.translate(c.startX,c.startY)}b=a.startDuration;0<b?(b=setTimeout(function(){a.pullSlices.call(a)},1200*b),a.timeOuts.push(b)):a.pullSlices()},measureMaxLabel:function(){var a= this.chartData,b=0,c;for(c=0;c<a.length;c++){var e=a[c],h=this.formatString(this.labelText,e),f=this.labelFunction;f&&(h=f(e,h));e=d.text(this.container,h,this.color,this.fontFamily,this.fontSize);h=e.getBBox().width;h>b&&(b=h);e.remove()}return b}})})();(function(){var d=window.AmCharts;d.AmRectangularChart=d.Class({inherits:d.AmCoordinateChart,construct:function(a){d.AmRectangularChart.base.construct.call(this,a);this.theme=a;this.createEvents("zoomed");this.marginRight=this.marginBottom=this.marginTop=this.marginLeft=20;this.verticalPosition=this.horizontalPosition=this.depth3D=this.angle=0;this.heightMultiplier=this.widthMultiplier=1;this.plotAreaFillColors="#FFFFFF";this.plotAreaFillAlphas=0;this.plotAreaBorderColor="#000000";this.plotAreaBorderAlpha= 0;this.zoomOutButtonImageSize=19;this.zoomOutButtonImage="lens.png";this.zoomOutText="Show all";this.zoomOutButtonColor="#e5e5e5";this.zoomOutButtonAlpha=0;this.zoomOutButtonRollOverAlpha=1;this.zoomOutButtonPadding=8;this.trendLines=[];this.autoMargins=!0;this.marginsUpdated=!1;this.autoMarginOffset=10;d.applyTheme(this,a,"AmRectangularChart")},initChart:function(){d.AmRectangularChart.base.initChart.call(this);this.updateDxy();var a=!0;!this.marginsUpdated&&this.autoMargins&&(this.resetMargins(), a=!1);this.processScrollbars();this.updateMargins();this.updatePlotArea();this.updateScrollbars();this.updateTrendLines();this.updateChartCursor();this.updateValueAxes();a&&(this.scrollbarOnly||this.updateGraphs())},drawChart:function(){d.AmRectangularChart.base.drawChart.call(this);this.drawPlotArea();if(d.ifArray(this.chartData)){var a=this.chartCursor;a&&a.draw()}},resetMargins:function(){var a={},b;if("xy"==this.type){var c=this.xAxes,e=this.yAxes;for(b=0;b<c.length;b++){var d=c[b];d.ignoreAxisWidth|| (d.setOrientation(!0),d.fixAxisPosition(),a[d.position]=!0)}for(b=0;b<e.length;b++)c=e[b],c.ignoreAxisWidth||(c.setOrientation(!1),c.fixAxisPosition(),a[c.position]=!0)}else{e=this.valueAxes;for(b=0;b<e.length;b++)c=e[b],c.ignoreAxisWidth||(c.setOrientation(this.rotate),c.fixAxisPosition(),a[c.position]=!0);(b=this.categoryAxis)&&!b.ignoreAxisWidth&&(b.setOrientation(!this.rotate),b.fixAxisPosition(),b.fixAxisPosition(),a[b.position]=!0)}a.left&&(this.marginLeft=0);a.right&&(this.marginRight=0);a.top&& (this.marginTop=0);a.bottom&&(this.marginBottom=0);this.fixMargins=a},measureMargins:function(){var a=this.valueAxes,b,c=this.autoMarginOffset,e=this.fixMargins,d=this.realWidth,f=this.realHeight,g=c,k=c,l=d;b=f;var m;for(m=0;m<a.length;m++)a[m].handleSynchronization(),b=this.getAxisBounds(a[m],g,l,k,b),g=Math.round(b.l),l=Math.round(b.r),k=Math.round(b.t),b=Math.round(b.b);if(a=this.categoryAxis)b=this.getAxisBounds(a,g,l,k,b),g=Math.round(b.l),l=Math.round(b.r),k=Math.round(b.t),b=Math.round(b.b); e.left&&g<c&&(this.marginLeft=Math.round(-g+c));e.right&&l>=d-c&&(this.marginRight=Math.round(l-d+c));e.top&&k<c+this.titleHeight&&(this.marginTop=Math.round(this.marginTop-k+c+this.titleHeight));e.bottom&&b>f-c&&(this.marginBottom=Math.round(this.marginBottom+b-f+c));this.initChart()},getAxisBounds:function(a,b,c,e,d){if(!a.ignoreAxisWidth){var f=a.labelsSet,g=a.tickLength;a.inside&&(g=0);if(f)switch(f=a.getBBox(),a.position){case "top":a=f.y;e>a&&(e=a);break;case "bottom":a=f.y+f.height;d<a&&(d= a);break;case "right":a=f.x+f.width+g+3;c<a&&(c=a);break;case "left":a=f.x-g,b>a&&(b=a)}}return{l:b,t:e,r:c,b:d}},drawZoomOutButton:function(){var a=this;if(!a.zbSet){var b=a.container.set();a.zoomButtonSet.push(b);var c=a.color,e=a.fontSize,h=a.zoomOutButtonImageSize,f=a.zoomOutButtonImage,g=d.lang.zoomOutText||a.zoomOutText,k=a.zoomOutButtonColor,l=a.zoomOutButtonAlpha,m=a.zoomOutButtonFontSize,n=a.zoomOutButtonPadding;isNaN(m)||(e=m);(m=a.zoomOutButtonFontColor)&&(c=m);var m=a.zoomOutButton,p; m&&(m.fontSize&&(e=m.fontSize),m.color&&(c=m.color),m.backgroundColor&&(k=m.backgroundColor),isNaN(m.backgroundAlpha)||(a.zoomOutButtonRollOverAlpha=m.backgroundAlpha));var q=m=0;void 0!==a.pathToImages&&f&&(p=a.container.image(a.pathToImages+f,0,0,h,h),d.setCN(a,p,"zoom-out-image"),b.push(p),p=p.getBBox(),m=p.width+5);void 0!==g&&(c=d.text(a.container,g,c,a.fontFamily,e,"start"),d.setCN(a,c,"zoom-out-label"),e=c.getBBox(),q=p?p.height/2-3:e.height/2,c.translate(m,q),b.push(c));p=b.getBBox();c=1; d.isModern||(c=0);k=d.rect(a.container,p.width+2*n+5,p.height+2*n-2,k,1,1,k,c);k.setAttr("opacity",l);k.translate(-n,-n);d.setCN(a,k,"zoom-out-bg");b.push(k);k.toBack();a.zbBG=k;p=k.getBBox();b.translate(a.marginLeftReal+a.plotAreaWidth-p.width+n,a.marginTopReal+n);b.hide();b.mouseover(function(){a.rollOverZB()}).mouseout(function(){a.rollOutZB()}).click(function(){a.clickZB()}).touchstart(function(){a.rollOverZB()}).touchend(function(){a.rollOutZB();a.clickZB()});for(l=0;l<b.length;l++)b[l].attr({cursor:"pointer"}); a.zbSet=b}},rollOverZB:function(){this.zbBG.setAttr("opacity",this.zoomOutButtonRollOverAlpha)},rollOutZB:function(){this.zbBG.setAttr("opacity",this.zoomOutButtonAlpha)},clickZB:function(){this.zoomOut()},zoomOut:function(){this.updateScrollbar=!0;this.zoom()},drawPlotArea:function(){var a=this.dx,b=this.dy,c=this.marginLeftReal,e=this.marginTopReal,h=this.plotAreaWidth-1,f=this.plotAreaHeight-1,g=this.plotAreaFillColors,k=this.plotAreaFillAlphas,l=this.plotAreaBorderColor,m=this.plotAreaBorderAlpha; "object"==typeof k&&(k=k[0]);g=d.polygon(this.container,[0,h,h,0,0],[0,0,f,f,0],g,k,1,l,m,this.plotAreaGradientAngle);d.setCN(this,g,"plot-area");g.translate(c+a,e+b);this.set.push(g);0!==a&&0!==b&&(g=this.plotAreaFillColors,"object"==typeof g&&(g=g[0]),g=d.adjustLuminosity(g,-.15),h=d.polygon(this.container,[0,a,h+a,h,0],[0,b,b,0,0],g,k,1,l,m),d.setCN(this,h,"plot-area-bottom"),h.translate(c,e+f),this.set.push(h),a=d.polygon(this.container,[0,0,a,a,0],[0,f,f+b,b,0],g,k,1,l,m),d.setCN(this,a,"plot-area-left"), a.translate(c,e),this.set.push(a));(c=this.bbset)&&this.scrollbarOnly&&c.remove()},updatePlotArea:function(){var a=this.updateWidth(),b=this.updateHeight(),c=this.container;this.realWidth=a;this.realWidth=b;c&&this.container.setSize(a,b);a=a-this.marginLeftReal-this.marginRightReal-this.dx;b=b-this.marginTopReal-this.marginBottomReal;1>a&&(a=1);1>b&&(b=1);this.plotAreaWidth=Math.round(a);this.plotAreaHeight=Math.round(b)},updateDxy:function(){this.dx=Math.round(this.depth3D*Math.cos(this.angle*Math.PI/ 180));this.dy=Math.round(-this.depth3D*Math.sin(this.angle*Math.PI/180));this.d3x=Math.round(this.columnSpacing3D*Math.cos(this.angle*Math.PI/180));this.d3y=Math.round(-this.columnSpacing3D*Math.sin(this.angle*Math.PI/180))},updateMargins:function(){var a=this.getTitleHeight();this.titleHeight=a;this.marginTopReal=this.marginTop-this.dy;this.fixMargins&&!this.fixMargins.top&&(this.marginTopReal+=a);this.marginBottomReal=this.marginBottom;this.marginLeftReal=this.marginLeft;this.marginRightReal=this.marginRight}, updateValueAxes:function(){var a=this.valueAxes,b=this.marginLeftReal,c=this.marginTopReal,e=this.plotAreaHeight,h=this.plotAreaWidth,f;for(f=0;f<a.length;f++){var g=a[f];g.axisRenderer=d.RecAxis;g.guideFillRenderer=d.RecFill;g.axisItemRenderer=d.RecItem;g.dx=this.dx;g.dy=this.dy;g.viW=h-1;g.viH=e-1;g.marginsChanged=!0;g.viX=b;g.viY=c;this.updateObjectSize(g)}},updateObjectSize:function(a){a.width=(this.plotAreaWidth-1)*this.widthMultiplier;a.height=(this.plotAreaHeight-1)*this.heightMultiplier;a.x= this.marginLeftReal+this.horizontalPosition;a.y=this.marginTopReal+this.verticalPosition},updateGraphs:function(){var a=this.graphs,b;for(b=0;b<a.length;b++){var c=a[b];c.x=this.marginLeftReal+this.horizontalPosition;c.y=this.marginTopReal+this.verticalPosition;c.width=this.plotAreaWidth*this.widthMultiplier;c.height=this.plotAreaHeight*this.heightMultiplier;c.index=b;c.dx=this.dx;c.dy=this.dy;c.rotate=this.rotate}},updateChartCursor:function(){var a=this.chartCursor;a&&(a=d.processObject(a,d.ChartCursor, this.theme),this.addChartCursor(a),a.x=this.marginLeftReal,a.y=this.marginTopReal,a.width=this.plotAreaWidth-1,a.height=this.plotAreaHeight-1,a.chart=this)},processScrollbars:function(){var a=this.chartScrollbar;a&&(a=d.processObject(a,d.ChartScrollbar,this.theme),this.addChartScrollbar(a))},updateScrollbars:function(){},addChartCursor:function(a){d.callMethod("destroy",[this.chartCursor]);a&&(this.listenTo(a,"changed",this.handleCursorChange),this.listenTo(a,"zoomed",this.handleCursorZoom));this.chartCursor= a},removeChartCursor:function(){d.callMethod("destroy",[this.chartCursor]);this.chartCursor=null},zoomTrendLines:function(){var a=this.trendLines,b;for(b=0;b<a.length;b++){var c=a[b];c.valueAxis.recalculateToPercents?c.set&&c.set.hide():(c.x=this.marginLeftReal+this.horizontalPosition,c.y=this.marginTopReal+this.verticalPosition,c.draw())}},addTrendLine:function(a){this.trendLines.push(a)},removeTrendLine:function(a){var b=this.trendLines,c;for(c=b.length-1;0<=c;c--)b[c]==a&&b.splice(c,1)},adjustMargins:function(a, b){var c=a.position,e=a.scrollbarHeight+a.offset;a.enabled&&("top"==c?b?this.marginLeftReal+=e:this.marginTopReal+=e:b?this.marginRightReal+=e:this.marginBottomReal+=e)},getScrollbarPosition:function(a,b,c){var e="bottom",d="top";a.oppositeAxis||(d=e,e="top");a.position=b?"bottom"==c||"left"==c?e:d:"top"==c||"right"==c?e:d},updateChartScrollbar:function(a,b){if(a){a.rotate=b;var c=this.marginTopReal,e=this.marginLeftReal,d=a.scrollbarHeight,f=this.dx,g=this.dy,k=a.offset;"top"==a.position?b?(a.y= c,a.x=e-d-k):(a.y=c-d+g-k,a.x=e+f):b?(a.y=c+g,a.x=e+this.plotAreaWidth+f+k):(a.y=c+this.plotAreaHeight+k,a.x=this.marginLeftReal)}},showZB:function(a){var b=this.zbSet;a&&(b=this.zoomOutText,""!==b&&b&&this.drawZoomOutButton());if(b=this.zbSet)this.zoomButtonSet.push(b),a?b.show():b.hide(),this.rollOutZB()},handleReleaseOutside:function(a){d.AmRectangularChart.base.handleReleaseOutside.call(this,a);(a=this.chartCursor)&&a.handleReleaseOutside&&a.handleReleaseOutside()},handleMouseDown:function(a){d.AmRectangularChart.base.handleMouseDown.call(this, a);var b=this.chartCursor;b&&b.handleMouseDown&&b.handleMouseDown(a)},handleCursorChange:function(){},update:function(){d.AmRectangularChart.base.update.call(this);this.chartCursor&&this.chartCursor.update&&this.chartCursor.update()}})})();(function(){var d=window.AmCharts;d.TrendLine=d.Class({construct:function(a){this.cname="TrendLine";this.createEvents("click");this.isProtected=!1;this.dashLength=0;this.lineColor="#00CC00";this.lineThickness=this.lineAlpha=1;d.applyTheme(this,a,this.cname)},draw:function(){var a=this;a.destroy();var b=a.chart,c=b.container,e,h,f,g,k=a.categoryAxis,l=a.initialDate,m=a.initialCategory,n=a.finalDate,p=a.finalCategory,q=a.valueAxis,r=a.valueAxisX,u=a.initialXValue,t=a.finalXValue,z=a.initialValue,y= a.finalValue,v=q.recalculateToPercents,w=b.dataDateFormat;k&&(l&&(l=d.getDate(l,w,"fff"),a.initialDate=l,e=k.dateToCoordinate(l)),m&&(e=k.categoryToCoordinate(m)),n&&(n=d.getDate(n,w,"fff"),a.finalDate=n,h=k.dateToCoordinate(n)),p&&(h=k.categoryToCoordinate(p)));r&&!v&&(isNaN(u)||(e=r.getCoordinate(u)),isNaN(t)||(h=r.getCoordinate(t)));q&&!v&&(isNaN(z)||(f=q.getCoordinate(z)),isNaN(y)||(g=q.getCoordinate(y)));if(!(isNaN(e)||isNaN(h)||isNaN(f)||isNaN(f))){b.rotate?(k=[f,g],g=[e,h]):(k=[e,h],g=[f,g]); l=a.lineColor;f=d.line(c,k,g,l,a.lineAlpha,a.lineThickness,a.dashLength);e=k;h=g;p=k[1]-k[0];q=g[1]-g[0];0===p&&(p=.01);0===q&&(q=.01);m=p/Math.abs(p);n=q/Math.abs(q);q=p*q/Math.abs(p*q)*Math.sqrt(Math.pow(p,2)+Math.pow(q,2));p=Math.asin(p/q);q=90*Math.PI/180-p;p=Math.abs(5*Math.cos(q));q=Math.abs(5*Math.sin(q));e.push(k[1]-m*q,k[0]-m*q);h.push(g[1]+n*p,g[0]+n*p);k=d.polygon(c,e,h,l,.005,0);c=c.set([k,f]);c.translate(b.marginLeftReal,b.marginTopReal);b.trendLinesSet.push(c);d.setCN(b,f,"trend-line"); d.setCN(b,f,"trend-line-"+a.id);a.line=f;a.set=c;if(f=a.initialImage)f=d.processObject(f,d.Image,a.theme),f.chart=b,f.draw(),f.translate(e[0]+f.offsetX,h[0]+f.offsetY),c.push(f.set);if(f=a.finalImage)f=d.processObject(f,d.Image,a.theme),f.chart=b,f.draw(),f.translate(e[1]+f.offsetX,h[1]+f.offsetY),c.push(f.set);k.mouseup(function(){a.handleLineClick()}).mouseover(function(){a.handleLineOver()}).mouseout(function(){a.handleLineOut()});k.touchend&&k.touchend(function(){a.handleLineClick()});c.clipRect(0, 0,b.plotAreaWidth,b.plotAreaHeight)}},handleLineClick:function(){var a={type:"click",trendLine:this,chart:this.chart};this.fire(a.type,a)},handleLineOver:function(){var a=this.rollOverColor;void 0!==a&&this.line.attr({stroke:a})},handleLineOut:function(){this.line.attr({stroke:this.lineColor})},destroy:function(){d.remove(this.set)}})})();(function(){var d=window.AmCharts;d.Image=d.Class({construct:function(a){this.cname="Image";this.height=this.width=20;this.rotation=this.offsetY=this.offsetX=0;this.balloonColor=this.color="#000000";this.opacity=1;d.applyTheme(this,a,this.cname)},draw:function(){var a=this;a.set&&a.set.remove();var b=a.chart.container;a.set=b.set();var c,e;a.url?(c=b.image(a.url,0,0,a.width,a.height),e=1):a.svgPath&&(c=b.path(a.svgPath),c.setAttr("fill",a.color),c.setAttr("stroke",a.outlineColor),b=c.getBBox(),e= Math.min(a.width/b.width,a.height/b.height));c&&(c.setAttr("opacity",a.opacity),a.set.rotate(a.rotation),c.translate(-a.width/2,-a.height/2,e),a.balloonText&&c.mouseover(function(b){a.chart.showBalloon(a.balloonText,a.balloonColor,!0)}).mouseout(function(b){a.chart.hideBalloon()}).touchend(function(b){a.chart.hideBalloon()}).touchstart(function(b){a.chart.showBalloon(a.balloonText,a.balloonColor,!0)}),a.set.push(c))},translate:function(a,b){this.set&&this.set.translate(a,b)}})})();(function(){var d=window.AmCharts;d.circle=function(a,b,c,e,h,f,g,k,l){0>=b&&(b=.001);if(void 0==h||0===h)h=.01;void 0===f&&(f="#000000");void 0===g&&(g=0);e={fill:c,stroke:f,"fill-opacity":e,"stroke-width":h,"stroke-opacity":g};a=isNaN(l)?a.circle(0,0,b).attr(e):a.ellipse(0,0,b,l).attr(e);k&&a.gradient("radialGradient",[c,d.adjustLuminosity(c,-.6)]);return a};d.text=function(a,b,c,e,h,f,g,k){f||(f="middle");"right"==f&&(f="end");"left"==f&&(f="start");isNaN(k)&&(k=1);void 0!==b&&(b=String(b),d.isIE&& !d.isModern&&(b=b.replace("&amp;","&"),b=b.replace("&","&amp;")));c={fill:c,"font-family":e,"font-size":h,opacity:k};!0===g&&(c["font-weight"]="bold");c["text-anchor"]=f;return a.text(b,c)};d.polygon=function(a,b,c,e,h,f,g,k,l,m,n){isNaN(f)&&(f=.01);isNaN(k)&&(k=h);var p=e,q=!1;"object"==typeof p&&1<p.length&&(q=!0,p=p[0]);void 0===g&&(g=p);h={fill:p,stroke:g,"fill-opacity":h,"stroke-width":f,"stroke-opacity":k};void 0!==n&&0<n&&(h["stroke-dasharray"]=n);n=d.dx;f=d.dy;a.handDrawn&&(c=d.makeHD(b,c, a.handDrawScatter),b=c[0],c=c[1]);g=Math.round;m&&(g=d.doNothing);m="M"+(g(b[0])+n)+","+(g(c[0])+f);for(k=1;k<b.length;k++)m+=" L"+(g(b[k])+n)+","+(g(c[k])+f);a=a.path(m+" Z").attr(h);q&&a.gradient("linearGradient",e,l);return a};d.rect=function(a,b,c,e,h,f,g,k,l,m,n){if(isNaN(b)||isNaN(c))return a.set();isNaN(f)&&(f=0);void 0===l&&(l=0);void 0===m&&(m=270);isNaN(h)&&(h=0);var p=e,q=!1;"object"==typeof p&&(p=p[0],q=!0);void 0===g&&(g=p);void 0===k&&(k=h);b=Math.round(b);c=Math.round(c);var r=0,u= 0;0>b&&(b=Math.abs(b),r=-b);0>c&&(c=Math.abs(c),u=-c);r+=d.dx;u+=d.dy;h={fill:p,stroke:g,"fill-opacity":h,"stroke-opacity":k};void 0!==n&&0<n&&(h["stroke-dasharray"]=n);a=a.rect(r,u,b,c,l,f).attr(h);q&&a.gradient("linearGradient",e,m);return a};d.bullet=function(a,b,c,e,h,f,g,k,l,m,n,p){var q;"circle"==b&&(b="round");switch(b){case "round":q=d.circle(a,c/2,e,h,f,g,k);break;case "square":q=d.polygon(a,[-c/2,c/2,c/2,-c/2],[c/2,c/2,-c/2,-c/2],e,h,f,g,k,m-180);break;case "rectangle":q=d.polygon(a,[-c, c,c,-c],[c/2,c/2,-c/2,-c/2],e,h,f,g,k,m-180);break;case "diamond":q=d.polygon(a,[-c/2,0,c/2,0],[0,-c/2,0,c/2],e,h,f,g,k);break;case "triangleUp":q=d.triangle(a,c,0,e,h,f,g,k);break;case "triangleDown":q=d.triangle(a,c,180,e,h,f,g,k);break;case "triangleLeft":q=d.triangle(a,c,270,e,h,f,g,k);break;case "triangleRight":q=d.triangle(a,c,90,e,h,f,g,k);break;case "bubble":q=d.circle(a,c/2,e,h,f,g,k,!0);break;case "line":q=d.line(a,[-c/2,c/2],[0,0],e,h,f,g,k);break;case "yError":q=a.set();q.push(d.line(a, [0,0],[-c/2,c/2],e,h,f));q.push(d.line(a,[-l,l],[-c/2,-c/2],e,h,f));q.push(d.line(a,[-l,l],[c/2,c/2],e,h,f));break;case "xError":q=a.set(),q.push(d.line(a,[-c/2,c/2],[0,0],e,h,f)),q.push(d.line(a,[-c/2,-c/2],[-l,l],e,h,f)),q.push(d.line(a,[c/2,c/2],[-l,l],e,h,f))}q&&q.pattern(n,NaN,p);return q};d.triangle=function(a,b,c,e,d,f,g,k){if(void 0===f||0===f)f=1;void 0===g&&(g="#000");void 0===k&&(k=0);e={fill:e,stroke:g,"fill-opacity":d,"stroke-width":f,"stroke-opacity":k};b/=2;var l;0===c&&(l=" M"+-b+ ","+b+" L0,"+-b+" L"+b+","+b+" Z");180==c&&(l=" M"+-b+","+-b+" L0,"+b+" L"+b+","+-b+" Z");90==c&&(l=" M"+-b+","+-b+" L"+b+",0 L"+-b+","+b+" Z");270==c&&(l=" M"+-b+",0 L"+b+","+b+" L"+b+","+-b+" Z");return a.path(l).attr(e)};d.line=function(a,b,c,e,h,f,g,k,l,m,n){if(a.handDrawn&&!n)return d.handDrawnLine(a,b,c,e,h,f,g,k,l,m,n);f={fill:"none","stroke-width":f};void 0!==g&&0<g&&(f["stroke-dasharray"]=g);isNaN(h)||(f["stroke-opacity"]=h);e&&(f.stroke=e);e=Math.round;m&&(e=d.doNothing);m=d.dx;h=d.dy;g= "M"+(e(b[0])+m)+","+(e(c[0])+h);for(k=1;k<b.length;k++)g+=" L"+(e(b[k])+m)+","+(e(c[k])+h);if(d.VML)return a.path(g,void 0,!0).attr(f);l&&(g+=" M0,0 L0,0");return a.path(g).attr(f)};d.makeHD=function(a,b,c){for(var e=[],d=[],f=1;f<a.length;f++)for(var g=Number(a[f-1]),k=Number(b[f-1]),l=Number(a[f]),m=Number(b[f]),n=Math.sqrt(Math.pow(l-g,2)+Math.pow(m-k,2)),n=Math.round(n/50)+1,l=(l-g)/n,m=(m-k)/n,p=0;p<=n;p++){var q=g+p*l+Math.random()*c,r=k+p*m+Math.random()*c;e.push(q);d.push(r)}return[e,d]}; d.handDrawnLine=function(a,b,c,e,h,f,g,k,l,m){var n,p=a.set();for(n=1;n<b.length;n++)for(var q=[b[n-1],b[n]],r=[c[n-1],c[n]],r=d.makeHD(q,r,a.handDrawScatter),q=r[0],r=r[1],u=1;u<q.length;u++)p.push(d.line(a,[q[u-1],q[u]],[r[u-1],r[u]],e,h,f+Math.random()*a.handDrawThickness-a.handDrawThickness/2,g,k,l,m,!0));return p};d.doNothing=function(a){return a};d.wedge=function(a,b,c,e,h,f,g,k,l,m,n,p,q){var r=Math.round;f=r(f);g=r(g);k=r(k);var u=r(g/f*k),t=d.VML,z=359.5+f/100;359.94<z&&(z=359.94);h>=z&& (h=z);var y=1/180*Math.PI,z=b+Math.sin(e*y)*k,v=c-Math.cos(e*y)*u,w=b+Math.sin(e*y)*f,A=c-Math.cos(e*y)*g,B=b+Math.sin((e+h)*y)*f,C=c-Math.cos((e+h)*y)*g,D=b+Math.sin((e+h)*y)*k,y=c-Math.cos((e+h)*y)*u,J={fill:d.adjustLuminosity(m.fill,-.2),"stroke-opacity":0,"fill-opacity":m["fill-opacity"]},E=0;180<Math.abs(h)&&(E=1);e=a.set();var O;t&&(z=r(10*z),w=r(10*w),B=r(10*B),D=r(10*D),v=r(10*v),A=r(10*A),C=r(10*C),y=r(10*y),b=r(10*b),l=r(10*l),c=r(10*c),f*=10,g*=10,k*=10,u*=10,1>Math.abs(h)&&1>=Math.abs(B- w)&&1>=Math.abs(C-A)&&(O=!0));h="";var I;p&&(J["fill-opacity"]=0,J["stroke-opacity"]=m["stroke-opacity"]/2,J.stroke=m.stroke);if(0<l){I=" M"+z+","+(v+l)+" L"+w+","+(A+l);t?(O||(I+=" A"+(b-f)+","+(l+c-g)+","+(b+f)+","+(l+c+g)+","+w+","+(A+l)+","+B+","+(C+l)),I+=" L"+D+","+(y+l),0<k&&(O||(I+=" B"+(b-k)+","+(l+c-u)+","+(b+k)+","+(l+c+u)+","+D+","+(l+y)+","+z+","+(l+v)))):(I+=" A"+f+","+g+",0,"+E+",1,"+B+","+(C+l)+" L"+D+","+(y+l),0<k&&(I+=" A"+k+","+u+",0,"+E+",0,"+z+","+(v+l)));I+=" Z";var W=l;t&&(W/= 10);for(var ea=0;ea<W;ea+=10){var P=a.path(I,void 0,void 0,"1000,1000").attr(J);e.push(P);P.translate(0,-ea)}I=a.path(" M"+z+","+v+" L"+z+","+(v+l)+" L"+w+","+(A+l)+" L"+w+","+A+" L"+z+","+v+" Z",void 0,void 0,"1000,1000").attr(J);l=a.path(" M"+B+","+C+" L"+B+","+(C+l)+" L"+D+","+(y+l)+" L"+D+","+y+" L"+B+","+C+" Z",void 0,void 0,"1000,1000").attr(J);e.push(I);e.push(l)}t?(O||(h=" A"+r(b-f)+","+r(c-g)+","+r(b+f)+","+r(c+g)+","+r(w)+","+r(A)+","+r(B)+","+r(C)),f=" M"+r(z)+","+r(v)+" L"+r(w)+","+r(A)+ h+" L"+r(D)+","+r(y)):f=" M"+z+","+v+" L"+w+","+A+(" A"+f+","+g+",0,"+E+",1,"+B+","+C)+" L"+D+","+y;0<k&&(t?O||(f+=" B"+(b-k)+","+(c-u)+","+(b+k)+","+(c+u)+","+D+","+y+","+z+","+v):f+=" A"+k+","+u+",0,"+E+",0,"+z+","+v);a.handDrawn&&(b=d.line(a,[z,w],[v,A],m.stroke,m.thickness*Math.random()*a.handDrawThickness,m["stroke-opacity"]),e.push(b));a=a.path(f+" Z",void 0,void 0,"1000,1000").attr(m);if(n){b=[];for(c=0;c<n.length;c++)b.push(d.adjustLuminosity(m.fill,n[c]));0<b.length&&a.gradient("linearGradient", b)}a.pattern(p,NaN,q);e.wedge=a;e.push(a);return e};d.adjustLuminosity=function(a,b){a=String(a).replace(/[^0-9a-f]/gi,"");6>a.length&&(a=String(a[0])+String(a[0])+String(a[1])+String(a[1])+String(a[2])+String(a[2]));b=b||0;var c="#",e,d;for(d=0;3>d;d++)e=parseInt(a.substr(2*d,2),16),e=Math.round(Math.min(Math.max(0,e+e*b),255)).toString(16),c+=("00"+e).substr(e.length);return c}})();(function(){var d=window.AmCharts;d.Bezier=d.Class({construct:function(a,b,c,e,h,f,g,k,l,m){"object"==typeof g&&(g=g[0]);"object"==typeof k&&(k=k[0]);0===k&&(g="none");f={fill:g,"fill-opacity":k,"stroke-width":f};void 0!==l&&0<l&&(f["stroke-dasharray"]=l);isNaN(h)||(f["stroke-opacity"]=h);e&&(f.stroke=e);e="M"+Math.round(b[0])+","+Math.round(c[0]);h=[];for(l=0;l<b.length;l++)h.push({x:Number(b[l]),y:Number(c[l])});1<h.length&&(b=this.interpolate(h),e+=this.drawBeziers(b));m?e+=m:d.VML||(e+="M0,0 L0,0"); this.path=a.path(e).attr(f);this.node=this.path.node},interpolate:function(a){var b=[];b.push({x:a[0].x,y:a[0].y});var c=a[1].x-a[0].x,e=a[1].y-a[0].y,h=d.bezierX,f=d.bezierY;b.push({x:a[0].x+c/h,y:a[0].y+e/f});var g;for(g=1;g<a.length-1;g++){var k=a[g-1],l=a[g],e=a[g+1];isNaN(e.x)&&(e=l);isNaN(l.x)&&(l=k);isNaN(k.x)&&(k=l);c=e.x-l.x;e=e.y-k.y;k=l.x-k.x;k>c&&(k=c);b.push({x:l.x-k/h,y:l.y-e/f});b.push({x:l.x,y:l.y});b.push({x:l.x+k/h,y:l.y+e/f})}e=a[a.length-1].y-a[a.length-2].y;c=a[a.length-1].x- a[a.length-2].x;b.push({x:a[a.length-1].x-c/h,y:a[a.length-1].y-e/f});b.push({x:a[a.length-1].x,y:a[a.length-1].y});return b},drawBeziers:function(a){var b="",c;for(c=0;c<(a.length-1)/3;c++)b+=this.drawBezierMidpoint(a[3*c],a[3*c+1],a[3*c+2],a[3*c+3]);return b},drawBezierMidpoint:function(a,b,c,e){var d=Math.round,f=this.getPointOnSegment(a,b,.75),g=this.getPointOnSegment(e,c,.75),k=(e.x-a.x)/16,l=(e.y-a.y)/16,m=this.getPointOnSegment(a,b,.375);a=this.getPointOnSegment(f,g,.375);a.x-=k;a.y-=l;b=this.getPointOnSegment(g, f,.375);b.x+=k;b.y+=l;c=this.getPointOnSegment(e,c,.375);k=this.getMiddle(m,a);f=this.getMiddle(f,g);g=this.getMiddle(b,c);m=" Q"+d(m.x)+","+d(m.y)+","+d(k.x)+","+d(k.y);m+=" Q"+d(a.x)+","+d(a.y)+","+d(f.x)+","+d(f.y);m+=" Q"+d(b.x)+","+d(b.y)+","+d(g.x)+","+d(g.y);return m+=" Q"+d(c.x)+","+d(c.y)+","+d(e.x)+","+d(e.y)},getMiddle:function(a,b){return{x:(a.x+b.x)/2,y:(a.y+b.y)/2}},getPointOnSegment:function(a,b,c){return{x:a.x+(b.x-a.x)*c,y:a.y+(b.y-a.y)*c}}})})();(function(){var d=window.AmCharts;d.AmDraw=d.Class({construct:function(a,b,c,e){d.SVG_NS="http://www.w3.org/2000/svg";d.SVG_XLINK="http://www.w3.org/1999/xlink";d.hasSVG=!!document.createElementNS&&!!document.createElementNS(d.SVG_NS,"svg").createSVGRect;1>b&&(b=10);1>c&&(c=10);this.div=a;this.width=b;this.height=c;this.rBin=document.createElement("div");d.hasSVG?(d.SVG=!0,b=this.createSvgElement("svg"),a.appendChild(b),this.container=b,this.addDefs(e),this.R=new d.SVGRenderer(this)):d.isIE&&d.VMLRenderer&& (d.VML=!0,d.vmlStyleSheet||(document.namespaces.add("amvml","urn:schemas-microsoft-com:vml"),31>document.styleSheets.length?(b=document.createStyleSheet(),b.addRule(".amvml","behavior:url(#default#VML); display:inline-block; antialias:true"),d.vmlStyleSheet=b):document.styleSheets[0].addRule(".amvml","behavior:url(#default#VML); display:inline-block; antialias:true")),this.container=a,this.R=new d.VMLRenderer(this,e),this.R.disableSelection(a))},createSvgElement:function(a){return document.createElementNS(d.SVG_NS, a)},circle:function(a,b,c,e){var h=new d.AmDObject("circle",this);h.attr({r:c,cx:a,cy:b});this.addToContainer(h.node,e);return h},ellipse:function(a,b,c,e,h){var f=new d.AmDObject("ellipse",this);f.attr({rx:c,ry:e,cx:a,cy:b});this.addToContainer(f.node,h);return f},setSize:function(a,b){0<a&&0<b&&(this.container.style.width=a+"px",this.container.style.height=b+"px")},rect:function(a,b,c,e,h,f,g){var k=new d.AmDObject("rect",this);d.VML&&(h=Math.round(100*h/Math.min(c,e)),c+=2*f,e+=2*f,k.bw=f,k.node.style.marginLeft= -f,k.node.style.marginTop=-f);1>c&&(c=1);1>e&&(e=1);k.attr({x:a,y:b,width:c,height:e,rx:h,ry:h,"stroke-width":f});this.addToContainer(k.node,g);return k},image:function(a,b,c,e,h,f){var g=new d.AmDObject("image",this);g.attr({x:b,y:c,width:e,height:h});this.R.path(g,a);this.addToContainer(g.node,f);return g},addToContainer:function(a,b){b||(b=this.container);b.appendChild(a)},text:function(a,b,c){return this.R.text(a,b,c)},path:function(a,b,c,e){var h=new d.AmDObject("path",this);e||(e="100,100"); h.attr({cs:e});c?h.attr({dd:a}):h.attr({d:a});this.addToContainer(h.node,b);return h},set:function(a){return this.R.set(a)},remove:function(a){if(a){var b=this.rBin;b.appendChild(a);b.innerHTML=""}},renderFix:function(){var a=this.container,b=a.style;b.top="0px";b.left="0px";var c=a.getBoundingClientRect(),a=c.left-Math.round(c.left),c=c.top-Math.round(c.top);a&&(b.left=a+"px");c&&(b.top=c+"px")},update:function(){this.R.update()},addDefs:function(a){if(d.hasSVG){var b=this.createSvgElement("desc"), c=this.container;c.setAttribute("version","1.1");c.style.position="absolute";this.setSize(this.width,this.height);d.rtl&&(c.setAttribute("direction","rtl"),c.style.left="auto",c.style.right="0px");a.addCodeCredits&&b.appendChild(document.createTextNode("JavaScript chart by amCharts "+a.version));c.appendChild(b);a.defs&&(b=this.createSvgElement("defs"),c.appendChild(b),d.parseDefs(a.defs,b),this.defs=b)}}})})();(function(){var d=window.AmCharts;d.AmDObject=d.Class({construct:function(a,b){this.D=b;this.R=b.R;this.node=this.R.create(this,a);this.y=this.x=0;this.scale=1},attr:function(a){this.R.attr(this,a);return this},getAttr:function(a){return this.node.getAttribute(a)},setAttr:function(a,b){this.R.setAttr(this,a,b);return this},clipRect:function(a,b,c,d){this.R.clipRect(this,a,b,c,d)},translate:function(a,b,c,d){d||(a=Math.round(a),b=Math.round(b));this.R.move(this,a,b,c);this.x=a;this.y=b;this.scale= c;this.angle&&this.rotate(this.angle)},rotate:function(a,b){this.R.rotate(this,a,b);this.angle=a},animate:function(a,b,c){for(var e in a)if(a.hasOwnProperty(e)){var h=e,f=a[e];c=d.getEffect(c);this.R.animate(this,h,f,b,c)}},push:function(a){if(a){var b=this.node;b.appendChild(a.node);var c=a.clipPath;c&&b.appendChild(c);(a=a.grad)&&b.appendChild(a)}},text:function(a){this.R.setText(this,a)},remove:function(){this.R.remove(this)},clear:function(){var a=this.node;if(a.hasChildNodes())for(;1<=a.childNodes.length;)a.removeChild(a.firstChild)}, hide:function(){this.setAttr("visibility","hidden")},show:function(){this.setAttr("visibility","visible")},getBBox:function(){return this.R.getBBox(this)},toFront:function(){var a=this.node;if(a){this.prevNextNode=a.nextSibling;var b=a.parentNode;b&&b.appendChild(a)}},toPrevious:function(){var a=this.node;a&&this.prevNextNode&&(a=a.parentNode)&&a.insertBefore(this.prevNextNode,null)},toBack:function(){var a=this.node;if(a){this.prevNextNode=a.nextSibling;var b=a.parentNode;if(b){var c=b.firstChild; c&&b.insertBefore(a,c)}}},mouseover:function(a){this.R.addListener(this,"mouseover",a);return this},mouseout:function(a){this.R.addListener(this,"mouseout",a);return this},click:function(a){this.R.addListener(this,"click",a);return this},dblclick:function(a){this.R.addListener(this,"dblclick",a);return this},mousedown:function(a){this.R.addListener(this,"mousedown",a);return this},mouseup:function(a){this.R.addListener(this,"mouseup",a);return this},touchstart:function(a){this.R.addListener(this, "touchstart",a);return this},touchend:function(a){this.R.addListener(this,"touchend",a);return this},contextmenu:function(a){this.node.addEventListener?this.node.addEventListener("contextmenu",a,!0):this.R.addListener(this,"contextmenu",a);return this},stop:function(){d.removeFromArray(this.R.animations,this.an_x);d.removeFromArray(this.R.animations,this.an_y)},length:function(){return this.node.childNodes.length},gradient:function(a,b,c){this.R.gradient(this,a,b,c)},pattern:function(a,b,c){a&&this.R.pattern(this, a,b,c)}})})();(function(){var d=window.AmCharts;d.VMLRenderer=d.Class({construct:function(a,b){this.chart=b;this.D=a;this.cNames={circle:"oval",ellipse:"oval",rect:"roundrect",path:"shape"};this.styleMap={x:"left",y:"top",width:"width",height:"height","font-family":"fontFamily","font-size":"fontSize",visibility:"visibility"}},create:function(a,b){var c;if("group"==b)c=document.createElement("div"),a.type="div";else if("text"==b)c=document.createElement("div"),a.type="text";else if("image"==b)c=document.createElement("img"), a.type="image";else{a.type="shape";a.shapeType=this.cNames[b];c=document.createElement("amvml:"+this.cNames[b]);var d=document.createElement("amvml:stroke");c.appendChild(d);a.stroke=d;var h=document.createElement("amvml:fill");c.appendChild(h);a.fill=h;h.className="amvml";d.className="amvml";c.className="amvml"}c.style.position="absolute";c.style.top=0;c.style.left=0;return c},path:function(a,b){a.node.setAttribute("src",b)},setAttr:function(a,b,c){if(void 0!==c){var e;8===document.documentMode&& (e=!0);var h=a.node,f=a.type,g=h.style;"r"==b&&(g.width=2*c,g.height=2*c);"oval"==a.shapeType&&("rx"==b&&(g.width=2*c),"ry"==b&&(g.height=2*c));"roundrect"==a.shapeType&&("width"!=b&&"height"!=b||--c);"cursor"==b&&(g.cursor=c);"cx"==b&&(g.left=c-d.removePx(g.width)/2);"cy"==b&&(g.top=c-d.removePx(g.height)/2);var k=this.styleMap[b];void 0!==k&&(g[k]=c);"text"==f&&("text-anchor"==b&&(a.anchor=c,k=h.clientWidth,"end"==c&&(g.marginLeft=-k+"px"),"middle"==c&&(g.marginLeft=-(k/2)+"px",g.textAlign="center"), "start"==c&&(g.marginLeft="0px")),"fill"==b&&(g.color=c),"font-weight"==b&&(g.fontWeight=c));if(g=a.children)for(k=0;k<g.length;k++)g[k].setAttr(b,c);if("shape"==f){"cs"==b&&(h.style.width="100px",h.style.height="100px",h.setAttribute("coordsize",c));"d"==b&&h.setAttribute("path",this.svgPathToVml(c));"dd"==b&&h.setAttribute("path",c);f=a.stroke;a=a.fill;"stroke"==b&&(e?f.color=c:f.setAttribute("color",c));"stroke-width"==b&&(e?f.weight=c:f.setAttribute("weight",c));"stroke-opacity"==b&&(e?f.opacity= c:f.setAttribute("opacity",c));"stroke-dasharray"==b&&(g="solid",0<c&&3>c&&(g="dot"),3<=c&&6>=c&&(g="dash"),6<c&&(g="longdash"),e?f.dashstyle=g:f.setAttribute("dashstyle",g));if("fill-opacity"==b||"opacity"==b)0===c?e?a.on=!1:a.setAttribute("on",!1):e?a.opacity=c:a.setAttribute("opacity",c);"fill"==b&&(e?a.color=c:a.setAttribute("color",c));"rx"==b&&(e?h.arcSize=c+"%":h.setAttribute("arcsize",c+"%"))}}},attr:function(a,b){for(var c in b)b.hasOwnProperty(c)&&this.setAttr(a,c,b[c])},text:function(a, b,c){var e=new d.AmDObject("text",this.D),h=e.node;h.style.whiteSpace="pre";h.innerHTML=a;this.D.addToContainer(h,c);this.attr(e,b);return e},getBBox:function(a){return this.getBox(a.node)},getBox:function(a){var b=a.offsetLeft,c=a.offsetTop,d=a.offsetWidth,h=a.offsetHeight,f;if(a.hasChildNodes()){var g,k,l;for(l=0;l<a.childNodes.length;l++){f=this.getBox(a.childNodes[l]);var m=f.x;isNaN(m)||(isNaN(g)?g=m:m<g&&(g=m));var n=f.y;isNaN(n)||(isNaN(k)?k=n:n<k&&(k=n));m=f.width+m;isNaN(m)||(d=Math.max(d, m));f=f.height+n;isNaN(f)||(h=Math.max(h,f))}0>g&&(b+=g);0>k&&(c+=k)}return{x:b,y:c,width:d,height:h}},setText:function(a,b){var c=a.node;c&&(c.innerHTML=b);this.setAttr(a,"text-anchor",a.anchor)},addListener:function(a,b,c){a.node["on"+b]=c},move:function(a,b,c){var e=a.node,h=e.style;"text"==a.type&&(c-=d.removePx(h.fontSize)/2-1);"oval"==a.shapeType&&(b-=d.removePx(h.width)/2,c-=d.removePx(h.height)/2);a=a.bw;isNaN(a)||(b-=a,c-=a);isNaN(b)||isNaN(c)||(e.style.left=b+"px",e.style.top=c+"px")},svgPathToVml:function(a){var b= a.split(" ");a="";var c,d=Math.round,h;for(h=0;h<b.length;h++){var f=b[h],g=f.substring(0,1),f=f.substring(1),k=f.split(","),l=d(k[0])+","+d(k[1]);"M"==g&&(a+=" m "+l);"L"==g&&(a+=" l "+l);"Z"==g&&(a+=" x e");if("Q"==g){var m=c.length,n=c[m-1],p=k[0],q=k[1],l=k[2],r=k[3];c=d(c[m-2]/3+2/3*p);n=d(n/3+2/3*q);p=d(2/3*p+l/3);q=d(2/3*q+r/3);a+=" c "+c+","+n+","+p+","+q+","+l+","+r}"A"==g&&(a+=" wa "+f);"B"==g&&(a+=" at "+f);c=k}return a},animate:function(a,b,c,d,h){var f=a.node,g=this.chart;if("translate"== b){b=c.split(",");c=b[1];var k=f.offsetTop;g.animate(a,"left",f.offsetLeft,b[0],d,h,"px");g.animate(a,"top",k,c,d,h,"px")}},clipRect:function(a,b,c,d,h){a=a.node;0===b&&0===c?(a.style.width=d+"px",a.style.height=h+"px",a.style.overflow="hidden"):a.style.clip="rect("+c+"px "+(b+d)+"px "+(c+h)+"px "+b+"px)"},rotate:function(a,b,c){if(0!==Number(b)){var e=a.node;a=e.style;c||(c=this.getBGColor(e.parentNode));a.backgroundColor=c;a.paddingLeft=1;c=b*Math.PI/180;var h=Math.cos(c),f=Math.sin(c),g=d.removePx(a.left), k=d.removePx(a.top),l=e.offsetWidth,e=e.offsetHeight;b/=Math.abs(b);a.left=g+l/2-l/2*Math.cos(c)-b*e/2*Math.sin(c)+3;a.top=k-b*l/2*Math.sin(c)+b*e/2*Math.sin(c);a.cssText=a.cssText+"; filter:progid:DXImageTransform.Microsoft.Matrix(M11='"+h+"', M12='"+-f+"', M21='"+f+"', M22='"+h+"', sizingmethod='auto expand');"}},getBGColor:function(a){var b="#FFFFFF";if(a.style){var c=a.style.backgroundColor;""!==c?b=c:a.parentNode&&(b=this.getBGColor(a.parentNode))}return b},set:function(a){var b=new d.AmDObject("group", this.D);this.D.container.appendChild(b.node);if(a){var c;for(c=0;c<a.length;c++)b.push(a[c])}return b},gradient:function(a,b,c,d){var h="";"radialGradient"==b&&(b="gradientradial",c.reverse());"linearGradient"==b&&(b="gradient");var f;for(f=0;f<c.length;f++){var g=Math.round(100*f/(c.length-1)),h=h+(g+"% "+c[f]);f<c.length-1&&(h+=",")}a=a.fill;90==d?d=0:270==d?d=180:180==d?d=90:0===d&&(d=270);8===document.documentMode?(a.type=b,a.angle=d):(a.setAttribute("type",b),a.setAttribute("angle",d));h&&(a.colors.value= h)},remove:function(a){a.clipPath&&this.D.remove(a.clipPath);this.D.remove(a.node)},disableSelection:function(a){void 0!==typeof a.onselectstart&&(a.onselectstart=function(){return!1});a.style.cursor="default"},pattern:function(a,b,c,e){c=a.node;a=a.fill;var h="none";b.color&&(h=b.color);c.fillColor=h;b=b.url;d.isAbsolute(b)||(b=e+b);8===document.documentMode?(a.type="tile",a.src=b):(a.setAttribute("type","tile"),a.setAttribute("src",b))},update:function(){}})})();(function(){var d=window.AmCharts;d.SVGRenderer=d.Class({construct:function(a){this.D=a;this.animations=[]},create:function(a,b){return document.createElementNS(d.SVG_NS,b)},attr:function(a,b){for(var c in b)b.hasOwnProperty(c)&&this.setAttr(a,c,b[c])},setAttr:function(a,b,c){void 0!==c&&a.node.setAttribute(b,c)},animate:function(a,b,c,e,h){var f=a.node;a["an_"+b]&&d.removeFromArray(this.animations,a["an_"+b]);"translate"==b?(f=(f=f.getAttribute("transform"))?String(f).substring(10,f.length-1):"0,0", f=f.split(", ").join(" "),f=f.split(" ").join(","),0===f&&(f="0,0")):f=Number(f.getAttribute(b));c={obj:a,frame:0,attribute:b,from:f,to:c,time:e,effect:h};this.animations.push(c);a["an_"+b]=c},update:function(){var a,b=this.animations;for(a=b.length-1;0<=a;a--){var c=b[a],e=1E3*c.time/d.updateRate,h=c.frame+1,f=c.obj,g=c.attribute,k,l,m;h<=e?(c.frame++,"translate"==g?(k=c.from.split(","),g=Number(k[0]),k=Number(k[1]),isNaN(k)&&(k=0),l=c.to.split(","),m=Number(l[0]),l=Number(l[1]),m=0===m-g?m:Math.round(d[c.effect](0, h,g,m-g,e)),c=0===l-k?l:Math.round(d[c.effect](0,h,k,l-k,e)),g="transform",c="translate("+m+","+c+")"):(l=Number(c.from),k=Number(c.to),m=k-l,c=d[c.effect](0,h,l,m,e),isNaN(c)&&(c=k),0===m&&this.animations.splice(a,1)),this.setAttr(f,g,c)):("translate"==g?(l=c.to.split(","),m=Number(l[0]),l=Number(l[1]),f.translate(m,l)):(k=Number(c.to),this.setAttr(f,g,k)),this.animations.splice(a,1))}},getBBox:function(a){if(a=a.node)try{return a.getBBox()}catch(b){}return{width:0,height:0,x:0,y:0}},path:function(a, b){a.node.setAttributeNS(d.SVG_XLINK,"xlink:href",b)},clipRect:function(a,b,c,e,h){var f=a.node,g=a.clipPath;g&&this.D.remove(g);var k=f.parentNode;k&&(f=document.createElementNS(d.SVG_NS,"clipPath"),g=d.getUniqueId(),f.setAttribute("id",g),this.D.rect(b,c,e,h,0,0,f),k.appendChild(f),b="#",d.baseHref&&!d.isIE&&(b=this.removeTarget(window.location.href)+b),this.setAttr(a,"clip-path","url("+b+g+")"),this.clipPathC++,a.clipPath=f)},text:function(a,b,c){var e=new d.AmDObject("text",this.D);a=String(a).split("\n"); var h=b["font-size"],f;for(f=0;f<a.length;f++){var g=this.create(null,"tspan");g.appendChild(document.createTextNode(a[f]));g.setAttribute("y",(h+2)*f+Math.round(h/2));g.setAttribute("x",0);g.style.fontSize=h+"px";e.node.appendChild(g)}e.node.setAttribute("y",Math.round(h/2));this.attr(e,b);this.D.addToContainer(e.node,c);return e},setText:function(a,b){var c=a.node;c&&(c.removeChild(c.firstChild),c.appendChild(document.createTextNode(b)))},move:function(a,b,c,d){isNaN(b)&&(b=0);isNaN(c)&&(c=0);b= "translate("+b+","+c+")";d&&(b=b+" scale("+d+")");this.setAttr(a,"transform",b)},rotate:function(a,b){var c=a.node.getAttribute("transform"),d="rotate("+b+")";c&&(d=c+" "+d);this.setAttr(a,"transform",d)},set:function(a){var b=new d.AmDObject("g",this.D);this.D.container.appendChild(b.node);if(a){var c;for(c=0;c<a.length;c++)b.push(a[c])}return b},addListener:function(a,b,c){a.node["on"+b]=c},gradient:function(a,b,c,e){var h=a.node,f=a.grad;f&&this.D.remove(f);b=document.createElementNS(d.SVG_NS, b);f=d.getUniqueId();b.setAttribute("id",f);if(!isNaN(e)){var g=0,k=0,l=0,m=0;90==e?l=100:270==e?m=100:180==e?g=100:0===e&&(k=100);b.setAttribute("x1",g+"%");b.setAttribute("x2",k+"%");b.setAttribute("y1",l+"%");b.setAttribute("y2",m+"%")}for(e=0;e<c.length;e++)g=document.createElementNS(d.SVG_NS,"stop"),k=100*e/(c.length-1),0===e&&(k=0),g.setAttribute("offset",k+"%"),g.setAttribute("stop-color",c[e]),b.appendChild(g);h.parentNode.appendChild(b);c="#";d.baseHref&&!d.isIE&&(c=this.removeTarget(window.location.href)+ c);h.setAttribute("fill","url("+c+f+")");a.grad=b},removeTarget:function(a){return a.split("#")[0]},pattern:function(a,b,c,e){var h=a.node;isNaN(c)&&(c=1);var f=a.patternNode;f&&this.D.remove(f);var f=document.createElementNS(d.SVG_NS,"pattern"),g=d.getUniqueId(),k=b;b.url&&(k=b.url);d.isAbsolute(k)||(k=e+k);e=Number(b.width);isNaN(e)&&(e=4);var l=Number(b.height);isNaN(l)&&(l=4);e/=c;l/=c;c=b.x;isNaN(c)&&(c=0);var m=-Math.random()*Number(b.randomX);isNaN(m)||(c=m);m=b.y;isNaN(m)&&(m=0);var n=-Math.random()* Number(b.randomY);isNaN(n)||(m=n);f.setAttribute("id",g);f.setAttribute("width",e);f.setAttribute("height",l);f.setAttribute("patternUnits","userSpaceOnUse");f.setAttribute("xlink:href",k);b.color&&(n=document.createElementNS(d.SVG_NS,"rect"),n.setAttributeNS(null,"height",e),n.setAttributeNS(null,"width",l),n.setAttributeNS(null,"fill",b.color),f.appendChild(n));this.D.image(k,0,0,e,l,f).translate(c,m);k="#";d.baseHref&&!d.isIE&&(k=this.removeTarget(window.location.href)+k);h.setAttribute("fill", "url("+k+g+")");a.patternNode=f;h.parentNode.appendChild(f)},remove:function(a){a.clipPath&&this.D.remove(a.clipPath);a.grad&&this.D.remove(a.grad);a.patternNode&&this.D.remove(a.patternNode);this.D.remove(a.node)}})})();AmCharts.AmDSet=AmCharts.Class({construct:function(d){this.create("g")},attr:function(d){this.R.attr(this.node,d)},move:function(d,a){this.R.move(this.node,d,a)}});(function(){var d=window.AmCharts;d.AmLegend=d.Class({construct:function(a){this.enabled=!0;this.cname="AmLegend";this.createEvents("rollOverMarker","rollOverItem","rollOutMarker","rollOutItem","showItem","hideItem","clickMarker","rollOverItem","rollOutItem","clickLabel");this.position="bottom";this.borderColor=this.color="#000000";this.borderAlpha=0;this.markerLabelGap=5;this.verticalGap=10;this.align="left";this.horizontalGap=0;this.spacing=10;this.markerDisabledColor="#AAB3B3";this.markerType= "square";this.markerSize=16;this.markerBorderThickness=this.markerBorderAlpha=1;this.marginBottom=this.marginTop=0;this.marginLeft=this.marginRight=20;this.autoMargins=!0;this.valueWidth=50;this.switchable=!0;this.switchType="x";this.switchColor="#FFFFFF";this.rollOverColor="#CC0000";this.reversedOrder=!1;this.labelText="[[title]]";this.valueText="[[value]]";this.useMarkerColorForLabels=!1;this.rollOverGraphAlpha=1;this.textClickEnabled=!1;this.equalWidths=!0;this.backgroundColor="#FFFFFF";this.backgroundAlpha= 0;this.useGraphSettings=!1;this.showEntries=!0;d.applyTheme(this,a,this.cname)},setData:function(a){this.legendData=a;this.invalidateSize()},invalidateSize:function(){this.destroy();this.entries=[];this.valueLabels=[];var a=this.legendData;this.enabled&&(d.ifArray(a)||d.ifArray(this.data))&&this.drawLegend()},drawLegend:function(){var a=this.chart,b=this.position,c=this.width,e=a.divRealWidth,h=a.divRealHeight,f=this.div,g=this.legendData;this.data&&(g=this.data);isNaN(this.fontSize)&&(this.fontSize= a.fontSize);if("right"==b||"left"==b)this.maxColumns=1,this.autoMargins&&(this.marginLeft=this.marginRight=10);else if(this.autoMargins){this.marginRight=a.marginRight;this.marginLeft=a.marginLeft;var k=a.autoMarginOffset;"bottom"==b?(this.marginBottom=k,this.marginTop=0):(this.marginTop=k,this.marginBottom=0)}c=void 0!==c?d.toCoordinate(c,e):a.realWidth;"outside"==b?(c=f.offsetWidth,h=f.offsetHeight,f.clientHeight&&(c=f.clientWidth,h=f.clientHeight)):(isNaN(c)||(f.style.width=c+"px"),f.className= "amChartsLegend "+a.classNamePrefix+"-legend-div");this.divWidth=c;(b=this.container)?(b.container.innerHTML="",f.appendChild(b.container),b.width=c,b.height=h,b.setSize(c,h),b.addDefs(a)):b=new d.AmDraw(f,c,h,a);this.container=b;this.lx=0;this.ly=8;h=this.markerSize;h>this.fontSize&&(this.ly=h/2-1);0<h&&(this.lx+=h+this.markerLabelGap);this.titleWidth=0;if(h=this.title)h=d.text(this.container,h,this.color,a.fontFamily,this.fontSize,"start",!0),d.setCN(a,h,"legend-title"),h.translate(this.marginLeft, this.marginTop+this.verticalGap+this.ly+1),a=h.getBBox(),this.titleWidth=a.width+15,this.titleHeight=a.height+6;this.index=this.maxLabelWidth=0;if(this.showEntries){for(a=0;a<g.length;a++)this.createEntry(g[a]);for(a=this.index=0;a<g.length;a++)this.createValue(g[a])}this.arrangeEntries();this.updateValues()},arrangeEntries:function(){var a=this.position,b=this.marginLeft+this.titleWidth,c=this.marginRight,e=this.marginTop,h=this.marginBottom,f=this.horizontalGap,g=this.div,k=this.divWidth,l=this.maxColumns, m=this.verticalGap,n=this.spacing,p=k-c-b,q=0,r=0,u=this.container;this.set&&this.set.remove();var t=u.set();this.set=t;var z=u.set();t.push(z);var y=this.entries,v,w;for(w=0;w<y.length;w++){v=y[w].getBBox();var A=v.width;A>q&&(q=A);v=v.height;v>r&&(r=v)}var A=r=0,B=f,C=0,D=0;for(w=0;w<y.length;w++){var J=y[w];this.reversedOrder&&(J=y[y.length-w-1]);v=J.getBBox();var E;this.equalWidths?E=A*(q+n+this.markerLabelGap):(E=B,B=B+v.width+f+n);v.height>D&&(D=v.height);E+v.width>p&&0<w&&0!==A&&(r++,E=A=0, B=E+v.width+f+n,C=C+D+m,D=0);J.translate(E,C);A++;!isNaN(l)&&A>=l&&(A=0,r++,C=C+D+m,B=f,D=0);z.push(J)}v=z.getBBox();l=v.height+2*m-1;"left"==a||"right"==a?(n=v.width+2*f,k=n+b+c,g.style.width=k+"px",this.ieW=k):n=k-b-c-1;c=d.polygon(this.container,[0,n,n,0],[0,0,l,l],this.backgroundColor,this.backgroundAlpha,1,this.borderColor,this.borderAlpha);d.setCN(this.chart,c,"legend-bg");t.push(c);t.translate(b,e);c.toBack();b=f;if("top"==a||"bottom"==a||"absolute"==a||"outside"==a)"center"==this.align?b= f+(n-v.width)/2:"right"==this.align&&(b=f+n-v.width);z.translate(b,m+1);this.titleHeight>l&&(l=this.titleHeight);a=l+e+h+1;0>a&&(a=0);a>this.chart.divRealHeight&&(g.style.top="0px");g.style.height=Math.round(a)+"px";u.setSize(this.divWidth,a)},createEntry:function(a){if(!1!==a.visibleInLegend){var b=this.chart,c=a.markerType;a.legendEntryWidth=this.markerSize;c||(c=this.markerType);var e=a.color,h=a.alpha;a.legendKeyColor&&(e=a.legendKeyColor());a.legendKeyAlpha&&(h=a.legendKeyAlpha());var f;!0=== a.hidden&&(f=e=this.markerDisabledColor);var g=a.pattern,k=a.customMarker;k||(k=this.customMarker);var l=this.container,m=this.markerSize,n=0,p=0,q=m/2;if(this.useGraphSettings){c=a.type;this.switchType=void 0;if("line"==c||"step"==c||"smoothedLine"==c||"ohlc"==c)g=l.set(),a.hidden||(e=a.lineColorR,f=a.bulletBorderColorR),n=d.line(l,[0,2*m],[m/2,m/2],e,a.lineAlpha,a.lineThickness,a.dashLength),d.setCN(b,n,"graph-stroke"),g.push(n),a.bullet&&(a.hidden||(e=a.bulletColorR),n=d.bullet(l,a.bullet,a.bulletSize, e,a.bulletAlpha,a.bulletBorderThickness,f,a.bulletBorderAlpha))&&(d.setCN(b,n,"graph-bullet"),n.translate(m+1,m/2),g.push(n)),q=0,n=m,p=m/3;else{var r;a.getGradRotation&&(r=a.getGradRotation());n=a.fillColorsR;!0===a.hidden&&(n=e);if(g=this.createMarker("rectangle",n,a.fillAlphas,a.lineThickness,e,a.lineAlpha,r,g))q=m,g.translate(q,m/2);n=m}d.setCN(b,g,"graph-"+c);d.setCN(b,g,"graph-"+a.id)}else k?g=l.image(k,0,0,m,m):(g=this.createMarker(c,e,h,void 0,void 0,void 0,void 0,g))&&g.translate(m/2,m/2); d.setCN(b,g,"legend-marker");this.addListeners(g,a);l=l.set([g]);this.switchable&&a.switchable&&l.setAttr("cursor","pointer");void 0!==a.id&&d.setCN(b,l,"legend-item-"+a.id);d.setCN(b,l,a.className,!0);(f=this.switchType)&&"none"!=f&&0<m&&("x"==f?(c=this.createX(),c.translate(m/2,m/2)):c=this.createV(),c.dItem=a,!0!==a.hidden?"x"==f?c.hide():c.show():"x"!=f&&c.hide(),this.switchable||c.hide(),this.addListeners(c,a),a.legendSwitch=c,l.push(c),d.setCN(b,c,"legend-switch"));f=this.color;a.showBalloon&& this.textClickEnabled&&void 0!==this.selectedColor&&(f=this.selectedColor);this.useMarkerColorForLabels&&(f=e);!0===a.hidden&&(f=this.markerDisabledColor);e=d.massReplace(this.labelText,{"[[title]]":a.title});c=this.fontSize;g&&(m<=c&&g.translate(q,m/2+this.ly-c/2+(c+2-m)/2-p),a.legendEntryWidth=g.getBBox().width);var u;e&&(e=d.fixBrakes(e),a.legendTextReal=e,u=this.labelWidth,u=isNaN(u)?d.text(this.container,e,f,b.fontFamily,c,"start"):d.wrappedText(this.container,e,f,b.fontFamily,c,"start",!1,u, 0),d.setCN(b,u,"legend-label"),u.translate(this.lx+n,this.ly),l.push(u),b=u.getBBox().width,this.maxLabelWidth<b&&(this.maxLabelWidth=b));this.entries[this.index]=l;a.legendEntry=this.entries[this.index];a.legendLabel=u;this.index++}},addListeners:function(a,b){var c=this;a&&a.mouseover(function(a){c.rollOverMarker(b,a)}).mouseout(function(a){c.rollOutMarker(b,a)}).click(function(a){c.clickMarker(b,a)})},rollOverMarker:function(a,b){this.switchable&&this.dispatch("rollOverMarker",a,b);this.dispatch("rollOverItem", a,b)},rollOutMarker:function(a,b){this.switchable&&this.dispatch("rollOutMarker",a,b);this.dispatch("rollOutItem",a,b)},clickMarker:function(a,b){this.switchable&&(!0===a.hidden?this.dispatch("showItem",a,b):this.dispatch("hideItem",a,b));this.dispatch("clickMarker",a,b)},rollOverLabel:function(a,b){a.hidden||(this.textClickEnabled&&a.legendLabel&&a.legendLabel.attr({fill:this.rollOverColor}),this.dispatch("rollOverItem",a,b))},rollOutLabel:function(a,b){if(!a.hidden){if(this.textClickEnabled&&a.legendLabel){var c= this.color;void 0!==this.selectedColor&&a.showBalloon&&(c=this.selectedColor);this.useMarkerColorForLabels&&(c=a.lineColor,void 0===c&&(c=a.color));a.legendLabel.attr({fill:c})}this.dispatch("rollOutItem",a,b)}},clickLabel:function(a,b){this.textClickEnabled?a.hidden||this.dispatch("clickLabel",a,b):this.switchable&&(!0===a.hidden?this.dispatch("showItem",a,b):this.dispatch("hideItem",a,b))},dispatch:function(a,b,c){b={type:a,dataItem:b,target:this,event:c,chart:this.chart};this.chart&&this.chart.handleLegendEvent(b); this.fire(a,b)},createValue:function(a){var b=this,c=b.fontSize,e=b.chart;if(!1!==a.visibleInLegend){var h=b.maxLabelWidth;b.forceWidth&&(h=b.labelWidth);b.equalWidths||(b.valueAlign="left");"left"==b.valueAlign&&(h=a.legendEntry.getBBox().width);var f=h;if(b.valueText&&0<b.valueWidth){var g=b.color;b.useMarkerColorForValues&&(g=a.color,a.legendKeyColor&&(g=a.legendKeyColor()));!0===a.hidden&&(g=b.markerDisabledColor);var k=b.valueText,h=h+b.lx+b.markerLabelGap+b.valueWidth,l="end";"left"==b.valueAlign&& (h-=b.valueWidth,l="start");g=d.text(b.container,k,g,b.chart.fontFamily,c,l);d.setCN(e,g,"legend-value");g.translate(h,b.ly);b.entries[b.index].push(g);f+=b.valueWidth+2*b.markerLabelGap;g.dItem=a;b.valueLabels.push(g)}b.index++;e=b.markerSize;e<c+7&&(e=c+7,d.VML&&(e+=3));c=b.container.rect(a.legendEntryWidth,0,f,e,0,0).attr({stroke:"none",fill:"#fff","fill-opacity":.005});c.dItem=a;b.entries[b.index-1].push(c);c.mouseover(function(c){b.rollOverLabel(a,c)}).mouseout(function(c){b.rollOutLabel(a,c)}).click(function(c){b.clickLabel(a, c)})}},createV:function(){var a=this.markerSize;return d.polygon(this.container,[a/5,a/2,a-a/5,a/2],[a/3,a-a/5,a/5,a/1.7],this.switchColor)},createX:function(){var a=(this.markerSize-4)/2,b={stroke:this.switchColor,"stroke-width":3},c=this.container,e=d.line(c,[-a,a],[-a,a]).attr(b),a=d.line(c,[-a,a],[a,-a]).attr(b);return this.container.set([e,a])},createMarker:function(a,b,c,e,h,f,g,k){var l=this.markerSize,m=this.container;h||(h=this.markerBorderColor);h||(h=b);isNaN(e)&&(e=this.markerBorderThickness); isNaN(f)&&(f=this.markerBorderAlpha);return d.bullet(m,a,l,b,c,e,h,f,l,g,k,this.chart.path)},validateNow:function(){this.invalidateSize()},updateValues:function(){var a=this.valueLabels,b=this.chart,c,e=this.data;for(c=0;c<a.length;c++){var h=a[c],f=h.dItem,g=" ";if(e)f.value?h.text(f.value):h.text("");else{var k;if(void 0!==f.type){k=f.currentDataItem;var l=this.periodValueText;f.legendPeriodValueText&&(l=f.legendPeriodValueText);k?(g=this.valueText,f.legendValueText&&(g=f.legendValueText),g=b.formatString(g, k)):l&&b.formatPeriodString&&(l=d.massReplace(l,{"[[title]]":f.title}),g=b.formatPeriodString(l,f))}else g=b.formatString(this.valueText,f);if(l=this.valueFunction)k&&(f=k),g=l(f,g);h.text(g)}}},renderFix:function(){if(!d.VML){var a=this.container;a&&a.renderFix()}},destroy:function(){this.div.innerHTML="";d.remove(this.set)}})})();(function(){var d=window.AmCharts;d.formatMilliseconds=function(a,b){if(-1!=a.indexOf("fff")){var c=b.getMilliseconds(),d=String(c);10>c&&(d="00"+c);10<=c&&100>c&&(d="0"+c);a=a.replace(/fff/g,d)}return a};d.extractPeriod=function(a){var b=d.stripNumbers(a),c=1;b!=a&&(c=Number(a.slice(0,a.indexOf(b))));return{period:b,count:c}};d.getDate=function(a,b,c){return a instanceof Date?d.newDate(a,c):b&&isNaN(a)?d.stringToDate(a,b):new Date(a)};d.newDate=function(a,b){return b&&-1==b.indexOf("fff")?new Date(a): d.useUTC?new Date(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds(),a.getUTCMilliseconds()):new Date(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds())};d.resetDateToMin=function(a,b,c,e){void 0===e&&(e=1);var h,f,g,k,l,m,n;d.useUTC?(h=a.getUTCFullYear(),f=a.getUTCMonth(),g=a.getUTCDate(),k=a.getUTCHours(),l=a.getUTCMinutes(),m=a.getUTCSeconds(),n=a.getUTCMilliseconds(),a=a.getUTCDay()):(h=a.getFullYear(), f=a.getMonth(),g=a.getDate(),k=a.getHours(),l=a.getMinutes(),m=a.getSeconds(),n=a.getMilliseconds(),a=a.getDay());switch(b){case "YYYY":h=Math.floor(h/c)*c;f=0;g=1;n=m=l=k=0;break;case "MM":f=Math.floor(f/c)*c;g=1;n=m=l=k=0;break;case "WW":g=a>=e?g-a+e:g-(7+a)+e;n=m=l=k=0;break;case "DD":n=m=l=k=0;break;case "hh":k=Math.floor(k/c)*c;n=m=l=0;break;case "mm":l=Math.floor(l/c)*c;n=m=0;break;case "ss":m=Math.floor(m/c)*c;n=0;break;case "fff":n=Math.floor(n/c)*c}d.useUTC?(a=new Date,a.setUTCFullYear(h, f,g),a.setUTCHours(k,l,m,n)):a=new Date(h,f,g,k,l,m,n);return a};d.getPeriodDuration=function(a,b){void 0===b&&(b=1);var c;switch(a){case "YYYY":c=316224E5;break;case "MM":c=26784E5;break;case "WW":c=6048E5;break;case "DD":c=864E5;break;case "hh":c=36E5;break;case "mm":c=6E4;break;case "ss":c=1E3;break;case "fff":c=1}return c*b};d.intervals={s:{nextInterval:"ss",contains:1E3},ss:{nextInterval:"mm",contains:60,count:0},mm:{nextInterval:"hh",contains:60,count:1},hh:{nextInterval:"DD",contains:24,count:2}, DD:{nextInterval:"",contains:Infinity,count:3}};d.getMaxInterval=function(a,b){var c=d.intervals;return a>=c[b].contains?(a=Math.round(a/c[b].contains),b=c[b].nextInterval,d.getMaxInterval(a,b)):"ss"==b?c[b].nextInterval:b};d.dayNames="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");d.shortDayNames="Sun Mon Tue Wed Thu Fri Sat".split(" ");d.monthNames="January February March April May June July August September October November December".split(" ");d.shortMonthNames="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "); d.getWeekNumber=function(a){a=new Date(a);a.setHours(0,0,0);a.setDate(a.getDate()+4-(a.getDay()||7));var b=new Date(a.getFullYear(),0,1);return Math.ceil(((a-b)/864E5+1)/7)};d.stringToDate=function(a,b){var c={},e=[{pattern:"YYYY",period:"year"},{pattern:"YY",period:"year"},{pattern:"MM",period:"month"},{pattern:"M",period:"month"},{pattern:"DD",period:"date"},{pattern:"D",period:"date"},{pattern:"JJ",period:"hours"},{pattern:"J",period:"hours"},{pattern:"HH",period:"hours"},{pattern:"H",period:"hours"}, {pattern:"KK",period:"hours"},{pattern:"K",period:"hours"},{pattern:"LL",period:"hours"},{pattern:"L",period:"hours"},{pattern:"NN",period:"minutes"},{pattern:"N",period:"minutes"},{pattern:"SS",period:"seconds"},{pattern:"S",period:"seconds"},{pattern:"QQQ",period:"milliseconds"},{pattern:"QQ",period:"milliseconds"},{pattern:"Q",period:"milliseconds"}],h=!0,f=b.indexOf("AA");-1!=f&&(a.substr(f,2),"pm"==a.toLowerCase&&(h=!1));var f=b,g,k,l;for(l=0;l<e.length;l++)k=e[l].period,c[k]=0,"date"==k&&(c[k]= 1);for(l=0;l<e.length;l++)if(g=e[l].pattern,k=e[l].period,-1!=b.indexOf(g)){var m=d.getFromDateString(g,a,f);b=b.replace(g,"");if("KK"==g||"K"==g||"LL"==g||"L"==g)h||(m+=12);c[k]=m}d.useUTC?(e=new Date,e.setUTCFullYear(c.year,c.month,c.date),e.setUTCHours(c.hours,c.minutes,c.seconds,c.milliseconds)):e=new Date(c.year,c.month,c.date,c.hours,c.minutes,c.seconds,c.milliseconds);return e};d.getFromDateString=function(a,b,c){if(void 0!==b)return c=c.indexOf(a),b=String(b),b=b.substr(c,a.length),"0"==b.charAt(0)&& (b=b.substr(1,b.length-1)),b=Number(b),isNaN(b)&&(b=0),-1!=a.indexOf("M")&&b--,b};d.formatDate=function(a,b,c){c||(c=d);var e,h,f,g,k,l,m,n=d.getWeekNumber(a);d.useUTC?(e=a.getUTCFullYear(),h=a.getUTCMonth(),f=a.getUTCDate(),g=a.getUTCDay(),k=a.getUTCHours(),l=a.getUTCMinutes(),m=a.getUTCSeconds(),a=a.getUTCMilliseconds()):(e=a.getFullYear(),h=a.getMonth(),f=a.getDate(),g=a.getDay(),k=a.getHours(),l=a.getMinutes(),m=a.getSeconds(),a=a.getMilliseconds());var p=String(e).substr(2,2),q=h+1;9>h&&(q="0"+ q);var r="0"+g;b=b.replace(/W/g,n);n=k;24==n&&(n=0);var u=n;10>u&&(u="0"+u);b=b.replace(/JJ/g,u);b=b.replace(/J/g,n);u=k;0===u&&(u=24,-1!=b.indexOf("H")&&f--);n=f;10>f&&(n="0"+f);var t=u;10>t&&(t="0"+t);b=b.replace(/HH/g,t);b=b.replace(/H/g,u);u=k;11<u&&(u-=12);t=u;10>t&&(t="0"+t);b=b.replace(/KK/g,t);b=b.replace(/K/g,u);u=k;0===u&&(u=12);12<u&&(u-=12);t=u;10>t&&(t="0"+t);b=b.replace(/LL/g,t);b=b.replace(/L/g,u);u=l;10>u&&(u="0"+u);b=b.replace(/NN/g,u);b=b.replace(/N/g,l);l=m;10>l&&(l="0"+l);b=b.replace(/SS/g, l);b=b.replace(/S/g,m);m=a;10>m&&(m="00"+m);100>m&&(m="0"+m);l=a;10>l&&(l="00"+l);b=b.replace(/QQQ/g,m);b=b.replace(/QQ/g,l);b=b.replace(/Q/g,a);b=12>k?b.replace(/A/g,"am"):b.replace(/A/g,"pm");b=b.replace(/YYYY/g,"@IIII@");b=b.replace(/YY/g,"@II@");b=b.replace(/MMMM/g,"@XXXX@");b=b.replace(/MMM/g,"@XXX@");b=b.replace(/MM/g,"@XX@");b=b.replace(/M/g,"@X@");b=b.replace(/DD/g,"@RR@");b=b.replace(/D/g,"@R@");b=b.replace(/EEEE/g,"@PPPP@");b=b.replace(/EEE/g,"@PPP@");b=b.replace(/EE/g,"@PP@");b=b.replace(/E/g, "@P@");b=b.replace(/@IIII@/g,e);b=b.replace(/@II@/g,p);b=b.replace(/@XXXX@/g,c.monthNames[h]);b=b.replace(/@XXX@/g,c.shortMonthNames[h]);b=b.replace(/@XX@/g,q);b=b.replace(/@X@/g,h+1);b=b.replace(/@RR@/g,n);b=b.replace(/@R@/g,f);b=b.replace(/@PPPP@/g,c.dayNames[g]);b=b.replace(/@PPP@/g,c.shortDayNames[g]);b=b.replace(/@PP@/g,r);return b=b.replace(/@P@/g,g)};d.changeDate=function(a,b,c,e,h){if(d.useUTC)return d.changeUTCDate(a,b,c,e,h);var f=-1;void 0===e&&(e=!0);void 0===h&&(h=!1);!0===e&&(f=1);switch(b){case "YYYY":a.setFullYear(a.getFullYear()+ c*f);e||h||a.setDate(a.getDate()+1);break;case "MM":b=a.getMonth();a.setMonth(a.getMonth()+c*f);a.getMonth()>b+c*f&&a.setDate(a.getDate()-1);e||h||a.setDate(a.getDate()+1);break;case "DD":a.setDate(a.getDate()+c*f);break;case "WW":a.setDate(a.getDate()+c*f*7);break;case "hh":a.setHours(a.getHours()+c*f);break;case "mm":a.setMinutes(a.getMinutes()+c*f);break;case "ss":a.setSeconds(a.getSeconds()+c*f);break;case "fff":a.setMilliseconds(a.getMilliseconds()+c*f)}return a};d.changeUTCDate=function(a,b, c,d,h){var f=-1;void 0===d&&(d=!0);void 0===h&&(h=!1);!0===d&&(f=1);switch(b){case "YYYY":a.setUTCFullYear(a.getUTCFullYear()+c*f);d||h||a.setUTCDate(a.getUTCDate()+1);break;case "MM":b=a.getUTCMonth();a.setUTCMonth(a.getUTCMonth()+c*f);a.getUTCMonth()>b+c*f&&a.setUTCDate(a.getUTCDate()-1);d||h||a.setUTCDate(a.getUTCDate()+1);break;case "DD":a.setUTCDate(a.getUTCDate()+c*f);break;case "WW":a.setUTCDate(a.getUTCDate()+c*f*7);break;case "hh":a.setUTCHours(a.getUTCHours()+c*f);break;case "mm":a.setUTCMinutes(a.getUTCMinutes()+ c*f);break;case "ss":a.setUTCSeconds(a.getUTCSeconds()+c*f);break;case "fff":a.setUTCMilliseconds(a.getUTCMilliseconds()+c*f)}return a}})();
# -*- coding: utf-8 -*- """Various utilities.""" from . import utils as tasks, rq from datetime import datetime def setup(): """Set up the application schedule. Remove any already scheduled jobs.""" scheduler = rq.get_scheduler() for job in scheduler.get_jobs(): job.delete() tasks.process_tasks.schedule(datetime.utcnow(), interval=3600)
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import unittest import pytest import uuid from datetime import datetime from dateutil.tz import tzutc import sys from azure.core import MatchConditions from azure.core.exceptions import ( ResourceExistsError, ResourceNotFoundError, HttpResponseError, ClientAuthenticationError ) from azure.data.tables.aio import TableServiceClient from azure.data.tables._models import BatchErrorException from azure.data.tables import ( TableEntity, UpdateMode, EntityProperty, EdmType, BatchTransactionResult ) from _shared.testcase import TableTestCase, LogCaptured from devtools_testutils import CachedResourceGroupPreparer, CachedStorageAccountPreparer #------------------------------------------------------------------------------ TEST_TABLE_PREFIX = 'table' #------------------------------------------------------------------------------ class StorageTableBatchTest(TableTestCase): async def _set_up(self, storage_account, storage_account_key): self.ts = TableServiceClient(self.account_url(storage_account, "table"), storage_account_key) self.table_name = self.get_resource_name('uttable') self.table = self.ts.get_table_client(self.table_name) if self.is_live: try: await self.ts.create_table(self.table_name) except ResourceExistsError: pass self.test_tables = [] async def _tear_down(self): if self.is_live: try: await self.ts.delete_table(self.table_name) except: pass for table_name in self.test_tables: try: await self.ts.delete_table(table_name) except: pass await self.table.close() #--Helpers----------------------------------------------------------------- def _get_table_reference(self, prefix=TEST_TABLE_PREFIX): table_name = self.get_resource_name(prefix) self.test_tables.append(table_name) return self.ts.get_table_client(table_name) def _create_pk_rk(self, pk, rk): try: pk = pk if pk is not None else self.get_resource_name('pk').decode('utf-8') rk = rk if rk is not None else self.get_resource_name('rk').decode('utf-8') except AttributeError: pk = pk if pk is not None else self.get_resource_name('pk') rk = rk if rk is not None else self.get_resource_name('rk') return pk, rk def _create_random_entity_dict(self, pk=None, rk=None): """ Creates a dictionary-based entity with fixed values, using all of the supported data types. """ # partition = pk if pk is not None else self.get_resource_name('pk').decode('utf-8') # row = rk if rk is not None else self.get_resource_name('rk').decode('utf-8') partition, row = self._create_pk_rk(pk, rk) properties = { 'PartitionKey': partition, 'RowKey': row, 'age': 39, 'sex': u'male', 'married': True, 'deceased': False, 'optional': None, 'ratio': 3.1, 'evenratio': 3.0, 'large': 933311100, 'Birthday': datetime(1973, 10, 4, tzinfo=tzutc()), 'birthday': datetime(1970, 10, 4, tzinfo=tzutc()), 'binary': b'binary', 'other': EntityProperty(value=20, type=EdmType.INT32), 'clsid': uuid.UUID('c9da6455-213d-42c9-9a79-3e9149a57833') } return TableEntity(**properties) def _create_updated_entity_dict(self, partition, row): ''' Creates a dictionary-based entity with fixed values, with a different set of values than the default entity. It adds fields, changes field values, changes field types, and removes fields when compared to the default entity. ''' return { 'PartitionKey': partition, 'RowKey': row, 'age': u'abc', 'sex': u'female', 'sign': u'aquarius', 'birthday': datetime(1991, 10, 4, tzinfo=tzutc()) } def _assert_default_entity(self, entity): ''' Asserts that the entity passed in matches the default entity. ''' assert entity['age'] == 39 assert entity['sex'] == 'male' assert entity['married'] == True assert entity['deceased'] == False assert not "optional" in entity assert entity['ratio'] == 3.1 assert entity['evenratio'] == 3.0 assert entity['large'] == 933311100 assert entity['Birthday'] == datetime(1973, 10, 4, tzinfo=tzutc()) assert entity['birthday'] == datetime(1970, 10, 4, tzinfo=tzutc()) assert entity['binary'].value == b'binary' assert entity['other'] == 20 assert entity['clsid'] == uuid.UUID('c9da6455-213d-42c9-9a79-3e9149a57833') assert '_metadata' in entity def _assert_updated_entity(self, entity): ''' Asserts that the entity passed in matches the updated entity. ''' assert entity.age == 'abc' assert entity.sex == 'female' assert not hasattr(entity, "married") assert not hasattr(entity, "deceased") assert entity.sign == 'aquarius' assert not hasattr(entity, "optional") assert not hasattr(entity, "ratio") assert not hasattr(entity, "evenratio") assert not hasattr(entity, "large") assert not hasattr(entity, "Birthday") assert entity.birthday, datetime(1991, 10, 4, tzinfo=tzutc()) assert not hasattr(entity, "other") assert not hasattr(entity, "clsid") assert entity['_metadata']['etag'] is not None def _assert_valid_batch_transaction(self, transaction, length): assert isinstance(transaction, BatchTransactionResult) assert length == len(transaction.entities) assert length == len(transaction.results) assert length == len(transaction.requests) #--Test cases for batch --------------------------------------------- @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_single_insert(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = '001' entity.RowKey = 'batch_insert' entity.test = EntityProperty(True) entity.test2 = 'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() batch = self.table.create_batch() batch.create_entity(entity) transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, 1) sent_entity = transaction_result.get_entity(entity.RowKey) assert sent_entity is not None e = await self.table.get_entity(row_key=entity.RowKey, partition_key=entity.PartitionKey) assert e.test == entity.test.value assert e.test2 == entity.test2 assert e.test3 == entity.test3 assert e.test4 == entity.test4.value assert sent_entity['test'] == entity.test.value assert sent_entity['test2'] == entity.test2 assert sent_entity['test3'] == entity.test3 assert sent_entity['test4'] == entity.test4.value finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_single_update(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = '001' entity.RowKey = 'batch_insert' entity.test = EntityProperty(True) entity.test2 = 'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() resp = await self.table.create_entity(entity) assert resp is not None entity.test3 = 5 entity.test5 = datetime.utcnow() batch = self.table.create_batch() batch.update_entity(entity, mode=UpdateMode.MERGE) transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, 1) assert transaction_result.get_entity(entity.RowKey) is not None result = await self.table.get_entity(row_key=entity.RowKey, partition_key=entity.PartitionKey) assert result.PartitionKey == u'001' assert result.RowKey == u'batch_insert' assert result.test3 == 5 finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_update(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = u'001' entity.RowKey = u'batch_update' entity.test = EntityProperty(True) entity.test2 = u'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() await self.table.create_entity(entity) entity = await self.table.get_entity(u'001', u'batch_update') assert 3 == entity.test3 entity.test2 = u'value1' batch = self.table.create_batch() batch.update_entity(entity) transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, 1) assert transaction_result.get_entity(entity.RowKey) is not None result = await self.table.get_entity('001', 'batch_update') assert 'value1' == result.test2 assert entity.PartitionKey == u'001' assert entity.RowKey == u'batch_update' finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_merge(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = u'001' entity.RowKey = u'batch_merge' entity.test = EntityProperty(True) entity.test2 = u'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() await self.table.create_entity(entity) resp_entity = await self.table.get_entity(partition_key=u'001', row_key=u'batch_merge') assert 3 == entity.test3 entity = TableEntity() entity.PartitionKey = u'001' entity.RowKey = u'batch_merge' entity.test2 = u'value1' batch = self.table.create_batch() batch.update_entity(entity, mode=UpdateMode.MERGE) transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, 1) assert transaction_result.get_entity(entity.RowKey) is not None resp_entity = await self.table.get_entity(partition_key=u'001', row_key=u'batch_merge') assert entity.test2 == resp_entity.test2 assert 1234567890 == resp_entity.test4 assert entity.PartitionKey == resp_entity.PartitionKey assert entity.RowKey == resp_entity.RowKey finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_update_if_match(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: entity = self._create_random_entity_dict() resp = await self.table.create_entity(entity=entity) etag = resp['etag'] # Act sent_entity = self._create_updated_entity_dict(entity['PartitionKey'], entity['RowKey']) batch = self.table.create_batch() batch.update_entity( sent_entity, etag=etag, match_condition=MatchConditions.IfNotModified, mode=UpdateMode.REPLACE ) transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, 1) assert transaction_result.get_entity(sent_entity['RowKey']) is not None entity = await self.table.get_entity(partition_key=entity['PartitionKey'], row_key=entity['RowKey']) self._assert_updated_entity(entity) finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_update_if_doesnt_match(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: entity = self._create_random_entity_dict() resp = await self.table.create_entity(entity) assert resp is not None # Act sent_entity1 = self._create_updated_entity_dict(entity['PartitionKey'], entity['RowKey']) batch = self.table.create_batch() batch.update_entity( sent_entity1, etag=u'W/"datetime\'2012-06-15T22%3A51%3A44.9662825Z\'"', match_condition=MatchConditions.IfNotModified ) with pytest.raises(HttpResponseError): await self.table.send_batch(batch) # Assert received_entity = await self.table.get_entity(entity['PartitionKey'], entity['RowKey']) self._assert_default_entity(received_entity) finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_insert_replace(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = '001' entity.RowKey = 'batch_insert_replace' entity.test = True entity.test2 = 'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() batch = self.table.create_batch() batch.upsert_entity(entity) transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, 1) assert transaction_result.get_entity(entity.RowKey) is not None entity = await self.table.get_entity('001', 'batch_insert_replace') assert entity is not None assert 'value' == entity.test2 assert 1234567890 == entity.test4 finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_insert_merge(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = '001' entity.RowKey = 'batch_insert_merge' entity.test = True entity.test2 = 'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() batch = self.table.create_batch() batch.upsert_entity(entity, mode=UpdateMode.MERGE) transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, 1) assert transaction_result.get_entity(entity.RowKey) is not None entity = await self.table.get_entity('001', 'batch_insert_merge') assert entity is not None assert 'value' == entity.test2 assert 1234567890 == entity.test4 finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_delete(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = u'001' entity.RowKey = u'batch_delete' entity.test = EntityProperty(True) entity.test2 = u'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() await self.table.create_entity(entity) entity = await self.table.get_entity(partition_key=u'001', row_key=u'batch_delete') assert 3 == entity.test3 batch = self.table.create_batch() batch.delete_entity(partition_key=entity.PartitionKey, row_key=entity.RowKey) transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, 1) assert transaction_result.get_entity(entity.RowKey) is not None with pytest.raises(ResourceNotFoundError): entity = await self.table.get_entity(partition_key=entity.PartitionKey, row_key=entity.RowKey) finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_inserts(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = 'batch_inserts' entity.test = EntityProperty(True) entity.test2 = 'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) transaction_count = 0 batch = self.table.create_batch() for i in range(100): entity.RowKey = str(i) batch.create_entity(entity) transaction_count += 1 transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, transaction_count) assert transaction_result.get_entity(entity.RowKey) is not None entities = self.table.query_entities("PartitionKey eq 'batch_inserts'") length = 0 async for e in entities: length += 1 # Assert assert entities is not None assert 100 == length finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_all_operations_together(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = '003' entity.RowKey = 'batch_all_operations_together-1' entity.test = EntityProperty(True) entity.test2 = 'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() await self.table.create_entity(entity) entity.RowKey = 'batch_all_operations_together-2' await self.table.create_entity(entity) entity.RowKey = 'batch_all_operations_together-3' await self.table.create_entity(entity) entity.RowKey = 'batch_all_operations_together-4' await self.table.create_entity(entity) transaction_count = 0 batch = self.table.create_batch() entity.RowKey = 'batch_all_operations_together' batch.create_entity(entity) transaction_count += 1 entity.RowKey = 'batch_all_operations_together-1' batch.delete_entity(entity.PartitionKey, entity.RowKey) transaction_count += 1 entity.RowKey = 'batch_all_operations_together-2' entity.test3 = 10 batch.update_entity(entity) transaction_count += 1 entity.RowKey = 'batch_all_operations_together-3' entity.test3 = 100 batch.update_entity(entity, mode=UpdateMode.MERGE) transaction_count += 1 entity.RowKey = 'batch_all_operations_together-4' entity.test3 = 10 batch.upsert_entity(entity) transaction_count += 1 entity.RowKey = 'batch_all_operations_together-5' batch.upsert_entity(entity, mode=UpdateMode.MERGE) transaction_count += 1 transaction_result = await self.table.send_batch(batch) # Assert self._assert_valid_batch_transaction(transaction_result, transaction_count) assert transaction_result.get_entity('batch_all_operations_together') is not None assert transaction_result.get_entity('batch_all_operations_together-1') is not None assert transaction_result.get_entity('batch_all_operations_together-2') is not None assert transaction_result.get_entity('batch_all_operations_together-3') is not None assert transaction_result.get_entity('batch_all_operations_together-4') is not None assert transaction_result.get_entity('batch_all_operations_together-5') is not None entities = self.table.query_entities("PartitionKey eq '003'") length = 0 async for e in entities: length += 1 assert 5 == length finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_all_operations_together_context_manager(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: # Act entity = TableEntity() entity.PartitionKey = '003' entity.RowKey = 'batch_all_operations_together-1' entity.test = EntityProperty(True) entity.test2 = 'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() await self.table.create_entity(entity) entity.RowKey = 'batch_all_operations_together-2' await self.table.create_entity(entity) entity.RowKey = 'batch_all_operations_together-3' await self.table.create_entity(entity) entity.RowKey = 'batch_all_operations_together-4' await self.table.create_entity(entity) async with self.table.create_batch() as batch: entity.RowKey = 'batch_all_operations_together' batch.create_entity(entity) entity.RowKey = 'batch_all_operations_together-1' batch.delete_entity(entity.PartitionKey, entity.RowKey) entity.RowKey = 'batch_all_operations_together-2' entity.test3 = 10 batch.update_entity(entity) entity.RowKey = 'batch_all_operations_together-3' entity.test3 = 100 batch.update_entity(entity, mode=UpdateMode.MERGE) entity.RowKey = 'batch_all_operations_together-4' entity.test3 = 10 batch.upsert_entity(entity) entity.RowKey = 'batch_all_operations_together-5' batch.upsert_entity(entity, mode=UpdateMode.MERGE) # Assert entities = self.table.query_entities("PartitionKey eq '003'") length = 0 async for e in entities: length += 1 assert 4 == length finally: await self._tear_down() @pytest.mark.skip("Not sure this is how the batching should operate, will consult w/ Anna") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_reuse(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: table2 = self._get_table_reference('table2') table2.create_table() # Act entity = TableEntity() entity.PartitionKey = '003' entity.RowKey = 'batch_all_operations_together-1' entity.test = EntityProperty(True) entity.test2 = 'value' entity.test3 = 3 entity.test4 = EntityProperty(1234567890) entity.test5 = datetime.utcnow() batch = self.table.create_batch() batch.create_entity(entity) entity.RowKey = 'batch_all_operations_together-2' batch.create_entity(entity) entity.RowKey = 'batch_all_operations_together-3' batch.create_entity(entity) entity.RowKey = 'batch_all_operations_together-4' batch.create_entity(entity) await self.table.send_batch(batch) with pytest.raises(HttpResponseError): resp = await table2.send_batch(batch) # Assert entities = self.table.query_entities("PartitionKey eq '003'") length = 0 async for e in entities: length += 1 assert 5 == length finally: await self._tear_down() # @pytest.mark.skip("This does not throw an error, but it should") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_same_row_operations_fail(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: entity = self._create_random_entity_dict('001', 'batch_negative_1') await self.table.create_entity(entity) # Act batch = self.table.create_batch() entity = self._create_updated_entity_dict( '001', 'batch_negative_1') batch.update_entity(entity) entity = self._create_random_entity_dict( '001', 'batch_negative_1') batch.update_entity(entity) # Assert with pytest.raises(BatchErrorException): await self.table.send_batch(batch) finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_different_partition_operations_fail(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: entity = self._create_random_entity_dict('001', 'batch_negative_1') await self.table.create_entity(entity) # Act batch = self.table.create_batch() entity = self._create_updated_entity_dict( '001', 'batch_negative_1') batch.update_entity(entity) entity = self._create_random_entity_dict( '002', 'batch_negative_1') # Assert with pytest.raises(ValueError): batch.create_entity(entity) finally: await self._tear_down() @pytest.mark.skip("This does not throw an error, but it should") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_batch_too_many_ops(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: entity = self._create_random_entity_dict('001', 'batch_negative_1') await self.table.create_entity(entity) # Act with pytest.raises(ValueError): batch = self.table.create_batch() for i in range(0, 101): entity = TableEntity() entity.PartitionKey = 'large' entity.RowKey = 'item{0}'.format(i) batch.create_entity(entity) # Assert finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_new_non_existent_table(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: entity = self._create_random_entity_dict('001', 'batch_negative_1') tc = self.ts.get_table_client("doesntexist") batch = tc.create_batch() batch.create_entity(entity) with pytest.raises(ResourceNotFoundError): resp = await tc.send_batch(batch) # Assert finally: await self._tear_down() @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_new_invalid_key(self, resource_group, location, storage_account, storage_account_key): # Arrange invalid_key = storage_account_key[0:-6] + "==" # cut off a bit from the end to invalidate key_list = list(storage_account_key) key_list[-6:] = list("0000==") invalid_key = ''.join(key_list) self.ts = TableServiceClient(self.account_url(storage_account, "table"), invalid_key) self.table_name = self.get_resource_name('uttable') self.table = self.ts.get_table_client(self.table_name) entity = self._create_random_entity_dict('001', 'batch_negative_1') batch = self.table.create_batch() batch.create_entity(entity) with pytest.raises(ClientAuthenticationError): resp = await self.table.send_batch(batch) @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires Python3") @CachedResourceGroupPreparer(name_prefix="tablestest") @CachedStorageAccountPreparer(name_prefix="tablestest") async def test_new_delete_nonexistent_entity(self, resource_group, location, storage_account, storage_account_key): # Arrange await self._set_up(storage_account, storage_account_key) try: entity = self._create_random_entity_dict('001', 'batch_negative_1') batch = self.table.create_batch() batch.delete_entity(entity['PartitionKey'], entity['RowKey']) with pytest.raises(ResourceNotFoundError): resp = await self.table.send_batch(batch) finally: await self._tear_down() #------------------------------------------------------------------------------ if __name__ == '__main__': unittest.main()
# Copyright 2020 Chris Cummins <chrisc.101@gmail.com>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module defines a formatter for JSON files.""" import subprocess import tempfile from tools.format.formatters.base import file_formatter class FormatText(file_formatter.FileFormatter): """Format text files.""" def __init__(self, *args, **kwargs): super(FormatText, self).__init__(*args, **kwargs) self.sed = self._Which("sed") def RunOne(self, path): with tempfile.NamedTemporaryFile(dir=self.cache_path) as tmpfile: add_newline = subprocess.Popen( [self.sed, "-e", "$a\\"], stdout=tmpfile, stderr=subprocess.DEVNULL, stdin=subprocess.PIPE, ) strip_trailing_whitespace = subprocess.Popen( [self.sed, "s/[[:space:]]*$//", str(path)], stdout=add_newline.stdin, stderr=subprocess.DEVNULL, ) add_newline.communicate() tmpfile.seek(0) with open(path, "wb") as f: f.write(tmpfile.read()) if strip_trailing_whitespace.returncode: return f"sed 's/[[:space:]]*$//' failed for: {path}" if add_newline.returncode: return f"sed -e '$a\\' failed for: {path}"
import { postActions } from '../actions/post-detail-action'; const initialState = { data: { content: {}, slug: '' }, error: null, requesting: false, }; const postReducer = (state = initialState, action) => { switch (action.type) { case postActions.PENDING: { return { ...state, requesting: true }; } case postActions.FULFILLED: { return { ...state, requesting: false, data: action.payload }; } case postActions.REJECTED: { return { ...state, requesting: false, error: 'Terjadi kesalahan saat mengambil data lagu' }; } default: { return state; } } }; export default postReducer;
// // AmbientOcclusionEffect.h // libraries/render-utils/src/ // // Created by Niraj Venkat on 7/15/15. // Copyright 2015 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_AmbientOcclusionEffect_h #define hifi_AmbientOcclusionEffect_h #include <string> #include <DependencyManager.h> #include "render/DrawTask.h" #include "LightingModel.h" #include "DeferredFrameTransform.h" #include "DeferredFramebuffer.h" #include "SurfaceGeometryPass.h" #include "ssao_shared.h" class AmbientOcclusionFramebuffer { public: AmbientOcclusionFramebuffer(); gpu::FramebufferPointer getOcclusionFramebuffer(); gpu::TexturePointer getOcclusionTexture(); gpu::FramebufferPointer getOcclusionBlurredFramebuffer(); gpu::TexturePointer getOcclusionBlurredTexture(); gpu::FramebufferPointer getNormalFramebuffer(); gpu::TexturePointer getNormalTexture(); #if SSAO_USE_QUAD_SPLIT gpu::FramebufferPointer getOcclusionSplitFramebuffer(int index); gpu::TexturePointer getOcclusionSplitTexture(); #endif // Update the source framebuffer size which will drive the allocation of all the other resources. bool update(const gpu::TexturePointer& linearDepthBuffer, int resolutionLevel, int depthResolutionLevel, bool isStereo); gpu::TexturePointer getLinearDepthTexture(); const glm::ivec2& getSourceFrameSize() const { return _frameSize; } bool isStereo() const { return _isStereo; } protected: void clear(); void allocate(); gpu::TexturePointer _linearDepthTexture; gpu::FramebufferPointer _occlusionFramebuffer; gpu::TexturePointer _occlusionTexture; gpu::FramebufferPointer _occlusionBlurredFramebuffer; gpu::TexturePointer _occlusionBlurredTexture; gpu::FramebufferPointer _normalFramebuffer; gpu::TexturePointer _normalTexture; #if SSAO_USE_QUAD_SPLIT gpu::FramebufferPointer _occlusionSplitFramebuffers[SSAO_SPLIT_COUNT*SSAO_SPLIT_COUNT]; gpu::TexturePointer _occlusionSplitTexture; #endif glm::ivec2 _frameSize; int _resolutionLevel{ 0 }; int _depthResolutionLevel{ 0 }; bool _isStereo{ false }; }; using AmbientOcclusionFramebufferPointer = std::shared_ptr<AmbientOcclusionFramebuffer>; class AmbientOcclusionEffectConfig : public render::GPUJobConfig::Persistent { Q_OBJECT Q_PROPERTY(bool horizonBased MEMBER horizonBased NOTIFY dirty) Q_PROPERTY(bool ditheringEnabled MEMBER ditheringEnabled NOTIFY dirty) Q_PROPERTY(bool borderingEnabled MEMBER borderingEnabled NOTIFY dirty) Q_PROPERTY(bool fetchMipsEnabled MEMBER fetchMipsEnabled NOTIFY dirty) Q_PROPERTY(bool jitterEnabled MEMBER jitterEnabled NOTIFY dirty) Q_PROPERTY(int resolutionLevel MEMBER resolutionLevel WRITE setResolutionLevel) Q_PROPERTY(float edgeSharpness MEMBER edgeSharpness WRITE setEdgeSharpness) Q_PROPERTY(int blurRadius MEMBER blurRadius WRITE setBlurRadius) // SSAO Q_PROPERTY(float ssaoRadius MEMBER ssaoRadius WRITE setSSAORadius) Q_PROPERTY(float ssaoObscuranceLevel MEMBER ssaoObscuranceLevel WRITE setSSAOObscuranceLevel) Q_PROPERTY(float ssaoFalloffAngle MEMBER ssaoFalloffAngle WRITE setSSAOFalloffAngle) Q_PROPERTY(float ssaoNumSpiralTurns MEMBER ssaoNumSpiralTurns WRITE setSSAONumSpiralTurns) Q_PROPERTY(int ssaoNumSamples MEMBER ssaoNumSamples WRITE setSSAONumSamples) // HBAO Q_PROPERTY(float hbaoRadius MEMBER hbaoRadius WRITE setHBAORadius) Q_PROPERTY(float hbaoObscuranceLevel MEMBER hbaoObscuranceLevel WRITE setHBAOObscuranceLevel) Q_PROPERTY(float hbaoFalloffAngle MEMBER hbaoFalloffAngle WRITE setHBAOFalloffAngle) Q_PROPERTY(int hbaoNumSamples MEMBER hbaoNumSamples WRITE setHBAONumSamples) public: AmbientOcclusionEffectConfig(); const int MAX_RESOLUTION_LEVEL = 4; const int MAX_BLUR_RADIUS = 15; void setEdgeSharpness(float sharpness); void setResolutionLevel(int level); void setBlurRadius(int radius); void setSSAORadius(float newRadius); void setSSAOObscuranceLevel(float level); void setSSAOFalloffAngle(float bias); void setSSAONumSpiralTurns(float turns); void setSSAONumSamples(int samples); void setHBAORadius(float newRadius); void setHBAOObscuranceLevel(float level); void setHBAOFalloffAngle(float bias); void setHBAONumSamples(int samples); float perspectiveScale; float edgeSharpness; int blurRadius; // 0 means no blurring int resolutionLevel; float ssaoRadius; float ssaoObscuranceLevel; // intensify or dim down the obscurance effect float ssaoFalloffAngle; float ssaoNumSpiralTurns; // defining an angle span to distribute the samples ray directions int ssaoNumSamples; float hbaoRadius; float hbaoObscuranceLevel; // intensify or dim down the obscurance effect float hbaoFalloffAngle; int hbaoNumSamples; bool horizonBased; // Use horizon based AO bool ditheringEnabled; // randomize the distribution of taps per pixel, should always be true bool borderingEnabled; // avoid evaluating information from non existing pixels out of the frame, should always be true bool fetchMipsEnabled; // fetch taps in sub mips to otpimize cache, should always be true bool jitterEnabled; // Add small jittering to AO samples at each frame signals: void dirty(); }; #define SSAO_RANDOM_SAMPLE_COUNT 16 class AmbientOcclusionEffect { public: using Input = render::VaryingSet4<LightingModelPointer, DeferredFrameTransformPointer, DeferredFramebufferPointer, LinearDepthFramebufferPointer>; using Output = render::VaryingSet2<AmbientOcclusionFramebufferPointer, gpu::BufferView>; using Config = AmbientOcclusionEffectConfig; using JobModel = render::Job::ModelIO<AmbientOcclusionEffect, Input, Output, Config>; AmbientOcclusionEffect(); void configure(const Config& config); void run(const render::RenderContextPointer& renderContext, const Input& input, Output& output); // Class describing the uniform buffer with all the parameters common to the AO shaders class AOParameters : public AmbientOcclusionParams { public: AOParameters(); int getResolutionLevel() const { return _resolutionInfo.x; } float getRadius() const { return _radiusInfo.x; } float getPerspectiveScale() const { return _resolutionInfo.z; } float getObscuranceLevel() const { return _radiusInfo.w; } float getFalloffAngle() const { return (float)_falloffInfo.x; } float getNumSpiralTurns() const { return _sampleInfo.z; } int getNumSamples() const { return (int)_sampleInfo.x; } bool isFetchMipsEnabled() const { return _sampleInfo.w; } bool isDitheringEnabled() const { return _ditheringInfo.x != 0.0f; } bool isBorderingEnabled() const { return _ditheringInfo.w != 0.0f; } bool isHorizonBased() const { return _resolutionInfo.y != 0.0f; } }; using AOParametersBuffer = gpu::StructBuffer<AOParameters>; private: // Class describing the uniform buffer with all the parameters common to the bilateral blur shaders class BlurParameters : public AmbientOcclusionBlurParams { public: BlurParameters(); float getEdgeSharpness() const { return (float)_blurInfo.x; } int getBlurRadius() const { return (int)_blurInfo.w; } }; using BlurParametersBuffer = gpu::StructBuffer<BlurParameters>; using FrameParametersBuffer = gpu::StructBuffer< AmbientOcclusionFrameParams>; void updateBlurParameters(); void updateFramebufferSizes(); void updateRandomSamples(); void updateJitterSamples(); int getDepthResolutionLevel() const; AOParametersBuffer _aoParametersBuffer; FrameParametersBuffer _aoFrameParametersBuffer[SSAO_SPLIT_COUNT*SSAO_SPLIT_COUNT]; BlurParametersBuffer _vblurParametersBuffer; BlurParametersBuffer _hblurParametersBuffer; float _blurEdgeSharpness{ 0.0f }; static const gpu::PipelinePointer& getOcclusionPipeline(); static const gpu::PipelinePointer& getBilateralBlurPipeline(); static const gpu::PipelinePointer& getMipCreationPipeline(); static const gpu::PipelinePointer& getGatherPipeline(); static const gpu::PipelinePointer& getBuildNormalsPipeline(); static gpu::PipelinePointer _occlusionPipeline; static gpu::PipelinePointer _bilateralBlurPipeline; static gpu::PipelinePointer _mipCreationPipeline; static gpu::PipelinePointer _gatherPipeline; static gpu::PipelinePointer _buildNormalsPipeline; AmbientOcclusionFramebufferPointer _framebuffer; std::array<float, SSAO_RANDOM_SAMPLE_COUNT * SSAO_SPLIT_COUNT*SSAO_SPLIT_COUNT> _randomSamples; int _frameId{ 0 }; bool _isJitterEnabled{ true }; gpu::RangeTimerPointer _gpuTimer; friend class DebugAmbientOcclusion; }; class DebugAmbientOcclusionConfig : public render::Job::Config { Q_OBJECT Q_PROPERTY(bool showCursorPixel MEMBER showCursorPixel NOTIFY dirty) Q_PROPERTY(glm::vec2 debugCursorTexcoord MEMBER debugCursorTexcoord NOTIFY dirty) public: DebugAmbientOcclusionConfig() : render::Job::Config(false) {} bool showCursorPixel{ false }; glm::vec2 debugCursorTexcoord{ 0.5f, 0.5f }; signals: void dirty(); }; class DebugAmbientOcclusion { public: using Inputs = render::VaryingSet4<DeferredFrameTransformPointer, DeferredFramebufferPointer, LinearDepthFramebufferPointer, AmbientOcclusionEffect::AOParametersBuffer>; using Config = DebugAmbientOcclusionConfig; using JobModel = render::Job::ModelI<DebugAmbientOcclusion, Inputs, Config>; DebugAmbientOcclusion(); void configure(const Config& config); void run(const render::RenderContextPointer& renderContext, const Inputs& inputs); private: // Class describing the uniform buffer with all the parameters common to the debug AO shaders class Parameters { public: // Pixel info glm::vec4 pixelInfo { 0.0f, 0.0f, 0.0f, 0.0f }; Parameters() {} }; gpu::StructBuffer<Parameters> _parametersBuffer; const gpu::PipelinePointer& getDebugPipeline(); gpu::PipelinePointer _debugPipeline; bool _showCursorPixel{ false }; }; #endif // hifi_AmbientOcclusionEffect_h
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import collections import copy import glob import importlib import itertools import json import math import os import time from bisect import bisect from itertools import product import demjson import numpy as np import torch import yaml from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from ray import tune from torch_geometric.utils import remove_self_loops def save_checkpoint(state, checkpoint_dir="checkpoints/"): filename = os.path.join(checkpoint_dir, "checkpoint.pt") torch.save(state, filename) class Complete(object): def __call__(self, data): device = data.edge_index.device row = torch.arange(data.num_nodes, dtype=torch.long, device=device) col = torch.arange(data.num_nodes, dtype=torch.long, device=device) row = row.view(-1, 1).repeat(1, data.num_nodes).view(-1) col = col.repeat(data.num_nodes) edge_index = torch.stack([row, col], dim=0) edge_attr = None if data.edge_attr is not None: idx = data.edge_index[0] * data.num_nodes + data.edge_index[1] size = list(data.edge_attr.size()) size[0] = data.num_nodes * data.num_nodes edge_attr = data.edge_attr.new_zeros(size) edge_attr[idx] = data.edge_attr edge_index, edge_attr = remove_self_loops(edge_index, edge_attr) data.edge_attr = edge_attr data.edge_index = edge_index return data def warmup_lr_lambda(current_step, optim_config): """Returns a learning rate multiplier. Till `warmup_steps`, learning rate linearly increases to `initial_lr`, and then gets multiplied by `lr_gamma` every time a milestone is crossed. """ # keep this block for older configs that have warmup_epochs instead of warmup_steps # and lr_milestones are defined in epochs if ( any(x < 100 for x in optim_config["lr_milestones"]) or "warmup_epochs" in optim_config ): raise Exception( "ConfigError: please define lr_milestones in steps not epochs and define warmup_steps instead of warmup_epochs" ) if current_step <= optim_config["warmup_steps"]: alpha = current_step / float(optim_config["warmup_steps"]) return optim_config["warmup_factor"] * (1.0 - alpha) + alpha else: idx = bisect(optim_config["lr_milestones"], current_step) return pow(optim_config["lr_gamma"], idx) def print_cuda_usage(): print("Memory Allocated:", torch.cuda.memory_allocated() / (1024 * 1024)) print( "Max Memory Allocated:", torch.cuda.max_memory_allocated() / (1024 * 1024), ) print("Memory Cached:", torch.cuda.memory_cached() / (1024 * 1024)) print("Max Memory Cached:", torch.cuda.max_memory_cached() / (1024 * 1024)) def conditional_grad(dec): "Decorator to enable/disable grad depending on whether force/energy predictions are being made" # Adapted from https://stackoverflow.com/questions/60907323/accessing-class-property-as-decorator-argument def decorator(func): def cls_method(self, *args, **kwargs): f = func if self.regress_forces: f = dec(func) return f(self, *args, **kwargs) return cls_method return decorator def plot_histogram(data, xlabel="", ylabel="", title=""): assert isinstance(data, list) # Preset fig = Figure(figsize=(5, 4), dpi=150) canvas = FigureCanvas(fig) ax = fig.gca() # Plot ax.hist(data, bins=20, rwidth=0.9, zorder=3) # Axes ax.grid(color="0.95", zorder=0) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_title(title) fig.tight_layout(pad=2) # Return numpy array canvas.draw() image_from_plot = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) image_from_plot = image_from_plot.reshape( fig.canvas.get_width_height()[::-1] + (3,) ) return image_from_plot # Override the collation method in `pytorch_geometric.data.InMemoryDataset` def collate(data_list): keys = data_list[0].keys data = data_list[0].__class__() for key in keys: data[key] = [] slices = {key: [0] for key in keys} for item, key in product(data_list, keys): data[key].append(item[key]) if torch.is_tensor(item[key]): s = slices[key][-1] + item[key].size( item.__cat_dim__(key, item[key]) ) elif isinstance(item[key], int) or isinstance(item[key], float): s = slices[key][-1] + 1 else: raise ValueError("Unsupported attribute type") slices[key].append(s) if hasattr(data_list[0], "__num_nodes__"): data.__num_nodes__ = [] for item in data_list: data.__num_nodes__.append(item.num_nodes) for key in keys: if torch.is_tensor(data_list[0][key]): data[key] = torch.cat( data[key], dim=data.__cat_dim__(key, data_list[0][key]) ) else: data[key] = torch.tensor(data[key]) slices[key] = torch.tensor(slices[key], dtype=torch.long) return data, slices def add_edge_distance_to_graph( batch, device="cpu", dmin=0.0, dmax=6.0, num_gaussians=50, ): # Make sure x has positions. if not all(batch.pos[0][:] == batch.x[0][-3:]): batch.x = torch.cat([batch.x, batch.pos.float()], dim=1) # First set computations to be tracked for positions. batch.x = batch.x.requires_grad_(True) # Then compute Euclidean distance between edge endpoints. pdist = torch.nn.PairwiseDistance(p=2.0) distances = pdist( batch.x[batch.edge_index[0]][:, -3:], batch.x[batch.edge_index[1]][:, -3:], ) # Expand it using a gaussian basis filter. gdf_filter = torch.linspace(dmin, dmax, num_gaussians) var = gdf_filter[1] - gdf_filter[0] gdf_filter, var = gdf_filter.to(device), var.to(device) gdf_distances = torch.exp( -((distances.view(-1, 1) - gdf_filter) ** 2) / var ** 2 ) # Reassign edge attributes. batch.edge_weight = distances batch.edge_attr = gdf_distances.float() return batch # Copied from https://github.com/facebookresearch/mmf/blob/master/mmf/utils/env.py#L89. def setup_imports(): from ocpmodels.common.registry import registry # First, check if imports are already setup has_already_setup = registry.get("imports_setup", no_warning=True) if has_already_setup: return # Automatically load all of the modules, so that # they register with registry root_folder = registry.get("ocpmodels_root", no_warning=True) if root_folder is None: root_folder = os.path.dirname(os.path.abspath(__file__)) root_folder = os.path.join(root_folder, "..") trainer_folder = os.path.join(root_folder, "trainers") trainer_pattern = os.path.join(trainer_folder, "**", "*.py") datasets_folder = os.path.join(root_folder, "datasets") datasets_pattern = os.path.join(datasets_folder, "*.py") model_folder = os.path.join(root_folder, "models") model_pattern = os.path.join(model_folder, "*.py") importlib.import_module("ocpmodels.common.meter") files = ( glob.glob(datasets_pattern, recursive=True) + glob.glob(model_pattern, recursive=True) + glob.glob(trainer_pattern, recursive=True) ) for f in files: for key in ["/trainers", "/datasets", "/models"]: if f.find(key) != -1: splits = f.split(os.sep) file_name = splits[-1] module_name = file_name[: file_name.find(".py")] importlib.import_module( "ocpmodels.%s.%s" % (key[1:], module_name) ) registry.register("imports_setup", True) def create_config_dict(args): overrides = {} for arg in args: arg = arg.strip("--") key, val = arg.split("=") overrides[key] = val return overrides def update_config(original, update): """ Recursively update a dict. Parameters must be specified in original to be overwritten """ for basekey, baseval in original.items(): if isinstance(baseval, dict): for key, val in baseval.items(): if key in update: original[basekey][key] = demjson.decode(update[key]) return original def build_config(args, args_override): config = yaml.safe_load(open(args.config_yml, "r")) # Load config from included files. includes = config.get("includes", []) if not isinstance(includes, list): raise AttributeError( "Includes must be a list, {} provided".format(type(includes)) ) for include in includes: include_config = yaml.safe_load(open(include, "r")) config.update(include_config) if includes != []: config.pop("includes") # Check for overriden parameters. if args_override != []: overrides = create_config_dict(args_override) config = update_config(config, overrides) # Some other flags. config["mode"] = args.mode config["identifier"] = args.identifier config["seed"] = args.seed config["is_debug"] = args.debug config["run_dir"] = args.run_dir config["is_vis"] = args.vis config["print_every"] = args.print_every config["amp"] = args.amp config["nonddp"] = args.nonddp config["checkpoint"] = args.checkpoint config["cpu"] = args.cpu # Submit config["submit"] = args.submit # Distributed config["local_rank"] = args.local_rank config["distributed_port"] = args.distributed_port config["world_size"] = args.num_nodes * args.num_gpus config["distributed_backend"] = args.distributed_backend return config def create_grid(base_config, sweep_file): def _flatten_sweeps(sweeps, root_key="", sep="."): flat_sweeps = [] for key, value in sweeps.items(): new_key = root_key + sep + key if root_key else key if isinstance(value, collections.MutableMapping): flat_sweeps.extend(_flatten_sweeps(value, new_key).items()) else: flat_sweeps.append((new_key, value)) return collections.OrderedDict(flat_sweeps) def _update_config(config, keys, override_vals, sep="."): for key, value in zip(keys, override_vals): key_path = key.split(sep) child_config = config for name in key_path[:-1]: child_config = child_config[name] child_config[key_path[-1]] = value return config sweeps = yaml.safe_load(open(sweep_file, "r")) flat_sweeps = _flatten_sweeps(sweeps) keys = list(flat_sweeps.keys()) values = list(itertools.product(*flat_sweeps.values())) configs = [] for i, override_vals in enumerate(values): config = copy.deepcopy(base_config) config = _update_config(config, keys, override_vals) config["identifier"] = config["identifier"] + f"_run{i}" configs.append(config) return configs def save_experiment_log(args, jobs, configs): log_file = args.logdir / "exp" / time.strftime("%Y-%m-%d-%I-%M-%S%p.log") log_file.parent.mkdir(exist_ok=True, parents=True) with open(log_file, "w") as f: for job, config in zip(jobs, configs): print( json.dumps( { "config": config, "slurm_id": job.job_id, "timestamp": time.strftime("%I:%M:%S%p %Z %b %d, %Y"), } ), file=f, ) return log_file def get_pbc_distances( pos, edge_index, cell, cell_offsets, neighbors, return_offsets=False, return_distance_vec=False, ): row, col = edge_index distance_vectors = pos[row] - pos[col] # correct for pbc neighbors = neighbors.to(cell.device) cell = torch.repeat_interleave(cell, neighbors, dim=0) offsets = cell_offsets.float().view(-1, 1, 3).bmm(cell.float()).view(-1, 3) distance_vectors += offsets # compute distances distances = distance_vectors.norm(dim=-1) # redundancy: remove zero distances nonzero_idx = torch.arange(len(distances))[distances != 0] edge_index = edge_index[:, nonzero_idx] distances = distances[nonzero_idx] out = { "edge_index": edge_index, "distances": distances, } if return_distance_vec: out["distance_vec"] = distance_vectors[nonzero_idx] if return_offsets: out["offsets"] = offsets[nonzero_idx] return out def radius_graph_pbc(data, radius, max_num_neighbors_threshold, device): batch_size = len(data.natoms) # position of the atoms atom_pos = data.pos # Before computing the pairwise distances between atoms, first create a list of atom indices to compare for the entire batch num_atoms_per_image = data.natoms num_atoms_per_image_sqr = (num_atoms_per_image ** 2).long() # index offset between images index_offset = ( torch.cumsum(num_atoms_per_image, dim=0) - num_atoms_per_image ) index_offset_expand = torch.repeat_interleave( index_offset, num_atoms_per_image_sqr ) num_atoms_per_image_expand = torch.repeat_interleave( num_atoms_per_image, num_atoms_per_image_sqr ) # Compute a tensor containing sequences of numbers that range from 0 to num_atoms_per_image_sqr for each image # that is used to compute indices for the pairs of atoms. This is a very convoluted way to implement # the following (but 10x faster since it removes the for loop) # for batch_idx in range(batch_size): # batch_count = torch.cat([batch_count, torch.arange(num_atoms_per_image_sqr[batch_idx], device=device)], dim=0) num_atom_pairs = torch.sum(num_atoms_per_image_sqr) index_sqr_offset = ( torch.cumsum(num_atoms_per_image_sqr, dim=0) - num_atoms_per_image_sqr ) index_sqr_offset = torch.repeat_interleave( index_sqr_offset, num_atoms_per_image_sqr ) atom_count_sqr = ( torch.arange(num_atom_pairs, device=device) - index_sqr_offset ) # Compute the indices for the pairs of atoms (using division and mod) # If the systems get too large this apporach could run into numerical precision issues index1 = ( (atom_count_sqr // num_atoms_per_image_expand) ).long() + index_offset_expand index2 = ( atom_count_sqr % num_atoms_per_image_expand ).long() + index_offset_expand # Get the positions for each atom pos1 = torch.index_select(atom_pos, 0, index1) pos2 = torch.index_select(atom_pos, 0, index2) # Tensor of unit cells. Assumes 9 cells in -1, 0, 1 offsets in the x and y dimensions unit_cell = torch.tensor( [ [-1, -1, 0], [-1, 0, 0], [-1, 1, 0], [0, -1, 0], [0, 0, 0], [0, 1, 0], [1, -1, 0], [1, 0, 0], [1, 1, 0], ], device=device, ).float() num_cells = len(unit_cell) unit_cell_per_atom = unit_cell.view(1, num_cells, 3).repeat( len(index2), 1, 1 ) unit_cell = torch.transpose(unit_cell, 0, 1) unit_cell_batch = unit_cell.view(1, 3, num_cells).expand( batch_size, -1, -1 ) # Compute the x, y, z positional offsets for each cell in each image data_cell = torch.transpose(data.cell, 1, 2) pbc_offsets = torch.bmm(data_cell, unit_cell_batch) pbc_offsets_per_atom = torch.repeat_interleave( pbc_offsets, num_atoms_per_image_sqr, dim=0 ) # Expand the positions and indices for the 9 cells pos1 = pos1.view(-1, 3, 1).expand(-1, -1, num_cells) pos2 = pos2.view(-1, 3, 1).expand(-1, -1, num_cells) index1 = index1.view(-1, 1).repeat(1, num_cells).view(-1) index2 = index2.view(-1, 1).repeat(1, num_cells).view(-1) # Add the PBC offsets for the second atom pos2 = pos2 + pbc_offsets_per_atom # Compute the squared distance between atoms atom_distance_sqr = torch.sum((pos1 - pos2) ** 2, dim=1) atom_distance_sqr = atom_distance_sqr.view(-1) # Remove pairs that are too far apart mask_within_radius = torch.le(atom_distance_sqr, radius * radius) # Remove pairs with the same atoms (distance = 0.0) mask_not_same = torch.gt(atom_distance_sqr, 0.0001) mask = torch.logical_and(mask_within_radius, mask_not_same) index1 = torch.masked_select(index1, mask) index2 = torch.masked_select(index2, mask) unit_cell = torch.masked_select( unit_cell_per_atom.view(-1, 3), mask.view(-1, 1).expand(-1, 3) ) unit_cell = unit_cell.view(-1, 3) num_atoms = len(data.pos) num_neighbors = torch.zeros(num_atoms, device=device) num_neighbors.index_add_(0, index1, torch.ones(len(index1), device=device)) num_neighbors = num_neighbors.long() max_num_neighbors = torch.max(num_neighbors).long() # Compute neighbors per image _max_neighbors = copy.deepcopy(num_neighbors) _max_neighbors[ _max_neighbors > max_num_neighbors_threshold ] = max_num_neighbors_threshold _num_neighbors = torch.zeros(num_atoms + 1, device=device).long() _natoms = torch.zeros(data.natoms.shape[0] + 1, device=device).long() _num_neighbors[1:] = torch.cumsum(_max_neighbors, dim=0) _natoms[1:] = torch.cumsum(data.natoms, dim=0) num_neighbors_image = ( _num_neighbors[_natoms[1:]] - _num_neighbors[_natoms[:-1]] ) # If max_num_neighbors is below the threshold, return early if ( max_num_neighbors <= max_num_neighbors_threshold or max_num_neighbors_threshold <= 0 ): return torch.stack((index2, index1)), unit_cell, num_neighbors_image atom_distance_sqr = torch.masked_select(atom_distance_sqr, mask) # Create a tensor of size [num_atoms, max_num_neighbors] to sort the distances of the neighbors. # Fill with values greater than radius*radius so we can easily remove unused distances later. distance_sort = torch.zeros( num_atoms * max_num_neighbors, device=device ).fill_(radius * radius + 1.0) # Create an index map to map distances from atom_distance_sqr to distance_sort index_neighbor_offset = torch.cumsum(num_neighbors, dim=0) - num_neighbors index_neighbor_offset_expand = torch.repeat_interleave( index_neighbor_offset, num_neighbors ) index_sort_map = ( index1 * max_num_neighbors + torch.arange(len(index1), device=device) - index_neighbor_offset_expand ) distance_sort.index_copy_(0, index_sort_map, atom_distance_sqr) distance_sort = distance_sort.view(num_atoms, max_num_neighbors) # Sort neighboring atoms based on distance distance_sort, index_sort = torch.sort(distance_sort, dim=1) # Select the max_num_neighbors_threshold neighbors that are closest distance_sort = distance_sort[:, :max_num_neighbors_threshold] index_sort = index_sort[:, :max_num_neighbors_threshold] # Offset index_sort so that it indexes into index1 index_sort = index_sort + index_neighbor_offset.view(-1, 1).expand( -1, max_num_neighbors_threshold ) # Remove "unused pairs" with distances greater than the radius mask_within_radius = torch.le(distance_sort, radius * radius) index_sort = torch.masked_select(index_sort, mask_within_radius) # At this point index_sort contains the index into index1 of the closest max_num_neighbors_threshold neighbors per atom # Create a mask to remove all pairs not in index_sort mask_num_neighbors = torch.zeros(len(index1), device=device).bool() mask_num_neighbors.index_fill_(0, index_sort, True) # Finally mask out the atoms to ensure each atom has at most max_num_neighbors_threshold neighbors index1 = torch.masked_select(index1, mask_num_neighbors) index2 = torch.masked_select(index2, mask_num_neighbors) unit_cell = torch.masked_select( unit_cell.view(-1, 3), mask_num_neighbors.view(-1, 1).expand(-1, 3) ) unit_cell = unit_cell.view(-1, 3) edge_index = torch.stack((index2, index1)) return edge_index, unit_cell, num_neighbors_image def get_pruned_edge_idx(edge_index, num_atoms=None, max_neigh=1e9): assert num_atoms is not None # removes neighbors > max_neigh # assumes neighbors are sorted in increasing distance _nonmax_idx = [] for i in range(num_atoms): idx_i = torch.arange(len(edge_index[1]))[(edge_index[1] == i)][ :max_neigh ] _nonmax_idx.append(idx_i) _nonmax_idx = torch.cat(_nonmax_idx) return _nonmax_idx def tune_reporter( iters, train_metrics, val_metrics, test_metrics=None, metric_to_opt="val_loss", min_max="min", ): """ Wrapper function for tune.report() Args: iters(dict): dict with training iteration info (e.g. steps, epochs) train_metrics(dict): train metrics dict val_metrics(dict): val metrics dict test_metrics(dict, optional): test metrics dict, default is None metric_to_opt(str, optional): str for val metric to optimize, default is val_loss min_max(str, optional): either "min" or "max", determines whether metric_to_opt is to be minimized or maximized, default is min """ # labels metric dicts train = label_metric_dict(train_metrics, "train") val = label_metric_dict(val_metrics, "val") # this enables tolerance for NaNs assumes val set is used for optimization if math.isnan(val[metric_to_opt]): if min_max == "min": val[metric_to_opt] = 100000.0 if min_max == "max": val[metric_to_opt] = 0.0 if test_metrics: test = label_metric_dict(test_metrics, "test") else: test = {} # report results to Ray Tune tune.report(**iters, **train, **val, **test) def label_metric_dict(metric_dict, split): new_dict = {} for key in metric_dict: new_dict["{}_{}".format(split, key)] = metric_dict[key] metric_dict = new_dict return metric_dict
import gutil from 'gulp-util'; import prettyHrtime from 'pretty-hrtime'; let startTime; /** * Provides gulp style logs to the bundle method in browserify */ export default { start(filepath) { startTime = process.hrtime(); gutil.log('Bundling', gutil.colors.green(filepath) + '...'); }, end(filepath) { let taskTime = process.hrtime(startTime); let prettyTime = prettyHrtime(taskTime); gutil.log('Bundled', gutil.colors.green(filepath), 'in', gutil.colors.magenta(prettyTime)); } };
let mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix.browserSync({ proxy: { target: 'blog.lo', reqHeaders: function () { return { host: "blog.lo" }; } }, files: [ 'resources/views/**/*.php', 'public/**/*.html', 'public/**/*.php', 'public/js/**/*.js', '!public/css/**/*.css' ], }); mix.js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css');
#!C:\StudentWork\SITE_BOOTCAMP_QA\StudentWork\abdullah_j\Python\Main\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3' __requires__ = 'pip==19.0.3' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('pip==19.0.3', 'console_scripts', 'pip3')() )
const fs = require('fs'); const http = require('http'); const url = require('url'); function tiempo(iso) { return{ hour: iso.getHours(), minute: iso.getMinutes(), second: iso.getSeconds() } } function unix(iso){ return{ unixtime: iso.getTime() } } const server = http.createServer(function(req, res){ let urlParsed = url.parse(req.url, true); let resultado = ''; if(req.method === 'GET'){ if(urlParsed.pathname == '/api/parsetime') { resultado=tiempo(new Date(urlParsed.query.iso)); } if(urlParsed.pathname == '/api/unixtime') { resultado=unix(new Date(urlParsed.query.iso)); } if(resultado){ res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(resultado)); } else{ res.end(); } } }) server.listen(Number(process.argv[2]));
function solve() { const VALID_TITLE_PATTERN = /^([\S]+\s?)*\S$/g; const VALID_NAME_PATTERN = /^[A-Z][a-z]*$/g; let _title; let _presentations; let _students = []; let _homeworks = []; let Course = { init: function(title, presentations) { if (typeof(title) !== 'string') { throw 'Error, invalid title argument'; } if (!title.match(VALID_TITLE_PATTERN)) { throw 'Error, invalid title'; } if (!Array.isArray(presentations) || presentations.length === 0) { throw 'Error, invalid presentations argument'; } presentations.forEach(function (element) { if (typeof(element) !== 'string' || !element.match(VALID_TITLE_PATTERN)) { throw 'Error, invalid presentation title'; } }); _title = title; _presentations = presentations; }, addStudent: function(name) { if (typeof(name) !== 'string' || name.trim().length === 0) { throw 'Error, invalid name argument'; } const names = name.split(' '); if (names.length > 2) { throw 'Error, more than 2 names'; } let firstName = names[0]; let lastName = names[1]; if (!firstName.match(VALID_NAME_PATTERN) || !lastName.match(VALID_NAME_PATTERN)) { throw 'Error, invalid first or last name'; } let student = { ID: _students.length + 1, firstname: firstName, lastname: lastName }; _students.push(student); return student.ID; }, getAllStudents: function() { let result = []; _students.forEach(function (student) { result.push({ firstname: student.firstname, lastname: student.lastname, id: student.ID }); }); return result; }, submitHomework: function(studentID, homeworkID) { if (!Number.isInteger(studentID) || !Number.isInteger(homeworkID)) { throw 'Argument must be an integer'; } if (homeworkID < 1 || homeworkID > _presentations.length) { throw 'Invalid homework id'; } let student = _students.find(function (element) { return element.ID === studentID; }); if (!student) { throw 'Invalid student id'; } _homeworks.push({ studentID: studentID, homeworkID: homeworkID }); }, pushExamResults: function(results) { /*if (!Array.isArray(results)) { throw 'Invalid argument results'; } results.forEach(function (result) { if (!result.hasOwnProperty('StudentID') || !result.hasOwnProperty('score')) { throw 'Invalid argument'; } let score = +result['score']; let studentId = +result['StudentID']; if (Number.isNaN(score) || Number.isNaN(studentId)) { throw 'Invalid value for score and studentId, must be numbers'; } let student = _students.find(function (st) { return st.ID === studentId; }); if (!student) { throw 'Invalid student id'; } student.score = score; }); // not listed get 0 _students.forEach(function (st) { if (!st.hasOwnProperty('score')) { st.score = 0; } });*/ }, getTopStudents: function() { } }; return Course; }
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var stacking_context_1 = require("../stacking-context"); var color_1 = require("../../css/types/color"); var logger_1 = require("../../core/logger"); var border_style_1 = require("../../css/property-descriptors/border-style"); var path_1 = require("../path"); var background_clip_1 = require("../../css/property-descriptors/background-clip"); var bound_curves_1 = require("../bound-curves"); var bezier_curve_1 = require("../bezier-curve"); var vector_1 = require("../vector"); var image_1 = require("../../css/types/image"); var border_1 = require("../border"); var background_1 = require("../background"); var parser_1 = require("../../css/syntax/parser"); var text_1 = require("../../css/layout/text"); var css_line_break_1 = require("css-line-break"); var image_element_container_1 = require("../../dom/replaced-elements/image-element-container"); var box_sizing_1 = require("../box-sizing"); var canvas_element_container_1 = require("../../dom/replaced-elements/canvas-element-container"); var svg_element_container_1 = require("../../dom/replaced-elements/svg-element-container"); var effects_1 = require("../effects"); var bitwise_1 = require("../../core/bitwise"); var gradient_1 = require("../../css/types/functions/gradient"); var length_percentage_1 = require("../../css/types/length-percentage"); var font_metrics_1 = require("../font-metrics"); var bounds_1 = require("../../css/layout/bounds"); var list_style_type_1 = require("../../css/property-descriptors/list-style-type"); var line_height_1 = require("../../css/property-descriptors/line-height"); var input_element_container_1 = require("../../dom/replaced-elements/input-element-container"); var text_align_1 = require("../../css/property-descriptors/text-align"); var textarea_element_container_1 = require("../../dom/elements/textarea-element-container"); var select_element_container_1 = require("../../dom/elements/select-element-container"); var iframe_element_container_1 = require("../../dom/replaced-elements/iframe-element-container"); var MASK_OFFSET = 10000; var CanvasRenderer = /** @class */ (function () { function CanvasRenderer(options) { this._activeEffects = []; this.canvas = options.canvas ? options.canvas : document.createElement('canvas'); this.ctx = this.canvas.getContext('2d'); this.options = options; this.canvas.width = Math.floor(options.width * options.scale); this.canvas.height = Math.floor(options.height * options.scale); this.canvas.style.width = options.width + "px"; this.canvas.style.height = options.height + "px"; this.fontMetrics = new font_metrics_1.FontMetrics(document); this.ctx.scale(this.options.scale, this.options.scale); this.ctx.translate(-options.x + options.scrollX, -options.y + options.scrollY); this.ctx.textBaseline = 'bottom'; this._activeEffects = []; logger_1.Logger.getInstance(options.id).debug("Canvas renderer initialized (" + options.width + "x" + options.height + " at " + options.x + "," + options.y + ") with scale " + options.scale); } CanvasRenderer.prototype.applyEffects = function (effects, target) { var _this = this; while (this._activeEffects.length) { this.popEffect(); } effects.filter(function (effect) { return bitwise_1.contains(effect.target, target); }).forEach(function (effect) { return _this.applyEffect(effect); }); }; CanvasRenderer.prototype.applyEffect = function (effect) { this.ctx.save(); if (effects_1.isTransformEffect(effect)) { this.ctx.translate(effect.offsetX, effect.offsetY); this.ctx.transform(effect.matrix[0], effect.matrix[1], effect.matrix[2], effect.matrix[3], effect.matrix[4], effect.matrix[5]); this.ctx.translate(-effect.offsetX, -effect.offsetY); } if (effects_1.isClipEffect(effect)) { this.path(effect.path); this.ctx.clip(); } this._activeEffects.push(effect); }; CanvasRenderer.prototype.popEffect = function () { this._activeEffects.pop(); this.ctx.restore(); }; CanvasRenderer.prototype.renderStack = function (stack) { return __awaiter(this, void 0, void 0, function () { var styles; return __generator(this, function (_a) { switch (_a.label) { case 0: styles = stack.element.container.styles; if (!styles.isVisible()) return [3 /*break*/, 2]; this.ctx.globalAlpha = styles.opacity; return [4 /*yield*/, this.renderStackContent(stack)]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/]; } }); }); }; CanvasRenderer.prototype.renderNode = function (paint) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!paint.container.styles.isVisible()) return [3 /*break*/, 3]; return [4 /*yield*/, this.renderNodeBackgroundAndBorders(paint)]; case 1: _a.sent(); return [4 /*yield*/, this.renderNodeContent(paint)]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); }; CanvasRenderer.prototype.renderTextWithLetterSpacing = function (text, letterSpacing) { var _this = this; if (letterSpacing === 0) { this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height); } else { var letters = css_line_break_1.toCodePoints(text.text).map(function (i) { return css_line_break_1.fromCodePoint(i); }); letters.reduce(function (left, letter) { _this.ctx.fillText(letter, left, text.bounds.top + text.bounds.height); return left + _this.ctx.measureText(letter).width; }, text.bounds.left); } }; CanvasRenderer.prototype.createFontStyle = function (styles) { var fontVariant = styles.fontVariant .filter(function (variant) { return variant === 'normal' || variant === 'small-caps'; }) .join(''); var fontFamily = styles.fontFamily.join(', '); var fontSize = parser_1.isDimensionToken(styles.fontSize) ? "" + styles.fontSize.number + styles.fontSize.unit : styles.fontSize.number + "px"; return [ [styles.fontStyle, fontVariant, styles.fontWeight, fontSize, fontFamily].join(' '), fontFamily, fontSize ]; }; CanvasRenderer.prototype.renderTextNode = function (text, styles) { return __awaiter(this, void 0, void 0, function () { var _a, font, fontFamily, fontSize; var _this = this; return __generator(this, function (_b) { _a = this.createFontStyle(styles), font = _a[0], fontFamily = _a[1], fontSize = _a[2]; this.ctx.font = font; text.textBounds.forEach(function (text) { _this.ctx.fillStyle = color_1.asString(styles.color); _this.renderTextWithLetterSpacing(text, styles.letterSpacing); var textShadows = styles.textShadow; if (textShadows.length && text.text.trim().length) { textShadows .slice(0) .reverse() .forEach(function (textShadow) { _this.ctx.shadowColor = color_1.asString(textShadow.color); _this.ctx.shadowOffsetX = textShadow.offsetX.number * _this.options.scale; _this.ctx.shadowOffsetY = textShadow.offsetY.number * _this.options.scale; _this.ctx.shadowBlur = textShadow.blur.number; _this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height); }); _this.ctx.shadowColor = ''; _this.ctx.shadowOffsetX = 0; _this.ctx.shadowOffsetY = 0; _this.ctx.shadowBlur = 0; } if (styles.textDecorationLine.length) { _this.ctx.fillStyle = color_1.asString(styles.textDecorationColor || styles.color); styles.textDecorationLine.forEach(function (textDecorationLine) { switch (textDecorationLine) { case 1 /* UNDERLINE */: // Draws a line at the baseline of the font // TODO As some browsers display the line as more than 1px if the font-size is big, // need to take that into account both in position and size var baseline = _this.fontMetrics.getMetrics(fontFamily, fontSize).baseline; _this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top + baseline), text.bounds.width, 1); break; case 2 /* OVERLINE */: _this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top), text.bounds.width, 1); break; case 3 /* LINE_THROUGH */: // TODO try and find exact position for line-through var middle = _this.fontMetrics.getMetrics(fontFamily, fontSize).middle; _this.ctx.fillRect(text.bounds.left, Math.ceil(text.bounds.top + middle), text.bounds.width, 1); break; } }); } }); return [2 /*return*/]; }); }); }; CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) { if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) { var box = box_sizing_1.contentBox(container); var path = bound_curves_1.calculatePaddingBoxPath(curves); this.path(path); this.ctx.save(); this.ctx.clip(); this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, box.left, box.top, box.width, box.height); this.ctx.restore(); } }; CanvasRenderer.prototype.renderNodeContent = function (paint) { return __awaiter(this, void 0, void 0, function () { var container, curves, styles, _i, _a, child, image, e_1, image, e_2, iframeRenderer, canvas, size, bounds, x, textBounds, img, image, url, e_3, bounds; return __generator(this, function (_b) { switch (_b.label) { case 0: this.applyEffects(paint.effects, 4 /* CONTENT */); container = paint.container; curves = paint.curves; styles = container.styles; _i = 0, _a = container.textNodes; _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/, 4]; child = _a[_i]; return [4 /*yield*/, this.renderTextNode(child, styles)]; case 2: _b.sent(); _b.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: if (!(container instanceof image_element_container_1.ImageElementContainer)) return [3 /*break*/, 8]; _b.label = 5; case 5: _b.trys.push([5, 7, , 8]); return [4 /*yield*/, this.options.cache.match(container.src)]; case 6: image = _b.sent(); this.renderReplacedElement(container, curves, image); return [3 /*break*/, 8]; case 7: e_1 = _b.sent(); logger_1.Logger.getInstance(this.options.id).error("Error loading image " + container.src); return [3 /*break*/, 8]; case 8: if (container instanceof canvas_element_container_1.CanvasElementContainer) { this.renderReplacedElement(container, curves, container.canvas); } if (!(container instanceof svg_element_container_1.SVGElementContainer)) return [3 /*break*/, 12]; _b.label = 9; case 9: _b.trys.push([9, 11, , 12]); return [4 /*yield*/, this.options.cache.match(container.svg)]; case 10: image = _b.sent(); this.renderReplacedElement(container, curves, image); return [3 /*break*/, 12]; case 11: e_2 = _b.sent(); logger_1.Logger.getInstance(this.options.id).error("Error loading svg " + container.svg.substring(0, 255)); return [3 /*break*/, 12]; case 12: if (!(container instanceof iframe_element_container_1.IFrameElementContainer && container.tree)) return [3 /*break*/, 14]; iframeRenderer = new CanvasRenderer({ id: this.options.id, scale: this.options.scale, backgroundColor: container.backgroundColor, x: 0, y: 0, scrollX: 0, scrollY: 0, width: container.width, height: container.height, cache: this.options.cache, windowWidth: container.width, windowHeight: container.height }); return [4 /*yield*/, iframeRenderer.render(container.tree)]; case 13: canvas = _b.sent(); this.ctx.drawImage(canvas, 0, 0, container.width, container.width, container.bounds.left, container.bounds.top, container.bounds.width, container.bounds.height); _b.label = 14; case 14: if (container instanceof input_element_container_1.InputElementContainer) { size = Math.min(container.bounds.width, container.bounds.height); if (container.type === input_element_container_1.CHECKBOX) { if (container.checked) { this.ctx.save(); this.path([ new vector_1.Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79), new vector_1.Vector(container.bounds.left + size * 0.16, container.bounds.top + size * 0.5549), new vector_1.Vector(container.bounds.left + size * 0.27347, container.bounds.top + size * 0.44071), new vector_1.Vector(container.bounds.left + size * 0.39694, container.bounds.top + size * 0.5649), new vector_1.Vector(container.bounds.left + size * 0.72983, container.bounds.top + size * 0.23), new vector_1.Vector(container.bounds.left + size * 0.84, container.bounds.top + size * 0.34085), new vector_1.Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79) ]); this.ctx.fillStyle = color_1.asString(input_element_container_1.INPUT_COLOR); this.ctx.fill(); this.ctx.restore(); } } else if (container.type === input_element_container_1.RADIO) { if (container.checked) { this.ctx.save(); this.ctx.beginPath(); this.ctx.arc(container.bounds.left + size / 2, container.bounds.top + size / 2, size / 4, 0, Math.PI * 2, true); this.ctx.fillStyle = color_1.asString(input_element_container_1.INPUT_COLOR); this.ctx.fill(); this.ctx.restore(); } } } if (isTextInputElement(container) && container.value.length) { this.ctx.font = this.createFontStyle(styles)[0]; this.ctx.fillStyle = color_1.asString(styles.color); this.ctx.textBaseline = 'middle'; this.ctx.textAlign = canvasTextAlign(container.styles.textAlign); bounds = box_sizing_1.contentBox(container); x = 0; switch (container.styles.textAlign) { case text_align_1.TEXT_ALIGN.CENTER: x += bounds.width / 2; break; case text_align_1.TEXT_ALIGN.RIGHT: x += bounds.width; break; } textBounds = bounds.add(x, 0, 0, -bounds.height / 2 + 1); this.ctx.save(); this.path([ new vector_1.Vector(bounds.left, bounds.top), new vector_1.Vector(bounds.left + bounds.width, bounds.top), new vector_1.Vector(bounds.left + bounds.width, bounds.top + bounds.height), new vector_1.Vector(bounds.left, bounds.top + bounds.height) ]); this.ctx.clip(); this.renderTextWithLetterSpacing(new text_1.TextBounds(container.value, textBounds), styles.letterSpacing); this.ctx.restore(); this.ctx.textBaseline = 'bottom'; this.ctx.textAlign = 'left'; } if (!bitwise_1.contains(container.styles.display, 2048 /* LIST_ITEM */)) return [3 /*break*/, 20]; if (!(container.styles.listStyleImage !== null)) return [3 /*break*/, 19]; img = container.styles.listStyleImage; if (!(img.type === image_1.CSSImageType.URL)) return [3 /*break*/, 18]; image = void 0; url = img.url; _b.label = 15; case 15: _b.trys.push([15, 17, , 18]); return [4 /*yield*/, this.options.cache.match(url)]; case 16: image = _b.sent(); this.ctx.drawImage(image, container.bounds.left - (image.width + 10), container.bounds.top); return [3 /*break*/, 18]; case 17: e_3 = _b.sent(); logger_1.Logger.getInstance(this.options.id).error("Error loading list-style-image " + url); return [3 /*break*/, 18]; case 18: return [3 /*break*/, 20]; case 19: if (paint.listValue && container.styles.listStyleType !== list_style_type_1.LIST_STYLE_TYPE.NONE) { this.ctx.font = this.createFontStyle(styles)[0]; this.ctx.fillStyle = color_1.asString(styles.color); this.ctx.textBaseline = 'middle'; this.ctx.textAlign = 'right'; bounds = new bounds_1.Bounds(container.bounds.left, container.bounds.top + length_percentage_1.getAbsoluteValue(container.styles.paddingTop, container.bounds.width), container.bounds.width, line_height_1.computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 1); this.renderTextWithLetterSpacing(new text_1.TextBounds(paint.listValue, bounds), styles.letterSpacing); this.ctx.textBaseline = 'bottom'; this.ctx.textAlign = 'left'; } _b.label = 20; case 20: return [2 /*return*/]; } }); }); }; CanvasRenderer.prototype.renderStackContent = function (stack) { return __awaiter(this, void 0, void 0, function () { var _i, _a, child, _b, _c, child, _d, _e, child, _f, _g, child, _h, _j, child, _k, _l, child, _m, _o, child; return __generator(this, function (_p) { switch (_p.label) { case 0: // https://www.w3.org/TR/css-position-3/#painting-order // 1. the background and borders of the element forming the stacking context. return [4 /*yield*/, this.renderNodeBackgroundAndBorders(stack.element)]; case 1: // https://www.w3.org/TR/css-position-3/#painting-order // 1. the background and borders of the element forming the stacking context. _p.sent(); _i = 0, _a = stack.negativeZIndex; _p.label = 2; case 2: if (!(_i < _a.length)) return [3 /*break*/, 5]; child = _a[_i]; return [4 /*yield*/, this.renderStack(child)]; case 3: _p.sent(); _p.label = 4; case 4: _i++; return [3 /*break*/, 2]; case 5: // 3. For all its in-flow, non-positioned, block-level descendants in tree order: return [4 /*yield*/, this.renderNodeContent(stack.element)]; case 6: // 3. For all its in-flow, non-positioned, block-level descendants in tree order: _p.sent(); _b = 0, _c = stack.nonInlineLevel; _p.label = 7; case 7: if (!(_b < _c.length)) return [3 /*break*/, 10]; child = _c[_b]; return [4 /*yield*/, this.renderNode(child)]; case 8: _p.sent(); _p.label = 9; case 9: _b++; return [3 /*break*/, 7]; case 10: _d = 0, _e = stack.nonPositionedFloats; _p.label = 11; case 11: if (!(_d < _e.length)) return [3 /*break*/, 14]; child = _e[_d]; return [4 /*yield*/, this.renderStack(child)]; case 12: _p.sent(); _p.label = 13; case 13: _d++; return [3 /*break*/, 11]; case 14: _f = 0, _g = stack.nonPositionedInlineLevel; _p.label = 15; case 15: if (!(_f < _g.length)) return [3 /*break*/, 18]; child = _g[_f]; return [4 /*yield*/, this.renderStack(child)]; case 16: _p.sent(); _p.label = 17; case 17: _f++; return [3 /*break*/, 15]; case 18: _h = 0, _j = stack.inlineLevel; _p.label = 19; case 19: if (!(_h < _j.length)) return [3 /*break*/, 22]; child = _j[_h]; return [4 /*yield*/, this.renderNode(child)]; case 20: _p.sent(); _p.label = 21; case 21: _h++; return [3 /*break*/, 19]; case 22: _k = 0, _l = stack.zeroOrAutoZIndexOrTransformedOrOpacity; _p.label = 23; case 23: if (!(_k < _l.length)) return [3 /*break*/, 26]; child = _l[_k]; return [4 /*yield*/, this.renderStack(child)]; case 24: _p.sent(); _p.label = 25; case 25: _k++; return [3 /*break*/, 23]; case 26: _m = 0, _o = stack.positiveZIndex; _p.label = 27; case 27: if (!(_m < _o.length)) return [3 /*break*/, 30]; child = _o[_m]; return [4 /*yield*/, this.renderStack(child)]; case 28: _p.sent(); _p.label = 29; case 29: _m++; return [3 /*break*/, 27]; case 30: return [2 /*return*/]; } }); }); }; CanvasRenderer.prototype.mask = function (paths) { this.ctx.beginPath(); this.ctx.moveTo(0, 0); this.ctx.lineTo(this.canvas.width, 0); this.ctx.lineTo(this.canvas.width, this.canvas.height); this.ctx.lineTo(0, this.canvas.height); this.ctx.lineTo(0, 0); this.formatPath(paths.slice(0).reverse()); this.ctx.closePath(); }; CanvasRenderer.prototype.path = function (paths) { this.ctx.beginPath(); this.formatPath(paths); this.ctx.closePath(); }; CanvasRenderer.prototype.formatPath = function (paths) { var _this = this; paths.forEach(function (point, index) { var start = bezier_curve_1.isBezierCurve(point) ? point.start : point; if (index === 0) { _this.ctx.moveTo(start.x, start.y); } else { _this.ctx.lineTo(start.x, start.y); } if (bezier_curve_1.isBezierCurve(point)) { _this.ctx.bezierCurveTo(point.startControl.x, point.startControl.y, point.endControl.x, point.endControl.y, point.end.x, point.end.y); } }); }; CanvasRenderer.prototype.renderRepeat = function (path, pattern, offsetX, offsetY) { this.path(path); this.ctx.fillStyle = pattern; this.ctx.translate(offsetX, offsetY); this.ctx.fill(); this.ctx.translate(-offsetX, -offsetY); }; CanvasRenderer.prototype.resizeImage = function (image, width, height) { if (image.width === width && image.height === height) { return image; } var canvas = this.canvas.ownerDocument.createElement('canvas'); canvas.width = width; canvas.height = height; var ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, width, height); return canvas; }; CanvasRenderer.prototype.renderBackgroundImage = function (container) { return __awaiter(this, void 0, void 0, function () { var index, _loop_1, this_1, _i, _a, backgroundImage; return __generator(this, function (_b) { switch (_b.label) { case 0: index = container.styles.backgroundImage.length - 1; _loop_1 = function (backgroundImage) { var image, url, e_4, _a, path, x, y, width, height, pattern, _b, path, x, y, width, height, _c, lineLength, x0, x1, y0, y1, canvas, ctx, gradient_2, pattern, _d, path, left, top_1, width, height, position, x, y, _e, rx, ry, radialGradient_1, midX, midY, f, invF; return __generator(this, function (_f) { switch (_f.label) { case 0: if (!(backgroundImage.type === image_1.CSSImageType.URL)) return [3 /*break*/, 5]; image = void 0; url = backgroundImage.url; _f.label = 1; case 1: _f.trys.push([1, 3, , 4]); return [4 /*yield*/, this_1.options.cache.match(url)]; case 2: image = _f.sent(); return [3 /*break*/, 4]; case 3: e_4 = _f.sent(); logger_1.Logger.getInstance(this_1.options.id).error("Error loading background-image " + url); return [3 /*break*/, 4]; case 4: if (image) { _a = background_1.calculateBackgroundRendering(container, index, [ image.width, image.height, image.width / image.height ]), path = _a[0], x = _a[1], y = _a[2], width = _a[3], height = _a[4]; pattern = this_1.ctx.createPattern(this_1.resizeImage(image, width, height), 'repeat'); this_1.renderRepeat(path, pattern, x, y); } return [3 /*break*/, 6]; case 5: if (image_1.isLinearGradient(backgroundImage)) { _b = background_1.calculateBackgroundRendering(container, index, [null, null, null]), path = _b[0], x = _b[1], y = _b[2], width = _b[3], height = _b[4]; _c = gradient_1.calculateGradientDirection(backgroundImage.angle, width, height), lineLength = _c[0], x0 = _c[1], x1 = _c[2], y0 = _c[3], y1 = _c[4]; canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; ctx = canvas.getContext('2d'); gradient_2 = ctx.createLinearGradient(x0, y0, x1, y1); gradient_1.processColorStops(backgroundImage.stops, lineLength).forEach(function (colorStop) { return gradient_2.addColorStop(colorStop.stop, color_1.asString(colorStop.color)); }); ctx.fillStyle = gradient_2; ctx.fillRect(0, 0, width, height); pattern = this_1.ctx.createPattern(canvas, 'repeat'); this_1.renderRepeat(path, pattern, x, y); } else if (image_1.isRadialGradient(backgroundImage)) { _d = background_1.calculateBackgroundRendering(container, index, [ null, null, null ]), path = _d[0], left = _d[1], top_1 = _d[2], width = _d[3], height = _d[4]; position = backgroundImage.position.length === 0 ? [length_percentage_1.FIFTY_PERCENT] : backgroundImage.position; x = length_percentage_1.getAbsoluteValue(position[0], width); y = length_percentage_1.getAbsoluteValue(position[position.length - 1], height); _e = gradient_1.calculateRadius(backgroundImage, x, y, width, height), rx = _e[0], ry = _e[1]; if (rx > 0 && rx > 0) { radialGradient_1 = this_1.ctx.createRadialGradient(left + x, top_1 + y, 0, left + x, top_1 + y, rx); gradient_1.processColorStops(backgroundImage.stops, rx * 2).forEach(function (colorStop) { return radialGradient_1.addColorStop(colorStop.stop, color_1.asString(colorStop.color)); }); this_1.path(path); this_1.ctx.fillStyle = radialGradient_1; if (rx !== ry) { midX = container.bounds.left + 0.5 * container.bounds.width; midY = container.bounds.top + 0.5 * container.bounds.height; f = ry / rx; invF = 1 / f; this_1.ctx.save(); this_1.ctx.translate(midX, midY); this_1.ctx.transform(1, 0, 0, f, 0, 0); this_1.ctx.translate(-midX, -midY); this_1.ctx.fillRect(left, invF * (top_1 - midY) + midY, width, height * invF); this_1.ctx.restore(); } else { this_1.ctx.fill(); } } } _f.label = 6; case 6: index--; return [2 /*return*/]; } }); }; this_1 = this; _i = 0, _a = container.styles.backgroundImage.slice(0).reverse(); _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/, 4]; backgroundImage = _a[_i]; return [5 /*yield**/, _loop_1(backgroundImage)]; case 2: _b.sent(); _b.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/]; } }); }); }; CanvasRenderer.prototype.renderBorder = function (color, side, curvePoints) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { this.path(border_1.parsePathForBorder(curvePoints, side)); this.ctx.fillStyle = color_1.asString(color); this.ctx.fill(); return [2 /*return*/]; }); }); }; CanvasRenderer.prototype.renderNodeBackgroundAndBorders = function (paint) { return __awaiter(this, void 0, void 0, function () { var styles, hasBackground, borders, backgroundPaintingArea, side, _i, borders_1, border; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: this.applyEffects(paint.effects, 2 /* BACKGROUND_BORDERS */); styles = paint.container.styles; hasBackground = !color_1.isTransparent(styles.backgroundColor) || styles.backgroundImage.length; borders = [ { style: styles.borderTopStyle, color: styles.borderTopColor }, { style: styles.borderRightStyle, color: styles.borderRightColor }, { style: styles.borderBottomStyle, color: styles.borderBottomColor }, { style: styles.borderLeftStyle, color: styles.borderLeftColor } ]; backgroundPaintingArea = calculateBackgroundCurvedPaintingArea(background_1.getBackgroundValueForIndex(styles.backgroundClip, 0), paint.curves); if (!(hasBackground || styles.boxShadow.length)) return [3 /*break*/, 2]; this.ctx.save(); this.path(backgroundPaintingArea); this.ctx.clip(); if (!color_1.isTransparent(styles.backgroundColor)) { this.ctx.fillStyle = color_1.asString(styles.backgroundColor); this.ctx.fill(); } return [4 /*yield*/, this.renderBackgroundImage(paint.container)]; case 1: _a.sent(); this.ctx.restore(); styles.boxShadow .slice(0) .reverse() .forEach(function (shadow) { _this.ctx.save(); var borderBoxArea = bound_curves_1.calculateBorderBoxPath(paint.curves); var maskOffset = shadow.inset ? 0 : MASK_OFFSET; var shadowPaintingArea = path_1.transformPath(borderBoxArea, -maskOffset + (shadow.inset ? 1 : -1) * shadow.spread.number, (shadow.inset ? 1 : -1) * shadow.spread.number, shadow.spread.number * (shadow.inset ? -2 : 2), shadow.spread.number * (shadow.inset ? -2 : 2)); if (shadow.inset) { _this.path(borderBoxArea); _this.ctx.clip(); _this.mask(shadowPaintingArea); } else { _this.mask(borderBoxArea); _this.ctx.clip(); _this.path(shadowPaintingArea); } _this.ctx.shadowOffsetX = shadow.offsetX.number + maskOffset; _this.ctx.shadowOffsetY = shadow.offsetY.number; _this.ctx.shadowColor = color_1.asString(shadow.color); _this.ctx.shadowBlur = shadow.blur.number; _this.ctx.fillStyle = shadow.inset ? color_1.asString(shadow.color) : 'rgba(0,0,0,1)'; _this.ctx.fill(); _this.ctx.restore(); }); _a.label = 2; case 2: side = 0; _i = 0, borders_1 = borders; _a.label = 3; case 3: if (!(_i < borders_1.length)) return [3 /*break*/, 6]; border = borders_1[_i]; if (!(border.style !== border_style_1.BORDER_STYLE.NONE && !color_1.isTransparent(border.color))) return [3 /*break*/, 5]; return [4 /*yield*/, this.renderBorder(border.color, side++, paint.curves)]; case 4: _a.sent(); _a.label = 5; case 5: _i++; return [3 /*break*/, 3]; case 6: return [2 /*return*/]; } }); }); }; CanvasRenderer.prototype.render = function (element) { return __awaiter(this, void 0, void 0, function () { var stack; return __generator(this, function (_a) { switch (_a.label) { case 0: if (this.options.backgroundColor) { this.ctx.fillStyle = color_1.asString(this.options.backgroundColor); this.ctx.fillRect(this.options.x - this.options.scrollX, this.options.y - this.options.scrollY, this.options.width, this.options.height); } stack = stacking_context_1.parseStackingContexts(element); return [4 /*yield*/, this.renderStack(stack)]; case 1: _a.sent(); this.applyEffects([], 2 /* BACKGROUND_BORDERS */); return [2 /*return*/, this.canvas]; } }); }); }; return CanvasRenderer; }()); exports.CanvasRenderer = CanvasRenderer; var isTextInputElement = function (container) { if (container instanceof textarea_element_container_1.TextareaElementContainer) { return true; } else if (container instanceof select_element_container_1.SelectElementContainer) { return true; } else if (container instanceof input_element_container_1.InputElementContainer && container.type !== input_element_container_1.RADIO && container.type !== input_element_container_1.CHECKBOX) { return true; } return false; }; var calculateBackgroundCurvedPaintingArea = function (clip, curves) { switch (clip) { case background_clip_1.BACKGROUND_CLIP.BORDER_BOX: return bound_curves_1.calculateBorderBoxPath(curves); case background_clip_1.BACKGROUND_CLIP.CONTENT_BOX: return bound_curves_1.calculateContentBoxPath(curves); case background_clip_1.BACKGROUND_CLIP.PADDING_BOX: default: return bound_curves_1.calculatePaddingBoxPath(curves); } }; var canvasTextAlign = function (textAlign) { switch (textAlign) { case text_align_1.TEXT_ALIGN.CENTER: return 'center'; case text_align_1.TEXT_ALIGN.RIGHT: return 'right'; case text_align_1.TEXT_ALIGN.LEFT: default: return 'left'; } }; //# sourceMappingURL=canvas-renderer.js.map
/********************************************************************* Copyright 2013 Karl Jones All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. For Further Information Please Contact me at Karljj1@yahoo.com http://p.sf.net/kdis/UserGuide *********************************************************************/ /******************************************************************** class: Acknowledge_PDU DIS: (5) 1278.1 - 1995 created: 2008/10/19 author: Karl Jones purpose: Sent to acknowledges receipt of a Start/Resume PDU, Stop/Freeze PDU, Create Entity PDU or Remove Entity PDU. size: 256 bits / 32 octets *********************************************************************/ #pragma once #include "./Simulation_Management_Header.h" #include "./Create_Entity_PDU.h" #include "./Remove_Entity_PDU.h" #include "./Start_Resume_PDU.h" #include "./Stop_Freeze_PDU.h" namespace KDIS { namespace PDU { class KDIS_EXPORT Acknowledge_PDU : public Simulation_Management_Header { protected: KUINT16 m_ui16AcknowledgeFlag; KUINT16 m_ui16ResponseFlag; KUINT32 m_ui32RequestID; public: static const KUINT16 ACKNOWLEDGE_PDU_SIZE = 32; Acknowledge_PDU(); Acknowledge_PDU( const Header & H ); Acknowledge_PDU( KDataStream & stream ) ; Acknowledge_PDU( const Header & H, KDataStream & stream ) ; Acknowledge_PDU( const KDIS::DATA_TYPE::EntityIdentifier & OriginatingEntityID, const KDIS::DATA_TYPE::EntityIdentifier & ReceivingEntityID, KDIS::DATA_TYPE::ENUMS::AcknowledgeFlag AF, KDIS::DATA_TYPE::ENUMS::AcknowledgeResponseFlag ARF, KUINT32 RequestID ); Acknowledge_PDU( const Simulation_Management_Header & SimMgrHeader, KDIS::DATA_TYPE::ENUMS::AcknowledgeFlag AF, KDIS::DATA_TYPE::ENUMS::AcknowledgeResponseFlag ARF, KUINT32 RequestID ); // Generate a response to a specific PDU Acknowledge_PDU( const Create_Entity_PDU & pdu, KDIS::DATA_TYPE::ENUMS::AcknowledgeResponseFlag ARF ); Acknowledge_PDU( const Remove_Entity_PDU & pdu, KDIS::DATA_TYPE::ENUMS::AcknowledgeResponseFlag ARF ); Acknowledge_PDU( const Start_Resume_PDU & pdu, KDIS::DATA_TYPE::ENUMS::AcknowledgeResponseFlag ARF ); Acknowledge_PDU( const Stop_Freeze_PDU & pdu, KDIS::DATA_TYPE::ENUMS::AcknowledgeResponseFlag ARF ); virtual ~Acknowledge_PDU(); //************************************ // FullName: KDIS::PDU::Acknowledge_PDU::SetAcknowledgeFlag // KDIS::PDU::Acknowledge_PDU::GetAcknowledgeFlag // Description: Indicates the type of message being acknowledged // Parameter: AcknowledgeFlag AF //************************************ void SetAcknowledgeFlag( KDIS::DATA_TYPE::ENUMS::AcknowledgeFlag AF ); KDIS::DATA_TYPE::ENUMS::AcknowledgeFlag GetAcknowledgeFlag() const; //************************************ // FullName: KDIS::PDU::Acknowledge_PDU::SetAcknowledgeResponseFlag // KDIS::PDU::Acknowledge_PDU::GetAcknowledgeResponseFlag // Description: Indicates if the receiving entity is able to comply with the request // Parameter: AcknowledgeResponseFlag ARF //************************************ void SetAcknowledgeResponseFlag( KDIS::DATA_TYPE::ENUMS::AcknowledgeResponseFlag ARF ); KDIS::DATA_TYPE::ENUMS::AcknowledgeResponseFlag GetAcknowledgeResponseFlag() const; //************************************ // FullName: KDIS::PDU::Acknowledge_PDU::SetRequestID // KDIS::PDU::Acknowledge_PDU::GetRequestID // Description: Request ID // Parameter: KUINT32 ID, void //************************************ void SetRequestID( KUINT32 ID ); KUINT32 GetRequestID() const; //************************************ // FullName: KDIS::PDU::Acknowledge_PDU::GetAsString // Description: Returns a string representation of the PDU. //************************************ virtual KString GetAsString() const; //************************************ // FullName: KDIS::PDU::Acknowledge_PDU::Decode // Description: Convert From Network Data. // Parameter: KDataStream & stream // Parameter: bool ignoreHeader = false - Decode the header from the stream? //************************************ virtual void Decode( KDataStream & stream, bool ignoreHeader = false ) ; //************************************ // FullName: KDIS::PDU::Acknowledge_PDU::Encode // Description: Convert To Network Data. //************************************ virtual KDataStream Encode() const; virtual void Encode( KDataStream & stream ) const; KBOOL operator == ( const Acknowledge_PDU & Value ) const; KBOOL operator != ( const Acknowledge_PDU & Value ) const; }; } // END namespace PDU } // END namespace KDIS
import functools import logging from threading import Event from typing import Any, Optional, Type from webmesh.message_protocols import AbstractMessageProtocol, SimpleDictProtocol from webmesh.message_serializers import MessagePackSerializer, AbstractMessageSerializer from webmesh.websocket.websocket_connection import WebSocketConnection from webmesh.websocket.websocket_server import WebSocketServer, AbstractWebSocketHandler class WebMeshHandler(AbstractWebSocketHandler): def __init__(self): self.consumers = {} def on_message(self, connection: WebSocketConnection, path: str, data: Any) -> Optional[Any]: if path in self.consumers: consumer = self.consumers[path] return consumer(data, path, connection) else: # Not found stuff pass def on(self, path): def wrapper(func): @functools.wraps(func) def run(message, path, connection): connection.logger.debug(f'Message received on {path}: {message}') return func(message, path, connection) self.consumers[path] = run return run return wrapper class WebMeshServer(WebSocketServer): def __init__(self, host: str = '0.0.0.0', port: int = 4269, debug: bool = False, max_parallelism: int = 5, serializer_type: Type[AbstractMessageSerializer] = MessagePackSerializer, protocol_type: Type[AbstractMessageProtocol] = SimpleDictProtocol ): handler = WebMeshHandler() super().__init__(handler, serializer_type, protocol_type, max_parallelism=max_parallelism) self.host = host self.port = port self.debug = debug self.logger = logging.getLogger('webmesh.server') self.consumers = {} self.on = handler.on def listen(self, host: str = '0.0.0.0', port: int = 4269, blocking: bool = False): super().listen(host, port, blocking) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s, %(name)s, %(asctime)s]' '[%(threadName)s]' '[%(filename)s:%(funcName)s:%(lineno)d]:' ' %(message)s') server = WebMeshServer() @server.on('/id') def _id(payload, path, connection: WebSocketConnection): print('hello') return connection.id server.listen() Event().wait() server.close()
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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 ebcli.resources.statics import namespaces, option_names from ebcli.lib import elasticbeanstalk from ebcli.operations import commonops def open_app(app_name, env_name): env = elasticbeanstalk.get_environment(app_name=app_name, env_name=env_name) settings = elasticbeanstalk.describe_configuration_settings( app_name, env_name) option_settings = settings.get('OptionSettings', []) http_port = elasticbeanstalk.get_option_setting( option_settings, namespaces.LOAD_BALANCER, option_names.LOAD_BALANCER_HTTP_PORT) if http_port == 'OFF': ssl = True else: ssl = False commonops.open_webpage_in_browser(env.cname, ssl=ssl)
/*========================================================================= Program: Visualization Toolkit Module: vtkDelimitedTextReader.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ // .NAME vtkDelimitedTextReader - reader for pulling in flat text files // // .SECTION Description // vtkDelimitedTextReader is an interface for pulling in data from a // flat, delimited text file (delimiter can be any character). // // This class emits ProgressEvent for every 100 lines it reads. // // .SECTION Thanks // Thanks to Andy Wilson and Brian Wylie from Sandia National Laboratories // for implementing this class. // // .SECTION Caveats // // This reader assumes that the first line in the file (whether that's // headers or the first document) contains at least as many fields as // any other line in the file. #ifndef __vtkDelimitedTextReader_h #define __vtkDelimitedTextReader_h #include "vtkTableAlgorithm.h" class vtkTable; //BTX struct vtkDelimitedTextReaderInternals; //ETX class VTK_INFOVIS_EXPORT vtkDelimitedTextReader : public vtkTableAlgorithm { public: static vtkDelimitedTextReader* New(); vtkTypeRevisionMacro(vtkDelimitedTextReader,vtkTableAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); vtkGetStringMacro(FileName); vtkSetStringMacro(FileName); // Description: // Get/set the characters that will be used to separate fields. For // example, set this to "," for a comma-separated value file. Set // it to ".:;" for a file where columns can be separated by a // period, colon or semicolon. The order of the characters in the // string does not matter. Defaults to a comma. vtkSetStringMacro(FieldDelimiterCharacters); vtkGetStringMacro(FieldDelimiterCharacters); // Description: // Get/set the character that will begin and end strings. Microsoft // Excel, for example, will export the following format: // // "First Field","Second Field","Field, With, Commas","Fourth Field" // // The third field has a comma in it. By using a string delimiter, // this will be correctly read. The delimiter defaults to '"'. vtkGetMacro(StringDelimiter, char); vtkSetMacro(StringDelimiter, char); // Description: // Set/get whether to use the string delimiter. Defaults to on. vtkSetMacro(UseStringDelimiter, bool); vtkGetMacro(UseStringDelimiter, bool); vtkBooleanMacro(UseStringDelimiter, bool); // Description: // Set/get whether to treat the first line of the file as headers. vtkGetMacro(HaveHeaders,bool); vtkSetMacro(HaveHeaders,bool); // Description: // Set/get whether to merge successive delimiters. Use this if (for // example) your fields are separated by spaces but you don't know // exactly how many. vtkSetMacro(MergeConsecutiveDelimiters, bool); vtkGetMacro(MergeConsecutiveDelimiters, bool); vtkBooleanMacro(MergeConsecutiveDelimiters, bool); // Description: // Set/get the maximum number of records to read from the file (zero = unlimited) vtkGetMacro(MaxRecords, int); vtkSetMacro(MaxRecords, int); // Description: // When set to true, the reader will detect numeric columns and create // vtkDoubleArray or vtkIntArray for those instead of vtkStringArray. Default // is off. vtkSetMacro(DetectNumericColumns, bool); vtkGetMacro(DetectNumericColumns, bool); vtkBooleanMacro(DetectNumericColumns, bool); protected: vtkDelimitedTextReader(); ~vtkDelimitedTextReader(); vtkDelimitedTextReaderInternals* Internals; int RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector*); void OpenFile(); char* FileName; char *FieldDelimiterCharacters; char StringDelimiter; bool UseStringDelimiter; bool HaveHeaders; bool MergeConsecutiveDelimiters; char *ReadBuffer; int MaxRecords; bool DetectNumericColumns; private: vtkDelimitedTextReader(const vtkDelimitedTextReader&); // Not implemented void operator=(const vtkDelimitedTextReader&); // Not implemented }; #endif
const path = require('path') const timers = require('timers') const Module = require('module') process.atomBinding = function (name) { try { return process.binding('atom_' + process.type + '_' + name) } catch (error) { if (/No such module/.test(error.message)) { return process.binding('atom_common_' + name) } } } if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { // Add common/api/lib to module search paths. Module.globalPaths.push(path.join(__dirname, 'api')) } // setImmediate and process.nextTick makes use of uv_check and uv_prepare to // run the callbacks, however since we only run uv loop on requests, the // callbacks wouldn't be called until something else activated the uv loop, // which would delay the callbacks for arbitrary long time. So we should // initiatively activate the uv loop once setImmediate and process.nextTick is // called. var wrapWithActivateUvLoop = function (func) { return function () { process.activateUvLoop() return func.apply(this, arguments) } } process.nextTick = wrapWithActivateUvLoop(process.nextTick) global.setImmediate = wrapWithActivateUvLoop(timers.setImmediate) global.clearImmediate = timers.clearImmediate if (process.type === 'browser') { // setTimeout needs to update the polling timeout of the event loop, when // called under Chromium's event loop the node's event loop won't get a chance // to update the timeout, so we have to force the node's event loop to // recalculate the timeout in browser process. global.setTimeout = wrapWithActivateUvLoop(timers.setTimeout) global.setInterval = wrapWithActivateUvLoop(timers.setInterval) } // If we're running as a Windows Store app, __dirname will be set // to C:/Program Files/WindowsApps. // // Nobody else get's to install there, changing the path is forbidden // We can therefore say that we're running as appx if (process.platform === 'win32' && __dirname.indexOf('\\Program Files\\WindowsApps\\') === 2) { process.windowsStore = true }
r""" Interfaces to R This is the reference to the Sagemath R interface, usable from any Sage program. The %r interface creating an R cell in the sage notebook is decribed in the Notebook manual. The %R and %%R interface creating an R line or an R cell in the Jupyter notebook are briefly decribed at the end of this page. This documentation will be expanded and placed in the Jupyter notebook manual when this manual exists. The following examples try to follow "An Introduction to R" which can be found at http://cran.r-project.org/doc/manuals/R-intro.html . EXAMPLES: Simple manipulations; numbers and vectors The simplest data structure in R is the numeric vector which consists of an ordered collection of numbers. To create a vector named $x$ using the R interface in Sage, you pass the R interpreter object a list or tuple of numbers:: sage: x = r([10.4,5.6,3.1,6.4,21.7]); x [1] 10.4 5.6 3.1 6.4 21.7 You can invert elements of a vector x in R by using the invert operator or by doing 1/x:: sage: ~x [1] 0.09615385 0.17857143 0.32258065 0.15625000 0.04608295 sage: 1/x [1] 0.09615385 0.17857143 0.32258065 0.15625000 0.04608295 The following assignment creates a vector $y$ with 11 entries which consists of two copies of $x$ with a 0 in between:: sage: y = r([x,0,x]); y [1] 10.4 5.6 3.1 6.4 21.7 0.0 10.4 5.6 3.1 6.4 21.7 Vector Arithmetic The following command generates a new vector $v$ of length 11 constructed by adding together (element by element) $2x$ repeated 2.2 times, $y$ repeated just once, and 1 repeated 11 times:: sage: v = 2*x+y+1; v [1] 32.2 17.8 10.3 20.2 66.1 21.8 22.6 12.8 16.9 50.8 43.5 One can compute the sum of the elements of an R vector in the following two ways:: sage: sum(x) [1] 47.2 sage: x.sum() [1] 47.2 One can calculate the sample variance of a list of numbers:: sage: ((x-x.mean())^2/(x.length()-1)).sum() [1] 53.853 sage: x.var() [1] 53.853 sage: x.sort() [1] 3.1 5.6 6.4 10.4 21.7 sage: x.min() [1] 3.1 sage: x.max() [1] 21.7 sage: x [1] 10.4 5.6 3.1 6.4 21.7 sage: r(-17).sqrt() [1] NaN sage: r('-17+0i').sqrt() [1] 0+4.123106i Generating an arithmetic sequence:: sage: r('1:10') [1] 1 2 3 4 5 6 7 8 9 10 Because ``from`` is a keyword in Python, it can't be used as a keyword argument. Instead, ``from_`` can be passed, and R will recognize it as the correct thing:: sage: r.seq(length=10, from_=-1, by=.2) [1] -1.0 -0.8 -0.6 -0.4 -0.2 0.0 0.2 0.4 0.6 0.8 sage: x = r([10.4,5.6,3.1,6.4,21.7]); sage: x.rep(2) [1] 10.4 5.6 3.1 6.4 21.7 10.4 5.6 3.1 6.4 21.7 sage: x.rep(times=2) [1] 10.4 5.6 3.1 6.4 21.7 10.4 5.6 3.1 6.4 21.7 sage: x.rep(each=2) [1] 10.4 10.4 5.6 5.6 3.1 3.1 6.4 6.4 21.7 21.7 Missing Values:: sage: na = r('NA') sage: z = r([1,2,3,na]) sage: z [1] 1 2 3 NA sage: ind = r.is_na(z) sage: ind [1] FALSE FALSE FALSE TRUE sage: zero = r(0) sage: zero / zero [1] NaN sage: inf = r('Inf') sage: inf-inf [1] NaN sage: r.is_na(inf) [1] FALSE sage: r.is_na(inf-inf) [1] TRUE sage: r.is_na(zero/zero) [1] TRUE sage: r.is_na(na) [1] TRUE sage: r.is_nan(inf-inf) [1] TRUE sage: r.is_nan(zero/zero) [1] TRUE sage: r.is_nan(na) [1] FALSE Character Vectors:: sage: labs = r.paste('c("X","Y")', '1:10', sep='""'); labs [1] "X1" "Y2" "X3" "Y4" "X5" "Y6" "X7" "Y8" "X9" "Y10" Index vectors; selecting and modifying subsets of a data set:: sage: na = r('NA') sage: x = r([10.4,5.6,3.1,6.4,21.7,na]); x [1] 10.4 5.6 3.1 6.4 21.7 NA sage: x['!is.na(self)'] [1] 10.4 5.6 3.1 6.4 21.7 sage: x = r([10.4,5.6,3.1,6.4,21.7,na]); x [1] 10.4 5.6 3.1 6.4 21.7 NA sage: (x+1)['(!is.na(self)) & self>0'] [1] 11.4 6.6 4.1 7.4 22.7 sage: x = r([10.4,-2,3.1,-0.5,21.7,na]); x [1] 10.4 -2.0 3.1 -0.5 21.7 NA sage: (x+1)['(!is.na(self)) & self>0'] [1] 11.4 4.1 0.5 22.7 Distributions:: sage: r.options(width="60"); $width [1] 100 sage: rr = r.dnorm(r.seq(-3,3,0.1)) sage: rr [1] 0.004431848 0.005952532 0.007915452 0.010420935 [5] 0.013582969 0.017528300 0.022394530 0.028327038 [9] 0.035474593 0.043983596 0.053990967 0.065615815 [13] 0.078950158 0.094049077 0.110920835 0.129517596 [17] 0.149727466 0.171368592 0.194186055 0.217852177 [21] 0.241970725 0.266085250 0.289691553 0.312253933 [25] 0.333224603 0.352065327 0.368270140 0.381387815 [29] 0.391042694 0.396952547 0.398942280 0.396952547 [33] 0.391042694 0.381387815 0.368270140 0.352065327 [37] 0.333224603 0.312253933 0.289691553 0.266085250 [41] 0.241970725 0.217852177 0.194186055 0.171368592 [45] 0.149727466 0.129517596 0.110920835 0.094049077 [49] 0.078950158 0.065615815 0.053990967 0.043983596 [53] 0.035474593 0.028327038 0.022394530 0.017528300 [57] 0.013582969 0.010420935 0.007915452 0.005952532 [61] 0.004431848 Convert R Data Structures to Python/Sage:: sage: rr = r.dnorm(r.seq(-3,3,0.1)) sage: sum(rr._sage_()) 9.9772125168981... Or you get a dictionary to be able to access all the information:: sage: rs = r.summary(r.c(1,4,3,4,3,2,5,1)) sage: rs Min. 1st Qu. Median Mean 3rd Qu. Max. 1.000 1.750 3.000 2.875 4.000 5.000 sage: d = rs._sage_() sage: d['DATA'] [1, 1.75, 3, 2.875, 4, 5] sage: d['_Names'] ['Min.', '1st Qu.', 'Median', 'Mean', '3rd Qu.', 'Max.'] sage: d['_r_class'] ['summaryDefault', 'table'] It is also possible to access the plotting capabilities of R through Sage. For more information see the documentation of r.plot() or r.png(). THE JUPYTER NOTEBOOK INTERFACE (work in progress). The %r interface described in the Sage notebook manual is not useful in the Jupyter notebook : it creates a inferior R interpreter which cannot be escaped. The RPy2 library allows the creation of an R cell in the Jupyter notebook analogous to the %r escape in command line or %r cell in a Sage notebook. The interface is loaded by a cell containing the sole code : "%load_ext rpy2.ipython" After execution of this code, the %R and %%R magics are available : - %R allows the execution of a single line of R code. Data exchange is possible via the -i and -o options. Do "%R?" in a standalone cell to get the documentation. - %%R alows the execution in R of the whole text of a cell, with similar options (do "%%R?" in a standalone cell for documentation). A few important points must be noted : - The R interpreter launched by this interface IS (currently) DIFFERENT from the R interpreter used br other r... functions. - Data exchanged via the -i and -o options have a format DIFFERENT from the format used by the r... functions (RPy2 mostly uses arrays, and bugs the user to use the pandas Python package). - R graphics are (beautifully) displayed in output cells, but are not directly importable. You have to save them as .png, .pdf or .svg files and import them in Sage for further use. In its current incarnation, this interface is mostly useful to statisticians needing Sage for a few symbolic computations but mostly using R for applied work. AUTHORS: - Mike Hansen (2007-11-01) - William Stein (2008-04-19) - Harald Schilly (2008-03-20) - Mike Hansen (2008-04-19) - Emmanuel Charpentier (2015-12-12, RPy2 interface) """ ########################################################################## # # Copyright (C) 2007 William Stein <wstein@gmail.com> # 2007 Mike Hansen <mhansen@gmail.com> # 2008 Harald Schilly <harald.schilly@gmail.com> # # Distributed under the terms of the GNU General Public License (GPL) # # http://www.gnu.org/licenses/ # ########################################################################## from __future__ import print_function from __future__ import absolute_import from .expect import Expect, ExpectElement, ExpectFunction, FunctionElement from sage.env import DOT_SAGE import re import six import sage.rings.integer from sage.structure.element import parent from sage.misc.cachefunc import cached_method from sage.interfaces.tab_completion import ExtraTabCompletion COMMANDS_CACHE = '%s/r_commandlist.sobj'%DOT_SAGE PROMPT = '__SAGE__R__PROMPT__> ' prompt_re = re.compile("^>", re.M) #there is a mirror network, but lets take #1 for now RRepositoryURL = "http://cran.r-project.org/" RFilteredPackages = ['.GlobalEnv'] # crosscheck with https://svn.r-project.org/R/trunk/src/main/names.c # but package:base should cover this. i think. RBaseCommands = ['c', "NULL", "NA", "True", "False", "Inf", "NaN"] class R(ExtraTabCompletion, Expect): def __init__(self, maxread=None, script_subdirectory=None, server_tmpdir = None, logfile=None, server=None, init_list_length=1024, seed=None): """ An interface to the R interpreter. R is a comprehensive collection of methods for statistics, modelling, bioinformatics, data analysis and much more. For more details, see http://www.r-project.org/about.html Resources: * http://r-project.org/ provides more information about R. * http://rseek.org/ R's own search engine. EXAMPLES:: sage: r.summary(r.c(1,2,3,111,2,3,2,3,2,5,4)) Min. 1st Qu. Median Mean 3rd Qu. Max. 1.00 2.00 3.00 12.55 3.50 111.00 TESTS:: sage: r == loads(dumps(r)) True """ Expect.__init__(self, # The capitalized version of this is used for printing. name = 'r', # This is regexp of the input prompt. If you can change # it to be very obfuscated that would be better. Even # better is to use sequence numbers. # options(prompt=\"<prompt> \") prompt = '> ', #default, later comes the change # This is the command that starts up your program command = "R --vanilla --quiet", server=server, server_tmpdir=server_tmpdir, script_subdirectory = script_subdirectory, # If this is true, then whenever the user presses Control-C to # interrupt a calculation, the whole interface is restarted. restart_on_ctrlc = False, # If true, print out a message when starting # up the command when you first send a command # to this interface. verbose_start = False, logfile=logfile, # If an input is longer than this number of characters, then # try to switch to outputting to a file. eval_using_file_cutoff=1024) self.__seq = 0 self.__var_store_len = 0 self.__init_list_length = init_list_length self._prompt_wait = [self._prompt] self._seed = seed def set_seed(self, seed=None): """ Sets the seed for R interpeter. The seed should be an integer. EXAMPLES:: sage: r = R() sage: r.set_seed(1) 1 sage: r.sample("1:10", 5) [1] 3 4 5 7 2 """ if seed is None: seed = self.rand_seed() self.eval('set.seed(%d)' % seed) self._seed = seed return seed def _start(self): """ Start up the R interpreter and sets the initial prompt and options. This is called the first time the R interface is actually used. EXAMPLES:: sage: r = R() sage: r._start() """ Expect._start(self) # width is line width, what's a good value? maximum is 10000! # pager needed to replace help view from less to printout # option device= is for plotting, is set to x11, NULL would be better? self._change_prompt(PROMPT) self.eval('options(prompt=\"%s\",continue=\"%s\", width=100,pager="cat",device="png")'%(PROMPT, PROMPT)) self.expect().expect(PROMPT) self.eval('options(repos="%s")'%RRepositoryURL) self.eval('options(CRAN="%s")'%RRepositoryURL) # don't abort on errors, just raise them! # necessary for non-interactive execution self.eval('options(error = expression(NULL))') # set random seed self.set_seed(self._seed) def png(self, *args, **kwds): """ Creates an R PNG device. This should primarily be used to save an R graphic to a custom file. Note that when using this in the notebook, one must plot in the same cell that one creates the device. See r.plot() documentation for more information about plotting via R in Sage. These examples won't work on the many platforms where R still gets built without graphics support. EXAMPLES:: sage: filename = tmp_filename() + '.png' sage: r.png(filename='"%s"'%filename) # optional -- rgraphics NULL sage: x = r([1,2,3]) sage: y = r([4,5,6]) sage: r.plot(x,y) # This saves to filename, but is not viewable from command line; optional -- rgraphics null device 1 sage: import os; os.unlink(filename) # We remove the file for doctesting; optional -- rgraphics We want to make sure that we actually can view R graphics, which happens differently on different platforms:: sage: s = r.eval('capabilities("png")') # Should be on Linux and Solaris sage: t = r.eval('capabilities("aqua")') # Should be on all supported Mac versions sage: "TRUE" in s+t # optional -- rgraphics True """ #Check to see if R has PNG support s = self.eval('capabilities("png")') t = r.eval('capabilities("aqua")') if "TRUE" not in s+t: raise RuntimeError("R was not compiled with PNG support") from sage.server.support import EMBEDDED_MODE if EMBEDDED_MODE: self.setwd('"%s"'%os.path.abspath('.')) return RFunction(self, 'png')(*args, **kwds) def convert_r_list(self, l): r""" Converts an R list to a Python list. EXAMPLES:: sage: s = 'c(".GlobalEnv", "package:stats", "package:graphics", "package:grDevices", \n"package:utils", "package:datasets", "package:methods", "Autoloads", \n"package:base")' sage: r.convert_r_list(s) ['.GlobalEnv', 'package:stats', 'package:graphics', 'package:grDevices', 'package:utils', 'package:datasets', 'package:methods', 'Autoloads', 'package:base'] """ pl = [] l = "".join(l.split("\n")) l = l[2:len(l)-1] for l in l.split(","): pl.append(l.strip().strip('"')) return pl def install_packages(self, package_name): """ Install an R package into Sage's R installation. EXAMPLES:: sage: r.install_packages('aaMI') # not tested ... R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. ... Please restart Sage in order to use 'aaMI'. """ cmd = """options(repos="%s"); install.packages("%s")"""%(RRepositoryURL, package_name) os.system("time echo '%s' | R --vanilla"%cmd) print("Please restart Sage in order to use '%s'." % package_name) def __repr__(self): """ Return string representation of this R interface. EXAMPLES:: sage: r.__repr__() 'R Interpreter' """ return 'R Interpreter' def __reduce__(self): """ Used in serializing an R interface. EXAMPLES:: sage: rlr, t = r.__reduce__() sage: rlr(*t) R Interpreter """ return reduce_load_R, tuple([]) def __getattr__(self, attrname): """ Called when you get an attribute of the R interface. This manufactures an R function, which is a Python function that can then be called with various inputs. EXAMPLES:: sage: c = r.c; c c sage: type(c) <class 'sage.interfaces.r.RFunction'> """ if attrname[:1] == "_": raise AttributeError return RFunction(self, attrname) def _quit_string(self): r""" Return the string that when typed into R causes the R interpreter to exit. EXAMPLES:: sage: r._quit_string() 'quit(save="no")' """ return 'quit(save="no")' def _read_in_file_command(self, filename): r""" Return the R command (as a string) to read in a file named filename into the R interpreter. EXAMPLES:: sage: r._read_in_file_command('file.txt') 'file=file("file.txt",open="r")\nsource(file)' """ return 'file=file("%s",open="r")\nsource(file)'%filename def read(self, filename): r""" Read filename into the R interpreter by calling R's source function on a read-only file connection. EXAMPLES:: sage: filename = tmp_filename() sage: f = open(filename, 'w') sage: f.write('a <- 2+2\n') sage: f.close() sage: r.read(filename) sage: r.get('a') '[1] 4' """ self.eval( self._read_in_file_command(filename) ) def _install_hints(self): """ EXAMPLES:: sage: print(r._install_hints()) R is currently installed with Sage. """ return "R is currently installed with Sage.\n" def _source(self, s): """ Returns the source code of an R function as a string. INPUT: - s -- the name of the function as a string EXAMPLES:: sage: print(r._source("c")) function (..., recursive = FALSE) .Primitive("c") """ if s[-2:] == "()": s = s[-2:] return self.eval('%s'%s) def source(self, s): """ Display the R source (if possible) about the function named s. INPUT: - s -- a string representing the function whose source code you want to see OUTPUT: string -- source code EXAMPLES:: sage: print(r.source("c")) function (..., recursive = FALSE) .Primitive("c") """ return self._source(s) def version(self): """ Return the version of R currently running. OUTPUT: tuple of ints; string EXAMPLES:: sage: r.version() # not tested ((3, 0, 1), 'R version 3.0.1 (2013-05-16)') sage: rint, rstr = r.version() sage: rint[0] >= 3 True sage: rstr.startswith('R version') True """ major_re = re.compile('^major\s*(\d.*?)$', re.M) minor_re = re.compile('^minor\s*(\d.*?)$', re.M) version_string_re = re.compile('^version.string\s*(R.*?)$', re.M) s = self.eval('version') major = int( major_re.findall(s)[0].strip() ) minor = tuple(int(i) for i in minor_re.findall(s)[0].strip().split(".") ) version_string = version_string_re.findall(s)[0].strip() return ( (major,) + minor, version_string ) def library(self, library_name): """ Load the library library_name into the R interpreter. This function raises an ImportError if the given library is not known. INPUT: - library_name -- string EXAMPLES:: sage: r.library('grid') sage: 'grid' in r.eval('(.packages())') True sage: r.library('foobar') Traceback (most recent call last): ... ImportError: ... """ ret = self.eval('require("%s")'%library_name) # try hard to parse the message string in a locale-independent way if ' library(' in ret: # locale-independent key-word raise ImportError("%s"%ret) else: try: # We need to rebuild keywords! del self.__tab_completion except AttributeError: pass self._tab_completion(verbose=False, use_disk_cache=False) require = library #overwrites require def available_packages(self): """ Returns a list of all available R package names. This list is not necessarily sorted. OUTPUT: list of strings .. note:: This requires an internet connection. The CRAN server is that is checked is defined at the top of sage/interfaces/r.py. EXAMPLES:: sage: ap = r.available_packages() # optional - internet sage: len(ap) > 20 # optional - internet True """ p = self.new('available.packages("%s/src/contrib")'%RRepositoryURL) s = str(p).splitlines()[1:] v = [x.split()[0].strip("'") for x in s] return v #The following was more structural, but breaks on my machine. (stein) #p = p._sage_() #s = p['_Dim'][0] #l = [[p['DATA'][i],p['DATA'][s+1+i]] for i in xrange(0,s)] #return l def _object_class(self): """ Return the underlying class of elements of the R interface object. OUTPUT: a Python class EXAMPLES:: sage: r._object_class() <class 'sage.interfaces.r.RElement'> """ return RElement def _true_symbol(self): """ Return the symbol that represents True in R. OUTPUT: string EXAMPLES:: sage: r._true_symbol() '[1] TRUE' This is used behinds the scenes to implement comparison:: sage: r('1') == r('1') [1] TRUE sage: r('1') == r('2') [1] FALSE """ # return the string rep of truth, i.e., what the system outputs # when you type 1==1. return "[1] TRUE" def _false_symbol(self): """ Return the symbol that represents True in R. OUTPUT: string EXAMPLES:: sage: r._false_symbol() '[1] FALSE' """ # return the string rep of false, i.e., what the system outputs # when you type 1==2. return "[1] FALSE" def _equality_symbol(self): """ EXAMPLES:: sage: r._equality_symbol() '==' """ # return the symbol for checking equality, e.g., == or eq. return "==" def help(self, command): """ Returns help string for a given command. INPUT: - command -- a string OUTPUT: HelpExpression -- a subclass of string whose __repr__ method is __str__, so it prints nicely EXAMPLES:: sage: r.help('c') c package:base R Documentation ... .. note:: This is similar to typing r.command?. """ s = self.eval('help("%s")'%command).strip() # ?cmd is only an unsafe shortcut import sage.plot.plot if sage.plot.plot.EMBEDDED_MODE: s = s.replace('_\x08','') return HelpExpression(s) def _assign_symbol(self): """ Return the symbol used in R for assignment, which is ' <- '. OUTPUT: string EXAMPLES:: sage: r._assign_symbol() ' <- ' """ return " <- " def _left_list_delim(self): """ Return the left delimiter for lists in R, which is 'c(' OUTPUT: string EXAMPLES:: sage: r._left_list_delim() 'c(' """ return "c(" def _right_list_delim(self): """ Return the right delimiter for lists in R, which is 'c(' OUTPUT: string EXAMPLES:: sage: r._right_list_delim() ')' """ return ")" def console(self): """ Runs the R console as a separate new R process. EXAMPLES:: sage: r.console() # not tested R version 2.6.1 (2007-11-26) Copyright (C) 2007 The R Foundation for Statistical Computing ISBN 3-900051-07-0 ... """ r_console() def function_call(self, function, args=None, kwds=None): """ Return the result of calling an R function, with given args and keyword args. OUTPUT: RElement -- an object in R EXAMPLES:: sage: r.function_call('length', args=[ [1,2,3] ]) [1] 3 """ args, kwds = self._convert_args_kwds(args, kwds) self._check_valid_function_name(function) return self.new("%s(%s)"%(function, ",".join([s.name() for s in args] + [self._sage_to_r_name(key)+'='+kwds[key].name() for key in kwds ] ))) def call(self, function_name, *args, **kwds): r""" This is an alias for :meth:`function_call`. EXAMPLES:: sage: r.call('length', [1,2,3]) [1] 3 """ return self.function_call(function_name, args=args, kwds=kwds) def _an_element_impl(self): """ Returns an element belonging to the R interpreter. This is used behind the scenes when doing things like comparisons, etc. OUTPUT: RElement -- an R element. EXAMPLES:: sage: r._an_element_impl() [1] 0 sage: type(_) <class 'sage.interfaces.r.RElement'> """ return self(0) def set(self, var, value): """ Set the variable var in R to what the string value evaluates to in R. INPUT: - var -- a string - value -- a string EXAMPLES:: sage: r.set('a', '2 + 3') sage: r.get('a') '[1] 5' """ cmd = '%s <- %s'%(var,value) out = self.eval(cmd) if out.find("error") != -1: raise TypeError("Error executing code in R\nCODE:\n\t%s\nR ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ Returns the string representation of the variable var. INPUT: - var -- a string OUTPUT: string EXAMPLES:: sage: r.set('a', 2) sage: r.get('a') '[1] 2' """ s = self.eval('%s'%var) #return self._remove_indices_re.sub("", s).strip() return s def na(self): """ Returns the NA in R. OUTPUT: RElement -- an element of R EXAMPLES:: sage: r.na() [1] NA """ return self('NA') def completions(self, s): """ Return all commands names that complete the command starting with the string s. This is like typing s[Ctrl-T] in the R interpreter. INPUT: - s -- string OUTPUT: list -- a list of strings EXAMPLES:: sage: dummy = r._tab_completion(use_disk_cache=False) #clean doctest sage: r.completions('tes') ['testInheritedMethods', 'testPlatformEquivalence', 'testVirtual'] """ return [name for name in self._tab_completion() if name[:len(s)] == s] def _commands(self): """ Return list of all commands defined in R. OUTPUT: list -- a sorted list of strings EXAMPLES:: sage: l = r._commands() sage: 'AIC' in l True sage: len(l) > 200 True """ v = RBaseCommands ll = self.eval('dput(search())') # loaded libs ll = self.convert_r_list(ll) for lib in ll: if lib in RFilteredPackages: continue if lib.find("package:") != 0: continue #only packages raw = self.eval('dput(objects("%s"))'%lib) raw = self.convert_r_list(raw) raw = [x.replace(".","_") for x in raw] #TODO are there others? many of them are shortcuts or #should be done on another level, like selections in lists #instead of calling obj.[[( fun-args) or other crazy stuff like that #TODO further filtering, check if strings are now #really functions, in R: exists(s, mode = "function")) # (apply to vector with sapply(vec,func)) #filter only python compatible identifiers valid = re.compile('[^a-zA-Z0-9_]+') raw = [x for x in raw if valid.search(x) is None] v += raw v.sort() return v def _tab_completion(self, verbose=True, use_disk_cache=True): """ Return list of all R functions. INPUT: - verbose -- bool (default: True); if True, display debugging information - use_disk_cache -- bool (default: True); if True, use the disk cache of tab completions to save time. OUTPUT: list -- list of string EXAMPLES:: sage: t = r._tab_completion(verbose=False) sage: len(t) > 200 True """ try: return self.__tab_completion except AttributeError: import sage.misc.persist if use_disk_cache: try: self.__tab_completion = sage.misc.persist.load(COMMANDS_CACHE) return self.__tab_completion except IOError: pass if verbose and use_disk_cache: print("\nBuilding R command completion list (this takes") print("a few seconds only the first time you do it).") print("To force rebuild later, delete %s." % COMMANDS_CACHE) v = self._commands() self.__tab_completion = v if len(v) > 200 and use_disk_cache: sage.misc.persist.save(v, COMMANDS_CACHE) return v def plot(self, *args, **kwds): """ The R plot function. Type r.help('plot') for much more extensive documentation about this function. See also below for a brief introduction to more plotting with R. If one simply wants to view an R graphic, using this function is is sufficient (because it calls dev.off() to turn off the device). However, if one wants to save the graphic to a specific file, it should be used as in the example below to write the output. EXAMPLES: This example saves a plot to the standard R output, usually a filename like ``Rplot001.png`` - from the command line, in the current directory, and in the cell directory in the notebook:: sage: d=r.setwd('"%s"'%SAGE_TMP) # for doctesting only; ignore if you are trying this; sage: r.plot("1:10") # optional -- rgraphics null device 1 To save to a specific file name, one should use :meth:`png` to set the output device to that file. If this is done in the notebook, it must be done in the same cell as the plot itself:: sage: filename = tmp_filename() + '.png' sage: r.png(filename='"%s"'%filename) # Note the double quotes in single quotes!; optional -- rgraphics NULL sage: x = r([1,2,3]) sage: y = r([4,5,6]) sage: r.plot(x,y) # optional -- rgraphics null device 1 sage: import os; os.unlink(filename) # For doctesting, we remove the file; optional -- rgraphics Please note that for more extensive use of R's plotting capabilities (such as the lattices package), it is advisable to either use an interactive plotting device or to use the notebook. The following examples are not tested, because they differ depending on operating system:: sage: r.X11() # not tested - opens interactive device on systems with X11 support sage: r.quartz() # not tested - opens interactive device on OSX sage: r.hist("rnorm(100)") # not tested - makes a plot sage: r.library("lattice") # not tested - loads R lattice plotting package sage: r.histogram(x = "~ wt | cyl", data="mtcars") # not tested - makes a lattice plot sage: r.dev_off() # not tested, turns off the interactive viewer In the notebook, one can use r.png() to open the device, but would need to use the following since R lattice graphics do not automatically print away from the command line:: sage: filename = tmp_filename() + '.png' # Not needed in notebook, used for doctesting sage: r.png(filename='"%s"'%filename) # filename not needed in notebook, used for doctesting; optional -- rgraphics NULL sage: r.library("lattice") sage: r("print(histogram(~wt | cyl, data=mtcars))") # plot should appear; optional -- rgraphics sage: import os; os.unlink(filename) # We remove the file for doctesting, not needed in notebook; optional -- rgraphics """ # We have to define this to override the plot function defined in the # superclass. from sage.server.support import EMBEDDED_MODE if EMBEDDED_MODE: self.setwd('"%s"'%os.path.abspath('.')) RFunction(self, 'plot')(*args, **kwds) return RFunction(self, 'dev.off')() def _strip_prompt(self, code): """ Remove the standard R prompt from the beginning of lines in code. INPUT: - code -- a string OUTPUT: a string EXAMPLES:: sage: s = '> a <- 2\n> b <- 3' sage: r._strip_prompt(s) ' a <- 2\n b <- 3' """ return prompt_re.sub("", code) def eval(self, code, globals=None, locals=None, synchronize=True, *args, **kwds): """ Evaluates a command inside the R interpreter and returns the output as a string. EXAMPLES:: sage: r.eval('1+1') '[1] 2' """ # TODO split code at ";" outside of quotes and send them as individual # lines without ";". return Expect.eval(self, code, synchronize=synchronize, *args, **kwds) def _r_to_sage_name(self, s): """ Returns a Sage/Python identifier from an R one. This involves replacing periods with underscores, <- with __, and prepending _ in front of Python keywords. INPUT: - s -- a string OUTPUT: a string EXAMPLES:: sage: f = r._r_to_sage_name sage: f('t.test') 't_test' sage: f('attr<-') 'attr__' sage: f('parent.env<-') 'parent_env__' sage: f('class') 'class_' """ from keyword import iskeyword s = s.replace('.', '_') s = s.replace('<-', '__') if iskeyword(s): s += '_' return s def _sage_to_r_name(self, s): r""" The reverse of :meth:`_r_to_sage_name`. See the docs for that method. EXAMPLES:: sage: f = r._sage_to_r_name sage: f('t_test') 't.test' sage: f('attr__') 'attr<-' sage: f('parent_env__') 'parent.env<-' sage: r._r_to_sage_name(f('parent_env__')) 'parent_env__' sage: f('class_') 'class' """ if len(s) > 1 and s[-2:] == "__": s = s[:-2] + '<-' if len(s) > 0 and s[-1] == '_': s = s[:-1] s = s.replace('_', '.') return s def __getitem__(self, s): """ Returns the RFunction with name s. INPUT: - s -- a string OUTPUT: RFunction -- the R function that in R has name s EXAMPLES:: sage: r['as.data.frame'] as.data.frame sage: r['print'] print """ return RFunction(self, s, r_name=True) def chdir(self, dir): """ Changes the working directory to ``dir`` INPUT: - ``dir`` -- the directory to change to. EXAMPLES:: sage: import tempfile sage: tmpdir = tempfile.mkdtemp() sage: r.chdir(tmpdir) Check that ``tmpdir`` and ``r.getwd()`` refer to the same directory. We need to use ``realpath()`` in case ``$TMPDIR`` (by default ``/tmp``) is a symbolic link (see :trac:`10264`). :: sage: os.path.realpath(tmpdir) == sageobj(r.getwd()) # known bug (trac #9970) True """ self.execute('setwd(%r)' % dir) # patterns for _sage_() rel_re_param = re.compile('\s([\w\.]+)\s=') rel_re_xrange = re.compile('([\d]+):([\d]+)') rel_re_integer = re.compile('([^\d])([\d]+)L') rel_re_terms = re.compile('terms\s*=\s*(.*?),') rel_re_call = re.compile('call\s*=\s*(.*?)\),') class RElement(ExtraTabCompletion, ExpectElement): def _tab_completion(self): """ Return a list of all methods of this object. .. note:: Currently returns all R commands. EXAMPLES:: sage: a = r([1,2,3]) sage: t = a._tab_completion() sage: len(t) > 200 True """ # TODO: rewrite it, just take methods(class=class(self)) return self.parent()._tab_completion() def tilde(self, x): """ The tilde regression operator in R. EXAMPLES:: sage: x = r([1,2,3,4,5]) sage: y = r([3,5,7,9,11]) sage: a = r.lm( y.tilde(x) ) # lm( y ~ x ) sage: d = a._sage_() sage: d['DATA']['coefficients']['DATA'][1] 2 """ par = self.parent() rx = par(x) return par.new("%s ~ %s" % (self.name(), rx.name())) stat_model = tilde def __len__(self): """ Return the length of this object. OUTPUT: integer EXAMPLES:: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: len(x) 5 """ return int(self.parent().eval('dput(length(%s))'%self.name())[:-1] ) def __getattr__(self, attrname): """ Return attribute of this object, which is an R function with this object as the first input. INPUT: - attrname -- string OUTPUT: RFunctionElement EXAMPLES:: sage: x = r([1,2,3]) sage: length = x.length sage: type(length) <class 'sage.interfaces.r.RFunctionElement'> sage: length() [1] 3 """ self._check_valid() if attrname[:1] == "_": raise AttributeError return RFunctionElement(self, attrname) def __getitem__(self, n): """ Return element(s) of self. INPUT: - n -- an integer, a tuple, a string that makes sense to R, or an RElement OUTPUT: RElement EXAMPLES:: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: x[0] numeric(0) sage: x[1] [1] 10.4 sage: x[-1] [1] 5.6 3.1 6.4 21.7 sage: x[-2] [1] 10.4 3.1 6.4 21.7 sage: x[-3] [1] 10.4 5.6 6.4 21.7 sage: x['c(2,3)'] [1] 5.6 3.1 sage: key = r.c(2,3) sage: x[key] [1] 5.6 3.1 sage: m = r.array('1:3',r.c(2,4,2)) sage: m , , 1 [,1] [,2] [,3] [,4] [1,] 1 3 2 1 [2,] 2 1 3 2 , , 2 [,1] [,2] [,3] [,4] [1,] 3 2 1 3 [2,] 1 3 2 1 sage: m[1,2,2] [1] 2 sage: m[1,r.c(1,2),1] [1] 1 3 """ P = self._check_valid() if isinstance(n, six.string_types): n = n.replace('self', self._name) return P.new('%s[%s]'%(self._name, n)) elif parent(n) is P: # the key is RElement itself return P.new('%s[%s]'%(self._name, n.name())) elif not isinstance(n,tuple): return P.new('%s[%s]'%(self._name, n)) else: L = [] for i in xrange(len(n)): if parent(n[i]) is P: L.append(n[i].name()) else: L.append(str(n[i])) return P.new('%s[%s]'%(self._name, ','.join(L))) def __nonzero__(self): """ Implements bool(self). .. note:: bool(self) will only return True if self == 0 contains a FALSE in its representation. EXAMPLES:: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: bool(x) True sage: y = r([0,0,0,0]) sage: bool(y) False sage: bool(r(0)) False sage: bool(r(1)) True """ return "FALSE" in repr(self==0) def _comparison(self, other, symbol): """ Used to implement comparison of two objects. INPUT: - other -- RElement - symbol -- string OUTPUT: RElement -- output is an R element; not a bool! TESTS:: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: x._comparison(10.4, "==") [1] TRUE FALSE FALSE FALSE FALSE """ P = self.parent() other = P(other) return P('%s %s %s'%(self.name(), symbol, other.name())) def __eq__(self, other): """ Equality testing term by term. INPUT: - other -- RElement OUTPUT: RElement -- an R element; not a bool! EXAMPLES: Notice that comparison is term by term and returns an R element. :: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: x == 10.4 [1] TRUE FALSE FALSE FALSE FALSE """ return self._comparison(other, "==") def __lt__(self, other): """ Less than testing term by term. INPUT: - other -- RElement OUTPUT: RElement -- an R element; not a bool! EXAMPLES: Notice that comparison is term by term and returns an R element. :: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: x < 7 [1] FALSE TRUE TRUE TRUE FALSE """ return self._comparison(other, "<") def __gt__(self, other): """ Greater than testing term by term. INPUT: - other -- RElement OUTPUT: RElement -- an R element; not a bool! EXAMPLES: Notice that comparison is term by term and returns an R element. :: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: x > 8 [1] TRUE FALSE FALSE FALSE TRUE """ return self._comparison(other, ">") def __le__(self, other): """ Less than or equal testing term by term. INPUT: - other -- RElement OUTPUT: RElement -- an R element; not a bool! EXAMPLES:: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: x <= 10.4 [1] TRUE TRUE TRUE TRUE FALSE """ return self._comparison(other, "<=") def __ge__(self, other): """ Greater than or equal testing term by term. INPUT: - other -- RElement OUTPUT: RElement -- an R element; not a bool! EXAMPLES:: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: x >= 10.4 [1] TRUE FALSE FALSE FALSE TRUE """ return self._comparison(other, ">=") def __ne__(self, other): """ Not equal testing term by term. INPUT: - other -- RElement OUTPUT: RElement -- an R element; not a bool! EXAMPLES:: sage: x = r([10.4,5.6,3.1,6.4,21.7]) sage: x != 10.4 [1] FALSE TRUE TRUE TRUE TRUE """ return self._comparison(other, "!=") def __cmp__(self, other): r""" Return 0, 1, or -1 depending on how self and other compare. This is *not* called by the comparison operators, which do term-by-term comparison and return R elements. INPUT: - self, other -- R elements OUTPUT: 0, 1, or -1 EXAMPLES:: sage: one = r(1) sage: two = r(2) sage: cmp(one,one) 0 sage: cmp(one,two) -1 sage: cmp(two,one) 1 """ P = self.parent() if P.eval("%s %s %s"%(self.name(), P._equality_symbol(), other.name())) == P._true_symbol(): return 0 elif P.eval("%s %s %s"%(self.name(), P._lessthan_symbol(), other.name())) == P._true_symbol(): return -1 elif P.eval("%s %s %s"%(self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol(): return 1 else: return -1 # everything is supposed to be comparable in Python, so we define # the comparison thus when no comparable in interfaced system. def dot_product(self, other): """ Implements the notation self . other. INPUT: - self, other -- R elements OUTPUT: R element EXAMPLES:: sage: c = r.c(1,2,3,4) sage: c.dot_product(c.t()) [,1] [,2] [,3] [,4] [1,] 1 2 3 4 [2,] 2 4 6 8 [3,] 3 6 9 12 [4,] 4 8 12 16 sage: v = r([3,-1,8]) sage: v.dot_product(v) [,1] [1,] 74 """ P = self._check_valid() Q = P(other) # the R operator is %*% for matrix multiplication return P('%s %%*%% %s'%(self.name(), Q.name())) def _subs_dots(self, x): """ Replace dots by underscores; used internally to implement conversation from R expression to Sage objects. INPUT: - x -- regular expression match: ``<type '_sre.SRE_Match'>`` OUTPUT: string EXAMPLES:: sage: import re sage: a = r([1,2,3]) sage: rel_re_param = re.compile('\s([\w\.]+)\s=') sage: rel_re_param.sub(a._subs_dots, ' test.test =') ' test_test =' """ return x.group().replace('.','_') def _subs_xrange(self, x): """ Change endpoints of xranges. This is used internally in the code for converting R expressions to Sage objects. INPUT: - x -- regular expression match: ``<type '_sre.SRE_Match'>`` OUTPUT: string EXAMPLES:: sage: import re sage: a = r([1,2,3]) sage: rel_re_xrange = re.compile('([\d]+):([\d]+)') sage: rel_re_xrange.sub(a._subs_xrange, ' 1:10') ' xrange(1,11)' """ g = x.groups() g1 = int(g[1]) + 1 return 'xrange(%s,%s)'%(g[0],g1) def _subs_integer(self, x): """ Replaces strings like 'dL' with 'Integer(d)' where d is some integer. This is used internally in the code for converting R expressions to Sage objects. EXAMPLES:: sage: import re sage: a = r([1,2,3]) sage: rel_re_integer = re.compile('([^\d])([\d]+)L') sage: rel_re_integer.sub(a._subs_integer, ' 1L 2L') ' Integer(1) Integer(2)' sage: rel_re_integer.sub(a._subs_integer, '1L 2L') '1L Integer(2)' """ return '%sInteger(%s)'%x.groups() def _convert_nested_r_list(self, exp): """ Converts a string representing a (possibly) nested list in R to a (possibly) nested Python list. This is used internally in the code for converting R expressions to Sage objects. INPUT: - exp -- a string OUTPUT: a string EXAMPLES:: sage: a = r([1,2,3]) sage: s = 'c(1, 2, 3)' sage: a._convert_nested_r_list(s) '[1, 2, 3]' """ from re import compile as re_compile from re import split as re_split splt = re_compile('(c\(|\(|\))') # c( or ( or ) lvl = 0 ret = [] for token in re_split(splt, exp): if token == 'c(': ret.append('[') lvl += 1 elif token == '(': ret.append(token) if lvl > 0 : lvl += 1 elif token == ')': if lvl == 1: ret.append(']') lvl -= 1 else: ret.append(token) if lvl > 0: lvl -= 1 else: ret.append(token) return ''.join(ret) def _r_list(self, *args, **kwds): """ This is used internally in the code for converting R expressions to Sage objects. EXAMPLES:: sage: a = r([1,2,3]) sage: list(sorted(a._r_list(1,2,3,k=5).items())) [('#0', 1), ('#1', 2), ('#2', 3), ('k', 5)] """ ret = dict(kwds) i = 0 for k in args: ret['#%s'%i] = k i += 1 return ret def _r_structure(self, __DATA__, **kwds): """ This is used internally in the code for converting R expressions to Sage objects. EXAMPLES:: sage: a = r([1,2,3]) sage: d = a._r_structure('data', a=1, b=2) sage: list(sorted(d.items())) [('DATA', 'data'), ('a', 1), ('b', 2)] sage: a._r_structure([1,2,3,4], _Dim=(2,2)) [1 3] [2 4] """ if '_Dim' in kwds: #we have a matrix # TODO what about more than 2 dimensions? # additional checks!! try: from sage.matrix.constructor import matrix d = kwds.get('_Dim') # TODO: higher dimensions? happens often in statistics if len(d) != 2: raise TypeError #since R does it the other way round, we assign #transposed and then transpose the matrix :) m = matrix(d[1], d[0], [i for i in __DATA__]) return m.transpose() except TypeError: pass d = dict(DATA=__DATA__) d.update(kwds) return d def _sage_(self): r""" Returns Sage representation of the R object. R objects are basic C structures, of different kind, that can be stacked together. This is similar to Python lists with variable objects, including lists of lists. If R lists have names, they are translated to a Python dictionary, with anonymous list entries called ``#{number}``. OUTPUT: object -- Python object EXAMPLES:: sage: rs = r.summary(r.c(1,4,3,4,3,2,5,1)) sage: d = rs._sage_() sage: list(sorted(d.items())) [('DATA', [1, 1.75, 3, 2.875, 4, 5]), ('_Names', ['Min.', '1st Qu.', 'Median', 'Mean', '3rd Qu.', 'Max.']), ('_r_class', ['summaryDefault', 'table'])] """ self._check_valid() P = self.parent() # This is the core of the trick: using dput # dput prints out the internal structure of R's data elements # options via .deparseOpts(control=...) # TODO: dput also works with a file, if things get huge! # [[However, using a file for output often isn't necessary # since pipe buffering works pretty well for output. # That said, benchmark this. -- William Stein]] exp = P.eval('dput(%s)'%self.name()) # Preprocess expression # example what this could be: # structure(list(statistic = structure(0.233549683248457, .Names = "t"), # parameter = structure(5.58461538461538, .Names = "df"), p.value = 0.823657802106985, # conf.int = structure(c(-2.41722062247400, 2.91722062247400 # ), conf.level = 0.95), estimate = structure(c(2.75, 2.5), .Names = c("mean of x", # "mean of y")), null.value = structure(0, .Names = "difference in means"), # alternative = "two.sided", method = "Welch Two Sample t-test", # data.name = "c(1, 2, 3, 5) and c(1, 2, 3, 4)"), .Names = c("statistic", # "parameter", "p.value", "conf.int", "estimate", "null.value", # "alternative", "method", "data.name"), class = "htest") # R's structure (from help): # structure(.Data, ...) # .Data: an object which will have various attributes attached to it. # ...: attributes, specified in 'tag=value' form, which will be # attached to data. #For historical reasons (these names are used when deparsing), # attributes '".Dim"', '".Dimnames"', '".Names"', '".Tsp"' and # '".Label"' are renamed to '"dim"', '"dimnames"', '"names"', # '"tsp"' and '"levels"'. # we want this in a single line exp.replace('\n','') exp = "".join(exp.split("\n")) # python compatible parameters exp = rel_re_param.sub(self._subs_dots, exp) # Rename class since it is a Python keyword exp = re.sub(' class = ', ' _r_class = ',exp) # Change 'structure' to '_r_structure' # TODO: check that we are outside of quotes "" exp = re.sub(' structure\(', ' _r_structure(', exp) exp = re.sub('^structure\(', '_r_structure(', exp) #special case # Change 'list' to '_r_list' exp = re.sub(' list\(', ' _r_list(', exp) exp = re.sub('\(list\(', '(_r_list(', exp) # Change 'a:b' to 'xrange(a,b+1)' exp = rel_re_xrange.sub(self._subs_xrange, exp) # Change 'dL' to 'Integer(d)' exp = rel_re_integer.sub(self._subs_integer, exp) # Wrap the right hand side of terms = ... in quotes since it # has a ~ in it. exp = rel_re_terms.sub(r'terms = "\1",', exp) # Change call = ..., to call = "...", exp = rel_re_call.sub(r'call = "\1",', exp) # seems to work for # rr = r.summary(r.princomp(r.matrix(r.c(1,2,3,4,3,4,1,2,2),4))) # rr._sage_() # but the call expression get's evaluated. why?!? TODO # translation: # c is an ordered list # list is a dictionary (where _Names give the entries names. # map entries in names to (value, name) in each entry? # structure is .. see above .. strucuture(DATA,**kw) # TODO: thinking of just replacing c( with ( to get a long tuple? exp = self._convert_nested_r_list(exp) # Set up the globals globs = {'NA':None, 'NULL':None, 'FALSE':False, 'TRUE':True, '_r_list':self._r_list, '_r_structure':self._r_structure, 'Integer':sage.rings.integer.Integer, 'character':str} return eval(exp, globs, globs) def _latex_(self): r""" Return LaTeX representation of this R object. This calls the ``latex`` command in R. OUTPUT: a latex expression (basically a string) EXAMPLES:: sage: latex(r(2)) # optional - Hmisc (R package) 2 """ from sage.misc.latex import LatexExpr self._check_valid() P = self.parent() # latex is in Hmisc, this is currently not part of Sage's R!!! try: P.library('Hmisc') except ImportError: raise RuntimeError("The R package 'Hmisc' is required for R to LaTeX conversion, but it is not available.") return LatexExpr(P.eval('latex(%s, file="");'%self.name())) class RFunctionElement(FunctionElement): def __reduce__(self): """ EXAMPLES:: sage: a = r([1,2,3]) sage: a.mean mean sage: dumps(a.mean) Traceback (most recent call last): ... NotImplementedError: pickling of R element methods is not yet supported """ raise NotImplementedError("pickling of R element methods is not yet supported") def _sage_doc_(self): """ Returns the help for self as a string. EXAMPLES:: sage: a = r([1,2,3]) sage: length = a.length sage: print(length._sage_doc_()) length package:base R Documentation ... <BLANKLINE> """ M = self._obj.parent() return M.help(self._name) def _sage_src_(self): """ Returns the source code of self. EXAMPLES:: sage: a = r([1,2,3]) sage: length = a.length sage: print(length._sage_src_()) function (x) .Primitive("length") """ M = self._obj.parent() return M.source(self._name) def __call__(self, *args, **kwds): """ EXAMPLES:: sage: a = r([1,2,3]) sage: length = a.length sage: length() [1] 3 """ return self._obj.parent().function_call(self._name, args=[self._obj] + list(args), kwds=kwds) class RFunction(ExpectFunction): def __init__(self, parent, name, r_name=None): """ A Function in the R interface. INPUT: - parent -- the R interface - name -- the name of the function for Python - r_name -- the name of the function in R itself (which can have dots in it) EXAMPLES:: sage: length = r.length sage: type(length) <class 'sage.interfaces.r.RFunction'> sage: loads(dumps(length)) length """ self._parent = parent if r_name: self._name = name else: self._name = parent._sage_to_r_name(name) def __cmp__(self, other): """ EXAMPLES:: sage: r.mean == loads(dumps(r.mean)) True sage: r.mean == r.lr False """ if not isinstance(other, RFunction): return cmp(type(self), type(other)) return cmp(self._name, other._name) def _sage_doc_(self): """ Returns the help for self. EXAMPLES:: sage: length = r.length sage: print(length._sage_doc_()) length package:base R Documentation ... <BLANKLINE> """ M = self._parent return M.help(self._name) def _sage_src_(self): """ Returns the source of self. EXAMPLES:: sage: length = r.length sage: print(length._sage_src_()) function (x) .Primitive("length") """ M = self._parent return M.source(self._name) def __call__(self, *args, **kwds): """ EXAMPLES:: sage: length = r.length sage: length([1,2,3]) [1] 3 """ return self._parent.function_call(self._name, args=list(args), kwds=kwds) def is_RElement(x): """ Return True if x is an element in an R interface. INPUT: - x -- object OUTPUT: bool EXAMPLES:: sage: from sage.interfaces.r import is_RElement sage: is_RElement(2) False sage: is_RElement(r(2)) True """ return isinstance(x, RElement) # An instance of R r = R() def reduce_load_R(): """ Used for reconstructing a copy of the R interpreter from a pickle. EXAMPLES:: sage: from sage.interfaces.r import reduce_load_R sage: reduce_load_R() R Interpreter """ return r import os def r_console(): """ Spawn a new R command-line session. EXAMPLES:: sage: r.console() # not tested R version 2.6.1 (2007-11-26) Copyright (C) 2007 The R Foundation for Statistical Computing ISBN 3-900051-07-0 ... """ from sage.repl.rich_output.display_manager import get_display_manager if not get_display_manager().is_in_terminal(): raise RuntimeError('Can use the console only in the terminal. Try %%r magics instead.') # This will only spawn local processes os.system('R --vanilla') def r_version(): """ Return the R version. EXAMPLES:: sage: r_version() # not tested ((3, 0, 1), 'R version 3.0.1 (2013-05-16)') sage: rint, rstr = r_version() sage: rint[0] >= 3 True sage: rstr.startswith('R version') True """ return r.version() class HelpExpression(str): """ Used to improve printing of output of r.help. """ def __repr__(self): """ Return string representation of self. OUTPUT: string EXAMPLES:: sage: a = sage.interfaces.r.HelpExpression("This\nis\nR!") sage: type(a) <class 'sage.interfaces.r.HelpExpression'> sage: a This is R! """ return str(self)
// Copyright 2018 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // // ----------------------------------------------------------------------------- // File: stacktrace.h // ----------------------------------------------------------------------------- // // This file contains routines to extract the current stack trace and associated // stack frames. These functions are thread-safe and async-signal-safe. // // Note that stack trace functionality is platform dependent and requires // additional support from the compiler/build system in most cases. (That is, // this functionality generally only works on platforms/builds that have been // specifically configured to support it.) // // Note: stack traces in Abseil that do not utilize a symbolizer will result in // frames consisting of function addresses rather than human-readable function // names. (See symbolize.h for information on symbolizing these values.) #ifndef IRESEARCH_ABSL_DEBUGGING_STACKTRACE_H_ #define IRESEARCH_ABSL_DEBUGGING_STACKTRACE_H_ #include "absl/base/config.h" namespace iresearch_absl { IRESEARCH_ABSL_NAMESPACE_BEGIN // GetStackFrames() // // Records program counter values for up to `max_depth` frames, skipping the // most recent `skip_count` stack frames, stores their corresponding values // and sizes in `results` and `sizes` buffers, and returns the number of frames // stored. (Note that the frame generated for the `absl::GetStackFrames()` // routine itself is also skipped.) // // Example: // // main() { foo(); } // foo() { bar(); } // bar() { // void* result[10]; // int sizes[10]; // int depth = iresearch_absl::GetStackFrames(result, sizes, 10, 1); // } // // The current stack frame would consist of three function calls: `bar()`, // `foo()`, and then `main()`; however, since the `GetStackFrames()` call sets // `skip_count` to `1`, it will skip the frame for `bar()`, the most recently // invoked function call. It will therefore return 2 and fill `result` with // program counters within the following functions: // // result[0] foo() // result[1] main() // // (Note: in practice, a few more entries after `main()` may be added to account // for startup processes.) // // Corresponding stack frame sizes will also be recorded: // // sizes[0] 16 // sizes[1] 16 // // (Stack frame sizes of `16` above are just for illustration purposes.) // // Stack frame sizes of 0 or less indicate that those frame sizes couldn't // be identified. // // This routine may return fewer stack frame entries than are // available. Also note that `result` and `sizes` must both be non-null. extern int GetStackFrames(void** result, int* sizes, int max_depth, int skip_count); // GetStackFramesWithContext() // // Records program counter values obtained from a signal handler. Records // program counter values for up to `max_depth` frames, skipping the most recent // `skip_count` stack frames, stores their corresponding values and sizes in // `results` and `sizes` buffers, and returns the number of frames stored. (Note // that the frame generated for the `absl::GetStackFramesWithContext()` routine // itself is also skipped.) // // The `uc` parameter, if non-null, should be a pointer to a `ucontext_t` value // passed to a signal handler registered via the `sa_sigaction` field of a // `sigaction` struct. (See // http://man7.org/linux/man-pages/man2/sigaction.2.html.) The `uc` value may // help a stack unwinder to provide a better stack trace under certain // conditions. `uc` may safely be null. // // The `min_dropped_frames` output parameter, if non-null, points to the // location to note any dropped stack frames, if any, due to buffer limitations // or other reasons. (This value will be set to `0` if no frames were dropped.) // The number of total stack frames is guaranteed to be >= skip_count + // max_depth + *min_dropped_frames. extern int GetStackFramesWithContext(void** result, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames); // GetStackTrace() // // Records program counter values for up to `max_depth` frames, skipping the // most recent `skip_count` stack frames, stores their corresponding values // in `results`, and returns the number of frames // stored. Note that this function is similar to `absl::GetStackFrames()` // except that it returns the stack trace only, and not stack frame sizes. // // Example: // // main() { foo(); } // foo() { bar(); } // bar() { // void* result[10]; // int depth = iresearch_absl::GetStackTrace(result, 10, 1); // } // // This produces: // // result[0] foo // result[1] main // .... ... // // `result` must not be null. extern int GetStackTrace(void** result, int max_depth, int skip_count); // GetStackTraceWithContext() // // Records program counter values obtained from a signal handler. Records // program counter values for up to `max_depth` frames, skipping the most recent // `skip_count` stack frames, stores their corresponding values in `results`, // and returns the number of frames stored. (Note that the frame generated for // the `absl::GetStackFramesWithContext()` routine itself is also skipped.) // // The `uc` parameter, if non-null, should be a pointer to a `ucontext_t` value // passed to a signal handler registered via the `sa_sigaction` field of a // `sigaction` struct. (See // http://man7.org/linux/man-pages/man2/sigaction.2.html.) The `uc` value may // help a stack unwinder to provide a better stack trace under certain // conditions. `uc` may safely be null. // // The `min_dropped_frames` output parameter, if non-null, points to the // location to note any dropped stack frames, if any, due to buffer limitations // or other reasons. (This value will be set to `0` if no frames were dropped.) // The number of total stack frames is guaranteed to be >= skip_count + // max_depth + *min_dropped_frames. extern int GetStackTraceWithContext(void** result, int max_depth, int skip_count, const void* uc, int* min_dropped_frames); // SetStackUnwinder() // // Provides a custom function for unwinding stack frames that will be used in // place of the default stack unwinder when invoking the static // GetStack{Frames,Trace}{,WithContext}() functions above. // // The arguments passed to the unwinder function will match the // arguments passed to `absl::GetStackFramesWithContext()` except that sizes // will be non-null iff the caller is interested in frame sizes. // // If unwinder is set to null, we revert to the default stack-tracing behavior. // // ***************************************************************************** // WARNING // ***************************************************************************** // // iresearch_absl::SetStackUnwinder is not suitable for general purpose use. It is // provided for custom runtimes. // Some things to watch out for when calling `absl::SetStackUnwinder()`: // // (a) The unwinder may be called from within signal handlers and // therefore must be async-signal-safe. // // (b) Even after a custom stack unwinder has been unregistered, other // threads may still be in the process of using that unwinder. // Therefore do not clean up any state that may be needed by an old // unwinder. // ***************************************************************************** extern void SetStackUnwinder(int (*unwinder)(void** pcs, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames)); // DefaultStackUnwinder() // // Records program counter values of up to `max_depth` frames, skipping the most // recent `skip_count` stack frames, and stores their corresponding values in // `pcs`. (Note that the frame generated for this call itself is also skipped.) // This function acts as a generic stack-unwinder; prefer usage of the more // specific `GetStack{Trace,Frames}{,WithContext}()` functions above. // // If you have set your own stack unwinder (with the `SetStackUnwinder()` // function above, you can still get the default stack unwinder by calling // `DefaultStackUnwinder()`, which will ignore any previously set stack unwinder // and use the default one instead. // // Because this function is generic, only `pcs` is guaranteed to be non-null // upon return. It is legal for `sizes`, `uc`, and `min_dropped_frames` to all // be null when called. // // The semantics are the same as the corresponding `GetStack*()` function in the // case where `absl::SetStackUnwinder()` was never called. Equivalents are: // // null sizes | non-nullptr sizes // |==========================================================| // null uc | GetStackTrace() | GetStackFrames() | // non-null uc | GetStackTraceWithContext() | GetStackFramesWithContext() | // |==========================================================| extern int DefaultStackUnwinder(void** pcs, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames); namespace debugging_internal { // Returns true for platforms which are expected to have functioning stack trace // implementations. Intended to be used for tests which want to exclude // verification of logic known to be broken because stack traces are not // working. extern bool StackTraceWorksForTest(); } // namespace debugging_internal IRESEARCH_ABSL_NAMESPACE_END } // namespace absl #endif // IRESEARCH_ABSL_DEBUGGING_STACKTRACE_H_
import numpy as np LM = np.zeros(15).astype(int) ### Indices for key landmarks LM[0] = 360 #lm_nose_tip = 30 LM[1] = 1191 #lm_right_eye_R = 45 LM[2] = 1203#lm_right_eye_L = 42 LM[3] = 606#lm_left_eye_L = 36 LM[4] = 436#lm_left_eye_R = 39 LM[5] = 140#lm_mouth_L = 48 LM[6] = 824#lm_mouth_R = 54 LM[7] = 223#lm_mouth_middle_Top_T = 51 LM[8] = 776#lm_mouth_middle_Top_B = 62 LM[9] = 767#lm_mouth_middle_Bottom_T = 66 LM[10] = 242#lm_mouth_middle_Bottom_B = 57 LM [11] = 546# boundary_left LM [12] = 1162 # boundary_right LM [13] = 509# boundary_left_top LM [14] = 1080# boundary_right_top
from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship from models.base import Base from models.servers import Server from models.users import User class Status(Base): __tablename__ = 'status' id = Column(Integer, primary_key=True) server_status = Column(Integer) user_id = Column(Integer, ForeignKey('users.id'), nullable=False) server_id = Column(Integer, ForeignKey('servers.id'), nullable=False) user = relationship(User) server = relationship(Server) def __init__(self, server_status, user, server): self.server_status = server_status self.user = user self.server = server
import localStorageMock from './localStorage.js'; function checkCompleted() { const editButtons = document.querySelectorAll('.description'); editButtons.forEach((btn) => { btn.addEventListener('keypress', (e) => { if (e.key === 'Enter') { e.preventDefault(); } }); }); } export default (e) => { const tasks = Storage.getItem('stock'); const todoArray = JSON.parse(tasks); const todoObject = todoArray.find((x) => x.index === Number(e.target.parentElement.id)); const index = todoArray.indexOf(todoObject); todoArray[index].description = e.target.textContent; localStorageMock.setItem('todo', tasks); }; checkCompleted();
this["UI"] = this["UI"] || {}; this["UI"]["templates"] = this["UI"]["templates"] || {}; this["UI"]["templates"]["body_cell"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression; return "<td class=\"pjax-table-cell\" data-property=\"" + alias3(((helper = (helper = helpers.property || (depth0 != null ? depth0.property : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"property","hash":{},"data":data}) : helper))) + "\" data-value=\"" + alias3(((helper = (helper = helpers.value || (depth0 != null ? depth0.value : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"value","hash":{},"data":data}) : helper))) + "\">" + alias3(((helper = (helper = helpers.display_value || (depth0 != null ? depth0.display_value : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"display_value","hash":{},"data":data}) : helper))) + "</td>"; },"useData":true}); this["UI"]["templates"]["body_checkbox_cell"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var helper; return "<td class=\"pjax-table-cell\" data-property=\"id\" data-value=\"" + this.escapeExpression(((helper = (helper = helpers.value || (depth0 != null ? depth0.value : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0,{"name":"value","hash":{},"data":data}) : helper))) + "\">\n <input type=\"checkbox\">\n</td>"; },"useData":true}); this["UI"]["templates"]["body_row"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var stack1, helper; return "<tr class=\"pjax-table-row\">" + ((stack1 = ((helper = (helper = helpers.cells || (depth0 != null ? depth0.cells : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0,{"name":"cells","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "</tr>"; },"useData":true}); this["UI"]["templates"]["footer_cell"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { return "<td class=\"pjax-table-footer pjax-table-footer-static-content\" colspan=\"7\"></td>"; },"useData":true}); this["UI"]["templates"]["footer_row"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var stack1, helper; return "<tr class=\"pjax-table-footer-row\">" + ((stack1 = ((helper = (helper = helpers.cells || (depth0 != null ? depth0.cells : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0,{"name":"cells","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "</tr>"; },"useData":true}); this["UI"]["templates"]["header_cell"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression; return "<th class=\"pjax-table-header sortable\" \n data-sortable=\"true\" \n data-property=\"" + alias3(((helper = (helper = helpers.property || (depth0 != null ? depth0.property : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"property","hash":{},"data":data}) : helper))) + "\" \n data-current-sort-direction=\"" + alias3(((helper = (helper = helpers.current_sort || (depth0 != null ? depth0.current_sort : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"current_sort","hash":{},"data":data}) : helper))) + "\" \n data-default-sort-direction=\"asc\">\n " + alias3(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"name","hash":{},"data":data}) : helper))) + "\n <span class=\"pjax-table-sort-indicator\">\n <i class=\"fa fa-caret-" + alias3((helpers.sortIcon || (depth0 && depth0.sortIcon) || alias1).call(depth0,(depth0 != null ? depth0.current_sort : depth0),{"name":"sortIcon","hash":{},"data":data})) + "\"></i>\n </span>\n</th>\n"; },"useData":true}); this["UI"]["templates"]["header_checkbox_cell"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { return "<th class=\"pjax-table-header sortable\" \n data-property=\"id\" \n data-select-all-enabled=\"true\">\n <input type=\"checkbox\">\n <span class=\"pjax-table-sort-indicator\">\n <i class=\"fa fa-caret-" + this.escapeExpression((helpers.sortIcon || (depth0 && depth0.sortIcon) || helpers.helperMissing).call(depth0,(depth0 != null ? depth0.current_sort : depth0),{"name":"sortIcon","hash":{},"data":data})) + "\"></i>\n </span>\n</th>\n"; },"useData":true}); this["UI"]["templates"]["header_row"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var stack1, helper; return "<tr class=\"pjax-table-header-row\">" + ((stack1 = ((helper = (helper = helpers.cells || (depth0 != null ? depth0.cells : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0,{"name":"cells","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "</tr>"; },"useData":true}); this["UI"]["templates"]["pagination"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { var stack1, helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression; return " <div class=\"btn-group\">\n <button type=\"button\" class=\"btn btn-default btn-sm ui-prev-page\" " + ((stack1 = helpers['if'].call(depth0,(depth0 != null ? depth0.on_first_page : depth0),{"name":"if","hash":{},"fn":this.program(2, data, 0),"inverse":this.noop,"data":data})) != null ? stack1 : "") + ">\n <i class=\"fa fa-chevron-left\"></i>\n </button>\n </div>\n\n <div class=\"btn-group\">\n <div class=\"ui-page-index-dropdown dropdown\" data-current-page=\"" + alias3(((helper = (helper = helpers.$current_page || (depth0 != null ? depth0.$current_page : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"$current_page","hash":{},"data":data}) : helper))) + "\">\n <button class=\"btn btn-default btn-sm dropdown-toggle\" data-toggle=\"dropdown\">\n <span class=\"dropdown-label\">Page " + alias3(((helper = (helper = helpers.current_page || (depth0 != null ? depth0.current_page : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"current_page","hash":{},"data":data}) : helper))) + "</span>\n <i class=\"fa fa-angle-down\"></i>\n </button>\n <ul class=\"dropdown-menu open-up ui-page-select-dropdown\">\n " + ((stack1 = ((helper = (helper = helpers.page_items || (depth0 != null ? depth0.page_items : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"page_items","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "\n </ul>\n </div>\n </div>\n\n <div class=\"btn-group\">\n <button type=\"button\" class=\"btn btn-default btn-sm ui-next-page\" " + ((stack1 = helpers['if'].call(depth0,(depth0 != null ? depth0.on_last_page : depth0),{"name":"if","hash":{},"fn":this.program(2, data, 0),"inverse":this.noop,"data":data})) != null ? stack1 : "") + ">\n <i class=\"fa fa-fw fa-chevron-right\"></i>\n </button>\n </div>\n"; },"2":function(depth0,helpers,partials,data) { return "disabled"; },"4":function(depth0,helpers,partials,data) { var helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression; return " <div class=\"btn-group btn-sm btn-link\">Page " + alias3(((helper = (helper = helpers.current_page || (depth0 != null ? depth0.current_page : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"current_page","hash":{},"data":data}) : helper))) + " of " + alias3(((helper = (helper = helpers.last_page || (depth0 != null ? depth0.last_page : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"last_page","hash":{},"data":data}) : helper))) + "</div>\n"; },"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var stack1, helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression; return "<div class=\"pjax-table-pagination ui-pagination\">\n <div class=\"pull-left btn-toolbar\">\n <div class=\"dropdown btn-group\" data-per-page=\"" + alias3(((helper = (helper = helpers.$perpage || (depth0 != null ? depth0.$perpage : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"$perpage","hash":{},"data":data}) : helper))) + "\">\n <button data-toggle=\"dropdown\" class=\"btn btn-default btn-sm dropdown-toggle\">\n <span class=\"dropdown-label\">Per Page " + alias3(((helper = (helper = helpers.current_perpage || (depth0 != null ? depth0.current_perpage : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"current_perpage","hash":{},"data":data}) : helper))) + "</span>\n <i class=\"fa fa-fw fa-angle-down\"></i>\n </button>\n <ul class=\"dropdown-menu open-up ui-perpage-dropdown\">\n <li class=\"dropdown-item\" data-value=\"10\"><a>10</a></li>\n <li class=\"dropdown-item\" data-value=\"20\"><a>20</a></li>\n <li class=\"dropdown-item\" data-value=\"50\"><a>50</a></li>\n <li class=\"dropdown-item\" data-value=\"100\"><a>100</a></li>\n </ul>\n </div>\n <div class=\"btn-group btn-sm btn-link\">From " + alias3(((helper = (helper = helpers.from || (depth0 != null ? depth0.from : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"from","hash":{},"data":data}) : helper))) + " to " + alias3(((helper = (helper = helpers.to || (depth0 != null ? depth0.to : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"to","hash":{},"data":data}) : helper))) + " of " + alias3(((helper = (helper = helpers.total || (depth0 != null ? depth0.total : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"total","hash":{},"data":data}) : helper))) + "</div>\n </div>\n\n <div class=\"pull-right btn-toolbar\">\n" + ((stack1 = helpers['if'].call(depth0,(depth0 != null ? depth0.on_last_page : depth0),{"name":"if","hash":{},"fn":this.program(1, data, 0),"inverse":this.program(4, data, 0),"data":data})) != null ? stack1 : "") + " </div>\n</div>\n"; },"useData":true}); this["UI"]["templates"]["pagination_page_item"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { return " active "; },"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var stack1, helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression; return "<li class=\"dropdown-item\" data-value=\"" + alias3(((helper = (helper = helpers.index || (depth0 != null ? depth0.index : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"index","hash":{},"data":data}) : helper))) + "\">\n <a class=\"item " + ((stack1 = helpers['if'].call(depth0,(depth0 != null ? depth0.active : depth0),{"name":"if","hash":{},"fn":this.program(1, data, 0),"inverse":this.noop,"data":data})) != null ? stack1 : "") + "\">" + alias3(((helper = (helper = helpers.index || (depth0 != null ? depth0.index : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"index","hash":{},"data":data}) : helper))) + "</a>\n</li>"; },"useData":true}); this["UI"]["templates"]["table"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var stack1, helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression; return "<div id=\"pjax-table\"\n data-pjax-table \n data-pjax-container=\"#pjax-table\"\n data-url=\"/\" >\n <table class=\"table pjax-table\"\n data-total-rows=\"" + alias3(((helper = (helper = helpers.total_rows || (depth0 != null ? depth0.total_rows : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"total_rows","hash":{},"data":data}) : helper))) + "\"\n data-current-sort-property=\"" + alias3(((helper = (helper = helpers.sort_property || (depth0 != null ? depth0.sort_property : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"sort_property","hash":{},"data":data}) : helper))) + "\"\n data-current-sort-direction=\"" + alias3(((helper = (helper = helpers.sort_order || (depth0 != null ? depth0.sort_order : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"sort_order","hash":{},"data":data}) : helper))) + "\"\n data-current-search-str=\"" + alias3(((helper = (helper = helpers.current_search_str || (depth0 != null ? depth0.current_search_str : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"current_search_str","hash":{},"data":data}) : helper))) + "\"\n data-current-page=\"" + alias3(((helper = (helper = helpers.current_page || (depth0 != null ? depth0.current_page : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"current_page","hash":{},"data":data}) : helper))) + "\"\n data-current-perpage=\"" + alias3(((helper = (helper = helpers.current_perpage || (depth0 != null ? depth0.current_perpage : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"current_perpage","hash":{},"data":data}) : helper))) + "\">\n <thead>\n " + ((stack1 = ((helper = (helper = helpers.header_rows || (depth0 != null ? depth0.header_rows : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"header_rows","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "\n </thead>\n <tbody>\n " + ((stack1 = ((helper = (helper = helpers.body_rows || (depth0 != null ? depth0.body_rows : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"body_rows","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "\n </tbody>\n <tfoot>\n " + ((stack1 = ((helper = (helper = helpers.footer_rows || (depth0 != null ? depth0.footer_rows : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"footer_rows","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "\n </tfoot>\n </table>\n <div>\n " + ((stack1 = ((helper = (helper = helpers.pagination || (depth0 != null ? depth0.pagination : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"pagination","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "\n </div>\n</div>\n"; },"useData":true});
/** * Bio component that queries for data * with Gatsby's useStaticQuery component * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from "react" import { useStaticQuery, graphql } from "gatsby" import Image from "gatsby-image" import { rhythm } from "../utils/typography" const Bio = () => { const data = useStaticQuery(graphql` query BioQuery { avatar: file(absolutePath: { regex: "/profile-pic.jpg/" }) { childImageSharp { fixed(width: 50, height: 50) { ...GatsbyImageSharpFixed } } } site { siteMetadata { author { name summary } social { twitter } } } } `) const { author, social } = data.site.siteMetadata return ( <div > </div> ) } export default Bio
import React, { Component } from 'react'; import { connect } from 'react-redux'; import ee from 'event-emitter'; import Menu from 'controls/menu/Menu'; import Toolbar from 'components/user-form/toolbar/Toolbar'; import Form from 'components/user-form/form/Form'; class UserForm extends Component { constructor(props) { super(props); let emitter = ee(); this.submit = () => emitter.emit('user-form-submit'); this.onSubmit = (callback) => emitter.on('user-form-submit', callback); this.offSubmit = () => emitter.off('user-form-submit'); } render() { return ( <div> <Menu/> <Toolbar type={ this.props.type } submit={ this.submit } /> <Form type={ this.props.type } userId={ this.props.userId } onSubmit={ this.onSubmit } offSubmit={ this.offSubmit } /> </div> ); } } function mapStateToProps(state, ownProps) { return { type: ownProps.match.params.type || 'create', userId: parseInt(ownProps.match.params.userId) || null }; } export default connect(mapStateToProps, () => { return {} })(UserForm);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _mssql = _interopRequireDefault(require("mssql")); var _xlsxStyle = _interopRequireDefault(require("xlsx-style")); var _mathjs = require("mathjs"); var _FuenteDatoVariableAtributos = _interopRequireDefault(require("./FuenteDatoVariableAtributos.js")); var _Modal = _interopRequireDefault(require("../../../Modal/Modal.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /*COMPONENTE CONTENEDOR PADRE / ORIGINAL DE PROCESO CREAR VARIABLE ESTILO VARIABLE*/ //var fuenteDatoAtributo = {}; /*var columnaSeleccionada = {}, operacionSeleccionada = {}; const operaciones = [{valor: "Asignar Valor Único"}, {valor: "Asignar Valor Único Si"}, {valor: "Asignar Valor Multiples"}, {valor: "Asignar Valor Multiples Si"}, {valor: "Contar"}, {valor: "Contar Si"}]; const operacionesNumero = [{valor: "Asignar Valor Único"}, {valor: "Asignar Valor Único Si"}, {valor: "Asignar Valor Multiples"}, {valor: "Asignar Valor Multiples Si"}, {valor: "Contar"}, {valor: "Contar Si"}, {valor: "Calcular Promedio"}, {valor: "Máximo"}, {valor: "Mínimo"}, {valor: "Sumar"}]; const operacionesFecha = [{valor: "Asignar Valor Único"}, {valor: "Asignar Valor Único Si"}, {valor: "Asignar Valor Multiples"}, {valor: "Asignar Valor Multiples Si"}, {valor: "Contar"}, {valor: "Contar Si"}]; const operacionesBoolean = [{valor: "Asignar Valor Único"}, {valor: "Asignar Valor Único Si"}, {valor: "Asignar Valor Multiples"}, {valor: "Asignar Valor Multiples Si"}, {valor: "Contar"}, {valor: "Contar Si"}]; const operacionesCadena = [{valor: "Asignar Valor Único"}, {valor: "Asignar Valor Único Si"}, {valor: "Asignar Valor Multiples"}, {valor: "Asignar Valor Multiples Si"}, {valor: "Contar"}, {valor: "Contar Si"}, {valor: "Sumar"}];*/ var mostrarEsObjetoGlobal = true; var mostrarEsColeccionGlobal = true; var mostrarInstruccionSQLGlobal = true; var tituloGlobal = "Instrucción SQL"; var valorPeriodicidadGlobal = "-1"; var tipoVariable = ''; var periodicidad = [{ nombre: "diario" }, { nombre: "semanal" }, { nombre: "mensual" }, { nombre: "trimestral" }, { nombre: "bi-anual" }, { nombre: "anual" }]; /* ************************************** ************************************** VARIABLES CALCULO ************************************** ************************************** */ var nivelMaximoVariables = 0; var arregloDeFuentesDeDatos = []; //Arreglo con las fuentes de datos //objeto: {tablaID, nombre, descripcion, esObjeto, objetoPadreID, guardar, nivel, [arreglo de atributos]} //objeto arreglo de atributos: {nombre, tipo, formula} window.arregloDeVariables = []; //Arreglo con las variables window.arregloDeErroresVariables = []; //objeto: {nombre, descripcion, esObjeto, objetoPadreID, guardar, nivel, [arreglo de atributos]} //objeto arreglo de atributos: {nombre, tipo, formula} window.arregloConexionesATablas = []; //Arreglo con los valores para poder conectarse a las tablas window.arregloResultadosDeTablas = []; //Arreglo con los valores obtenidos despues de conectarse a las tablas var banderaImportacionCamposVariablesINICIO = 0; //Bandera para saber si termino de importar los campos de las variables var banderaImportacionCamposVariablesFIN = 0; //Bandera para saber si termino de importar los campos de las variables var banderaImportacionSegmentosCamposVariablesINICIO = 0; //Bandera para saber si termino de importar los segmentos de reglas de los campos de las variables var banderaImportacionSegmentosCamposVariablesFIN = 0; //Bandera para saber si termino de importar los segmentos de reglas de los campos de las variables var banderaImportacionReglasSegmentosCamposVariablesINICIO = 0; //Bandera para saber si termino de importar las reglas de los segmentos de los campos de las variables var banderaImportacionReglasSegmentosCamposVariablesFIN = 0; //Bandera para saber si termino de importar las reglas de los segmentos de los campos de las variables var banderaImportacionFormulasCamposVariablesINICIO = 0; //Bandera para saber si termino de importar las formulas de los campos de las variables var banderaImportacionFormulasCamposVariablesFIN = 0; //Bandera para saber si termino de importar las formulas de los campos de las variables var banderaImportacionElementosFormulasCamposVariablesINICIO = 0; //Bandera para saber si termino de importar los elementos de las formulas de los campos de las variables var banderaImportacionElementosFormulasCamposVariablesFIN = 0; //Bandera para saber si termino de importar los elementos de las formulas de los campos de las variables var banderaImportacionConecionesATablasINICIO = 0; //Bandera para saber si termino de importar los valores para poder conetarse a las tablas var banderaImportacionConecionesATablasFIN = 0; //Bandera para saber si termino de importar los valores para poder conetarse a las tablas var banderaImportacionValoresDeTablasDeFuenteDeDatosINICIO = 0; //Bandera para saber si termino de importar los valores de las tablas de fuentes de datos var banderaImportacionValoresDeTablasDeFuenteDeDatosFIN = 0; //Bandera para saber si termino de importar los valores de las tablas de fuentes de datos window.arregloDeExcel = []; //Arreglo de variables de excel window.arregloDeErroresExcel = []; //objeto: {nombre, descripcion, esObjeto, objetoPadreID, guardar, nivel, [arreglo de atributos]} //objeto arreglo de atributos: {nombre, tipo, formula} var banderaImportacionVariablesExcelINICIO = 0; //Bandera para saber si termino de importar variables excel var banderaImportacionVariablesExcelFIN = 0; //Bandera para saber si termino de importar variables excel window.arregloDeFormas = []; //Arreglo con las variables de formas window.arregloDeErroresFormas = []; window.arregloHTMLFormas = []; //Arreglo que contiene el codigo html de las formas var banderaVerificarPeriodicidadINICIO = 0; //Bandera para saber si termino de verificar periodicidad de todo tipo de variable(excel, forma y variable) var banderaVerificarPeriodicidadFIN = 0; //Bandera para saber si termino de verificar periodicidad de todo tipo de variable(excel, forma y variable) var banderaImportarValoresPeriodicidadINICIO = 0; //Bandera para saber si termino de verificar periodicidad de todo tipo de variable(excel, forma y variable) var banderaImportarValoresPeriodicidadFIN = 0; //Bandera para saber si termino de verificar periodicidad de todo tipo de variable(excel, forma y variable) /* ************************************** ************************************** VARIABLES CALCULO FIN ************************************** ************************************** */ var FuenteDatoVariable = /*#__PURE__*/ function (_React$Component) { _inherits(FuenteDatoVariable, _React$Component); function FuenteDatoVariable(props) { var _this; _classCallCheck(this, FuenteDatoVariable); _this = _possibleConstructorReturn(this, _getPrototypeOf(FuenteDatoVariable).call(this, props)); _this.state = { mostrarEsObjeto: mostrarEsObjetoGlobal, mostrarEsColeccion: mostrarEsColeccionGlobal, titulo: tituloGlobal, mostrarInstruccionSQL: mostrarInstruccionSQLGlobal, valorPeriodicidad: valorPeriodicidadGlobal, tipoVariable: tipoVariable, usuarios: [] }; _this.saveBitacora = _this.saveBitacora.bind(_assertThisInitialized(_this)); _this.cambioInstruccionSQL = _this.cambioInstruccionSQL.bind(_assertThisInitialized(_this)); _this.cambioAColeccion = _this.cambioAColeccion.bind(_assertThisInitialized(_this)); _this.cambioAObjeto = _this.cambioAObjeto.bind(_assertThisInitialized(_this)); _this.cambiarTitulo = _this.cambiarTitulo.bind(_assertThisInitialized(_this)); _this.actualizarPeriodicidad = _this.actualizarPeriodicidad.bind(_assertThisInitialized(_this)); _this.cargarDatePicker = _this.cargarDatePicker.bind(_assertThisInitialized(_this)); _this.traerArchivosExcel = _this.traerArchivosExcel.bind(_assertThisInitialized(_this)); _this.traerVariablesExcel = _this.traerVariablesExcel.bind(_assertThisInitialized(_this)); _this.revisarFinImportacionVariablesExcel = _this.revisarFinImportacionVariablesExcel.bind(_assertThisInitialized(_this)); _this.traerFormas = _this.traerFormas.bind(_assertThisInitialized(_this)); _this.getNivelMaximoVariables = _this.getNivelMaximoVariables.bind(_assertThisInitialized(_this)); _this.traerVariables = _this.traerVariables.bind(_assertThisInitialized(_this)); _this.traerInstruccionSQLCampos = _this.traerInstruccionSQLCampos.bind(_assertThisInitialized(_this)); _this.traerInstruccionSQL = _this.traerInstruccionSQL.bind(_assertThisInitialized(_this)); _this.traerAtributosVariables = _this.traerAtributosVariables.bind(_assertThisInitialized(_this)); _this.revisarFinImportacionCamposVariables = _this.revisarFinImportacionCamposVariables.bind(_assertThisInitialized(_this)); _this.inicioTraerSegmentosDeCamposVariables = _this.inicioTraerSegmentosDeCamposVariables.bind(_assertThisInitialized(_this)); _this.traerSegmentosDeCamposVariables = _this.traerSegmentosDeCamposVariables.bind(_assertThisInitialized(_this)); _this.revisarFinImportacionSegmentosCamposVariables = _this.revisarFinImportacionSegmentosCamposVariables.bind(_assertThisInitialized(_this)); _this.inicioTraerReglasDeSegmentosVariables = _this.inicioTraerReglasDeSegmentosVariables.bind(_assertThisInitialized(_this)); _this.traerReglasDeSegmentosVariables = _this.traerReglasDeSegmentosVariables.bind(_assertThisInitialized(_this)); _this.revisarFinImportacionReglasSegmentosVariables = _this.revisarFinImportacionReglasSegmentosVariables.bind(_assertThisInitialized(_this)); _this.inicioTraerFormulasDeCamposVariables = _this.inicioTraerFormulasDeCamposVariables.bind(_assertThisInitialized(_this)); _this.traerFormulasDeCamposVariables = _this.traerFormulasDeCamposVariables.bind(_assertThisInitialized(_this)); _this.revisarFinImportacionFormulasCamposVariables = _this.revisarFinImportacionFormulasCamposVariables.bind(_assertThisInitialized(_this)); _this.inicioTraerElementosFormulasDeCamposVariables = _this.inicioTraerElementosFormulasDeCamposVariables.bind(_assertThisInitialized(_this)); _this.traerElementosFormulasDeCamposVariables = _this.traerElementosFormulasDeCamposVariables.bind(_assertThisInitialized(_this)); _this.revisarFinImportacionElementosFormulasCamposVariables = _this.revisarFinImportacionElementosFormulasCamposVariables.bind(_assertThisInitialized(_this)); _this.inicioTraerConeccionesATablas = _this.inicioTraerConeccionesATablas.bind(_assertThisInitialized(_this)); _this.noHaSidoImportadaConeccion = _this.noHaSidoImportadaConeccion.bind(_assertThisInitialized(_this)); _this.traerConeccionesATablas = _this.traerConeccionesATablas.bind(_assertThisInitialized(_this)); _this.finTraerConeccionesATablas = _this.finTraerConeccionesATablas.bind(_assertThisInitialized(_this)); _this.inicioTraerResultadosDeFuenteDeDatos = _this.inicioTraerResultadosDeFuenteDeDatos.bind(_assertThisInitialized(_this)); _this.traerResultadosDeFuenteDeDatos = _this.traerResultadosDeFuenteDeDatos.bind(_assertThisInitialized(_this)); _this.finTraerResultadosDeFuenteDeDatos = _this.finTraerResultadosDeFuenteDeDatos.bind(_assertThisInitialized(_this)); _this.addDays = _this.addDays.bind(_assertThisInitialized(_this)); _this.addMonths = _this.addMonths.bind(_assertThisInitialized(_this)); _this.addYears = _this.addYears.bind(_assertThisInitialized(_this)); _this.verificarPeriodicidad = _this.verificarPeriodicidad.bind(_assertThisInitialized(_this)); _this.traerPeriodicidadVariable = _this.traerPeriodicidadVariable.bind(_assertThisInitialized(_this)); _this.verificarFinPeriodicidad = _this.verificarFinPeriodicidad.bind(_assertThisInitialized(_this)); _this.iniciarImportacionValoresCalculados = _this.iniciarImportacionValoresCalculados.bind(_assertThisInitialized(_this)); _this.getResultsVariables = _this.getResultsVariables.bind(_assertThisInitialized(_this)); _this.getResultsVariablesFieldsInit = _this.getResultsVariablesFieldsInit.bind(_assertThisInitialized(_this)); _this.getFieldResults = _this.getFieldResults.bind(_assertThisInitialized(_this)); _this.getResultsIndicators = _this.getResultsIndicators.bind(_assertThisInitialized(_this)); _this.getResultsIndicatorsFieldsInit = _this.getResultsIndicatorsFieldsInit.bind(_assertThisInitialized(_this)); _this.getFieldIndicatorsResults = _this.getFieldIndicatorsResults.bind(_assertThisInitialized(_this)); _this.verificarFinImportacionValoresCalculados = _this.verificarFinImportacionValoresCalculados.bind(_assertThisInitialized(_this)); _this.codigoIniciacion = _this.codigoIniciacion.bind(_assertThisInitialized(_this)); _this.iniciacionElementosFormula = _this.iniciacionElementosFormula.bind(_assertThisInitialized(_this)); _this.iniciacionVariable = _this.iniciacionVariable.bind(_assertThisInitialized(_this)); _this.iniciacionCampo = _this.iniciacionCampo.bind(_assertThisInitialized(_this)); _this.crearCodigoFuenteDato = _this.crearCodigoFuenteDato.bind(_assertThisInitialized(_this)); _this.crearCodigoFuenteDatoSQL = _this.crearCodigoFuenteDatoSQL.bind(_assertThisInitialized(_this)); _this.crearCodigoSegmentoReglas = _this.crearCodigoSegmentoReglas.bind(_assertThisInitialized(_this)); _this.crearCodigoSegmentoReglasFormaOExcel = _this.crearCodigoSegmentoReglasFormaOExcel.bind(_assertThisInitialized(_this)); _this.arregloCodigoRegla = _this.arregloCodigoRegla.bind(_assertThisInitialized(_this)); _this.arregloCodigoReglaFormaOExcel = _this.arregloCodigoReglaFormaOExcel.bind(_assertThisInitialized(_this)); _this.agregarCodigoGuardarVariable = _this.agregarCodigoGuardarVariable.bind(_assertThisInitialized(_this)); _this.crearNivel = _this.crearNivel.bind(_assertThisInitialized(_this)); _this.isValidDate = _this.isValidDate.bind(_assertThisInitialized(_this)); _this.existeOperacion = _this.existeOperacion.bind(_assertThisInitialized(_this)); _this.guardarOperacionSQL = _this.guardarOperacionSQL.bind(_assertThisInitialized(_this)); _this.crearVariablesExcel = _this.crearVariablesExcel.bind(_assertThisInitialized(_this)); _this.getArregloPosicionesExcel = _this.getArregloPosicionesExcel.bind(_assertThisInitialized(_this)); _this.getObjetoLetraNumeroCelda = _this.getObjetoLetraNumeroCelda.bind(_assertThisInitialized(_this)); _this.esLetra = _this.esLetra.bind(_assertThisInitialized(_this)); _this.toColumnLetter = _this.toColumnLetter.bind(_assertThisInitialized(_this)); _this.toColumnNumber = _this.toColumnNumber.bind(_assertThisInitialized(_this)); _this.formaCrearVariable = _this.formaCrearVariable.bind(_assertThisInitialized(_this)); _this.iniciarMostrarFormas = _this.iniciarMostrarFormas.bind(_assertThisInitialized(_this)); _this.updateForm = _this.updateForm.bind(_assertThisInitialized(_this)); _this.loadFechas = _this.loadFechas.bind(_assertThisInitialized(_this)); _this.closeModalForma = _this.closeModalForma.bind(_assertThisInitialized(_this)); _this.iniciarCalculoExcel = _this.iniciarCalculoExcel.bind(_assertThisInitialized(_this)); _this.iniciarCalculoFormas = _this.iniciarCalculoFormas.bind(_assertThisInitialized(_this)); _this.iniciarHilo = _this.iniciarHilo.bind(_assertThisInitialized(_this)); _this.iniciarCalculoIndicadores = _this.iniciarCalculoIndicadores.bind(_assertThisInitialized(_this)); _this.guardarVariablesCalculadas = _this.guardarVariablesCalculadas.bind(_assertThisInitialized(_this)); _this.verificarSiExisteVariableEnResultadosHistoricos = _this.verificarSiExisteVariableEnResultadosHistoricos.bind(_assertThisInitialized(_this)); _this.crearTablaDeResultadoNombreVariable = _this.crearTablaDeResultadoNombreVariable.bind(_assertThisInitialized(_this)); _this.crearResultadoNombreVariable = _this.crearResultadoNombreVariable.bind(_assertThisInitialized(_this)); _this.guardarResultadosNombreVariable = _this.guardarResultadosNombreVariable.bind(_assertThisInitialized(_this)); _this.guardarVariable = _this.guardarVariable.bind(_assertThisInitialized(_this)); _this.borrarRiesgo = _this.borrarRiesgo.bind(_assertThisInitialized(_this)); _this.verificarPeriodicidadGuardar = _this.verificarPeriodicidadGuardar.bind(_assertThisInitialized(_this)); _this.updatePeriodicidad = _this.updatePeriodicidad.bind(_assertThisInitialized(_this)); _this.guardarPeriodicidad = _this.guardarPeriodicidad.bind(_assertThisInitialized(_this)); //valorPeriodicidadGlobal = this.props.periodicidadVariable; _this.verificarExistenciaErroresExcel = _this.verificarExistenciaErroresExcel.bind(_assertThisInitialized(_this)); _this.verificarExistenciaErroresForma = _this.verificarExistenciaErroresForma.bind(_assertThisInitialized(_this)); _this.verificarExistenciaErroresVariable = _this.verificarExistenciaErroresVariable.bind(_assertThisInitialized(_this)); _this.getUsuarios = _this.getUsuarios.bind(_assertThisInitialized(_this)); _this.goToTimeline = _this.goToTimeline.bind(_assertThisInitialized(_this)); return _this; } _createClass(FuenteDatoVariable, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; $('#fecha').datepicker({ format: "dd-mm-yyyy", todayHighlight: true, viewMode: "days", minViewMode: "days", language: 'es' }); $("#fecha").datepicker("setDate", this.props.fechaInicioVariable); var self = this; $('#fecha').datepicker().on('changeDate', function () { var fecha = $("#fecha").datepicker('getDate'); self.props.actualizarFechaInicio(fecha); }); setTimeout(function () { self.cargarDatePicker(); }, 600); if (this.props.tipoVariableOriginal.localeCompare("variable") == 0 && this.props.esPrimeraVez) { var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from Variables where ID = " + _this2.props.idVariable, function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { if (result.recordset.length > 0) { var titulo = "Instrucción SQL"; if (!result.recordset[0].esInstruccionSQL) { if (result.recordset[0].esObjeto) { titulo = "Variable Compuesta"; } else { titulo = "Variable Individual"; } } mostrarEsObjetoGlobal = result.recordset[0].esObjeto; mostrarEsColeccionGlobal = result.recordset[0].esColeccion; mostrarInstruccionSQLGlobal = result.recordset[0].esInstruccionSQL; valorPeriodicidadGlobal = result.recordset[0].periodicidad; _this2.setState({ titulo: titulo, mostrarEsObjeto: result.recordset[0].esObjeto, mostrarInstruccionSQL: result.recordset[0].esInstruccionSQL, mostrarEsColeccion: result.recordset[0].esColeccion, valorPeriodicidad: result.recordset[0].periodicidad }); //this.props.changeStateFirstTimeToFalse(); } }); } }); }); // fin transaction } if (this.props.tipoVariableOriginal.localeCompare("variable") == 0) { var _transaction = new _mssql["default"].Transaction(this.props.pool); _transaction.begin(function (err) { var rolledBack = false; _transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(_transaction); request.query("select * from Variables where ID = " + _this2.props.idVariable, function (err, result) { if (err) { console.log(err); if (!rolledBack) { _transaction.rollback(function (err) {}); } } else { _transaction.commit(function (err) { if (result.recordset.length > 0) { if (!result.recordset[0].esInstruccionSQL) { if (result.recordset[0].esObjeto) { tipoVariable = 'objeto'; } else { tipoVariable = 'escalar'; } } else { tipoVariable = 'sql'; } _this2.setState({ tipoVariable: tipoVariable }); } }); } }); }); // fin transaction } this.getUsuarios(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { tipoVariable = ''; } }, { key: "saveBitacora", value: function saveBitacora(fecha, descripcion) { var _this3 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("insert into Bitacora (usuarioID, nombreUsuario, fecha, descripcion) values (" + _this3.props.userID + ", '" + _this3.props.userName + "', '" + fecha.getFullYear() + "-" + (fecha.getMonth() + 1) + "-" + fecha.getDate() + "', '" + descripcion + "')", function (err, result) { if (err) { console.log(err); _this3.props.showMessage("Error", 'No se pudo guardar información de bitacora.', true, false, {}); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) {}); } }); }); // fin transaction } }, { key: "cambioInstruccionSQL", value: function cambioInstruccionSQL() { mostrarInstruccionSQLGlobal = !this.state.mostrarInstruccionSQL; mostrarEsObjetoGlobal = true; this.setState({ mostrarInstruccionSQL: !this.state.mostrarInstruccionSQL, mostrarEsObjeto: true }, this.cambiarTitulo); } }, { key: "cambioAObjeto", value: function cambioAObjeto() { mostrarEsObjetoGlobal = !this.state.mostrarEsObjeto; this.setState({ mostrarEsObjeto: !this.state.mostrarEsObjeto, tipoVariable: '' }, this.cambiarTitulo); } }, { key: "cambioAColeccion", value: function cambioAColeccion() { mostrarEsColeccionGlobal = !this.state.mostrarEsColeccion; this.setState({ mostrarEsColeccion: !this.state.mostrarEsColeccion }); } }, { key: "cambiarTitulo", value: function cambiarTitulo() { this.props.cambioDeArreglosDeAtributos(); if (this.state.mostrarInstruccionSQL) { tituloGlobal = "Instrucción SQL"; this.setState({ titulo: "Instrucción SQL" }); } else if (this.state.mostrarEsObjeto) { tituloGlobal = "Variable Compuesta"; this.setState({ titulo: "Variable Compuesta" }); } else { tituloGlobal = "Variable Individual"; this.setState({ titulo: "Variable Individual" }); } this.props.actualizarEstadoSiEsObjeto(this.state.mostrarEsObjeto); this.props.actualizarEstadoSiEsInstruccionSQL(this.state.mostrarInstruccionSQL); } }, { key: "actualizarPeriodicidad", value: function actualizarPeriodicidad() { var periodicidad = $("#periodicidad").val(); valorPeriodicidadGlobal = periodicidad; this.setState({ valorPeriodicidad: periodicidad }, this.cargarDatePicker); this.props.actualizarPeriodicidad(); } }, { key: "cargarDatePicker", value: function cargarDatePicker() { $('#fecha').datepicker({ format: "dd-mm-yyyy", todayHighlight: true, viewMode: "days", minViewMode: "days", language: 'es' }); if (this.props.fechaInicioVariable.toString().length > 0 && this.props.fechaInicioVariable.getFullYear() != 1964 && this.props.fechaInicioVariable.getMonth() != 4 && this.props.fechaInicioVariable.getDate() != 28) $("#fecha").datepicker("setDate", this.props.fechaInicioVariable); var self = this; $('#fecha').datepicker().on('changeDate', function () { var fecha = $("#fecha").datepicker('getDate'); self.props.actualizarFechaInicio(fecha); }); } /* ************************************** ************************************** CALCULO CODIGO ************************************** ************************************** */ }, { key: "traerArchivosExcel", value: function traerArchivosExcel() { var _this4 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from ExcelArchivos", function (err, result) { if (err) { console.log(err); _this4.traerFormas(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { arregloDeExcel = result.recordset; banderaImportacionVariablesExcelINICIO = 0; banderaImportacionVariablesExcelFIN = arregloDeExcel.length; for (var i = 0; i < arregloDeExcel.length; i++) { _this4.traerVariablesExcel(arregloDeExcel[i].ID, i); } ; if (arregloDeExcel.length == 0) { alert("No existen variables excel"); _this4.traerFormas(); } }); } }); }); // fin transaction } }, { key: "traerVariablesExcel", value: function traerVariablesExcel(excelArchivoID, index) { var _this5 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from ExcelVariables where excelArchivoID = " + excelArchivoID, function (err, result) { if (err) { console.log(err); banderaImportacionVariablesExcelINICIO++; _this5.revisarFinImportacionVariablesExcel(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { banderaImportacionVariablesExcelINICIO++; arregloDeExcel[index].variables = result.recordset; _this5.revisarFinImportacionVariablesExcel(); }); } }); }); // fin transaction } }, { key: "revisarFinImportacionVariablesExcel", value: function revisarFinImportacionVariablesExcel() { if (banderaImportacionVariablesExcelINICIO == banderaImportacionVariablesExcelFIN) { this.traerFormas(); } } }, { key: "traerFormas", value: function traerFormas() { var _this6 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from FormasVariables", function (err, result) { if (err) { console.log(err); _this6.traerRiesgos(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { arregloDeFormas = result.recordset; _this6.getNivelMaximoVariables(); }); } }); }); // fin transaction } }, { key: "getNivelMaximoVariables", value: function getNivelMaximoVariables() { var _this7 = this; nivelMaximoVariables = 0; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select MAX(nivel) AS nivel from VariablesCampos", function (err, result) { if (err) { console.log(err); _this7.traerVariables(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { if (result.recordset.length > 0) { nivelMaximoVariables = result.recordset[0].nivel; } arregloDeVariables = []; _this7.traerVariables(); }); } }); }); // fin transaction } }, { key: "traerVariables", value: function traerVariables() { var _this8 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from Variables", function (err, result) { if (err) { console.log(err); _this8.iniciarCalculoExcel(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { arregloDeVariables = result.recordset; banderaImportacionCamposVariablesINICIO = 0; banderaImportacionCamposVariablesFIN = arregloDeVariables.length; for (var i = 0; i < arregloDeVariables.length; i++) { if (arregloDeVariables[i].esInstruccionSQL) { _this8.traerInstruccionSQLCampos(arregloDeVariables[i], i); } else { _this8.traerAtributosVariables(arregloDeVariables[i].ID, i); } } ; if (arregloDeVariables.length == 0) { alert("No existen variables"); _this8.iniciarCalculoExcel(); } }); } }); }); // fin transaction } }, { key: "traerInstruccionSQLCampos", value: function traerInstruccionSQLCampos(variable, index) { var _this9 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from InstruccionSQLCampos where variableID = " + variable.ID, function (err, result) { if (err) { console.log(err); banderaImportacionCamposVariablesINICIO++; _this9.revisarFinImportacionCamposVariables(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { arregloDeVariables[index].atributos = result.recordset; _this9.traerInstruccionSQL(variable, index); }); } }); }); // fin transaction } }, { key: "traerInstruccionSQL", value: function traerInstruccionSQL(variable, index) { var _this10 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from InstruccionSQL where variableID = " + variable.ID, function (err, result) { if (err) { console.log(err); banderaImportacionCamposVariablesINICIO++; _this10.revisarFinImportacionCamposVariables(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { banderaImportacionCamposVariablesINICIO++; arregloDeVariables[index].instruccionSQL = result.recordset[0]; _this10.revisarFinImportacionCamposVariables(); }); } }); }); // fin transaction } }, { key: "traerAtributosVariables", value: function traerAtributosVariables(variableID, index) { var _this11 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from VariablesCampos where variableID = " + variableID, function (err, result) { if (err) { console.log(err); banderaImportacionCamposVariablesINICIO++; _this11.revisarFinImportacionCamposVariables(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { banderaImportacionCamposVariablesINICIO++; arregloDeVariables[index].atributos = result.recordset; _this11.revisarFinImportacionCamposVariables(); }); } }); }); // fin transaction } }, { key: "revisarFinImportacionCamposVariables", value: function revisarFinImportacionCamposVariables() { if (banderaImportacionCamposVariablesINICIO == banderaImportacionCamposVariablesFIN) { this.inicioTraerSegmentosDeCamposVariables(); } } }, { key: "inicioTraerSegmentosDeCamposVariables", value: function inicioTraerSegmentosDeCamposVariables() { console.log('inicioTraerSegmentosDeCamposVariables'); banderaImportacionSegmentosCamposVariablesINICIO = 0; banderaImportacionSegmentosCamposVariablesFIN = 0; for (var i = 0; i < arregloDeVariables.length; i++) { for (var j = 0; j < arregloDeVariables[i].atributos.length; j++) { banderaImportacionSegmentosCamposVariablesFIN++; this.traerSegmentosDeCamposVariables(arregloDeVariables[i].ID, arregloDeVariables[i].atributos[j].ID, i, j); } ; } ; } }, { key: "traerSegmentosDeCamposVariables", value: function traerSegmentosDeCamposVariables(variableID, variableCampoID, i, j) { var _this12 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from SegmentoReglasVariables where variableID = " + variableID + " and variableCampoID = " + variableCampoID, function (err, result) { if (err) { console.log(err); banderaImportacionSegmentosCamposVariablesINICIO++; _this12.revisarFinImportacionSegmentosCamposVariables(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { banderaImportacionSegmentosCamposVariablesINICIO++; arregloDeVariables[i].atributos[j].segmentoReglas = result.recordset; _this12.revisarFinImportacionSegmentosCamposVariables(); }); } }); }); // fin transaction } }, { key: "revisarFinImportacionSegmentosCamposVariables", value: function revisarFinImportacionSegmentosCamposVariables() { if (banderaImportacionSegmentosCamposVariablesINICIO == banderaImportacionSegmentosCamposVariablesFIN) { this.inicioTraerReglasDeSegmentosVariables(); } } }, { key: "inicioTraerReglasDeSegmentosVariables", value: function inicioTraerReglasDeSegmentosVariables() { console.log('inicioTraerReglasDeSegmentosVariables'); banderaImportacionReglasSegmentosCamposVariablesINICIO = 0; banderaImportacionReglasSegmentosCamposVariablesFIN = 0; for (var i = 0; i < arregloDeVariables.length; i++) { for (var j = 0; j < arregloDeVariables[i].atributos.length; j++) { for (var k = 0; k < arregloDeVariables[i].atributos[j].segmentoReglas.length; k++) { banderaImportacionReglasSegmentosCamposVariablesFIN++; this.traerReglasDeSegmentosVariables(arregloDeVariables[i].ID, arregloDeVariables[i].atributos[j].ID, arregloDeVariables[i].atributos[j].segmentoReglas[k].ID, i, j, k); } ; } ; } ; if (banderaImportacionReglasSegmentosCamposVariablesFIN == 0) { this.iniciarCalculoExcel(); } } }, { key: "traerReglasDeSegmentosVariables", value: function traerReglasDeSegmentosVariables(variableID, variableCampoID, segmentoCampoID, i, j, k) { var _this13 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from ReglasVariables where variableID = " + variableID + " and variableCampoID = " + variableCampoID + " and segmentoReglaID = " + segmentoCampoID, function (err, result) { if (err) { console.log(err); banderaImportacionReglasSegmentosCamposVariablesINICIO++; _this13.revisarFinImportacionReglasSegmentosVariables(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { banderaImportacionReglasSegmentosCamposVariablesINICIO++; arregloDeVariables[i].atributos[j].segmentoReglas[k].reglas = result.recordset; _this13.revisarFinImportacionReglasSegmentosVariables(); }); } }); }); // fin transaction } }, { key: "revisarFinImportacionReglasSegmentosVariables", value: function revisarFinImportacionReglasSegmentosVariables() { if (banderaImportacionReglasSegmentosCamposVariablesINICIO == banderaImportacionReglasSegmentosCamposVariablesFIN) { this.inicioTraerFormulasDeCamposVariables(); } } }, { key: "inicioTraerFormulasDeCamposVariables", value: function inicioTraerFormulasDeCamposVariables() { console.log('inicioTraerFormulasDeCamposVariables'); banderaImportacionFormulasCamposVariablesINICIO = 0; banderaImportacionFormulasCamposVariablesFIN = 0; for (var i = 0; i < arregloDeVariables.length; i++) { for (var j = 0; j < arregloDeVariables[i].atributos.length; j++) { banderaImportacionFormulasCamposVariablesFIN++; this.traerFormulasDeCamposVariables(arregloDeVariables[i].atributos[j].ID, i, j); } ; } ; } }, { key: "traerFormulasDeCamposVariables", value: function traerFormulasDeCamposVariables(variableCampoID, i, j) { var _this14 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from FormulasVariablesCampos where variableCampoID = " + variableCampoID, function (err, result) { if (err) { console.log(err); banderaImportacionFormulasCamposVariablesINICIO++; _this14.revisarFinImportacionFormulasCamposVariables(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { banderaImportacionFormulasCamposVariablesINICIO++; arregloDeVariables[i].atributos[j].formulas = result.recordset; _this14.revisarFinImportacionFormulasCamposVariables(); }); } }); }); // fin transaction } }, { key: "revisarFinImportacionFormulasCamposVariables", value: function revisarFinImportacionFormulasCamposVariables() { if (banderaImportacionFormulasCamposVariablesINICIO == banderaImportacionFormulasCamposVariablesFIN) { this.inicioTraerElementosFormulasDeCamposVariables(); } } }, { key: "inicioTraerElementosFormulasDeCamposVariables", value: function inicioTraerElementosFormulasDeCamposVariables() { console.log('inicioTraerElementosFormulasDeCamposVariables'); banderaImportacionElementosFormulasCamposVariablesINICIO = 0; banderaImportacionElementosFormulasCamposVariablesFIN = 0; for (var i = 0; i < arregloDeVariables.length; i++) { for (var j = 0; j < arregloDeVariables[i].atributos.length; j++) { for (var k = 0; k < arregloDeVariables[i].atributos[j].formulas.length; k++) { banderaImportacionElementosFormulasCamposVariablesFIN++; this.traerElementosFormulasDeCamposVariables(arregloDeVariables[i].atributos[j].formulas[k].ID, i, j, k); } ; } ; } ; } }, { key: "traerElementosFormulasDeCamposVariables", value: function traerElementosFormulasDeCamposVariables(idFormula, i, j, k) { var _this15 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from ElementoFormulasVariablesCampos where formulaID = " + idFormula, function (err, result) { if (err) { console.log(err); banderaImportacionElementosFormulasCamposVariablesINICIO++; _this15.revisarFinImportacionElementosFormulasCamposVariables(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { banderaImportacionElementosFormulasCamposVariablesINICIO++; arregloDeVariables[i].atributos[j].formulas[k].fuenteDeDatos = result.recordset; _this15.revisarFinImportacionElementosFormulasCamposVariables(); }); } }); }); // fin transaction } }, { key: "revisarFinImportacionElementosFormulasCamposVariables", value: function revisarFinImportacionElementosFormulasCamposVariables() { if (banderaImportacionElementosFormulasCamposVariablesINICIO == banderaImportacionElementosFormulasCamposVariablesFIN) { this.inicioTraerConeccionesATablas(); } } }, { key: "inicioTraerConeccionesATablas", value: function inicioTraerConeccionesATablas() { console.log('inicioTraerConeccionesATablas'); banderaImportacionConecionesATablasINICIO = 0; banderaImportacionConecionesATablasFIN = 0; arregloConexionesATablas = []; for (var i = 0; i < arregloDeVariables.length; i++) { for (var j = 0; j < arregloDeVariables[i].atributos.length; j++) { for (var k = 0; k < arregloDeVariables[i].atributos[j].segmentoReglas.length; k++) { if (arregloDeVariables[i].atributos[j].segmentoReglas[k].esConexionTabla && this.noHaSidoImportadaConeccion(arregloDeVariables[i].atributos[j].segmentoReglas[k])) { banderaImportacionConecionesATablasFIN++; //para asegurar que ID no sea asyncrono arregloConexionesATablas.push({ ID: arregloDeVariables[i].atributos[j].segmentoReglas[k].conexionTablaID }); //arregloDeVariables[i].atributos[j].formulas[k].fuenteDeDatos[l] this.traerConeccionesATablas(arregloDeVariables[i].atributos[j].segmentoReglas[k].conexionTablaID, arregloConexionesATablas.length - 1); } } ; } ; } ; if (banderaImportacionConecionesATablasFIN == 0) { //this.iniciarCalculoExcel(); this.verificarPeriodicidad(); } } }, { key: "noHaSidoImportadaConeccion", value: function noHaSidoImportadaConeccion(segmento) { for (var i = 0; i < arregloConexionesATablas.length; i++) { if (arregloConexionesATablas[i].ID == segmento.conexionTablaID) { return false; } } ; return true; } }, { key: "traerConeccionesATablas", value: function traerConeccionesATablas(tablaID, indexARemplazar) { var _this16 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from Tablas where ID = " + tablaID, function (err, result) { if (err) { console.log(err); banderaImportacionConecionesATablasINICIO++; _this16.finTraerConeccionesATablas(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { banderaImportacionConecionesATablasINICIO++; if (result.recordset.length > 0) arregloConexionesATablas[indexARemplazar] = result.recordset[0]; _this16.finTraerConeccionesATablas(); }); } }); }); // fin transaction } }, { key: "finTraerConeccionesATablas", value: function finTraerConeccionesATablas() { if (banderaImportacionConecionesATablasINICIO == banderaImportacionConecionesATablasFIN) { this.inicioTraerResultadosDeFuenteDeDatos(); } } }, { key: "inicioTraerResultadosDeFuenteDeDatos", value: function inicioTraerResultadosDeFuenteDeDatos() { console.log('inicioTraerResultadosDeFuenteDeDatos'); banderaImportacionValoresDeTablasDeFuenteDeDatosINICIO = 0; banderaImportacionValoresDeTablasDeFuenteDeDatosFIN = 0; arregloResultadosDeTablas = []; for (var i = 0; i < arregloConexionesATablas.length; i++) { banderaImportacionValoresDeTablasDeFuenteDeDatosFIN++; this.traerResultadosDeFuenteDeDatos(arregloConexionesATablas[i], i); } ; } }, { key: "traerResultadosDeFuenteDeDatos", value: function traerResultadosDeFuenteDeDatos(tabla, index) { var _this17 = this; var pool = new _mssql["default"].ConnectionPool({ user: tabla.usuario, password: tabla.contrasena, server: tabla.servidor, database: tabla.baseDatos, stream: true, connectionTimeout: 900000, requestTimeout: 900000, pool: { max: 40, min: 0, idleTimeoutMillis: 30000 }, options: { useUTC: false } }); pool.connect(function (err) { pool.request().query("select * from " + tabla.tabla, function (err, result) { banderaImportacionValoresDeTablasDeFuenteDeDatosINICIO++; console.log('resultados tabla: ' + tabla.tabla); console.log(result.recordset); if (result.recordset != undefined && result.recordset.length > 0) arregloResultadosDeTablas.splice(index, 0, result.recordset); _this17.finTraerResultadosDeFuenteDeDatos(); }); }); // fin pool connect } }, { key: "finTraerResultadosDeFuenteDeDatos", value: function finTraerResultadosDeFuenteDeDatos() { console.log('verificarPeriodicidad'); if (banderaImportacionValoresDeTablasDeFuenteDeDatosINICIO == banderaImportacionValoresDeTablasDeFuenteDeDatosFIN) { this.verificarPeriodicidad(); //this.iniciarCalculoExcel(); } } }, { key: "verificarPeriodicidad", value: function verificarPeriodicidad() { banderaVerificarPeriodicidadINICIO = 0; banderaVerificarPeriodicidadFIN = 0; for (var i = 0; i < arregloDeExcel.length; i++) { for (var j = 0; j < arregloDeExcel[i].variables.length; j++) { banderaVerificarPeriodicidadFIN++; this.traerPeriodicidadVariable(arregloDeExcel[i].variables[j], "excel", arregloDeExcel, i, j); } ; } ; for (var i = 0; i < arregloDeFormas.length; i++) { banderaVerificarPeriodicidadFIN++; this.traerPeriodicidadVariable(arregloDeFormas[i], "forma", arregloDeFormas, i, null); } ; for (var i = 0; i < arregloDeVariables.length; i++) { banderaVerificarPeriodicidadFIN++; this.traerPeriodicidadVariable(arregloDeVariables[i], "variable", arregloDeVariables, i, null); } ; for (var i = 0; i < arregloDeIndicadores.length; i++) { banderaVerificarPeriodicidadFIN++; this.traerPeriodicidadVariable(arregloDeIndicadores[i], "indicador", arregloDeIndicadores, i, null); } ; } }, { key: "addDays", value: function addDays(fecha, days) { var date = new Date(fecha); date.setDate(date.getDate() + days); return date; } }, { key: "addMonths", value: function addMonths(fecha, months) { var date = new Date(fecha); date.setMonth(date.getMonth() + months); return date; } }, { key: "addYears", value: function addYears(fecha, years) { var date = new Date(fecha); date.setYear(date.getYear() + years); return date; } }, { key: "minusDays", value: function minusDays(fecha, days) { var date = new Date(fecha); if (date.getDate() >= days) { date.setDate(date.getDate() - days); } else { date.setDate(days - date.getDate()); } return date; } }, { key: "minusMonths", value: function minusMonths(fecha, months) { var date = new Date(fecha); if (date.getMonth() >= months) { date.setMonth(date.getMonth() - months); } else { date.setMonth(months - date.getMonth()); } return date; } }, { key: "minusYears", value: function minusYears(fecha, years) { var date = new Date(fecha); if (date.getFullYear() >= years) { date.setYear(date.getFullYear() - years); } else { date.setYear(years - date.getFullYear()); } return date; } }, { key: "traerPeriodicidadVariable", value: function traerPeriodicidadVariable(variable, tabla, arreglo, indexI, indexJ) { var _this18 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from PeriodicidadCalculo where variableID = " + variable.ID + " and tablaVariable = '" + tabla + "'", function (err, result) { if (err) { console.log(err); _this18.verificarFinPeriodicidad(); banderaVerificarPeriodicidadINICIO++; if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { if (result.recordset.length > 0) { var fechaInicioCalculo = variable.fechaInicioCalculo; var fechaUltimoCalculo = result.recordset[0].fechaUltimoCalculo; var tieneUltimoCalculo = false; //si la fecha es null, realizar calculo (28, 4, 1964) POPS BIRTHDAY if (fechaUltimoCalculo.getFullYear() != 1964 && fechaUltimoCalculo.getMonth() != 4 && fechaUltimoCalculo.getDate() != 28) { tieneUltimoCalculo = true; } if (!tieneUltimoCalculo) { if (indexJ != null) arreglo[indexI].variables[indexJ].realizarCalculo = true;else arreglo[indexI].realizarCalculo = true; } else { var ultimoCalculoVigente = false; var periodicidad = variable.periodicidad; var fechaSiguienteCalculo = new Date(fechaInicioCalculo); while (fechaSiguienteCalculo.getFullYear() <= fechaUltimoCalculo.getFullYear() && fechaSiguienteCalculo.getMonth() <= fechaUltimoCalculo.getMonth() && fechaSiguienteCalculo.getDate() <= fechaUltimoCalculo.getDate()) { if (periodicidad.localeCompare("diario") == 0) { fechaSiguienteCalculo = _this18.addDays(fechaSiguienteCalculo, 1); } else if (periodicidad.localeCompare("semanal") == 0) { fechaSiguienteCalculo = _this18.addDays(fechaSiguienteCalculo, 7); } else if (periodicidad.localeCompare("mensual") == 0) { fechaSiguienteCalculo = _this18.addMonths(fechaSiguienteCalculo, 1); } else if (periodicidad.localeCompare("trimestral") == 0) { fechaSiguienteCalculo = _this18.addMonths(fechaSiguienteCalculo, 3); } else if (periodicidad.localeCompare("bi-anual") == 0) { fechaSiguienteCalculo = _this18.addMonths(fechaSiguienteCalculo, 6); } else if (periodicidad.localeCompare("anual") == 0) { fechaSiguienteCalculo = _this18.addYears(fechaSiguienteCalculo, 1); } } var tocaNuevoCalculo = false; if (periodicidad.localeCompare("diario") == 0) { if (fechaSiguienteCalculo.getDate() >= fechaUltimoCalculo.getDate() + 1) { tocaNuevoCalculo = true; } } else if (periodicidad.localeCompare("semanal") == 0) { if (fechaSiguienteCalculo.getDate() >= fechaUltimoCalculo.getDate() + 7) { tocaNuevoCalculo = true; } } else if (periodicidad.localeCompare("mensual") == 0) { if (fechaSiguienteCalculo.getMonth() >= fechaUltimoCalculo.getMonth() + 1) { tocaNuevoCalculo = true; } } else if (periodicidad.localeCompare("trimestral") == 0) { if (fechaSiguienteCalculo.getMonth() >= fechaUltimoCalculo.getMonth() + 3) { tocaNuevoCalculo = true; } } else if (periodicidad.localeCompare("bi-anual") == 0) { if (fechaSiguienteCalculo.getMonth() >= fechaUltimoCalculo.getMonth() + 6) { tocaNuevoCalculo = true; } } else if (periodicidad.localeCompare("anual") == 0) { if (fechaSiguienteCalculo.getFullYear() >= fechaUltimoCalculo.getFullYear() + 1) { tocaNuevoCalculo = true; } } if (tocaNuevoCalculo) { if (indexJ != null) arreglo[indexI].variables[indexJ].realizarCalculo = true;else arreglo[indexI].realizarCalculo = true; } else { if (indexJ != null) arreglo[indexI].variables[indexJ].realizarCalculo = false;else arreglo[indexI].realizarCalculo = false; } } } else { if (indexJ != null) arreglo[indexI].variables[indexJ].realizarCalculo = true;else arreglo[indexI].realizarCalculo = true; } banderaVerificarPeriodicidadINICIO++; _this18.verificarFinPeriodicidad(); }); } }); }); // fin transaction } }, { key: "verificarFinPeriodicidad", value: function verificarFinPeriodicidad() { console.log('verificarFinPeriodicidad'); if (banderaVerificarPeriodicidadINICIO == banderaVerificarPeriodicidadFIN) { this.iniciarImportacionValoresCalculados(); } } }, { key: "iniciarImportacionValoresCalculados", value: function iniciarImportacionValoresCalculados() { console.log('iniciarImportacionValoresCalculados'); banderaImportarValoresPeriodicidadINICIO = 0; banderaImportarValoresPeriodicidadFIN = 0; for (var i = 0; i < arregloDeExcel.length; i++) { for (var j = 0; j < arregloDeExcel[i].variables.length; j++) { if (!arregloDeExcel[i].variables[j].realizarCalculo) { banderaImportarValoresPeriodicidadFIN++; this.getResultsVariables(arregloDeExcel[i].variables[j], "excel", arregloDeExcel, i, j); } } ; } ; for (var i = 0; i < arregloDeFormas.length; i++) { if (!arregloDeFormas[i].realizarCalculo) { banderaImportarValoresPeriodicidadFIN++; this.getResultsVariables(arregloDeFormas[i], "forma", arregloDeFormas, i); } } ; for (var i = 0; i < arregloDeVariables.length; i++) { if (!arregloDeVariables[i].realizarCalculo) { banderaImportarValoresPeriodicidadFIN++; this.getResultsVariables(arregloDeVariables[i], "variable", arregloDeVariables, i); } } ; for (var i = 0; i < arregloDeIndicadores.length; i++) { if (!arregloDeIndicadores[i].realizarCalculo) { banderaImportarValoresPeriodicidadFIN++; this.getResultsIndicators(arregloDeIndicadores[i], i); } } ; if (banderaImportarValoresPeriodicidadFIN == 0) { this.verificarFinImportacionValoresCalculados(); } } }, { key: "getResultsVariables", value: function getResultsVariables(variable, tabla) { var _this19 = this; //OBTENER LA LISTA DE POSIBLES VARIABLES A VISUALIZAR var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from ResultadosNombreVariables where nombreVariable = '" + variable.nombre + "' and finVigencia = '1964-05-28'", function (err, result) { if (err) { console.log(err); banderaImportarValoresPeriodicidadINICIO++; _this19.verificarFinImportacionValoresCalculados(); if (!rolledBack) { transaction.rollback(function (err) {}); return []; } } else { transaction.commit(function (err) { if (result.recordset.length == 0) banderaImportarValoresPeriodicidadINICIO++; _this19.getResultsVariablesFieldsInit(result.recordset, variable, tabla); }); } }); }); // fin transaction } }, { key: "getResultsVariablesFieldsInit", value: function getResultsVariablesFieldsInit(resultados, variable, tabla) { var arregloTemp = []; for (var i = 0; i < resultados.length; i++) { arregloTemp.push(resultados[i]); this.getFieldResults(resultados[i], variable, tabla); } ; if (resultados.length == 0) { this.verificarFinImportacionValoresCalculados(); } } }, { key: "getFieldResults", value: function getFieldResults(resultado, variable, tabla) { var _this20 = this; var textoSelect = ''; var textoGroupBy = ' group by ID'; if (tabla.localeCompare("excel") == 0) { textoSelect += ' ID, ' + variable.nombre; textoGroupBy += ', ' + variable.nombre; } else if (tabla.localeCompare("variable") == 0) { for (var i = 0; i < variable.atributos.length; i++) { if (i > 0) textoSelect += ', ';else textoSelect += ' ID, '; textoSelect += variable.atributos[i].nombre; textoGroupBy += ', ' + variable.atributos[i].nombre; } ; } else { textoSelect += ' ID, ' + variable.nombre; textoGroupBy += ', ' + variable.nombre; } if (textoSelect.length > 0) textoSelect += ', '; textoSelect += ' max(f3ch4Gu4rd4do) as f3ch4Gu4rd4do'; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select " + textoSelect + " from " + resultado.nombreVariable + '_' + resultado.inicioVigencia.getFullYear() + '_' + (resultado.inicioVigencia.getMonth() + 1) + '_' + resultado.inicioVigencia.getDate() + '_' + resultado.inicioVigencia.getHours() + '_' + resultado.inicioVigencia.getMinutes() + '_' + resultado.inicioVigencia.getSeconds() + textoGroupBy, function (err, result) { if (err) { banderaImportarValoresPeriodicidadINICIO++; _this20.verificarFinImportacionValoresCalculados(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { if (result.recordset.length > 0) { if (tabla.localeCompare("excel") == 0 || tabla.localeCompare("forma") == 0) { window[variable.nombre] = result.recordset[result.recordset.length - 1][variable.nombre]; } else if (tabla.localeCompare("variable") == 0) { if (variable.esInstruccionSQL || variable.esColeccion) { window[variable.nombre] = result.recordset[result.recordset.length - 1]; } else { window[variable.nombre] = result.recordset[result.recordset.length - 1][variable.nombre]; } } } else { if (tabla.localeCompare("excel") == 0) { arregloDeErroresExcel.push({ nombre: variable.nombre }); } else if (tabla.localeCompare("forma") == 0) {//arregloDeErroresExcel.push({nombre: variable.nombre }); } else if (tabla.localeCompare("variable") == 0) {//arregloDeErroresExcel.push({nombre: variable.nombre }); } } banderaImportarValoresPeriodicidadINICIO++; _this20.verificarFinImportacionValoresCalculados(); }); } }); }); // fin transaction } }, { key: "getResultsIndicators", value: function getResultsIndicators(indicador, index) { var _this21 = this; //OBTENER LA LISTA DE POSIBLES VARIABLES A VISUALIZAR var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from ResultadosNombreIndicadores where nombreIndicador = '" + indicador.nombre + "' and finVigencia = '1964-05-28'", function (err, result) { if (err) { console.log(err); banderaImportarValoresPeriodicidadINICIO++; _this21.verificarFinImportacionValoresCalculados(); if (!rolledBack) { transaction.rollback(function (err) {}); return []; } } else { transaction.commit(function (err) { if (result.recordset.length == 0) banderaImportarValoresPeriodicidadINICIO++; _this21.getResultsIndicatorsFieldsInit(result.recordset, indicador, index); }); } }); }); // fin transaction } }, { key: "getResultsIndicatorsFieldsInit", value: function getResultsIndicatorsFieldsInit(resultados, indicador, index) { console.log('getResultsIndicatorsFieldsInit'); var arregloTemp = []; for (var i = 0; i < resultados.length; i++) { arregloTemp.push(resultados[i]); this.getFieldIndicatorsResults(resultados[i], indicador, index); } ; if (resultados.length == 0) { this.verificarFinImportacionValoresCalculados(); } } }, { key: "getFieldIndicatorsResults", value: function getFieldIndicatorsResults(resultado, indicador, index) { var _this22 = this; var textoSelect = ''; var textoGroupBy = ' group by ID'; for (var i = 0; i < indicador.atributos.length; i++) { if (i > 0) textoSelect += ', '; textoSelect += indicador.atributos[i]; textoGroupBy += ', ' + indicador.atributos[i]; } ; if (textoSelect.length > 0) textoSelect += ', '; textoSelect += ' max(f3ch4Gu4rd4do) as f3ch4Gu4rd4do'; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select " + textoSelect + " from " + resultado.nombreVariable + '_' + resultado.inicioVigencia.getFullYear() + '_' + (resultado.inicioVigencia.getMonth() + 1) + '_' + resultado.inicioVigencia.getDate() + '_' + resultado.inicioVigencia.getHours() + '_' + resultado.inicioVigencia.getMinutes() + '_' + resultado.inicioVigencia.getSeconds() + textoGroupBy, function (err, result) { if (err) { console.log(err); banderaImportarValoresPeriodicidadINICIO++; _this22.verificarFinImportacionValoresCalculados(); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { if (result.recordset.length > 0) { //window[indicador.nombre] = result.recordset[0]; arregloDeIndicadores[index] = result.recordset[0]; } else {// } banderaImportarValoresPeriodicidadINICIO++; _this22.verificarFinImportacionValoresCalculados(); }); } }); }); // fin transaction } }, { key: "verificarFinImportacionValoresCalculados", value: function verificarFinImportacionValoresCalculados() { console.log('verificarFinImportacionValoresCalculados'); if (banderaImportarValoresPeriodicidadINICIO == banderaImportarValoresPeriodicidadFIN) { this.iniciarCalculoExcel(); } } }, { key: "iniciarCalculoExcel", value: function iniciarCalculoExcel() { if (arregloDeExcel.length > 0) { this.crearVariablesExcel(); } this.iniciarCalculoFormas(); } }, { key: "iniciarCalculoFormas", value: function iniciarCalculoFormas() { if (arregloDeFormas.length > 0) { this.iniciarMostrarFormas(); } if (arregloDeFormas.length == 0) { this.iniciarHilo(); } } }, { key: "iniciarHilo", value: function iniciarHilo() { /*console.log('nivelMaximoVariables'); console.log(nivelMaximoVariables); console.log('arregloDeFuentesDeDatos'); console.log(arregloDeFuentesDeDatos); console.log('arregloDeVariables'); console.log(arregloDeVariables); console.log('arregloResultadosDeTablas'); console.log(arregloResultadosDeTablas); console.log('arregloConexionesATablas'); console.log(arregloConexionesATablas);*/ //DESCRIPCION DEL PROCEDIMIENTO //1) PRIMERO CREAR CODIGO PARA CREAR VARIABLES DE ELEMENTOS DE FORMULAS, AGRUPADAS POR TABLAS CORRESPONDIENTES -- SERA PRIMER METODO A LLAMAR //2) CREAR METODO NIVEL XX, CONTENDRA LLAMADO A METODO 'CALCULO VARIABLES NIVEL XX', Y JUSTO DESPUES LLAMARÁ AL SIGUIENTE NIVEL QUE SIGUE, O AL METODO DE MENSAJE FINAL //3) CREAR CODIGO 'CALCULO VARIABLES NIVEL XX' //AGRUPANDO ELEMENTOS DE FORMULA POR CONEXION A TABLA var arregloAgrupacionElementosFormulaPorConexionATablaVariables = []; //arreglo que contiene los segmento de reglas agrupados por el arreglo de tablas //la variable es insertado una unica vez cada por cada segmento de regla que pertenezca a la tabla var arregloAgrupacionElementosFormulaPorVariablesVariables = []; //arreglo que contiene los segmento de reglas de la variable a calcular agrupados por la posicion de la variable a comparar en el arregloDeVariables //la variable es insertado una unica vez cada por cada segmento de regla que pertenezca a la tabla var arregloAgrupacionElementosFormulaPorExcelVariables = []; //arreglo que contiene los segmento de reglas de la variable excel a calcular agrupados por la posicion de la variable a comparar en el arregloDeVariables //la variable es insertado una unica vez cada por cada segmento de regla que pertenezca a la tabla var arregloAgrupacionElementosFormulaPorFormasVariables = []; //arreglo que contiene los segmento de reglas de la variable forma a calcular agrupados por la posicion de la variable a comparar en el arregloDeVariables //la variable es insertado una unica vez cada por cada segmento de regla que pertenezca a la tabla var arregloAgrupacionElementosFormulaPorManualVariables = []; for (var i = 0; i < arregloDeVariables.length; i++) { for (var j = 0; j < arregloDeVariables[i].atributos.length; j++) { for (var k = 0; k < arregloDeVariables[i].atributos[j].segmentoReglas.length; k++) { if (arregloDeVariables[i].atributos[j].segmentoReglas[k].esConexionTabla) { for (var m = 0; m < arregloConexionesATablas.length; m++) { if (arregloDeVariables[i].atributos[j].segmentoReglas[k].conexionTablaID == arregloConexionesATablas[m].ID) { if (arregloAgrupacionElementosFormulaPorConexionATablaVariables[m] == undefined) arregloAgrupacionElementosFormulaPorConexionATablaVariables[m] = []; arregloAgrupacionElementosFormulaPorConexionATablaVariables[m].push({ segmentoRegla: arregloDeVariables[i].atributos[j].segmentoReglas[k], variable: arregloDeVariables[i], atributo: arregloDeVariables[i].atributos[j], index: k }); break; } } ; } else if (arregloDeVariables[i].atributos[j].segmentoReglas[k].excelArchivoID != -1 && arregloDeVariables[i].atributos[j].segmentoReglas[k].formaVariableID == -1 && arregloDeVariables[i].atributos[j].segmentoReglas[k].variableIDCreacionCodigo == -1) { for (var x = 0; x < arregloDeExcel.length; x++) { if (arregloDeVariables[i].atributos[j].segmentoReglas[k].excelArchivoID == arregloDeExcel[x].ID) { if (arregloAgrupacionElementosFormulaPorExcelVariables[x] == undefined) arregloAgrupacionElementosFormulaPorExcelVariables[x] = []; for (var y = 0; y < arregloDeExcel[x].variables.length; y++) { if (arregloDeVariables[i].atributos[j].segmentoReglas[k].excelVariableID == arregloDeExcel[x].variables[y].ID) { if (arregloAgrupacionElementosFormulaPorExcelVariables[x][y] == undefined) arregloAgrupacionElementosFormulaPorExcelVariables[x][y] = []; arregloAgrupacionElementosFormulaPorExcelVariables[x][y].push({ segmentoRegla: arregloDeVariables[i].atributos[j].segmentoReglas[k], variable: arregloDeVariables[i], variableCreacionCodigo: arregloDeExcel[x].variables[y], atributo: arregloDeVariables[i].atributos[j], index: k }); break; } } ; } } ; } else if (arregloDeVariables[i].atributos[j].segmentoReglas[k].formaVariableID != -1 && arregloDeVariables[i].atributos[j].segmentoReglas[k].excelArchivoID == -1 && arregloDeVariables[i].atributos[j].segmentoReglas[k].variableIDCreacionCodigo == -1) { for (var x = 0; x < arregloDeFormas.length; x++) { if (arregloDeVariables[i].atributos[j].segmentoReglas[k].formaVariableID == arregloDeFormas[x].ID) { if (arregloAgrupacionElementosFormulaPorFormasVariables[x] == undefined) arregloAgrupacionElementosFormulaPorFormasVariables[x] = []; arregloAgrupacionElementosFormulaPorFormasVariables[x].push({ segmentoRegla: arregloDeVariables[i].atributos[j].segmentoReglas[k], variable: arregloDeVariables[i], variableCreacionCodigo: arregloDeFormas[x], atributo: arregloDeVariables[i].atributos[j], index: k }); break; } } ; } else if (arregloDeVariables[i].atributos[j].segmentoReglas[k].esValorManual && arregloDeVariables[i].atributos[j].segmentoReglas[k].formaVariableID == -1 && arregloDeVariables[i].atributos[j].segmentoReglas[k].excelArchivoID == -1 && arregloDeVariables[i].atributos[j].segmentoReglas[k].variableIDCreacionCodigo == -1) { if (arregloAgrupacionElementosFormulaPorManualVariables[i] == undefined) arregloAgrupacionElementosFormulaPorManualVariables[i] = []; arregloAgrupacionElementosFormulaPorManualVariables[i].push({ segmentoRegla: arregloDeVariables[i].atributos[j].segmentoReglas[k], variable: arregloDeVariables[i], variableCreacionCodigo: arregloDeVariables[i], atributo: arregloDeVariables[i].atributos[j], index: k }); } else { for (var x = 0; x < arregloDeVariables.length; x++) { if (arregloDeVariables[i].atributos[j].segmentoReglas[k].variableIDCreacionCodigo == arregloDeVariables[x].ID) { if (arregloAgrupacionElementosFormulaPorVariablesVariables[x] == undefined) arregloAgrupacionElementosFormulaPorVariablesVariables[x] = []; arregloAgrupacionElementosFormulaPorVariablesVariables[x].push({ segmentoRegla: arregloDeVariables[i].atributos[j].segmentoReglas[k], variable: arregloDeVariables[i], variableCreacionCodigo: arregloDeVariables[x], atributo: arregloDeVariables[i].atributos[j], index: k }); break; } } ; } } ; } ; } ; /*console.log('arregloAgrupacionElementosFormulaPorConexionATablaVariables'); console.log(arregloAgrupacionElementosFormulaPorConexionATablaVariables); console.log('arregloAgrupacionElementosFormulaPorVariablesVariables'); console.log(arregloAgrupacionElementosFormulaPorVariablesVariables); console.log('arregloAgrupacionElementosFormulaPorExcelVariables'); console.log(arregloAgrupacionElementosFormulaPorExcelVariables); console.log('arregloAgrupacionElementosFormulaPorFormasVariables'); console.log(arregloAgrupacionElementosFormulaPorFormasVariables);*/ var existeVarSQL = false; //INICIALIZANDO VARIABLES EN MEMORIA for (var a = 0; a < arregloDeVariables.length; a++) { if (arregloDeVariables[a].realizarCalculo) { if (arregloDeVariables[a].esObjeto || arregloDeVariables[a].esInstruccionSQL) { //CREANDO ESPACIO EN MEMORIA DE ARREGLO DE VARIABLES window[arregloDeVariables[a].nombre] = []; } else { //CREANDO ESPACIO EN MEMORIA DE VARIABLE SI ES VAR PRIMITVA window[arregloDeVariables[a].nombre] = {}; } if (arregloDeVariables[a].esInstruccionSQL) { existeVarSQL = true; } } } //codigo var sql this.crearCodigoFuenteDatoSQL(); var codigo = ''; /*//AGREGAR CODIGO VARIABLES EXCEL codigo += this.crearNivel(false, arregloAgrupacionElementosFormulaPorExcelVariables, 0); //AGREGAR CODIGO VARIABLES FORMA codigo += this.crearNivel(false, arregloAgrupacionElementosFormulaPorFormasVariables, 0);*/ //codigo var general for (var i = 0; i <= nivelMaximoVariables; i++) { if (i == 0) { var llamarSiguienteNivel = false; if (nivelMaximoVariables >= 1) llamarSiguienteNivel = true; codigo += this.crearCodigoFuenteDato(llamarSiguienteNivel, arregloAgrupacionElementosFormulaPorConexionATablaVariables, 0); codigo += this.crearNivel(llamarSiguienteNivel, arregloAgrupacionElementosFormulaPorExcelVariables, 0); codigo += this.crearNivel(llamarSiguienteNivel, arregloAgrupacionElementosFormulaPorFormasVariables, 0); codigo += this.crearNivel(llamarSiguienteNivel, arregloAgrupacionElementosFormulaPorManualVariables, 0); } else { var llamarSiguienteNivel = false; if (nivelMaximoVariables > i) llamarSiguienteNivel = true; codigo += this.crearNivel(llamarSiguienteNivel, arregloAgrupacionElementosFormulaPorVariablesVariables, i); codigo += this.crearNivel(llamarSiguienteNivel, arregloAgrupacionElementosFormulaPorExcelVariables, i); codigo += this.crearNivel(llamarSiguienteNivel, arregloAgrupacionElementosFormulaPorFormasVariables, i); } } ; codigo += '\n\tiniciarCalculoIndicadores();'; window['calculoPrincipal'] = new Function('return function calculoPrincipalMain(evaluate, iniciarCalculoIndicadores, isValidDate, guardarOperacionSQL){' + codigo + '}')(); console.log(window['calculoPrincipal']); if (!existeVarSQL) { window['calculoPrincipal'](_mathjs.evaluate, this.iniciarCalculoIndicadores, this.isValidDate, this.guardarOperacionSQL); } else { for (var a = 0; a < arregloDeVariables.length; a++) { if (arregloDeVariables[a].esInstruccionSQL) { window["calculoSQL" + arregloDeVariables[a].nombre](_mssql["default"], this.props.pool, _mathjs.evaluate, this.iniciarCalculoIndicadores, this.isValidDate, this.guardarOperacionSQL); break; } } ; } /*console.log(window['calculoPrincipal']); for (var a = 0; a < arregloDeVariables.length; a++) { console.log('window["'+arregloDeVariables[a].nombre+'"]'); console.log(window[arregloDeVariables[a].nombre]); };*/ setTimeout(function () { for (var a = 0; a < arregloDeVariables.length; a++) { console.log('window["' + arregloDeVariables[a].nombre + '"]'); console.log(window[arregloDeVariables[a].nombre]); } ; }, 3000); setTimeout(function () { console.log('==========='); for (var a = 0; a < arregloDeFormas.length; a++) { console.log('window["' + arregloDeFormas[a].nombre + '"]'); console.log(window[arregloDeFormas[a].nombre]); } ; }, 3000); setTimeout(function () { console.log('==========='); for (var i = 0; i < arregloDeExcel.length; i++) { for (var j = 0; j < arregloDeExcel[i].variables.length; j++) { console.log('window["' + arregloDeExcel[i].variables[j].nombre + '"]'); console.log(window[arregloDeExcel[i].variables[j].nombre]); } ; } ; }, 3000); } }, { key: "codigoIniciacion", value: function codigoIniciacion(variable, tipoVariable, atributo, tabsText, esOperacionSQL, esPromedio) { if (tipoVariable.localeCompare("fuenteDato") == 0) { //atributo en este caso, es el valor del index del elemento en formula return this.iniciacionElementosFormula(variable, atributo, tabsText); } else if (tipoVariable.localeCompare("variable") == 0) { return this.iniciacionVariable(variable, tabsText); } else if (tipoVariable.localeCompare("atributo") == 0) { return this.iniciacionCampo(variable, atributo, tabsText, esOperacionSQL, esPromedio); } } }, { key: "iniciacionElementosFormula", value: function iniciacionElementosFormula(variable, index) { var iniciacionElementosFormula = ''; if (variable.tipoColumnaEnTabla.toLowerCase().localeCompare("date") == 0 && (variable.operacion.localeCompare("MAX") == 0 || variable.operacion.localeCompare("MIN") == 0)) { //CUANDO ES FECHA Y OPERACION ES MAX O MIN DE FUENTE DE DATOS, SE OBTIENE LA FECHA MAXIMA O MENOR ENCONTRADA //FORMULA NOMBRE FUENTE DE DATO (ELEMENTO DE FORMULA): //[nombreColumnaEnTabla]+[variableID]+[variableCampoID]+[idFormula]+[idConexionTabla]+[i] iniciacionElementosFormula += tabsText + 'var ' + variable.nombreColumnaEnTabla + variable.variableID + variable.variableCampoID + variable.idFormula + variable.idConexionTabla + index; iniciacionElementosFormula += ' = new Date(1964, 5, 28);'; //POPS BIRTHDAY -- FECHA NULA } else if (variable.tipoColumnaEnTabla.toLowerCase().localeCompare("date") == 0 && variable.operacion.length > 0) { //CUANDO ES FECHA Y OPERACION NO ES MAX O MIN DE FUENTE DE DATOS, SE OBTIENE UN NUMERO QUE VARIA POR OPERACION (DIA, MES, AÑO, COUNT) //FORMULA NOMBRE FUENTE DE DATO (ELEMENTO DE FORMULA): //[nombreColumnaEnTabla]+[variableID]+[variableCampoID]+[idFormula]+[idConexionTabla]+[i] iniciacionElementosFormula += tabsText + 'var ' + variable.nombreColumnaEnTabla + variable.variableID + variable.variableCampoID + variable.idFormula + variable.idConexionTabla + index; iniciacionElementosFormula += ' = 0;'; } if (variable.tipoColumnaEnTabla.toLowerCase().localeCompare("bool") == 0 && variable.operacion.localeCompare("COUNT") == 0) { //CUANDO ES BOOL Y OPERACION ES COUNT DE FUENTE DE DATOS //FORMULA NOMBRE FUENTE DE DATO (ELEMENTO DE FORMULA): //[nombreColumnaEnTabla]+[variableID]+[variableCampoID]+[idFormula]+[idConexionTabla]+[i] iniciacionElementosFormula += tabsText + 'var ' + variable.nombreColumnaEnTabla + variable.variableID + variable.variableCampoID + variable.idFormula + variable.idConexionTabla + index; iniciacionElementosFormula += ' = 0;'; } if (variable.tipoColumnaEnTabla.toLowerCase().localeCompare("numero") == 0 && this.existeOperacion(variable.operacion)) { //FORMULA NOMBRE FUENTE DE DATO (ELEMENTO DE FORMULA): //[nombreColumnaEnTabla]+[variableID]+[variableCampoID]+[idFormula]+[idConexionTabla]+[i] iniciacionElementosFormula += tabsText + 'var ' + variable.nombreColumnaEnTabla + variable.variableID + variable.variableCampoID + variable.idFormula + variable.idConexionTabla + index; iniciacionElementosFormula += ' = 0;'; } if (variable.tipoColumnaEnTabla.toLowerCase().localeCompare("cadena") == 0 && variable.operacion.localeCompare("COUNT") == 0) { //CUANDO ES BOOL Y OPERACION ES COUNT DE FUENTE DE DATOS //FORMULA NOMBRE FUENTE DE DATO (ELEMENTO DE FORMULA): //[nombreColumnaEnTabla]+[variableID]+[variableCampoID]+[idFormula]+[idConexionTabla]+[i] iniciacionElementosFormula += tabsText + 'var ' + variable.nombreColumnaEnTabla + variable.variableID + variable.variableCampoID + variable.idFormula + variable.idConexionTabla + index; iniciacionElementosFormula += ' = 0;'; } return iniciacionElementosFormula; } }, { key: "iniciacionVariable", value: function iniciacionVariable(variable, tabsText) { var iniciacionVariable = ''; if (variable.esObjeto || variable.esInstruccionSQL) { iniciacionVariable += tabsText + 'var ' + variable.nombre + 'NU3V0 = {};'; iniciacionVariable += '\n' + tabsText + 'var ' + variable.nombre + 'GU4RD4RV4L0R = false;'; } //validacion necesario porque cuando variable sea primitiva, codigo de instanciacion sera en campo / atributo return iniciacionVariable; } }, { key: "iniciacionCampo", value: function iniciacionCampo(variable, campo, tabsText, esOperacionSQL, esPromedio) { var iniciacionVariable = ''; if (!variable.esObjeto && !variable.esInstruccionSQL) { if (campo.tipo.toLowerCase().localeCompare("date") == 0) { iniciacionVariable += tabsText + 'var ' + variable.nombre + 'NU3V0 = new Date(1964, 4, 28);'; //POPS BIRTHDAY == null iniciacionVariable += '\n' + tabsText + 'var ' + variable.nombre + 'GU4RD4RV4L0R = false;'; } if (campo.tipo.toLowerCase().localeCompare("bool") == 0 || campo.tipo.toLowerCase().localeCompare("bit") == 0) { iniciacionVariable += tabsText + 'var ' + variable.nombre + 'NU3V0 = false;'; iniciacionVariable += '\n' + tabsText + 'var ' + variable.nombre + 'GU4RD4RV4L0R = false;'; } if (campo.tipo.toLowerCase().localeCompare("numero") == 0 || campo.tipo.toLowerCase().localeCompare("int") == 0 || campo.tipo.toLowerCase().localeCompare("decimal") == 0) { iniciacionVariable += tabsText + 'var ' + variable.nombre + 'NU3V0 = -1;'; iniciacionVariable += '\n' + tabsText + 'var ' + variable.nombre + 'GU4RD4RV4L0R = false;'; } if (campo.tipo.toLowerCase().localeCompare("cadena") == 0 || campo.tipo.toLowerCase().localeCompare("varchar") == 0) { iniciacionVariable += tabsText + 'var ' + variable.nombre + 'NU3V0 = "";'; iniciacionVariable += '\n' + tabsText + 'var ' + variable.nombre + 'GU4RD4RV4L0R = false;'; } if (esPromedio) { iniciacionVariable += '\n' + tabsText + "var " + variable.nombre + 'NU3V0T0T4L = 0;'; } } else if ((variable.esObjeto || variable.esInstruccionSQL) && esOperacionSQL) { if (campo.tipo.toLowerCase().localeCompare("date") == 0) { iniciacionVariable += tabsText + "var " + variable.nombre + campo.nombre + 'NU3V0 = new Date(1964, 4, 28);'; //POPS BIRTHDAY == null } if (campo.tipo.toLowerCase().localeCompare("bool") == 0 || campo.tipo.toLowerCase().localeCompare("bit") == 0) { iniciacionVariable += tabsText + "var " + variable.nombre + campo.nombre + 'NU3V0 = false;'; } if (campo.tipo.toLowerCase().localeCompare("numero") == 0 || campo.tipo.toLowerCase().localeCompare("int") == 0 || campo.tipo.toLowerCase().localeCompare("decimal") == 0) { iniciacionVariable += tabsText + "var " + variable.nombre + campo.nombre + 'NU3V0 = -1;'; } if (campo.tipo.toLowerCase().localeCompare("cadena") == 0 || campo.tipo.toLowerCase().localeCompare("varchar") == 0) { iniciacionVariable += tabsText + "var " + variable.nombre + campo.nombre + 'NU3V0 = "";'; } if (esPromedio) { iniciacionVariable += '\n' + tabsText + "var " + variable.nombre + campo.nombre + 'NU3V0T0T4L = 0;'; } } else { if (campo.tipo.toLowerCase().localeCompare("date") == 0) { iniciacionVariable += tabsText + variable.nombre + 'NU3V0.' + campo.nombre + ' = new Date(1964, 4, 28);'; //POPS BIRTHDAY == null } if (campo.tipo.toLowerCase().localeCompare("bool") == 0 || campo.tipo.toLowerCase().localeCompare("bit") == 0) { iniciacionVariable += tabsText + variable.nombre + 'NU3V0.' + campo.nombre + ' = false;'; } if (campo.tipo.toLowerCase().localeCompare("numero") == 0 || campo.tipo.toLowerCase().localeCompare("int") == 0 || campo.tipo.toLowerCase().localeCompare("decimal") == 0) { iniciacionVariable += tabsText + variable.nombre + 'NU3V0.' + campo.nombre + ' = -1;'; } if (campo.tipo.toLowerCase().localeCompare("cadena") == 0 || campo.tipo.toLowerCase().localeCompare("varchar") == 0) { iniciacionVariable += tabsText + variable.nombre + 'NU3V0.' + campo.nombre + ' = "";'; } } return iniciacionVariable; } }, { key: "crearCodigoFuenteDato", value: function crearCodigoFuenteDato(llamarSiguienteNivel, arregloAgrupacionElementosFormulaPorConexionATabla, nivelACrear) { //la creacion del codigo en esta parte pertenece a los campos que tienen asignacion unica de columna de tabla, y asignacion unica de columna de tabla con operacion como SUM, COUNT ect var codigo = ''; for (var i = 0; i < arregloConexionesATablas.length; i++) { var variablesInstanciadasID = [], variablesGuardadasID = []; if (!arregloConexionesATablas[i].esInstruccionSQL && arregloAgrupacionElementosFormulaPorConexionATabla[i] != undefined) { var codigoCuerpo = ''; var codigoIniciacionVarPrimitiva = ''; var codigoGuardarVariables = ''; var codigoGuardarVariableOperacionSQL = ''; for (var j = 0; j < arregloAgrupacionElementosFormulaPorConexionATabla[i].length; j++) { if (arregloConexionesATablas[i].ID == arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.conexionTablaID && arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.realizarCalculo) { if (j == 0) { //solo crear codigo for una vez por variable codigoCuerpo += '\n\t//CODIGO TABLA: ' + arregloConexionesATablas[i].nombre; codigoCuerpo += '\n\tfor ( var i = ' + i + '; i < ' + (i + 1) + '; i++) {'; codigoCuerpo += '\n\t\tfor ( var x = 0; x < arregloResultadosDeTablas[i].length; x++) {'; } var varFueInicializada = false; for (var w = 0; w < variablesInstanciadasID.length; w++) { if (variablesInstanciadasID[w] == arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.ID) { varFueInicializada = true; break; } } ; /*if(!varFueInicializada) { variablesInstanciadasID.push(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.ID);*/ if (arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.esObjeto) { if (!varFueInicializada) { variablesInstanciadasID.push(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.ID); codigoCuerpo += '\n\t\t\t//INICIACION VARIABLE: ' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre; codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable, "variable", {}, '\t\t\t'); //variable, tipoVariable, atributo } //for (var p = 0; p < arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.atributos.length; p++) { var contieneOperacionSQL = false, esPromedio = false; //viendo si la ultima regla del segmento (la de asignacion) es una operacion de SQL (AUTOSUMAR, PROMEDIO, MAX, MIN) if (this.existeOperacion(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas.length - 1].operacion)) contieneOperacionSQL = true; if (arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) esPromedio = true; if (!contieneOperacionSQL) codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo, '\t\t\t', false, esPromedio);else { codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo, '\t\t\t', false, false); codigoIniciacionVarPrimitiva += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo, '\t', true, esPromedio); } //}; } else { codigoIniciacionVarPrimitiva += '\n\t//INICIACION VARIABLE: ' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre; for (var p = 0; p < arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.atributos.length; p++) { var esPromedio = false; if (arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) esPromedio = true; codigoIniciacionVarPrimitiva += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.atributos[p], '\t', false, esPromedio); } ; } //} if (arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo.nivel == nivelACrear) { var posicionVariable = 0, posicionCampo = 0; EncontrarPosiciones: for (var a = 0; a < arregloDeVariables.length; a++) { if (arregloDeVariables[a].ID == arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.ID) { posicionVariable = a; for (var b = 0; b < arregloDeVariables[a].atributos.length; b++) { if (arregloDeVariables[a].atributos[b].ID == arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo.ID) { posicionCampo = b; break EncontrarPosiciones; } } ; } } ; var esArregloReferenciaArregloEnCodigo = arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.esObjeto; codigoCuerpo += this.crearCodigoSegmentoReglas(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla, arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas, 3, posicionVariable, posicionCampo, "arregloResultadosDeTablas[i]", true); } var varFueGuardada = false; for (var w = 0; w < variablesGuardadasID.length; w++) { if (variablesGuardadasID[w] == arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.ID) { varFueGuardada = true; break; } } ; if (!varFueGuardada) { variablesGuardadasID.push(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.ID); codigoGuardarVariables += this.agregarCodigoGuardarVariable(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable, arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributos, 3); } //for (var p = 0; p < arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.atributos.length; p++) { if (arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.esObjeto || arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.esInstruccionSQL) { var contieneOperacionSQL = false; //viendo si la ultima regla del segmento (la de asignacion) es una operacion de SQL (AUTOSUMAR, PROMEDIO, MAX, MIN) if (this.existeOperacion(arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas.length - 1].operacion)) contieneOperacionSQL = true; if (contieneOperacionSQL && arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") != 0) codigoGuardarVariableOperacionSQL += '\n\tguardarOperacionSQL(window["' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + '"], "' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo.nombre + '", ' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo.nombre + 'NU3V0);';else if (contieneOperacionSQL && arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) { codigoGuardarVariableOperacionSQL += '\n\tif(' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo.nombre + 'NU3V0T0T4L != 0 || ' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo.nombre + 'NU3V0T0T4L != -1) {'; codigoGuardarVariableOperacionSQL += '\n\t\tvar total = ' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo.nombre + 'NU3V0/' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo.nombre + 'NU3V0T0T4L;'; codigoGuardarVariableOperacionSQL += '\n\t\tguardarOperacionSQL(window["' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + '"], "' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].atributo.nombre + '", total);'; codigoGuardarVariableOperacionSQL += '\n\t}'; } } else if (!arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.esObjeto && !arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.esInstruccionSQL && arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorConexionATabla[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) { codigoGuardarVariableOperacionSQL += '\n\tvar total = ' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + 'NU3V0/' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + 'NU3V0T0T4L;'; codigoGuardarVariableOperacionSQL += '\n\twindow["' + arregloAgrupacionElementosFormulaPorConexionATabla[i][j].variable.nombre + '"] = total;'; } //}; //} if (j == arregloAgrupacionElementosFormulaPorConexionATabla[i].length - 1) { codigoCuerpo += codigoGuardarVariables; //solo crear codigo for una vez por variable codigoCuerpo += '\n\t\t};'; codigoCuerpo += '\n\t};\n'; codigo += codigoIniciacionVarPrimitiva + codigoCuerpo + codigoGuardarVariableOperacionSQL; } } } ; } } ; /*console.log('codigo'); console.log(codigo);*/ return codigo; } }, { key: "crearCodigoFuenteDatoSQL", value: function crearCodigoFuenteDatoSQL() { //sacar total variables SQL var contadorSQLTotal = 0; for (var a = 0; a < arregloDeVariables.length; a++) { if (arregloDeVariables[a].esInstruccionSQL) { contadorSQLTotal++; } } ; //crear arreglo de siguientes llamadas de metodos de variables SQL //la creacion del codigo en esta parte pertenece a las variables que ocupan calculo sql var codigo = ''; var contadorSQL = 0; for (var a = 0; a < arregloDeVariables.length; a++) { if (arregloDeVariables[a].esInstruccionSQL) { var siguienteMetodo; contadorSQL++; if (contadorSQL == contadorSQLTotal) { siguienteMetodo = "window['calculoPrincipal'](evaluate, iniciarCalculoIndicadores, isValidDate, guardarOperacionSQL)"; } else { siguienteMetodo = "window['calculoSQL" + arregloDeVariables[a + 1].nombre + "'](sql, pool, evaluate, iniciarCalculoIndicadores, isValidDate, guardarOperacionSQL)"; } codigo = this.crearCodigoSQL(arregloDeVariables[a], siguienteMetodo); window['calculoSQL' + arregloDeVariables[a].nombre] = new Function('return function calculoSQL' + arregloDeVariables[a].nombre + '(sql, pool, evaluate, iniciarCalculoIndicadores, isValidDate, guardarOperacionSQL){' + codigo + '\n}')(); console.log(window['calculoSQL' + arregloDeVariables[a].nombre]); } } ; return codigo; } }, { key: "crearCodigoSQL", value: function crearCodigoSQL(variable, siguienteMetodo) { var codigo = ''; codigo += "\nconst transaction = new sql.Transaction( pool );"; codigo += "\ntransaction.begin(err => {"; codigo += "\n\tvar rolledBack = false;"; codigo += "\n\ttransaction.on('rollback', aborted => {"; codigo += "\n\t\trolledBack = true;"; codigo += "\n\t});"; codigo += "\n\tconst request = new sql.Request(transaction);"; codigo += '\n\trequest.query("' + variable.instruccionSQL.instruccionSQL + '", (err, result) => {'; codigo += "\n\t\tif (err) {"; codigo += "\n\t\t\tif (!rolledBack) {"; codigo += "\n\t\t\t\tconsole.log(err);"; codigo += "\n\t\t\t\ttransaction.rollback(err => {"; codigo += "\n\t\t\t\t});"; codigo += '\n\t\t\t\t' + siguienteMetodo + ';'; codigo += "\n\t\t\t}"; codigo += "\n\t\t} else {"; codigo += "\n\t\t\ttransaction.commit(err => {"; codigo += "\n\t\t\t\tfor(var i = 0; i < result.recordset.length; i++) {"; codigo += '\n\t\t\t\t\t//INICIACION VARIABLE: ' + variable.nombre; codigo += '\n' + this.codigoIniciacion(variable, "variable", {}, '\t\t\t\t\t'); for (var p = 0; p < variable.atributos.length; p++) { codigo += '\n' + this.codigoIniciacion(variable, "atributo", variable.atributos[p], '\t\t\t\t\t'); } ; codigo += '\n\t\t\t\t\t//var insertoValor = false;'; for (var i = 0; i < variable.atributos.length; i++) { codigo += "\n\t\t\t\t\tif (result.recordset[i]." + variable.atributos[i].nombre + " != undefined ) {"; codigo += "\n\t\t\t\t\t\t" + variable.nombre + "NU3V0." + variable.atributos[i].nombre + " = result.recordset[i]." + variable.atributos[i].nombre + ";"; codigo += "\n\t\t\t\t\t\t" + variable.nombre + "GU4RD4RV4L0R = true;"; codigo += "\n\t\t\t\t\t}"; } ; codigo += '\n\t\t\t\t\tif (' + variable.nombre + 'GU4RD4RV4L0R) {'; codigo += '\n\t\t\t\t\t\twindow["' + variable.nombre + '"].push(' + variable.nombre + 'NU3V0);'; codigo += '\n\t\t\t\t\t}'; codigo += '\n\t\t\t\t};'; /*codigo += '\n\t\t\t\tconsole.log("window["variable.nombre"]");'; codigo += '\n\t\t\t\tconsole.log(window["'+variable.nombre+'"]);'; codigo += '\n\t\t\t\tconsole.log("result.recordset");'; codigo += '\n\t\t\t\tconsole.log(result.recordset);';*/ codigo += '\n\t\t\t\t' + siguienteMetodo + ';'; codigo += "\n\t\t\t});"; codigo += "\n\t\t}"; codigo += "\n\t});"; codigo += "\n});"; // fin transaction return codigo; } }, { key: "crearCodigoSegmentoReglas", value: function crearCodigoSegmentoReglas(segmentoReglas, reglas, tabs, posicionVariable, posicionCampo, nombreReferenciaArregloEnCodigo, esArregloReferenciaArregloEnCodigo) { var codigo = ''; var tabsText = ''; for (var i = 0; i < tabs; i++) { tabsText += '\t'; } ; for (var n = 0; n < reglas.length; n++) { if (reglas[n].reglaPadreID == -1 && reglas[n].operacion.localeCompare("ELSE") != 0) { var resultado = this.arregloCodigoRegla(reglas[n], tabs, posicionVariable, posicionCampo, [], reglas, nombreReferenciaArregloEnCodigo, esArregloReferenciaArregloEnCodigo); if (resultado.length > 0) resultado[0].codigo = "\n" + resultado[0].codigo; //$.merge( prestamosCuerpo, resultado ); for (var i = 0; i < resultado.length; i++) { codigo += resultado[i].codigo; } ; } } ; return codigo; } }, { key: "crearCodigoSegmentoReglasFormaOExcel", value: function crearCodigoSegmentoReglasFormaOExcel(segmentoReglas, reglas, tabs, posicionVariable, posicionCampo, nombreReferenciaArregloEnCodigo, esExcel) { var codigo = ''; var tabsText = ''; for (var i = 0; i < tabs; i++) { tabsText += '\t'; } ; for (var n = 0; n < reglas.length; n++) { if (reglas[n].reglaPadreID == -1 && reglas[n].operacion.localeCompare("ELSE") != 0) { var resultado = this.arregloCodigoReglaFormaOExcel(reglas[n], tabs, posicionVariable, posicionCampo, [], reglas, nombreReferenciaArregloEnCodigo, esExcel); if (resultado.length > 0) resultado[0].codigo = "\n" + resultado[0].codigo; //$.merge( prestamosCuerpo, resultado ); for (var i = 0; i < resultado.length; i++) { codigo += resultado[i].codigo; } ; } } ; return codigo; } }, { key: "agregarCodigoGuardarVariable", value: function agregarCodigoGuardarVariable(variable, campo, tabs) { var codigo = ''; var tabsText = ''; for (var i = 0; i < tabs; i++) { tabsText += '\t'; } ; //ver si elementoFormula es asignacion de columna //for (var i = 0; i < elementoFormula.length; i++) { //if (elementoFormula[i].operacion.toLowerCase().localeCompare("asig") == 0) { codigo += '\n' + tabsText + 'if (' + variable.nombre + 'GU4RD4RV4L0R' + ') {'; //codigo += '\n'+tabsText+'\tconsole.log('+variable.nombre+'NU3V0);'; if (variable.esObjeto) { codigo += '\n' + tabsText + '\twindow["' + variable.nombre + '"].push(' + variable.nombre + 'NU3V0);'; } else { codigo += '\n' + tabsText + '\twindow["' + variable.nombre + '"] = ' + variable.nombre + 'NU3V0;'; } codigo += '\n' + tabsText + '}'; //} //}; return codigo; } }, { key: "crearNivel", value: function crearNivel(llamarSiguienteNivel, arregloAgrupacionElementosFormulaPorVariables, nivelACrear) { //arregloAgrupacionElementosFormulaPorVariables contiene todas las variables que se calculan a base de otras variables //cada posicion nivel 0 representa la posicion de la variable en el arreglo de variables //cada posicion nivel 1 tiene la variable de la cual se va a calcular, el campo, la variable a crear y el segmento que pertenece a la variable de la cual se va a calcular var codigo = ''; for (var i = 0; i < arregloDeVariables.length; i++) { var variablesInstanciadasID = [], variablesGuardadasID = []; if ( /*!arregloDeVariables[i].esInstruccionSQL &&*/ arregloAgrupacionElementosFormulaPorVariables[i] != undefined) { var totalVarACrearNivel = 0; for (var j = 0; j < arregloAgrupacionElementosFormulaPorVariables[i].length; j++) { if (arregloAgrupacionElementosFormulaPorVariables[i][j] != undefined && arregloAgrupacionElementosFormulaPorVariables[i][j].length == undefined && arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nivel == nivelACrear) { totalVarACrearNivel++; } } ; var codigoCuerpo = ''; var codigoIniciacionVarPrimitiva = ''; var codigoGuardarVariables = ''; var totalVarCreadasNivel = 0; var codigoGuardarVariableOperacionSQL = ''; for (var j = 0; j < arregloAgrupacionElementosFormulaPorVariables[i].length; j++) { //arregloAgrupacionElementosFormulaPorVariables[i][j].length == undefined --- para ver si no son varias variables de excel if (arregloAgrupacionElementosFormulaPorVariables[i][j] != undefined && arregloAgrupacionElementosFormulaPorVariables[i][j].length == undefined && arregloAgrupacionElementosFormulaPorVariables[i][j].length == undefined && arregloDeVariables[i].ID == arregloAgrupacionElementosFormulaPorVariables[i][j].variableCreacionCodigo.ID && arregloDeVariables[i].nombre.localeCompare(arregloAgrupacionElementosFormulaPorVariables[i][j].variableCreacionCodigo.nombre) == 0 && arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nivel == nivelACrear && arregloAgrupacionElementosFormulaPorVariables[i][j].variable.realizarCalculo) { //segundo es para ver si no es arregloAgrupacionElementosFormulaPorVariables de excel totalVarCreadasNivel++; if (j == 0 && (arregloDeVariables[i].esObjeto || arregloDeVariables[i].esInstruccionSQL) && !arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.esValorManual) { //solo crear codigo for una vez por variable codigoCuerpo += '\n\t//CODIGO VARIABLE: ' + arregloDeVariables[i].nombre; codigoCuerpo += '\n\tfor ( var x = 0; x < window["' + arregloDeVariables[i].nombre + '"].length; x++) {'; } var varFueInicializada = false; for (var w = 0; w < variablesInstanciadasID.length; w++) { if (variablesInstanciadasID[w] == arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID) { varFueInicializada = true; break; } } ; /*if(!varFueInicializada) { variablesInstanciadasID.push(arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID);*/ if (arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esObjeto) { if (!varFueInicializada) { variablesInstanciadasID.push(arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID); codigoCuerpo += '\n\t\t//INICIACION VARIABLE: ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre; codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "variable", {}, '\t\t'); //variable, tipoVariable, atributo } //for (var p = 0; p < arregloAgrupacionElementosFormulaPorVariables[i][j].variable.atributos.length; p++) { var contieneOperacionSQL = false, esPromedio = false; //viendo si la ultima regla del segmento (la de asignacion) es una operacion de SQL (AUTOSUMAR, PROMEDIO, MAX, MIN) if (this.existeOperacion(arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion)) contieneOperacionSQL = true; if (arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) esPromedio = true; if (!contieneOperacionSQL) codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][j].atributo, '\t\t', false, esPromedio);else { codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][j].atributo, '\t\t', false, false); codigoIniciacionVarPrimitiva += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][j].atributo, '\t', true, esPromedio); } //}; } else { codigoIniciacionVarPrimitiva += '\n\t//INICIACION VARIABLE: ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre; for (var p = 0; p < arregloAgrupacionElementosFormulaPorVariables[i][j].variable.atributos.length; p++) { var esPromedio = false; if (arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) esPromedio = true; codigoIniciacionVarPrimitiva += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][j].variable.atributos[p], '\t', false, esPromedio); } ; } //} //if(arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nivel == nivelACrear) { var posicionVariable = 0, posicionCampo = 0; EncontrarPosiciones: for (var a = 0; a < arregloDeVariables.length; a++) { if (arregloDeVariables[a].ID == arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID) { posicionVariable = a; for (var b = 0; b < arregloDeVariables[a].atributos.length; b++) { if (arregloDeVariables[a].atributos[b].ID == arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.ID) { posicionCampo = b; break EncontrarPosiciones; } } ; } } ; var esArregloReferenciaArregloEnCodigo = false; if (arregloDeVariables[i].esObjeto || arregloDeVariables[i].esInstruccionSQL) esArregloReferenciaArregloEnCodigo = true; codigoCuerpo += this.crearCodigoSegmentoReglas(arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla, arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas, 2, posicionVariable, posicionCampo, 'window["' + arregloDeVariables[i].nombre + '"]', esArregloReferenciaArregloEnCodigo); //} var varFueGuardada = false; for (var w = 0; w < variablesGuardadasID.length; w++) { if (variablesGuardadasID[w] == arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID) { varFueGuardada = true; break; } } ; if (!varFueGuardada) { variablesGuardadasID.push(arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID); codigoGuardarVariables += this.agregarCodigoGuardarVariable(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, arregloAgrupacionElementosFormulaPorVariables[i][j].atributos, 2); } //for (var p = 0; p < arregloAgrupacionElementosFormulaPorVariables[i][j].variable.atributos.length; p++) { if (arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esObjeto || arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esInstruccionSQL) { var contieneOperacionSQL = false; //viendo si la ultima regla del segmento (la de asignacion) es una operacion de SQL (AUTOSUMAR, PROMEDIO, MAX, MIN) if (this.existeOperacion(arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion)) contieneOperacionSQL = true; if (contieneOperacionSQL && arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") != 0) codigoGuardarVariableOperacionSQL += '\n\tguardarOperacionSQL(window["' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + '"], "' + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + '", ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0);';else if (contieneOperacionSQL && arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) { //NU3V0T0T4L codigoGuardarVariableOperacionSQL += '\n\tif(' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0T0T4L != 0 || ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0T0T4L != -1) {'; codigoGuardarVariableOperacionSQL += '\n\t\tvar total = ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0/' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0T0T4L;'; codigoGuardarVariableOperacionSQL += '\n\t\tguardarOperacionSQL(window["' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + '"], "' + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + '", total);'; codigoGuardarVariableOperacionSQL += '\n\t}'; } else if (!arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esObjeto && !arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esInstruccionSQL && arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) { codigoGuardarVariableOperacionSQL += '\n\tvar total = ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + 'NU3V0/' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + 'NU3V0T0T4L;'; codigoGuardarVariableOperacionSQL += '\n\twindow["' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + '"] = total;'; } } //}; //} if (totalVarCreadasNivel == totalVarACrearNivel) { codigoCuerpo += codigoGuardarVariables; //solo crear codigo for una vez por variable if ((arregloDeVariables[i].esObjeto || arregloDeVariables[i].esInstruccionSQL) && !arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.esValorManual) codigoCuerpo += '\n\t};\n'; codigo += codigoIniciacionVarPrimitiva + codigoCuerpo + codigoGuardarVariableOperacionSQL; } } } ; } } ; for (var i = 0; i < arregloDeFormas.length; i++) { var variablesInstanciadasID = [], variablesGuardadasID = []; if (arregloAgrupacionElementosFormulaPorVariables[i] != undefined) { var totalVarACrearNivel = 0; for (var j = 0; j < arregloAgrupacionElementosFormulaPorVariables[i].length; j++) { if (arregloAgrupacionElementosFormulaPorVariables[i][j] != undefined && arregloAgrupacionElementosFormulaPorVariables[i][j].length == undefined && arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nivel == nivelACrear) { totalVarACrearNivel++; } } ; var codigoCuerpo = ''; var codigoIniciacionVarPrimitiva = ''; var codigoGuardarVariables = ''; var totalVarCreadasNivel = 0; var codigoGuardarVariableOperacionSQL = ''; for (var j = 0; j < arregloAgrupacionElementosFormulaPorVariables[i].length; j++) { if (arregloAgrupacionElementosFormulaPorVariables[i][j] != undefined && arregloAgrupacionElementosFormulaPorVariables[i][j].length == undefined && arregloDeFormas[i].ID == arregloAgrupacionElementosFormulaPorVariables[i][j].variableCreacionCodigo.ID && this.verificarExistenciaErroresForma(arregloAgrupacionElementosFormulaPorVariables[i][j].variableCreacionCodigo) && arregloDeFormas[i].nombre.localeCompare(arregloAgrupacionElementosFormulaPorVariables[i][j].variableCreacionCodigo.nombre) == 0 && arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nivel == nivelACrear && arregloAgrupacionElementosFormulaPorVariables[i][j].variable.realizarCalculo) { //segundo es para ver si no es arregloAgrupacionElementosFormulaPorVariables de excel totalVarCreadasNivel++; /*if(j == 0) { //solo crear codigo for una vez por variable codigoCuerpo += '\n\t//CODIGO VARIABLE: '+arregloDeFormas[i].nombre; codigoCuerpo += '\n\tfor ( var x = 0; x < window["'+arregloDeFormas[i].nombre+'"].length; x++) {'; }*/ var varFueInicializada = false; for (var w = 0; w < variablesInstanciadasID.length; w++) { if (variablesInstanciadasID[w] == arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID) { varFueInicializada = true; break; } } ; /*if(!varFueInicializada) { variablesInstanciadasID.push(arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID);*/ if (arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esObjeto) { if (!varFueInicializada) { variablesInstanciadasID.push(arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID); codigoCuerpo += '\n\t\t//INICIACION VARIABLE: ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre; codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "variable", {}, '\t\t'); //variable, tipoVariable, atributo } //for (var p = 0; p < arregloAgrupacionElementosFormulaPorVariables[i][j].variable.atributos.length; p++) { var contieneOperacionSQL = false, esPromedio = false; //viendo si la ultima regla del segmento (la de asignacion) es una operacion de SQL (AUTOSUMAR, PROMEDIO, MAX, MIN) if (this.existeOperacion(arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion)) contieneOperacionSQL = true; if (arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) esPromedio = true; if (!contieneOperacionSQL) codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][j].atributo, '\t\t', false, esPromedio);else { codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][j].atributo, '\t\t', false, false); codigoIniciacionVarPrimitiva += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][j].atributo, '\t', true, esPromedio); } //}; } else { codigoIniciacionVarPrimitiva += '\n\t//INICIACION VARIABLE: ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre; for (var p = 0; p < arregloAgrupacionElementosFormulaPorVariables[i][j].variable.atributos.length; p++) { var esPromedio = false; if (arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) esPromedio = true; codigoIniciacionVarPrimitiva += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][j].variable.atributos[p], '\t', false, esPromedio); } ; } //} //if(arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nivel == nivelACrear) { var posicionVariable = 0, posicionCampo = 0; EncontrarPosiciones: for (var a = 0; a < arregloDeVariables.length; a++) { if (arregloDeVariables[a].ID == arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID) { posicionVariable = a; for (var b = 0; b < arregloDeVariables[a].atributos.length; b++) { if (arregloDeVariables[a].atributos[b].ID == arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.ID) { posicionCampo = b; break EncontrarPosiciones; } } ; } } ; var esArregloReferenciaArregloEnCodigo = false; codigoCuerpo += this.crearCodigoSegmentoReglasFormaOExcel(arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla, arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas, 2, posicionVariable, posicionCampo, 'window["' + arregloDeFormas[i].nombre + '"]', false); //} var varFueGuardada = false; for (var w = 0; w < variablesGuardadasID.length; w++) { if (variablesGuardadasID[w] == arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID) { varFueGuardada = true; break; } } ; if (!varFueGuardada) { variablesGuardadasID.push(arregloAgrupacionElementosFormulaPorVariables[i][j].variable.ID); codigoGuardarVariables += this.agregarCodigoGuardarVariable(arregloAgrupacionElementosFormulaPorVariables[i][j].variable, arregloAgrupacionElementosFormulaPorVariables[i][j].atributos, 2); } //for (var p = 0; p < arregloAgrupacionElementosFormulaPorVariables[i][j].variable.atributos.length; p++) { if (arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esObjeto || arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esInstruccionSQL) { var contieneOperacionSQL = false; //viendo si la ultima regla del segmento (la de asignacion) es una operacion de SQL (AUTOSUMAR, PROMEDIO, MAX, MIN) if (this.existeOperacion(arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion)) contieneOperacionSQL = true; if (contieneOperacionSQL && arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") != 0) codigoGuardarVariableOperacionSQL += '\n\tguardarOperacionSQL(window["' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + '"], "' + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + '", ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0);';else if (contieneOperacionSQL && arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) { //NU3V0T0T4L codigoGuardarVariableOperacionSQL += '\n\tif(' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0T0T4L != 0 || ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0T0T4L != -1) {'; codigoGuardarVariableOperacionSQL += '\n\t\tvar total = ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0/' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + 'NU3V0T0T4L;'; codigoGuardarVariableOperacionSQL += '\n\t\tguardarOperacionSQL(window["' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + '"], "' + arregloAgrupacionElementosFormulaPorVariables[i][j].atributo.nombre + '", total);'; codigoGuardarVariableOperacionSQL += '\n\t}'; } else if (!arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esObjeto && !arregloAgrupacionElementosFormulaPorVariables[i][j].variable.esInstruccionSQL && arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) { codigoGuardarVariableOperacionSQL += '\n\tvar total = ' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + 'NU3V0/' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + 'NU3V0T0T4L;'; codigoGuardarVariableOperacionSQL += '\n\twindow["' + arregloAgrupacionElementosFormulaPorVariables[i][j].variable.nombre + '"] = total;'; } } //}; //} if (totalVarCreadasNivel == totalVarACrearNivel) { codigoCuerpo += codigoGuardarVariables; //solo crear codigo for una vez por variable /*if((arregloDeVariables[i].esObjeto || arregloDeVariables[i].esInstruccionSQL) && !arregloAgrupacionElementosFormulaPorVariables[i][j].segmentoRegla.esValorManual) codigoCuerpo += '\n\t};\n';*/ codigo += codigoIniciacionVarPrimitiva + codigoCuerpo + codigoGuardarVariableOperacionSQL; } } } ; } } ; for (var i = 0; i < arregloDeExcel.length; i++) { for (var p = 0; p < arregloDeExcel[i].variables.length; p++) { var variablesInstanciadasID = [], variablesGuardadasID = []; if (arregloAgrupacionElementosFormulaPorVariables[i] != undefined && arregloAgrupacionElementosFormulaPorVariables[i][p] != undefined && arregloAgrupacionElementosFormulaPorVariables[i][p].length != undefined) { var totalVarACrearNivel = 0; for (var j = 0; j < arregloAgrupacionElementosFormulaPorVariables[i][p].length; j++) { if (arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nivel == nivelACrear) { totalVarACrearNivel++; } } ; var codigoCuerpo = ''; var codigoIniciacionVarPrimitiva = ''; var codigoGuardarVariables = ''; var totalVarCreadasNivel = 0; var codigoGuardarVariableOperacionSQL = ''; for (var j = 0; j < arregloAgrupacionElementosFormulaPorVariables[i][p].length; j++) { if (arregloDeExcel[i].variables[p].ID == arregloAgrupacionElementosFormulaPorVariables[i][p][j].variableCreacionCodigo.ID && !this.verificarExistenciaErroresExcel(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variableCreacionCodigo) && arregloDeExcel[i].variables[p].nombre.localeCompare(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variableCreacionCodigo.nombre) == 0 && arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nivel == nivelACrear && arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.realizarCalculo) { totalVarCreadasNivel++; if (j == 0 && window[arregloDeExcel[i].variables[p].nombre].length != undefined) { //solo crear codigo for una vez por variable codigoCuerpo += '\n\t//CODIGO VARIABLE: ' + arregloDeExcel[i].variables[p].nombre; codigoCuerpo += '\n\tfor ( var x = 0; x < window["' + arregloDeExcel[i].variables[p].nombre + '"].length; x++) {'; } var varFueInicializada = false; for (var w = 0; w < variablesInstanciadasID.length; w++) { if (variablesInstanciadasID[w] == arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.ID) { varFueInicializada = true; break; } } ; /*if(!varFueInicializada) { variablesInstanciadasID.push(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.ID);*/ if (arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.esObjeto) { if (!varFueInicializada) { variablesInstanciadasID.push(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.ID); codigoCuerpo += '\n\t\t//INICIACION VARIABLE: ' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre; codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable, "variable", {}, '\t\t'); //variable, tipoVariable, atributo } //for (var p = 0; p < arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.atributos.length; p++) { var contieneOperacionSQL = false, esPromedio = false; //viendo si la ultima regla del segmento (la de asignacion) es una operacion de SQL (AUTOSUMAR, PROMEDIO, MAX, MIN) if (this.existeOperacion(arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas.length - 1].operacion)) contieneOperacionSQL = true; if (arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) esPromedio = true; if (!contieneOperacionSQL) codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo, '\t\t', false, esPromedio);else { codigoCuerpo += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo, '\t\t', false, false); codigoIniciacionVarPrimitiva += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo, '\t', true, esPromedio); } //}; } else { codigoIniciacionVarPrimitiva += '\n\t//INICIACION VARIABLE: ' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre; for (var k = 0; k < arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.atributos.length; k++) { var esPromedio = false; if (arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) esPromedio = true; codigoIniciacionVarPrimitiva += '\n' + this.codigoIniciacion(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable, "atributo", arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.atributos[k], '\t', false, esPromedio); } ; } //} //if(arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nivel == nivelACrear) { var posicionVariable = 0, posicionCampo = 0; EncontrarPosiciones: for (var a = 0; a < arregloDeVariables.length; a++) { if (arregloDeVariables[a].ID == arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.ID) { posicionVariable = a; for (var b = 0; b < arregloDeVariables[a].atributos.length; b++) { if (arregloDeVariables[a].atributos[b].ID == arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.ID) { posicionCampo = b; break EncontrarPosiciones; } } ; } } ; var esArregloReferenciaArregloEnCodigo = false; if (window[arregloDeExcel[i].variables[p].nombre].length != undefined) codigoCuerpo += this.crearCodigoSegmentoReglasFormaOExcel(arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla, arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas, 2, posicionVariable, posicionCampo, "window['" + arregloDeExcel[i].variables[p].nombre + "'][x]", true);else codigoCuerpo += this.crearCodigoSegmentoReglasFormaOExcel(arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla, arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas, 2, posicionVariable, posicionCampo, "window['" + arregloDeExcel[i].variables[p].nombre + "']", false); //} var varFueGuardada = false; for (var w = 0; w < variablesGuardadasID.length; w++) { if (variablesGuardadasID[w] == arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.ID) { varFueGuardada = true; break; } } ; if (!varFueGuardada) { variablesGuardadasID.push(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.ID); codigoGuardarVariables += this.agregarCodigoGuardarVariable(arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable, arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributos, 2); } //for (var p = 0; p < arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.atributos.length; p++) { if (arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.esObjeto || arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.esInstruccionSQL) { var contieneOperacionSQL = false; //viendo si la ultima regla del segmento (la de asignacion) es una operacion de SQL (AUTOSUMAR, PROMEDIO, MAX, MIN) if (this.existeOperacion(arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas.length - 1].operacion)) contieneOperacionSQL = true; if (contieneOperacionSQL && arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") != 0) codigoGuardarVariableOperacionSQL += '\n\tguardarOperacionSQL(window["' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + '"], "' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nombre + '", ' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nombre + 'NU3V0);';else if (contieneOperacionSQL && arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) { //NU3V0T0T4L codigoGuardarVariableOperacionSQL += '\n\tif(' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nombre + 'NU3V0T0T4L != 0 || ' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nombre + 'NU3V0T0T4L != -1) {'; codigoGuardarVariableOperacionSQL += '\n\t\tvar total = ' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nombre + 'NU3V0/' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nombre + 'NU3V0T0T4L;'; codigoGuardarVariableOperacionSQL += '\n\t\tguardarOperacionSQL(window["' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + '"], "' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].atributo.nombre + '", total);'; codigoGuardarVariableOperacionSQL += '\n\t}'; } else if (!arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.esObjeto && !arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.esInstruccionSQL && arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas[arregloAgrupacionElementosFormulaPorVariables[i][p][j].segmentoRegla.reglas.length - 1].operacion.localeCompare("PROM") == 0) { codigoGuardarVariableOperacionSQL += '\n\tvar total = ' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + 'NU3V0/' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + 'NU3V0T0T4L;'; codigoGuardarVariableOperacionSQL += '\n\twindow["' + arregloAgrupacionElementosFormulaPorVariables[i][p][j].variable.nombre + '"] = total;'; } } //}; //} if (totalVarCreadasNivel == totalVarACrearNivel) { codigoCuerpo += codigoGuardarVariables; //solo crear codigo for una vez por variable if (window[arregloDeExcel[i].variables[p].nombre].length != undefined) codigoCuerpo += '\n\t};\n'; codigo += codigoIniciacionVarPrimitiva + codigoCuerpo + codigoGuardarVariableOperacionSQL; } } } ; } } ; } ; return codigo; } }, { key: "arregloCodigoRegla", value: function arregloCodigoRegla(regla, tabs, posicionVariable, posicionCampo, arreglo, arregloDeReglas, nombreReferenciaArregloEnCodigo, esArregloReferenciaArregloEnCodigo) { var tabsText = ''; for (var i = 0; i < tabs; i++) { tabsText += '\t'; } ; var posicionesIF = []; var newTabsTextFormula = ''; if (!regla.esCondicion) { //asignaciones //si no es condicion, la variable de referencia se le agrega NU3V0 que hace referencia al objeto temporal vacio if (regla.operacion.indexOf('ASIG') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { if (formula[0].fuenteDeDatos != undefined && formula[0].fuenteDeDatos[0].esValorManual) { arreglo.push({ codigo: tabsText + "if ('" + formula[0].fuenteDeDatos[0].nombreVariable + "' != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0." + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + " = '" + formula[0].fuenteDeDatos[0].nombreVariable + "';", tipo: "ASIG" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0." + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + " = " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ";", tipo: "ASIG" }); } } else { if (formula[0].fuenteDeDatos != undefined && formula[0].fuenteDeDatos[0].esValorManual) { arreglo.push({ codigo: tabsText + "if ('" + formula[0].fuenteDeDatos[0].nombreVariable + "' != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0." + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + " = '" + formula[0].fuenteDeDatos[0].nombreVariable + "';", tipo: "ASIG" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0." + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + " = " + nombreReferenciaArregloEnCodigo + ";", tipo: "ASIG" }); } } } else { if (esArregloReferenciaArregloEnCodigo) { if (formula[0].fuenteDeDatos != undefined && formula[0].fuenteDeDatos[0].esValorManual) { arreglo.push({ codigo: tabsText + "if ('" + formula[0].fuenteDeDatos[0].nombreVariable + "' != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = '" + formula[0].fuenteDeDatos[0].nombreVariable + "';", tipo: "ASIG" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ";", tipo: "ASIG" }); } } else { if (formula[0].fuenteDeDatos != undefined && formula[0].fuenteDeDatos[0].esValorManual) { arreglo.push({ codigo: tabsText + "if ('" + formula[0].fuenteDeDatos[0].nombreVariable + "' != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = '" + formula[0].fuenteDeDatos[0].nombreVariable + "';", tipo: "ASIG" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "ASIG" }); } } } arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "ASIG" }); /*arreglo.push({codigo: "\n"+tabsText+"} else {\n", tipo: "ASIG"}); arreglo.push({codigo: "\n"+tabsText+"\tarregloDeErroresVariables.push({nombre: nombreVariable, ID: id})\n", tipo: "ASIG"}); arreglo.push({codigo: "\n"+tabsText+"} else {", tipo: "ASIG"});*/ } } else if (regla.operacion.indexOf('MAX') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("date") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getTime() < " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if( window['" + arregloDeVariables[posicionVariable].nombre + "'].length == 0)", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getDate() == 28 )", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getTime() < " + nombreReferenciaArregloEnCodigo + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if( window['" + arregloDeVariables[posicionVariable].nombre + "'].length == 0)", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getDate() == 28 )", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getTime() < " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getDate() == 28)", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getTime() < " + nombreReferenciaArregloEnCodigo + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getDate() == 28)", tipo: "MAX" }); ; arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || arregloDeVariables[posicionVariable].atributos[posicionCampo].tipo.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 < " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ";", tipo: "MAX" }); //arreglo.push({codigo: "\n\t\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 < " + nombreReferenciaArregloEnCodigo + ") {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); //arreglo.push({codigo: "\n\t\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 < " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 < " + nombreReferenciaArregloEnCodigo + ") {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } } } } else if (regla.operacion.indexOf('MIN') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("date") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getTime() > " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if( window['" + arregloDeVariables[posicionVariable].nombre + "'].length == 0)", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getDate() == 28)", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getTime() > " + nombreReferenciaArregloEnCodigo + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if( window['" + arregloDeVariables[posicionVariable].nombre + "'].length == 0)", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getDate() == 28)", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getTime() > " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getDate() == 28)", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getTime() > " + nombreReferenciaArregloEnCodigo + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getDate() == 28) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || arregloDeVariables[posicionVariable].atributos[posicionCampo].tipo.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 > " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " || " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ";", tipo: "MAX" }); //arreglo.push({codigo: "\n\t\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 > " + nombreReferenciaArregloEnCodigo + " || " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); //arreglo.push({codigo: "\n\t\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 > " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "} else if( " + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 > " + nombreReferenciaArregloEnCodigo + ") {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "} else if( " + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } } } } else if (regla.operacion.indexOf('PROM') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || arregloDeVariables[posicionVariable].atributos[posicionCampo].tipo.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 += " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0T0T4L++;", tipo: "MAX" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 += " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0T0T4L++;", tipo: "MAX" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( " + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 += " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0T0T4L++;", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( " + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 += " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0T0T4L++;", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } } } } else if (regla.operacion.indexOf('AUTOSUM') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ")) {", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1)", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "AUTOSUM" }); //arreglo.push({codigo: "\n\t\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = evaluate(" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 + " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "AUTOSUM" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1)", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "AUTOSUM" }); //arreglo.push({codigo: "\n\t\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = evaluate(" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 + " + nombreReferenciaArregloEnCodigo + ");", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "AUTOSUM" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ")) {", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1)", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = evaluate(" + arregloDeVariables[posicionVariable].nombre + "NU3V0 + " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ");", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "AUTOSUM" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1)", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = evaluate(" + arregloDeVariables[posicionVariable].nombre + "NU3V0 + " + nombreReferenciaArregloEnCodigo + ");", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "AUTOSUM" }); } } } } } else if (regla.operacion.indexOf('COUNT') == 0) { var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ") && !isNaN(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("varchar") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ".length > 0) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && " + nombreReferenciaArregloEnCodigo + ".length > 0) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ".length > 0) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && " + nombreReferenciaArregloEnCodigo + ".length > 0) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("bool") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " == true || " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " == false) ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && (" + nombreReferenciaArregloEnCodigo + " == true || " + nombreReferenciaArregloEnCodigo + " == false) ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " == true || " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " == false) ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && (" + nombreReferenciaArregloEnCodigo + " == true || " + nombreReferenciaArregloEnCodigo + " == false) ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("date") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ") ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + ") {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } else { if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[0].nombreColumnaEnTabla + ")) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } } } else if (regla.operacion.indexOf('FORMULA') == 0) { var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); for (var i = 0; i < formula[0].fuenteDeDatos.length; i++) { var saltoLinea = '\n'; if (formula[0].fuenteDeDatos[i].operacion != undefined && formula[0].fuenteDeDatos[i].operacion.length > 0) { //if(formula[0].fuenteDeDatos[i].esFuenteDeDato) { //elemento formula es de conexion de tabla if (esArregloReferenciaArregloEnCodigo) { arreglo.push({ codigo: saltoLinea + tabsText + newTabsTextFormula + "if (" + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[i].nombreColumnaEnTabla + " != undefined) {", tipo: "FORMULA" }); newTabsTextFormula += "\t"; arreglo.push({ codigo: saltoLinea + tabsText + newTabsTextFormula + "var " + formula[0].fuenteDeDatos[i].nombreVariable + " = " + nombreReferenciaArregloEnCodigo + "[x]." + formula[0].fuenteDeDatos[i].nombreColumnaEnTabla + ";", tipo: "FORMULA" }); /*arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"console.log('"+formula[0].fuenteDeDatos[i].nombreVariable+"');", tipo: "FORMULA"}); arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"console.log("+formula[0].fuenteDeDatos[i].nombreVariable+");", tipo: "FORMULA"});*/ } else { arreglo.push({ codigo: saltoLinea + tabsText + newTabsTextFormula + "if (window['" + formula[0].fuenteDeDatos[i].nombreColumnaEnTabla + "'] != undefined) {", tipo: "FORMULA" }); newTabsTextFormula += "\t"; arreglo.push({ codigo: saltoLinea + tabsText + newTabsTextFormula + "var " + formula[0].fuenteDeDatos[i].nombreVariable + " = window['" + formula[0].fuenteDeDatos[i].nombreColumnaEnTabla + "'];", tipo: "FORMULA" }); /*arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"console.log('"+formula[0].fuenteDeDatos[i].nombreVariable+"');", tipo: "FORMULA"}); arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"console.log("+formula[0].fuenteDeDatos[i].nombreVariable+");", tipo: "FORMULA"});*/ } /*} else { if (!arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"if ("+nombreReferenciaArregloEnCodigo+" != undefined) {", tipo: "FORMULA"}); newTabsTextFormula += "\t"; //elemento formula es variable primitiva if(i > 0) { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"var "+formula[0].fuenteDeDatos[i].nombreVariable+" = "+nombreReferenciaArregloEnCodigo+";", tipo: "FORMULA"}); } else { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"var "+formula[0].fuenteDeDatos[i].nombreVariable+" = "+nombreReferenciaArregloEnCodigo+";", tipo: "FORMULA"}); } } else { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"if ("+nombreReferenciaArregloEnCodigo+"[x]."+arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre+" != undefined) {", tipo: "FORMULA"}); newTabsTextFormula += "\t"; if(i > 0) { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"var "+formula[0].fuenteDeDatos[i].nombreVariable+" = "+nombreReferenciaArregloEnCodigo+"[x]."+arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre+";", tipo: "FORMULA"}); } else { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"var "+formula[0].fuenteDeDatos[i].nombreVariable+" = "+nombreReferenciaArregloEnCodigo+"[x]."+arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre+";", tipo: "FORMULA"}); } } }*/ } } ; //arreglo.push({codigo: "\n\t\t"+tabsText+arregloDeVariables[posicionVariable].nombre+"NU3V0."+arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre+" = math.eval(formula[0].formula);"}); if (arregloDeVariables[posicionVariable].esObjeto) arreglo.push({ codigo: "\n" + tabsText + newTabsTextFormula + arregloDeVariables[posicionVariable].nombre + "NU3V0." + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + " = " + formula[0].formula + ";" });else arreglo.push({ codigo: "\n" + tabsText + newTabsTextFormula + arregloDeVariables[posicionVariable].nombre + "NU3V0 = evaluate(" + formula[0].formula + ");" }); arreglo.push({ codigo: "\n" + tabsText + newTabsTextFormula + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); for (var i = formula[0].fuenteDeDatos.length; i > 0; i--) { posicionesIF.push(arreglo.length + i); } } } else { //condiciones if var arregloValoresAComparar = []; if (regla.valor.indexOf("LISTAID") == 0) {// } else if (regla.valor.indexOf("FECHA") == 0) { var fecha = regla.valor.substring(regla.valor.indexOf("[") + 1, regla.valor.lastIndexOf("]")); arregloValoresAComparar = ["new Date(" + fecha + ").getTime()"]; } else if (regla.valor.indexOf("TIEMPO") == 0) { var stringValores = regla.valor.substring(regla.valor.indexOf("[") + 1, regla.valor.lastIndexOf("]")); var diasAgregarCadena = stringValores.split(",")[0], mesesAgregarCadena = stringValores.split(",")[1], aniosAgregarCadena = stringValores.split(",")[2], futuro = stringValores.split(",")[3]; var diasAgregar = parseInt(diasAgregarCadena.indexOf("=") + 1), mesesAgregar = parseInt(mesesAgregarCadena.indexOf("=") + 1), aniosAgregar = parseInt(aniosAgregarCadena.indexOf("=") + 1); var esFuturo = true; if (futuro.localeCompare("FUTURO") == 0) esFuturo = true;else esFuturo = false; var hoy = new Date(); if (esFuturo) { hoy = this.addYears(hoy, aniosAgregar); hoy = this.addMonths(hoy, mesesAgregar); hoy = this.addDays(hoy, diasAgregar); } else { hoy = this.minusDays(hoy, diasAgregar); hoy = this.minusMonths(hoy, mesesAgregar); hoy = this.minusYears(hoy, aniosAgregar); } arregloValoresAComparar = ["new Date(" + hoy.getFullYear() + ", " + hoy.getMonth() + ", " + hoy.getDate() + ").getTime()"]; } else if (regla.valor.indexOf("MANUAL") == 0) { arregloValoresAComparar = [regla.valor.substring(regla.valor.indexOf("[") + 1, regla.valor.lastIndexOf("]"))]; } var nombreCampoDeArregloEnCodigo = ''; if (regla.esConexionTabla) { nombreCampoDeArregloEnCodigo = regla.nombreColumnaEnTabla; } else { nombreCampoDeArregloEnCodigo = arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre; } var tamArreglo = arreglo.length; //for (var j = 0; j < tamArreglo; j++) { for (var i = 0; i < arregloValoresAComparar.length; i++) { var comparacion = ""; var inicioComparacion = ""; var operacion = ""; if (regla.operacion.localeCompare("ES_MENOR") == 0 && regla.valor.indexOf("TIEMPO") != 0) { operacion = "<"; } else if (regla.operacion.localeCompare("ES_MENOR_O_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") != 0) { operacion = "<="; } else if (regla.operacion.localeCompare("ES_MAYOR_O_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") != 0) { operacion = ">="; } else if (regla.operacion.localeCompare("ES_MAYOR") == 0 && regla.valor.indexOf("TIEMPO") != 0) { operacion = ">"; } else if (regla.operacion.localeCompare("ES_IGUAL") == 0) { operacion = "=="; } else if (regla.operacion.localeCompare("NO_ES_IGUAL") == 0) { operacion = "!="; } else if (regla.operacion.localeCompare("ES_MENOR") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = ">"; } else if (regla.operacion.localeCompare("ES_MENOR_O_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = ">="; } else if (regla.operacion.localeCompare("ES_MAYOR_O_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = "<="; } else if (regla.operacion.localeCompare("ES_MAYOR") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = "<"; } else if (regla.operacion.localeCompare("ES_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = "=="; } else if (regla.operacion.localeCompare("NO_ES_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = "!="; } if (regla.tipoCampoObjetivo.localeCompare("date") == 0) { if (regla.operacion.localeCompare("encuentra") == 0) {// } else if (regla.operacion.localeCompare("no_encuentra") == 0) {// } else { if (esArregloReferenciaArregloEnCodigo) { inicioComparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + ")"; comparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + ".getTime() " + operacion + " " + arregloValoresAComparar[i]; } else { inicioComparacion = nombreReferenciaArregloEnCodigo + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + ")"; comparacion = nombreReferenciaArregloEnCodigo + ".getTime() " + operacion + " " + arregloValoresAComparar[i]; } } } else if (regla.tipoCampoObjetivo.localeCompare("varchar") == 0) { if (regla.operacion.localeCompare("encuentra") == 0) {// } else if (regla.operacion.localeCompare("no_encuentra") == 0) {// } else { if (esArregloReferenciaArregloEnCodigo) { inicioComparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " != undefined"; comparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + ".localeCompare('" + arregloValoresAComparar[i] + "') " + operacion + " 0"; } else { inicioComparacion = nombreReferenciaArregloEnCodigo + " != undefined"; comparacion = nombreReferenciaArregloEnCodigo + ".localeCompare('" + arregloValoresAComparar[i] + "') " + operacion + " 0"; } } } else if (regla.tipoCampoObjetivo.localeCompare("int") == 0 || regla.tipoCampoObjetivo.localeCompare("decimal") == 0) { if (regla.operacion.localeCompare("encuentra") == 0) {// } else if (regla.operacion.localeCompare("no_encuentra") == 0) {// } else { if (esArregloReferenciaArregloEnCodigo) { inicioComparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + ")"; comparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " " + operacion + " " + arregloValoresAComparar[i]; } else { inicioComparacion = nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")"; comparacion = nombreReferenciaArregloEnCodigo + " " + operacion + " " + arregloValoresAComparar[i]; } } } else if (regla.tipoCampoObjetivo.localeCompare("bit") == 0) { if (esArregloReferenciaArregloEnCodigo) { inicioComparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " != undefined"; comparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " " + operacion + " " + arregloValoresAComparar[i]; } else { inicioComparacion = nombreReferenciaArregloEnCodigo + " != undefined"; comparacion = nombreReferenciaArregloEnCodigo + " " + operacion + " " + arregloValoresAComparar[i]; } } if (i + 1 == arregloValoresAComparar.length) { comparacion += " ) {"; } if (i == 0) { //arreglo[j].codigo += comparacion; //arreglo.push({codigo: tabsText+"console.log("+nombreReferenciaArregloEnCodigo+"[x]);", tipo: "COMPARACION"}); //arreglo.push({codigo: '\n'+tabsText+"console.log( "+nombreReferenciaArregloEnCodigo+"[x]."+nombreCampoDeArregloEnCodigo+");", tipo: "COMPARACION"}); arreglo.push({ codigo: '\n' + tabsText + "if ( " + inicioComparacion + " && " + comparacion, tipo: "COMPARACION" }); } else { arreglo[arreglo.length - 1].codigo += " && " + comparacion; } } ; /*console.log("ENTROOO j"); };*/ posicionesIF.push(arreglo.length); } var cuerpo = arregloDeReglas.filter(function (object) { return object.reglaPadreID == regla.ID; }); if (cuerpo.length > 0) { var arregloCuerpo = []; for (var i = 0; i < cuerpo.length; i++) { /*var cuantasTabs = tabs; if(regla.esCondicion) cuantasTabs++;*/ var retorno = this.arregloCodigoRegla(cuerpo[i], tabs + 1, posicionVariable, posicionCampo, [], arregloDeReglas, nombreReferenciaArregloEnCodigo, esArregloReferenciaArregloEnCodigo); retorno[0].codigo = "\n" + retorno[0].codigo; $.merge(arregloCuerpo, retorno); } ; for (var i = 0; i < posicionesIF.length; i++) { arreglo.splice.apply(arreglo, [posicionesIF[i], 0].concat(arregloCuerpo)); if (regla.esCondicion) arreglo.splice(posicionesIF[i] + arregloCuerpo.length, 0, { codigo: "\n" + tabsText + "}", filtro: regla.filtro }); for (var j = i; j < posicionesIF.length; j++) { posicionesIF[j] += arregloCuerpo.length; } ; } ; if (posicionesIF.length == 0) $.merge(arreglo, arregloCuerpo); return arreglo; } else { if (regla.esCondicion || posicionesIF.length > 0) { for (var i = 0; i < posicionesIF.length; i++) { if (newTabsTextFormula.length > 0) newTabsTextFormula = newTabsTextFormula.substring(0, newTabsTextFormula.length - 1); arreglo.splice(posicionesIF[i], 0, { codigo: "\n" + tabsText + newTabsTextFormula + "}", filtro: regla.filtro }); } ; } return arreglo; } } }, { key: "arregloCodigoReglaFormaOExcel", value: function arregloCodigoReglaFormaOExcel(regla, tabs, posicionVariable, posicionCampo, arreglo, arregloDeReglas, nombreReferenciaArregloEnCodigo, esArregloReferenciaArregloEnCodigo) { //a este metodo solo entra cuando la asignacion, max, min, ect es de solo variables formula o excel, o formulas solo es de excel o formulas var tabsText = ''; for (var i = 0; i < tabs; i++) { tabsText += '\t'; } ; var posicionesIF = []; var newTabsTextFormula = ''; if (!regla.esCondicion) { //asignaciones //si no es condicion, la variable de referencia se le agrega NU3V0 que hace referencia al objeto temporal vacio if (regla.operacion.indexOf('ASIG') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (arregloDeVariables[posicionVariable].esObjeto) { if (formula[0].fuenteDeDatos != undefined && formula[0].fuenteDeDatos[0].esValorManual) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0." + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + " = '" + formula[0].fuenteDeDatos[0].nombreVariable + "';", tipo: "ASIG" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0." + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + " = " + nombreReferenciaArregloEnCodigo + ";", tipo: "ASIG" }); } } else { if (formula[0].fuenteDeDatos != undefined && formula[0].fuenteDeDatos[0].esValorManual) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = '" + formula[0].fuenteDeDatos[0].nombreVariable + "';", tipo: "ASIG" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "ASIG" }); } } arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "ASIG" }); } } else if (regla.operacion.indexOf('MAX') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("date") == 0) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getTime() < " + nombreReferenciaArregloEnCodigo + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getDate() == 28)", tipo: "MAX" }); ; arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || arregloDeVariables[posicionVariable].atributos[posicionCampo].tipo.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 < " + nombreReferenciaArregloEnCodigo + ") {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); //arreglo.push({codigo: "\n\t\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 < " + nombreReferenciaArregloEnCodigo + ") {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } } } else if (regla.operacion.indexOf('MIN') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("date") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getTime() > " + nombreReferenciaArregloEnCodigo + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if( window['" + arregloDeVariables[posicionVariable].nombre + "'].length == 0)", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0.getDate() == 28)", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( isValidDate(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getTime() > " + nombreReferenciaArregloEnCodigo + ".getTime()) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0.getFullYear() == 1964 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getMonth() == 4 && " + arregloDeVariables[posicionVariable].nombre + "NU3V0.getDate() == 28) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = new Date(" + nombreReferenciaArregloEnCodigo + ");", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || arregloDeVariables[posicionVariable].atributos[posicionCampo].tipo.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 > " + nombreReferenciaArregloEnCodigo + " || " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); //arreglo.push({codigo: "\n\t\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 > " + nombreReferenciaArregloEnCodigo + ") {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "} else if( " + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 ) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + "}", tipo: "MAX" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } } } else if (regla.operacion.indexOf('PROM') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || arregloDeVariables[posicionVariable].atributos[posicionCampo].tipo.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( " + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 += " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0T0T4L++;", tipo: "MAX" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + "if ( " + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "MAX" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 += " + nombreReferenciaArregloEnCodigo + ";", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0T0T4L++;", tipo: "MAX" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "MAX" }); } } } } else if (regla.operacion.indexOf('AUTOSUM') == 0) { //trayendo formula correcta var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula.length > 0) { //este tipo de operacion siempre sera una formula con un elemento de formula if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1)", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "AUTOSUM" }); //arreglo.push({codigo: "\n\t\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = evaluate(" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 + " + nombreReferenciaArregloEnCodigo + ");", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "AUTOSUM" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1)", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = evaluate(" + arregloDeVariables[posicionVariable].nombre + "NU3V0 + " + nombreReferenciaArregloEnCodigo + ");", tipo: "AUTOSUM" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "AUTOSUM" }); } } } } else if (regla.operacion.indexOf('COUNT') == 0) { var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("int") == 0 || formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("decimal") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ") && !isNaN(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ") ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("varchar") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && " + nombreReferenciaArregloEnCodigo + ".length > 0) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && " + nombreReferenciaArregloEnCodigo + ".length > 0) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("bool") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && (" + nombreReferenciaArregloEnCodigo + " == true || " + nombreReferenciaArregloEnCodigo + " == false) ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && (" + nombreReferenciaArregloEnCodigo + " == true || " + nombreReferenciaArregloEnCodigo + " == false) ) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } else if (formula[0].fuenteDeDatos[0].tipoColumnaEnTabla.toLowerCase().localeCompare("date") == 0) { if (arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + ") {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + "NU3V0++;", tipo: "COUNT" }); //arreglo.push({codigo: "\n\t"+tabsText+"if( window['"+arregloDeVariables[posicionVariable].nombre+"'].length == 0)", tipo: "BANDERA_ASIG"}); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } else { arreglo.push({ codigo: tabsText + "if (" + nombreReferenciaArregloEnCodigo + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + ")) {", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + "if (" + arregloDeVariables[posicionVariable].nombre + "NU3V0 == -1 )", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0 = 0;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "NU3V0++;", tipo: "COUNT" }); arreglo.push({ codigo: "\n\t" + tabsText + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); arreglo.push({ codigo: "\n" + tabsText + "}", tipo: "COUNT" }); } } } else if (regla.operacion.indexOf('FORMULA') == 0) { var formula = arregloDeVariables[posicionVariable].atributos[posicionCampo].formulas.filter(function (formula) { return regla.formulaID == formula.ID; }); for (var i = 0; i < formula[0].fuenteDeDatos.length; i++) { var saltoLinea = '\n'; if (formula[0].fuenteDeDatos[i].operacion != undefined && formula[0].fuenteDeDatos[i].operacion.length > 0) { //if(formula[0].fuenteDeDatos[i].esFuenteDeDato) { //elemento formula es de conexion de tabla arreglo.push({ codigo: saltoLinea + tabsText + newTabsTextFormula + "if (window['" + formula[0].fuenteDeDatos[i].nombreColumnaEnTabla + "'] != undefined) {", tipo: "FORMULA" }); newTabsTextFormula += "\t"; arreglo.push({ codigo: saltoLinea + tabsText + newTabsTextFormula + "var " + formula[0].fuenteDeDatos[i].nombreVariable + " = window['" + formula[0].fuenteDeDatos[i].nombreColumnaEnTabla + "'];", tipo: "FORMULA" }); /*arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"console.log('"+formula[0].fuenteDeDatos[i].nombreVariable+"');", tipo: "FORMULA"}); arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"console.log("+formula[0].fuenteDeDatos[i].nombreVariable+");", tipo: "FORMULA"});*/ /*} else { if (!arregloDeVariables[posicionVariable].esObjeto) { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"if ("+nombreReferenciaArregloEnCodigo+" != undefined) {", tipo: "FORMULA"}); newTabsTextFormula += "\t"; //elemento formula es variable primitiva if(i > 0) { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"var "+formula[0].fuenteDeDatos[i].nombreVariable+" = "+nombreReferenciaArregloEnCodigo+";", tipo: "FORMULA"}); } else { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"var "+formula[0].fuenteDeDatos[i].nombreVariable+" = "+nombreReferenciaArregloEnCodigo+";", tipo: "FORMULA"}); } } else { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"if ("+nombreReferenciaArregloEnCodigo+"[x]."+arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre+" != undefined) {", tipo: "FORMULA"}); newTabsTextFormula += "\t"; if(i > 0) { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"var "+formula[0].fuenteDeDatos[i].nombreVariable+" = "+nombreReferenciaArregloEnCodigo+"[x]."+arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre+";", tipo: "FORMULA"}); } else { arreglo.push({codigo: saltoLinea+tabsText+newTabsTextFormula+"var "+formula[0].fuenteDeDatos[i].nombreVariable+" = "+nombreReferenciaArregloEnCodigo+"[x]."+arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre+";", tipo: "FORMULA"}); } } }*/ } } ; //arreglo.push({codigo: "\n\t\t"+tabsText+arregloDeVariables[posicionVariable].nombre+"NU3V0."+arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre+" = math.eval(formula[0].formula);"}); if (arregloDeVariables[posicionVariable].esObjeto) arreglo.push({ codigo: "\n" + tabsText + newTabsTextFormula + arregloDeVariables[posicionVariable].nombre + "NU3V0." + arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre + " = " + formula[0].formula + ";" });else arreglo.push({ codigo: "\n" + tabsText + newTabsTextFormula + arregloDeVariables[posicionVariable].nombre + "NU3V0 = evaluate(" + formula[0].formula + ");" }); arreglo.push({ codigo: "\n" + tabsText + newTabsTextFormula + arregloDeVariables[posicionVariable].nombre + "GU4RD4RV4L0R = true;", tipo: "BANDERA_ASIG" }); for (var i = formula[0].fuenteDeDatos.length; i > 0; i--) { posicionesIF.push(arreglo.length + i); } } } else { //condiciones if var arregloValoresAComparar = []; if (regla.valor.indexOf("LISTAID") == 0) {// } else if (regla.valor.indexOf("FECHA") == 0) { var fecha = regla.valor.substring(regla.valor.indexOf("[") + 1, regla.valor.lastIndexOf("]")); arregloValoresAComparar = ["new Date(" + fecha + ").getTime()"]; } else if (regla.valor.indexOf("TIEMPO") == 0) { var stringValores = regla.valor.substring(regla.valor.indexOf("[") + 1, regla.valor.lastIndexOf("]")); var diasAgregarCadena = stringValores.split(",")[0], mesesAgregarCadena = stringValores.split(",")[1], aniosAgregarCadena = stringValores.split(",")[2], futuro = stringValores.split(",")[3]; var diasAgregar = parseInt(diasAgregarCadena.substring(diasAgregarCadena.indexOf("=") + 1)), mesesAgregar = parseInt(mesesAgregarCadena.substring(mesesAgregarCadena.indexOf("=") + 1)), aniosAgregar = parseInt(aniosAgregarCadena.substring(aniosAgregarCadena.indexOf("=") + 1)); var esFuturo = true; if (futuro.localeCompare("FUTURO") == 0) esFuturo = true;else esFuturo = false; var hoy = new Date(); if (esFuturo) { hoy = this.addYears(hoy, aniosAgregar); hoy = this.addMonths(hoy, mesesAgregar); hoy = this.addDays(hoy, diasAgregar); } else { hoy = this.minusYears(hoy, aniosAgregar); hoy = this.minusMonths(hoy, mesesAgregar); hoy = this.minusDays(hoy, diasAgregar); } arregloValoresAComparar = ["new Date(" + hoy.getFullYear() + ", " + hoy.getMonth() + ", " + hoy.getDate() + ").getTime()"]; } else if (regla.valor.indexOf("MANUAL") == 0) { arregloValoresAComparar = [regla.valor.substring(regla.valor.indexOf("[") + 1, regla.valor.lastIndexOf("]"))]; } var nombreCampoDeArregloEnCodigo = ''; if (regla.esConexionTabla) { nombreCampoDeArregloEnCodigo = regla.nombreColumnaEnTabla; } else { nombreCampoDeArregloEnCodigo = arregloDeVariables[posicionVariable].atributos[posicionCampo].nombre; } var tamArreglo = arreglo.length; //for (var j = 0; j < tamArreglo; j++) { for (var i = 0; i < arregloValoresAComparar.length; i++) { var comparacion = ""; var inicioComparacion = ""; var operacion = ""; if (regla.operacion.localeCompare("ES_MENOR") == 0 && regla.valor.indexOf("TIEMPO") != 0) { operacion = "<"; } else if (regla.operacion.localeCompare("ES_MENOR_O_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") != 0) { operacion = "<="; } else if (regla.operacion.localeCompare("ES_MAYOR_O_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") != 0) { operacion = ">="; } else if (regla.operacion.localeCompare("ES_MAYOR") == 0 && regla.valor.indexOf("TIEMPO") != 0) { operacion = ">"; } else if (regla.operacion.localeCompare("ES_IGUAL") == 0) { operacion = "=="; } else if (regla.operacion.localeCompare("NO_ES_IGUAL") == 0) { operacion = "!="; } else if (regla.operacion.localeCompare("ES_MENOR") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = ">"; } else if (regla.operacion.localeCompare("ES_MENOR_O_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = ">="; } else if (regla.operacion.localeCompare("ES_MAYOR_O_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = "<="; } else if (regla.operacion.localeCompare("ES_MAYOR") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = "<"; } else if (regla.operacion.localeCompare("ES_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = "=="; } else if (regla.operacion.localeCompare("NO_ES_IGUAL") == 0 && regla.valor.indexOf("TIEMPO") == 0) { operacion = "!="; } if (regla.tipoCampoObjetivo.localeCompare("date") == 0) { if (regla.operacion.localeCompare("encuentra") == 0) {// } else if (regla.operacion.localeCompare("no_encuentra") == 0) {// } else { if (esArregloReferenciaArregloEnCodigo) { inicioComparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + ")"; comparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + ".getTime() " + operacion + " " + arregloValoresAComparar[i]; } else { inicioComparacion = nombreReferenciaArregloEnCodigo + " != undefined && isValidDate(" + nombreReferenciaArregloEnCodigo + ")"; comparacion = nombreReferenciaArregloEnCodigo + ".getTime() " + operacion + " " + arregloValoresAComparar[i]; } } } else if (regla.tipoCampoObjetivo.localeCompare("varchar") == 0) { if (regla.operacion.localeCompare("encuentra") == 0) {// } else if (regla.operacion.localeCompare("no_encuentra") == 0) {// } else { if (esArregloReferenciaArregloEnCodigo) { inicioComparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " != undefined"; comparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + ".localeCompare('" + arregloValoresAComparar[i] + "') " + operacion + " 0"; } else { inicioComparacion = nombreReferenciaArregloEnCodigo + " != undefined"; comparacion = nombreReferenciaArregloEnCodigo + ".localeCompare('" + arregloValoresAComparar[i] + "') " + operacion + " 0"; } } } else if (regla.tipoCampoObjetivo.localeCompare("int") == 0 || regla.tipoCampoObjetivo.localeCompare("decimal") == 0) { if (regla.operacion.localeCompare("encuentra") == 0) {// } else if (regla.operacion.localeCompare("no_encuentra") == 0) {// } else { if (esArregloReferenciaArregloEnCodigo) { inicioComparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + ")"; comparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " " + operacion + " " + arregloValoresAComparar[i]; } else { inicioComparacion = nombreReferenciaArregloEnCodigo + " != undefined && !isNaN(" + nombreReferenciaArregloEnCodigo + ")"; comparacion = nombreReferenciaArregloEnCodigo + " " + operacion + " " + arregloValoresAComparar[i]; } } } else if (regla.tipoCampoObjetivo.localeCompare("bit") == 0) { if (esArregloReferenciaArregloEnCodigo) { inicioComparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " != undefined"; comparacion = nombreReferenciaArregloEnCodigo + "[x]." + nombreCampoDeArregloEnCodigo + " " + operacion + " " + arregloValoresAComparar[i]; } else { inicioComparacion = nombreReferenciaArregloEnCodigo + " != undefined"; comparacion = nombreReferenciaArregloEnCodigo + " " + operacion + " " + arregloValoresAComparar[i]; } } if (i + 1 == arregloValoresAComparar.length) { comparacion += " ) {"; } if (i == 0) { //arreglo[j].codigo += comparacion; //arreglo.push({codigo: tabsText+"console.log("+nombreReferenciaArregloEnCodigo+"[x]);", tipo: "COMPARACION"}); //arreglo.push({codigo: '\n'+tabsText+"console.log( "+nombreReferenciaArregloEnCodigo+"[x]."+nombreCampoDeArregloEnCodigo+");", tipo: "COMPARACION"}); arreglo.push({ codigo: '\n' + tabsText + "if ( " + inicioComparacion + " && " + comparacion, tipo: "COMPARACION" }); } else { arreglo[arreglo.length - 1].codigo += " && " + comparacion; } } ; /*console.log("ENTROOO j"); };*/ posicionesIF.push(arreglo.length); } var cuerpo = arregloDeReglas.filter(function (object) { return object.reglaPadreID == regla.ID; }); if (cuerpo.length > 0) { var arregloCuerpo = []; for (var i = 0; i < cuerpo.length; i++) { /*var cuantasTabs = tabs; if(regla.esCondicion) cuantasTabs++;*/ var retorno = this.arregloCodigoReglaFormaOExcel(cuerpo[i], tabs + 1, posicionVariable, posicionCampo, [], arregloDeReglas, nombreReferenciaArregloEnCodigo), esArregloReferenciaArregloEnCodigo; retorno[0].codigo = "\n" + retorno[0].codigo; $.merge(arregloCuerpo, retorno); } ; for (var i = 0; i < posicionesIF.length; i++) { arreglo.splice.apply(arreglo, [posicionesIF[i], 0].concat(arregloCuerpo)); if (regla.esCondicion) arreglo.splice(posicionesIF[i] + arregloCuerpo.length, 0, { codigo: "\n" + tabsText + "}", filtro: regla.filtro }); for (var j = i; j < posicionesIF.length; j++) { posicionesIF[j] += arregloCuerpo.length; } ; } ; if (posicionesIF.length == 0) $.merge(arreglo, arregloCuerpo); return arreglo; } else { if (regla.esCondicion || posicionesIF.length > 0) { for (var i = 0; i < posicionesIF.length; i++) { if (newTabsTextFormula.length > 0) newTabsTextFormula = newTabsTextFormula.substring(0, newTabsTextFormula.length - 1); arreglo.splice(posicionesIF[i], 0, { codigo: "\n" + tabsText + newTabsTextFormula + "}", filtro: regla.filtro }); } ; } return arreglo; } } }, { key: "isValidDate", value: function isValidDate(fecha) { if (Object.prototype.toString.call(fecha) === "[object Date]") { if (isNaN(fecha.getTime())) { //alert("Ingrese una fecha valida."); return false; } else { return true; } } else { //alert("Ingrese una fecha valida."); return false; } } }, { key: "existeOperacion", value: function existeOperacion(operacion) { if (operacion.localeCompare("COUNT") == 0 || operacion.localeCompare("MAX") == 0 || operacion.localeCompare("MIN") == 0 || operacion.localeCompare("DATE") == 0 || operacion.localeCompare("MONTH") == 0 || operacion.localeCompare("YEAR") == 0 || operacion.localeCompare("PROM") == 0 || operacion.localeCompare("AUTOSUM") == 0 || operacion.localeCompare("SUM") == 0) { return true; } return false; } }, { key: "guardarOperacionSQL", value: function guardarOperacionSQL(arreglo, campo, valorAInsertar) { if (arreglo.length != undefined) { // es coleccion for (var i = 0; i < arreglo.length; i++) { arreglo[i][campo] = valorAInsertar; } ; } else { // no es coleccion arreglo[campo] = valorAInsertar; } } //elementoFormula: objeto elementoFormula }, { key: "codigoElementosFormula", value: function codigoElementosFormula(elementoFormula, tabSpaces, objetoEnTabla, instanciacion) { var columnasDeTablaSeleccionadas = this.getColumnasDeTablaSeleccionadas(elementoFormula); if (elementoFormula.operacion.length == 0 && columnasDeTablaSeleccionadas.length == 1) { this.codigoElementosFormulaAsignacion(); } else if (elementoFormula.operacion.length > 0 && columnasDeTablaSeleccionadas.length == 1) { this.codigoElementosFormulaAsignacionOperacion(); } else { this.codigoElementosFormulaGlobal(); } } }, { key: "codigoElementosFormulaAsignacion", value: function codigoElementosFormulaAsignacion(elementoFormula, tabSpaces, objetoEnTabla, instanciacion) { var cadenaRetorno = ''; if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("date") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("MAX") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\tif(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + '.getTime() > window[' + instanciacion + '].getTime() && (window[' + instanciacion + '].getDate() != 28 && window[' + instanciacion + '].getMonth() != 5 && window[' + instanciacion + '].getFullYear() != 1964) ) {'; cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t} else if (window[' + instanciacion + '].getDate() == 28 && window[' + instanciacion + '].getMonth() == 5 && window[' + instanciacion + '].getFullYear() == 1964) {'; //valor nulo cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t}'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.localeCompare("MIN") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\tif(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + '.getTime() < window[' + instanciacion + '].getTime() && (window[' + instanciacion + '].getDate() != 28 && window[' + instanciacion + '].getMonth() != 5 && window[' + instanciacion + '].getFullYear() != 1964) ) {'; cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t} else if (window[' + instanciacion + '].getDate() == 28 && window[' + instanciacion + '].getMonth() == 5 && window[' + instanciacion + '].getFullYear() == 1964) {'; //valor nulo cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t}'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.localeCompare("DIA") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.localeCompare("MES") == 0) {} else if (elementoFormula.fuenteDato.operacion.localeCompare("AÑO") == 0) {} else if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.length == 0) {} } else if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("bool") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } } else if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("bool") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } } else if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("cadena") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } } } }, { key: "codigoElementosFormulaAsignacionOperacion", value: function codigoElementosFormulaAsignacionOperacion(elementoFormula, tabSpaces, objetoEnTabla, instanciacion) { var cadenaRetorno = ''; if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("date") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("MAX") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\tif(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + '.getTime() > window[' + instanciacion + '].getTime() && (window[' + instanciacion + '].getDate() != 28 && window[' + instanciacion + '].getMonth() != 5 && window[' + instanciacion + '].getFullYear() != 1964) ) {'; cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t} else if (window[' + instanciacion + '].getDate() == 28 && window[' + instanciacion + '].getMonth() == 5 && window[' + instanciacion + '].getFullYear() == 1964) {'; //valor nulo cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t}'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.localeCompare("MIN") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\tif(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + '.getTime() < window[' + instanciacion + '].getTime() && (window[' + instanciacion + '].getDate() != 28 && window[' + instanciacion + '].getMonth() != 5 && window[' + instanciacion + '].getFullYear() != 1964) ) {'; cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t} else if (window[' + instanciacion + '].getDate() == 28 && window[' + instanciacion + '].getMonth() == 5 && window[' + instanciacion + '].getFullYear() == 1964) {'; //valor nulo cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t}'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.localeCompare("DIA") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.localeCompare("MES") == 0) {} else if (elementoFormula.fuenteDato.operacion.localeCompare("AÑO") == 0) {} else if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.length == 0) {} } else if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("bool") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } } else if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("bool") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } } else if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("cadena") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } } } }, { key: "codigoElementosFormulaGlobal", value: function codigoElementosFormulaGlobal(elementoFormula, tabSpaces, objetoEnTabla, instanciacion) { var cadenaRetorno = ''; if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("date") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("MAX") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\tif(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + '.getTime() > window[' + instanciacion + '].getTime() && (window[' + instanciacion + '].getDate() != 28 && window[' + instanciacion + '].getMonth() != 5 && window[' + instanciacion + '].getFullYear() != 1964) ) {'; cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t} else if (window[' + instanciacion + '].getDate() == 28 && window[' + instanciacion + '].getMonth() == 5 && window[' + instanciacion + '].getFullYear() == 1964) {'; //valor nulo cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t}'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.localeCompare("MIN") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\tif(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + '.getTime() < window[' + instanciacion + '].getTime() && (window[' + instanciacion + '].getDate() != 28 && window[' + instanciacion + '].getMonth() != 5 && window[' + instanciacion + '].getFullYear() != 1964) ) {'; cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t} else if (window[' + instanciacion + '].getDate() == 28 && window[' + instanciacion + '].getMonth() == 5 && window[' + instanciacion + '].getFullYear() == 1964) {'; //valor nulo cadenaRetorno += '\n' + tabSpaces + '\t\twindow[' + instanciacion + '] = new Date(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ')'; cadenaRetorno += '\n' + tabSpaces + '\t}'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.localeCompare("DIA") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.localeCompare("MES") == 0) {} else if (elementoFormula.fuenteDato.operacion.localeCompare("AÑO") == 0) {} else if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } else if (elementoFormula.fuenteDato.operacion.length == 0) {} } else if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("bool") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } } else if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("bool") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } } else if (elementoFormula.fuenteDato.tipoColumnaEnTabla.localeCompare("cadena") == 0) { if (elementoFormula.fuenteDato.operacion.localeCompare("COUNT") == 0) { cadenaRetorno += tabSpaces + 'if(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ' != undefined && this.isValidDate(' + objetoEnTabla + '.' + elementoFormula.fuenteDato.nombreColumnaEnTabla + ') ) {'; cadenaRetorno += '\n' + tabSpaces + '\twindow[' + instanciacion + ']++'; cadenaRetorno += '\n' + tabSpaces + '}'; } } } }, { key: "iniciarCalculoIndicadores", value: function iniciarCalculoIndicadores() { this.guardarVariablesCalculadas(); } }, { key: "guardarVariablesCalculadas", value: function guardarVariablesCalculadas() { for (var a = 0; a < arregloDeVariables.length; a++) { if (arregloDeVariables[a].realizarCalculo && this.props.idVariable == arregloDeVariables[a].ID) { this.verificarSiExisteVariableEnResultadosHistoricos(arregloDeVariables[a]); } } ; } }, { key: "verificarSiExisteVariableEnResultadosHistoricos", value: function verificarSiExisteVariableEnResultadosHistoricos(variable) { var _this23 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from ResultadosNombreVariables where nombreVariable = '" + variable.nombre + "' and finVigencia = '1964-05-28'", function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { if (result.recordset.length == 0) { _this23.crearTablaDeResultadoNombreVariable(variable); } else { _this23.guardarResultadosNombreVariable(variable, result.recordset[0].inicioVigencia); } }); } }); }); // fin transaction } }, { key: "crearTablaDeResultadoNombreVariable", value: function crearTablaDeResultadoNombreVariable(variable) { var _this24 = this; //NOMBRE TABLA: NOMBREVARIABLE_AÑOVIGENCIA_MESVIGENCIA_DIAVIGENCIA_HORAVIGENCIA_MINUTOSVIGENCIA_SEGUNDOSVIGENCIA //VIGENCIA: DIA CREACION var hoy = new Date(); var textoCreacionTabla = 'CREATE TABLE ' + variable.nombre + '_' + hoy.getFullYear() + '_' + (hoy.getMonth() + 1) + '_' + hoy.getDate() + '_' + hoy.getHours() + '_' + hoy.getMinutes() + '_' + hoy.getSeconds() + ' ( ID int IDENTITY(1,1) PRIMARY KEY, '; for (var i = 0; i < variable.atributos.length; i++) { if (i != 0) textoCreacionTabla += ', '; if (variable.atributos[i].tipo.localeCompare("decimal") == 0) { textoCreacionTabla += variable.atributos[i].nombre + ' decimal(22,4)'; } else if (variable.atributos[i].tipo.localeCompare("int") == 0) { textoCreacionTabla += variable.atributos[i].nombre + ' int'; } else if (variable.atributos[i].tipo.localeCompare("varchar") == 0) { textoCreacionTabla += variable.atributos[i].nombre + ' varchar(1000)'; } else if (variable.atributos[i].tipo.localeCompare("bit") == 0) { textoCreacionTabla += variable.atributos[i].nombre + ' bit'; } else if (variable.atributos[i].tipo.localeCompare("date") == 0) { textoCreacionTabla += variable.atributos[i].nombre + ' date'; } } ; textoCreacionTabla += ', f3ch4Gu4rd4do date )'; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query(textoCreacionTabla, function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { //console.log("Tabla "+variable.nombre+'_'+hoy.getFullYear()+'_'+hoy.getMonth()+'_'+hoy.getDate()+'_'+hoy.getHours()+'_'+hoy.getMinutes()+'_'+hoy.getSeconds()+" creada."); _this24.crearResultadoNombreVariable(variable, hoy); }); } }); }); // fin transaction } }, { key: "crearResultadoNombreVariable", value: function crearResultadoNombreVariable(variable, hoy) { var _this25 = this; var mes = hoy.getMonth() + 1; if (mes.toString().length == 1) mes = '0' + mes; var dia = hoy.getDate(); if (dia.toString().length == 1) dia = '0' + dia; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("insert into ResultadosNombreVariables (nombreVariable, inicioVigencia, finVigencia) values ('" + variable.nombre + "', '" + hoy.getFullYear() + '-' + mes + '-' + dia + " " + hoy.getHours() + ":" + hoy.getMinutes() + ":" + hoy.getSeconds() + "', '1964-05-28')", function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { _this25.guardarResultadosNombreVariable(variable, hoy); }); } }); }); // fin transaction } }, { key: "guardarResultadosNombreVariable", value: function guardarResultadosNombreVariable(variable, fechaNombreTabla) { var _this26 = this; alert("Calculo realizado con exito."); var hoy = new Date(); var textoInsertPrincipio = 'INSERT INTO ' + variable.nombre + '_' + fechaNombreTabla.getFullYear() + '_' + (fechaNombreTabla.getMonth() + 1) + '_' + fechaNombreTabla.getDate() + '_' + fechaNombreTabla.getHours() + '_' + fechaNombreTabla.getMinutes() + '_' + fechaNombreTabla.getSeconds() + ' ( '; for (var i = 0; i < variable.atributos.length; i++) { if (i != 0) textoInsertPrincipio += ', '; textoInsertPrincipio += variable.atributos[i].nombre; } ; textoInsertPrincipio += ', f3ch4Gu4rd4do ) values ( '; var instruccionSQLBorrar = "DELETE FROM " + variable.nombre + "_" + fechaNombreTabla.getFullYear() + "_" + (fechaNombreTabla.getMonth() + 1) + "_" + fechaNombreTabla.getDate() + "_" + fechaNombreTabla.getHours() + "_" + fechaNombreTabla.getMinutes() + "_" + fechaNombreTabla.getSeconds() + " WHERE f3ch4Gu4rd4do = '" + hoy.getFullYear() + "-" + (hoy.getMonth() + 1) + "-" + hoy.getDate() + "' "; this.borrarVariable(instruccionSQLBorrar); if (variable.esInstruccionSQL || variable.esColeccion) { if (variable.esInstruccionSQL || variable.esObjeto) { for (var i = 0; i < window[variable.nombre].length; i++) { var instruccionSQLFinal = textoInsertPrincipio; for (var j = 0; j < variable.atributos.length; j++) { if (j > 0) instruccionSQLFinal += ', '; if (variable.atributos[j].tipo.localeCompare("decimal") == 0) { instruccionSQLFinal += window[variable.nombre][i][variable.atributos[j].nombre]; } else if (variable.atributos[j].tipo.localeCompare("int") == 0) { instruccionSQLFinal += window[variable.nombre][i][variable.atributos[j].nombre]; } else if (variable.atributos[j].tipo.localeCompare("varchar") == 0) { instruccionSQLFinal += "'" + window[variable.nombre][i][variable.atributos[j].nombre] + "'"; } else if (variable.atributos[j].tipo.localeCompare("bit") == 0) { instruccionSQLFinal += "'" + window[variable.nombre][i][variable.atributos[j].nombre] + "'"; } else if (variable.atributos[j].tipo.localeCompare("date") == 0) { instruccionSQLFinal += "'" + window[variable.nombre][i][variable.atributos[j].nombre].getFullYear() + "-" + (window[variable.nombre][i][variable.atributos[j].nombre].getMonth() + 1) + "-" + window[variable.nombre][i][variable.atributos[j].nombre].getDate() + "'"; } } ; instruccionSQLFinal += ", '" + hoy.getFullYear() + "-" + (hoy.getMonth() + 1) + "-" + hoy.getDate() + "' )"; var self = this; setTimeout(function () { self.guardarVariable(instruccionSQLFinal, variable, 'variable', hoy); }, 600); } ; } else if (!variable.esObjeto) { var _loop = function _loop() { var instruccionSQLFinal = textoInsertPrincipio; for (j = 0; j < variable.atributos.length; j++) { if (j > 0) instruccionSQLFinal += ', '; if (variable.atributos[j].tipo.localeCompare("decimal") == 0) { instruccionSQLFinal += window[variable.nombre][i]; } else if (variable.atributos[j].tipo.localeCompare("int") == 0) { instruccionSQLFinal += window[variable.nombre][i]; } else if (variable.atributos[j].tipo.localeCompare("varchar") == 0) { instruccionSQLFinal += "'" + window[variable.nombre][i] + "'"; } else if (variable.atributos[j].tipo.localeCompare("bit") == 0) { instruccionSQLFinal += "'" + window[variable.nombre][i] + "'"; } else if (variable.atributos[j].tipo.localeCompare("date") == 0) { instruccionSQLFinal += "'" + window[variable.nombre][i].getFullYear() + "-" + (window[variable.nombre][i].getMonth() + 1) + "-" + window[variable.nombre][i].getDate() + "'"; } } ; instruccionSQLFinal += ", '" + hoy.getFullYear() + "-" + (hoy.getMonth() + 1) + "-" + hoy.getDate() + "' )"; self = _this26; setTimeout(function () { self.guardarVariable(instruccionSQLFinal, variable, 'variable', hoy); }, 600); }; for (var i = 0; i < window[variable.nombre].length; i++) { var j; var self; _loop(); } ; } } else { if (variable.esObjeto) { var _instruccionSQLFinal = textoInsertPrincipio; for (var j = 0; j < variable.atributos.length; j++) { if (j > 0) _instruccionSQLFinal += ', '; if (variable.atributos[j].tipo.localeCompare("decimal") == 0) { _instruccionSQLFinal += window[variable.nombre][variable.atributos[j].nombre]; } else if (variable.atributos[j].tipo.localeCompare("int") == 0) { _instruccionSQLFinal += window[variable.nombre][variable.atributos[j].nombre]; } else if (variable.atributos[j].tipo.localeCompare("varchar") == 0) { _instruccionSQLFinal += "'" + window[variable.nombre][variable.atributos[j].nombre] + "'"; } else if (variable.atributos[j].tipo.localeCompare("bit") == 0) { _instruccionSQLFinal += "'" + window[variable.nombre][variable.atributos[j].nombre] + "'"; } else if (variable.atributos[j].tipo.localeCompare("date") == 0) { _instruccionSQLFinal += "'" + window[variable.nombre][variable.atributos[j].nombre].getFullYear() + "-" + (window[variable.nombre][variable.atributos[j].nombre].getMonth() + 1) + "-" + window[variable.nombre][variable.atributos[j].nombre].getDate() + "'"; } } ; _instruccionSQLFinal += ", '" + hoy.getFullYear() + "-" + (hoy.getMonth() + 1) + "-" + hoy.getDate() + "' )"; var self = this; setTimeout(function () { self.guardarVariable(_instruccionSQLFinal, variable, 'variable', hoy); }, 600); } else if (!variable.esObjeto) { var instruccionSQLFinal = textoInsertPrincipio; for (var j = 0; j < variable.atributos.length; j++) { if (j > 0) instruccionSQLFinal += ', '; if (variable.atributos[j].tipo.localeCompare("decimal") == 0) { instruccionSQLFinal += window[variable.nombre]; } else if (variable.atributos[j].tipo.localeCompare("int") == 0) { instruccionSQLFinal += window[variable.nombre]; } else if (variable.atributos[j].tipo.localeCompare("varchar") == 0) { instruccionSQLFinal += "'" + window[variable.nombre] + "'"; } else if (variable.atributos[j].tipo.localeCompare("bit") == 0) { instruccionSQLFinal += "'" + window[variable.nombre] + "'"; } else if (variable.atributos[j].tipo.localeCompare("date") == 0) { instruccionSQLFinal += "'" + window[variable.nombre].getFullYear() + "-" + (window[variable.nombre].getMonth() + 1) + "-" + window[variable.nombre].getDate() + "'"; } } ; instruccionSQLFinal += ", '" + hoy.getFullYear() + "-" + (hoy.getMonth() + 1) + "-" + hoy.getDate() + "' )"; var self = this; setTimeout(function () { self.guardarVariable(instruccionSQLFinal, variable, 'variable', hoy); }, 600); } } var tipoVar = ''; if (variable.esInstruccionSQL) { tipoVar = 'SQL'; } else if (variable.esObjeto) { tipoVar = 'objeto'; } else if (variable.esObjeto) { tipoVar = 'objeto'; } this.saveBitacora(hoy, "Usuario: " + this.props.userName + " realizo el cálculo para la variable tipo variable: " + variable.nombre); } }, { key: "guardarVariable", value: function guardarVariable(instruccionSQL, variable, tabla, hoy) { var _this27 = this; /*console.log('instruccionSQLFinal'); console.log(instruccionSQL);*/ var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query(instruccionSQL, function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { if (variable.periodicidad.localeCompare("-1") != 0) _this27.verificarPeriodicidadGuardar(variable, tabla, hoy); }); } }); }); // fin transaction } }, { key: "borrarVariable", value: function borrarVariable(instruccionSQL) { var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query(instruccionSQL, function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) {}); } }); }); // fin transaction } }, { key: "verificarPeriodicidadGuardar", value: function verificarPeriodicidadGuardar(variable, tabla, hoy) { var _this28 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from PeriodicidadCalculo where variableID = " + variable.ID + " and tablaVariable = '" + tabla + "'", function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { if (result.recordset.length > 0) { _this28.updatePeriodicidad(variable, tabla, hoy); } else { _this28.guardarPeriodicidad(variable, tabla, hoy); } }); } }); }); // fin transaction } }, { key: "updatePeriodicidad", value: function updatePeriodicidad(variable, tabla, hoy) { var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("update PeriodicidadCalculo set fechaUltimoCalculo = '" + hoy.getFullYear() + "-" + (hoy.getMonth() + 1) + "-" + hoy.getDate() + "' where variableID = " + variable.ID + " and tablaVariable = '" + tabla + "'", function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) {}); } }); }); // fin transaction } }, { key: "guardarPeriodicidad", value: function guardarPeriodicidad(variable, tabla, hoy) { var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("insert into PeriodicidadCalculo (variableID, tablaVariable, fechaInicio, fechaUltimoCalculo) values (" + variable.ID + ", '" + tabla + "', '" + hoy.getFullYear() + "-" + (hoy.getMonth() + 1) + "-" + hoy.getDate() + "', '" + hoy.getFullYear() + "-" + (hoy.getMonth() + 1) + "-" + hoy.getDate() + "') ", function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) {}); } }); }); // fin transaction } /* EXCEL */ }, { key: "crearVariablesExcel", value: function crearVariablesExcel() { for (var i = 0; i < arregloDeExcel.length; i++) { var workbook = null; workbook = _xlsxStyle["default"].readFile(arregloDeExcel[i].ubicacionArchivo); if (workbook != null) { for (var j = 0; j < arregloDeExcel[i].variables.length; j++) { for (var k = 0; k < workbook.SheetNames.length; k++) { if (workbook.SheetNames[k].localeCompare(arregloDeExcel[i].variables[j].nombreHoja) == 0) { break; } } ; var sheet = workbook.Sheets[workbook.SheetNames[k]]; if (sheet != null && arregloDeExcel[i].variables[j].realizarCalculo) { try { var arregloPosicionesExcel = this.getArregloPosicionesExcel(arregloDeExcel[i].variables[j].celdas); if (arregloPosicionesExcel.length == 1) { var variable; if (arregloDeExcel[i].variables[j].tipo.localeCompare('numero') == 0 && sheet[arregloPosicionesExcel[0]].t.localeCompare('n') == 0 && sheet[arregloPosicionesExcel[0]].w.indexOf('/') == -1) { variable = parseFloat(sheet[arregloPosicionesExcel[0]].v); } else if (arregloDeExcel[i].variables[j].tipo.localeCompare('bit') == 0 && sheet[arregloPosicionesExcel[0]].t.localeCompare('b') == 0 && sheet[arregloPosicionesExcel[0]].w.indexOf('/') == -1) { variable = sheet[arregloPosicionesExcel[0]].v; } else if (arregloDeExcel[i].variables[j].tipo.localeCompare('varchar') == 0 && sheet[arregloPosicionesExcel[0]].t.localeCompare('s') == 0 && sheet[arregloPosicionesExcel[0]].w.indexOf('/') == -1) { variable = sheet[arregloPosicionesExcel[0]].v; } else if (arregloDeExcel[i].variables[j].tipo.localeCompare('date') == 0 && (sheet[arregloPosicionesExcel[0]].t.localeCompare('d') == 0 || sheet[arregloPosicionesExcel[0]].t.localeCompare('n') == 0) && sheet[arregloPosicionesExcel[0]].w.indexOf('/') != -1) { variable = new Date(sheet[arregloPosicionesExcel[0]].w); } window[arregloDeExcel[i].variables[j].nombre] = variable; } else if (arregloPosicionesExcel.length > 1 && arregloDeExcel[i].variables[j].operacion.localeCompare("ASIG") == 0) { if (arregloDeExcel[i].variables[j].tipo.localeCompare('numero') == 0) { window[arregloDeExcel[i].variables[j].nombre] = []; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = parseFloat(sheet[arregloPosicionesExcel[k]].v); window[arregloDeExcel[i].variables[j].nombre].push(variable); } ; } else if (arregloDeExcel[i].variables[j].tipo.localeCompare('bit') == 0) { window[arregloDeExcel[i].variables[j].nombre] = []; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = sheet[arregloPosicionesExcel[k]].v; window[arregloDeExcel[i].variables[j].nombre].push(variable); } ; } else if (arregloDeExcel[i].variables[j].tipo.localeCompare('varchar') == 0) { window[arregloDeExcel[i].variables[j].nombre] = []; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = sheet[arregloPosicionesExcel[k]].v; window[arregloDeExcel[i].variables[j].nombre].push(variable); } ; } else if (arregloDeExcel[i].variables[j].tipo.localeCompare('date') == 0) { window[arregloDeExcel[i].variables[j].nombre] = []; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = new Date(sheet[arregloPosicionesExcel[k]].w); window[arregloDeExcel[i].variables[j].nombre].push(variable); } ; } } else if (arregloPosicionesExcel.length > 1) { if (arregloDeExcel[i].variables[j].tipo.localeCompare("numero") == 0 && arregloDeExcel[i].variables[j].operacion.localeCompare("SUM") == 0) { var suma = 0; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = parseFloat(sheet[arregloPosicionesExcel[k]].v); suma += variable; } ; window[arregloDeExcel[i].variables[j].nombre] = suma; } else if (arregloDeExcel[i].variables[j].tipo.localeCompare("numero") == 0 && arregloDeExcel[i].variables[j].operacion.localeCompare("PROM") == 0) { var suma = 0; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = parseFloat(sheet[arregloPosicionesExcel[k]].v); suma += variable; } ; var promedio = suma / arregloPosicionesExcel.length; window[arregloDeExcel[i].variables[j].nombre] = promedio; } else if (arregloDeExcel[i].variables[j].operacion.localeCompare("MAX") == 0) { if (arregloDeExcel[i].variables[j].tipo.localeCompare("numero") == 0) { var max = 0; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = parseFloat(sheet[arregloPosicionesExcel[k]].v); if (k == 0) max = variable; if (max < variable) { max = variable; } } ; window[arregloDeExcel[i].variables[j].nombre] = max; } if (arregloDeExcel[i].variables[j].tipo.localeCompare("date") == 0) { var max = new Date(1900, 1, 1); for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = new Date(sheet[arregloPosicionesExcel[k]].w); if (k == 0) max = variable; if (max.getTime() < variable.getTime()) { max = variable; } } ; window[arregloDeExcel[i].variables[j].nombre] = max; } } else if (arregloDeExcel[i].variables[j].operacion.localeCompare("MIN") == 0) { if (arregloDeExcel[i].variables[j].tipo.localeCompare("numero") == 0) { var min = 0; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = parseFloat(sheet[arregloPosicionesExcel[k]].v); if (k == 0) min = variable; if (min > variable) { min = variable; } } ; window[arregloDeExcel[i].variables[j].nombre] = min; } if (arregloDeExcel[i].variables[j].tipo.localeCompare("date") == 0) { var min = new Date(1900, 1, 1); for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = new Date(sheet[arregloPosicionesExcel[k]].w); if (k == 0) min = variable; if (min.getTime() > variable.getTime()) { min = variable; } } ; window[arregloDeExcel[i].variables[j].nombre] = min; } } else if (arregloDeExcel[i].variables[j].operacion.localeCompare("COUNT") == 0) { if (arregloDeExcel[i].variables[j].tipo.localeCompare("numero") == 0) { var count = 0; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = parseFloat(sheet[arregloPosicionesExcel[k]].v); if (!isNaN(variable)) count++; } ; window[arregloDeExcel[i].variables[j].nombre] = count; } if (arregloDeExcel[i].variables[j].tipo.localeCompare("date") == 0) { var count = 0; for (var k = 0; k < arregloPosicionesExcel.length; k++) { //var variable = new Date(sheet[arregloPosicionesExcel[k]].v); var variable; // if (sheet[arregloPosicionesExcel[k]].t.localeCompare('d') == 0) { variable = new Date(sheet[arregloPosicionesExcel[k]].w); } /* else { var partes; if(sheet[arregloPosicionesExcel[k]].w.indexOf("-") > -1) { partes = sheet[arregloPosicionesExcel[k]].w.split("-"); } else if(sheet[arregloPosicionesExcel[k]].w.indexOf("/") > -1) { partes = sheet[arregloPosicionesExcel[k]].w.split("/"); } var dia, mes, anio, entro = false; if(partes.length != undefined && partes.length == 3) { if(partes[0].length == 4) { anio = partes[0]; mes = partes[1]; dia = partes[2]; } else if(partes[2].length == 4) { anio = partes[2]; mes = partes[1]; dia = partes[0]; } } if(entro) { variable = new Date(parseInt(anio), parseInt(mes), parseInt(dia)); } else { arregloDeErroresExcel.push({nombre: arregloDeExcel[i].variables[j].nombre, ID: arregloDeExcel[i].variables[j].ID }); alert("problema para leer fecha: "+arregloDeExcel[i].variables[j].nombre); } }*/ // if (this.isValidDate(variable)) count++; } ; window[arregloDeExcel[i].variables[j].nombre] = count; } if (arregloDeExcel[i].variables[j].tipo.localeCompare("varchar") == 0) { var count = 0; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = sheet[arregloPosicionesExcel[k]].v; if (variable.length > 0) count++; } ; window[arregloDeExcel[i].variables[j].nombre] = count; } if (arregloDeExcel[i].variables[j].tipo.localeCompare("bit") == 0) { var count = 0; for (var k = 0; k < arregloPosicionesExcel.length; k++) { var variable = sheet[arregloPosicionesExcel[k]].v; if (variable != undefined) count++; } ; window[arregloDeExcel[i].variables[j].nombre] = count; } } } } catch (err) { console.log(err.message); arregloDeErroresExcel.push({ nombre: arregloDeExcel[i].variables[j].nombre, ID: arregloDeExcel[i].variables[j].ID }); } } else { if (arregloDeExcel[i].variables[j].realizarCalculo) { arregloDeErroresExcel.push({ nombre: arregloDeExcel[i].variables[j].nombre, ID: arregloDeExcel[i].variables[j].ID }); alert("problema para leer la hoja: " + arregloDeExcel[i].variables[j].nombreHoja); } } } ; } else { alert("problema para leer archivo: " + arregloDeExcel[i].ubicacionArchivo); } } ; } }, { key: "getArregloPosicionesExcel", value: function getArregloPosicionesExcel(celdas) { var celdaInicial = this.getObjetoLetraNumeroCelda(celdas.split(":")[0]); var celdaFinal; if (celdas.indexOf(":") >= 0) celdaFinal = this.getObjetoLetraNumeroCelda(celdas.split(":")[1]); var arregloPosicionesExcel = []; if (celdaFinal != undefined) { if (celdaInicial.columna.toLowerCase().localeCompare(celdaFinal.columna.toLowerCase()) == 0) { //misma columnas, se recorre para abajo en el archivo var filaInicial = parseInt(celdaInicial.fila); var filaFinal = parseInt(celdaFinal.fila); for (var i = filaInicial; i <= filaFinal; i++) { arregloPosicionesExcel.push(celdaInicial.columna.toUpperCase() + i); } ; } else { //misma fila, se recorre horizontal en el archivo var numeroColumnaInicial = this.toColumnNumber(celdaInicial.columna.toUpperCase()); var numeroColumnaFinal = this.toColumnNumber(celdaFinal.columna.toUpperCase()); for (var i = numeroColumnaInicial; i <= numeroColumnaFinal; i++) { arregloPosicionesExcel.push(toColumnLetter(i) + celdaInicial.fila); } ; } } else { //solo se selecciono una celda arregloPosicionesExcel.push(celdaInicial.columna + celdaInicial.fila); } return arregloPosicionesExcel; } }, { key: "getObjetoLetraNumeroCelda", value: function getObjetoLetraNumeroCelda(celda) { var columna = ''; var fila = ''; for (var i = 0; i < celda.length; i++) { if (this.esLetra(celda.charAt(i))) { columna += celda.charAt(i); } else { break; } } ; fila = celda.substring(i); var celdaObjeto = { columna: columna, fila: fila }; return celdaObjeto; } }, { key: "esLetra", value: function esLetra(caracter) { if (caracter.toLowerCase().localeCompare("a") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("b") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("c") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("d") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("e") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("f") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("g") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("h") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("i") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("j") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("k") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("l") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("m") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("n") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("o") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("p") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("q") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("r") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("s") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("t") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("u") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("v") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("w") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("x") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("y") == 0) { return true; } else if (caracter.toLowerCase().localeCompare("z") == 0) { return true; } } }, { key: "toColumnLetter", value: function toColumnLetter(num) { for (var ret = '', a = 1, b = 26; (num -= a) >= 0; a = b, b *= 26) { ret = String.fromCharCode(parseInt(num % b / a) + 65) + ret; } return ret; } }, { key: "toColumnNumber", value: function toColumnNumber(val) { var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', i, j, result = 0; for (i = 0, j = val.length - 1; i < val.length; i += 1, j -= 1) { result += Math.pow(base.length, j) * (base.indexOf(val[i]) + 1); } return result; } /* FORMAS */ }, { key: "formaCrearVariable", value: function formaCrearVariable(id, nombreVariable, tipoVariable, nombreSiguiente, indexSiguiente, tipoSiguiente, inputSiguiente) { //variableForma if (tipoVariable.localeCompare("numero") == 0) { try { var variable = parseFloat($("#variableForma" + id).val()); window[nombreVariable] = variable; } catch (err) { console.log(err.message); arregloDeErroresFormas.push({ nombre: nombreVariable, ID: id }); } } else if (tipoVariable.localeCompare("bit") == 0) { try { if ($("#variableForma" + id).is(':checked')) { window[nombreVariable] = true; } else { window[nombreVariable] = false; } } catch (err) { console.log(err.message); arregloDeErroresFormas.push({ nombre: nombreVariable, ID: id }); } } else if (tipoVariable.localeCompare("varchar") == 0) { try { var variable = $("#variableForma" + id).val(); window[nombreVariable] = variable; } catch (err) { console.log(err.message); arregloDeErroresFormas.push({ nombre: nombreVariable, ID: id }); } } else if (tipoVariable.localeCompare("date") == 0) { try { var variable = $("#variableForma" + id).datepicker('getDate'); window[nombreVariable] = variable; } catch (err) { console.log(err.message); arregloDeErroresFormas.push({ nombre: nombreVariable, ID: id }); } } if (nombreSiguiente != undefined) { this.updateForm(nombreSiguiente, indexSiguiente, tipoSiguiente, inputSiguiente); } else { this.closeModalForma(); this.iniciarHilo(); } } }, { key: "iniciarMostrarFormas", value: function iniciarMostrarFormas() { var _this29 = this; arregloHTMLFormas = []; for (var i = 0; i < arregloDeFormas.length; i++) { if (arregloDeFormas[i].tipo.localeCompare("numero") == 0) { if (i + 1 < arregloDeFormas.length) { (function () { var nombre = arregloDeFormas[i].nombre; var id = arregloDeFormas[i].ID; var tipo = arregloDeFormas[i].tipo; var indexSiguiente = i + 1; var nombreSiguiente = arregloDeFormas[i + 1].nombre; var idSiguiente = arregloDeFormas[i + 1].ID; var tipoSiguiente = arregloDeFormas[i + 1].tipo; arregloHTMLFormas[i] = _react["default"].createElement("div", { style: { width: "100%" } }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "variableForma" + arregloDeFormas[i].ID, className: "col-form-label" }, "Valor:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("input", { id: "variableForma" + arregloDeFormas[i].ID, type: "text", className: "form-control form-control-sm" }))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "text-center", style: { width: "100%" } }, _react["default"].createElement("a", { href: "#", className: "btn btn-brand active", onClick: function onClick() { return _this29.formaCrearVariable(id, nombre, tipo, nombreSiguiente, indexSiguiente, tipoSiguiente, "variableForma" + idSiguiente); } }, "Guardar")), _react["default"].createElement("br", null)); })(); } else { (function () { var nombre = arregloDeFormas[i].nombre; var id = arregloDeFormas[i].ID; var tipo = arregloDeFormas[i].tipo; arregloHTMLFormas[i] = _react["default"].createElement("div", { style: { width: "100%" } }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "variableForma" + arregloDeFormas[i].ID, className: "col-form-label" }, "Valor:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("input", { id: "variableForma" + arregloDeFormas[i].ID, type: "text", className: "form-control form-control-sm" }))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "text-center", style: { width: "100%" } }, _react["default"].createElement("a", { href: "#", className: "btn btn-brand active", onClick: function onClick() { return _this29.formaCrearVariable(id, nombre, tipo); } }, "Guardar")), _react["default"].createElement("br", null)); })(); } } else if (arregloDeFormas[i].tipo.localeCompare("bit") == 0) { if (i + 1 < arregloDeFormas.length) { (function () { var nombre = arregloDeFormas[i].nombre; var id = arregloDeFormas[i].ID; var tipo = arregloDeFormas[i].tipo; var indexSiguiente = i + 1; var nombreSiguiente = arregloDeFormas[i + 1].nombre; var idSiguiente = arregloDeFormas[i + 1].ID; var tipoSiguiente = arregloDeFormas[i + 1].tipo; arregloHTMLFormas[i] = _react["default"].createElement("div", { style: { width: "100%" } }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "variableForma" + arregloDeFormas[i].ID, className: "col-form-label" }, "Valor:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group" }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "switch-button switch-button-bool", style: { margin: "0 auto", display: "block" } }, _react["default"].createElement("input", { type: "checkbox", defaultChecked: true, name: "guardarFuenteDato", id: "variableForma" + arregloDeFormas[i].ID }), _react["default"].createElement("span", null, _react["default"].createElement("label", { htmlFor: "guardarFuenteDato" }))))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "text-center", style: { width: "100%" } }, _react["default"].createElement("a", { href: "#", className: "btn btn-brand active", onClick: function onClick() { return _this29.formaCrearVariable(id, nombre, tipo, nombreSiguiente, indexSiguiente, tipoSiguiente, "variableForma" + idSiguiente); } }, "Guardar")), _react["default"].createElement("br", null)); })(); } else { (function () { var nombre = arregloDeFormas[i].nombre; var id = arregloDeFormas[i].ID; var tipo = arregloDeFormas[i].tipo; arregloHTMLFormas[i] = _react["default"].createElement("div", { style: { width: "100%" } }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "variableForma" + arregloDeFormas[i].ID, className: "col-form-label" }, "Valor:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group" }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "switch-button switch-button-bool", style: { margin: "0 auto", display: "block" } }, _react["default"].createElement("input", { type: "checkbox", defaultChecked: true, name: "guardarFuenteDato", id: "variableForma" + arregloDeFormas[i].ID }), _react["default"].createElement("span", null, _react["default"].createElement("label", { htmlFor: "guardarFuenteDato" }))))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "text-center", style: { width: "100%" } }, _react["default"].createElement("a", { href: "#", className: "btn btn-brand active", onClick: function onClick() { return _this29.formaCrearVariable(id, nombre, tipo); } }, "Guardar")), _react["default"].createElement("br", null)); })(); } } else if (arregloDeFormas[i].tipo.localeCompare("varchar") == 0) { if (i + 1 < arregloDeFormas.length) { (function () { var nombre = arregloDeFormas[i].nombre; var id = arregloDeFormas[i].ID; var tipo = arregloDeFormas[i].tipo; var indexSiguiente = i + 1; var nombreSiguiente = arregloDeFormas[i + 1].nombre; var idSiguiente = arregloDeFormas[i + 1].ID; var tipoSiguiente = arregloDeFormas[i + 1].tipo; arregloHTMLFormas[i] = _react["default"].createElement("div", { style: { width: "100%" } }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "variableForma" + arregloDeFormas[i].ID, className: "col-form-label" }, "Valor:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("input", { id: "variableForma" + arregloDeFormas[i].ID, type: "text", className: "form-control form-control-sm" }))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "text-center", style: { width: "100%" } }, _react["default"].createElement("a", { href: "#", className: "btn btn-brand active", onClick: function onClick() { return _this29.formaCrearVariable(id, nombre, tipo, nombreSiguiente, indexSiguiente, tipoSiguiente, "variableForma" + idSiguiente); } }, "Guardar")), _react["default"].createElement("br", null)); })(); } else { (function () { var nombre = arregloDeFormas[i].nombre; var id = arregloDeFormas[i].ID; var tipo = arregloDeFormas[i].tipo; arregloHTMLFormas[i] = _react["default"].createElement("div", { style: { width: "100%" } }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "variableForma" + arregloDeFormas[i].ID, className: "col-form-label" }, "Valor:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("input", { id: "variableForma" + arregloDeFormas[i].ID, type: "text", className: "form-control form-control-sm" }))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "text-center", style: { width: "100%" } }, _react["default"].createElement("a", { href: "#", className: "btn btn-brand active", onClick: function onClick() { return _this29.formaCrearVariable(id, nombre, tipo); } }, "Guardar")), _react["default"].createElement("br", null)); })(); } } else if (arregloDeFormas[i].tipo.localeCompare("date") == 0) { if (i + 1 < arregloDeFormas.length) { (function () { var nombre = arregloDeFormas[i].nombre; var id = arregloDeFormas[i].ID; var tipo = arregloDeFormas[i].tipo; var indexSiguiente = i + 1; var nombreSiguiente = arregloDeFormas[i + 1].nombre; var idSiguiente = arregloDeFormas[i + 1].ID; var tipoSiguiente = arregloDeFormas[i + 1].tipo; arregloHTMLFormas[i] = _react["default"].createElement("div", { style: { width: "100%" } }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "variableForma" + arregloDeFormas[i].ID, className: "col-form-label" }, "Valor:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("div", { className: "row", style: { display: "flex", justifyContent: "center" } }, _react["default"].createElement("div", { id: "variableForma" + arregloDeFormas[i].ID, className: "center-block" })))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "text-center", style: { width: "100%" } }, _react["default"].createElement("a", { href: "#", className: "btn btn-brand active", onClick: function onClick() { return _this29.formaCrearVariable(id, nombre, tipo, nombreSiguiente, indexSiguiente, tipoSiguiente, "variableForma" + idSiguiente); } }, "Guardar")), _react["default"].createElement("br", null)); })(); } else { (function () { var nombre = arregloDeFormas[i].nombre; var id = arregloDeFormas[i].ID; var tipo = arregloDeFormas[i].tipo; arregloHTMLFormas[i] = _react["default"].createElement("div", { style: { width: "100%" } }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "variableForma" + arregloDeFormas[i].ID, className: "col-form-label" }, "Valor:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("div", { className: "row", style: { display: "flex", justifyContent: "center" } }, _react["default"].createElement("div", { id: "variableForma" + arregloDeFormas[i].ID, className: "center-block" })))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "text-center", style: { width: "100%" } }, _react["default"].createElement("a", { href: "#", className: "btn btn-brand active", onClick: function onClick() { return _this29.formaCrearVariable(id, nombre, tipo); } }, "Guardar")), _react["default"].createElement("br", null)); })(); } } } ; console.log('arregloHTMLFormas'); console.log(arregloHTMLFormas); this.updateForm(arregloDeFormas[0].nombre, 0, arregloDeFormas[0].tipo, "variableForma" + arregloDeFormas[0].ID); } }, { key: "updateForm", value: function updateForm(titulo, index, tipo, idInput) { this.setState({ showModalForma: true, tituloVariableForma: "Variable: " + titulo, htmlForma: arregloHTMLFormas[index] }, this.loadFechas(tipo, idInput)); } }, { key: "loadFechas", value: function loadFechas(tipo, idInput) { if (tipo.localeCompare("date") == 0) { setTimeout(function () { $('#' + idInput).datepicker({ format: "dd-mm-yyyy", todayHighlight: true, viewMode: "days", minViewMode: "days", language: 'es' }); }, 250); } } }, { key: "closeModalForma", value: function closeModalForma() { this.setState({ showModalForma: false }); } }, { key: "verificarExistenciaErroresExcel", value: function verificarExistenciaErroresExcel(variable) { for (var i = 0; i < arregloDeErroresExcel.length; i++) { if (arregloDeErroresExcel[i].nombre.localeCompare(variable.nombre) == 0 && arregloDeErroresExcel[i].ID == variable.ID) { return true; } } ; return false; } }, { key: "verificarExistenciaErroresForma", value: function verificarExistenciaErroresForma(variable) { for (var i = 0; i < arregloDeErroresFormas.length; i++) { if (arregloDeErroresFormas[i].nombre.localeCompare(variable.nombre) == 0 && arregloDeErroresFormas[i].ID == variable.ID) { return true; } } ; return false; } }, { key: "verificarExistenciaErroresVariable", value: function verificarExistenciaErroresVariable(variable) { for (var i = 0; i < arregloDeErroresVariables.length; i++) { if (arregloDeErroresVariables[i].nombre.localeCompare(variable.nombre) == 0 && arregloDeErroresVariables[i].ID == variable.ID) { return true; } } ; return false; } /* ************************************** ************************************** FIN CALCULO CODIGO ************************************** ************************************** */ }, { key: "getUsuarios", value: function getUsuarios() { var _this30 = this; var transaction = new _mssql["default"].Transaction(this.props.pool); transaction.begin(function (err) { var rolledBack = false; transaction.on('rollback', function (aborted) { rolledBack = true; }); var request = new _mssql["default"].Request(transaction); request.query("select * from Usuarios", function (err, result) { if (err) { console.log(err); if (!rolledBack) { transaction.rollback(function (err) {}); } } else { transaction.commit(function (err) { _this30.setState({ usuarios: result.recordset }); }); } }); }); // fin transaction } }, { key: "goToTimeline", value: function goToTimeline(esExcel, idVariableExcel, nombreVariable, esColeccion) { this.props.changeStateFirstTimeToTrue(); this.props.goToTimeline(esExcel, idVariableExcel, nombreVariable, esColeccion); } }, { key: "render", value: function render() { var _this31 = this; return _react["default"].createElement("div", null, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "nombreFuenteDato", className: "col-form-label" }, "Nombre de Variable")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("input", { id: "nombreFuenteDato", defaultValue: this.props.nombreVariable, onKeyUp: this.props.actualizarNombreVariable, type: "text", className: "form-control form-control-sm" }))), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "idFormula", className: "col-form-label" }, "Identificador de la Variable en F\xF3rmula")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("input", { id: "idFormula", defaultValue: this.props.idFormula, onKeyUp: this.props.actualizarIdFormula, type: "text", className: "form-control form-control-sm" }))), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3" }, _react["default"].createElement("label", { htmlFor: "descripcionFuenteDato", className: "col-form-label" }, "Descripci\xF3n de Variable:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9" }, _react["default"].createElement("textarea", { defaultValue: this.props.descripcionVariable, onKeyUp: this.props.actualizarDescripcionVariable, className: "form-control", id: "descripcionFuenteDato", rows: "3" }))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "esInstruccionSQL", className: "col-form-label" }, "Tipo de C\xE1lculo:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group" }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "switch-button-sql switch-button-yesno", style: { margin: "0 auto", display: "block" } }, _react["default"].createElement("input", { type: "checkbox", defaultChecked: this.state.mostrarInstruccionSQL, name: "esInstruccionSQL", id: "esInstruccionSQL", onClick: this.cambioInstruccionSQL }), _react["default"].createElement("span", null, _react["default"].createElement("label", { htmlFor: "esInstruccionSQL" }))))), !this.state.mostrarInstruccionSQL ? _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "esColeccion", className: "col-form-label" }, "Tipo de Conjunto:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group" }, _react["default"].createElement("div", { className: "switch-button-coleccion switch-button-yesno", style: { margin: "0 auto", display: "block" } }, _react["default"].createElement("input", { type: "checkbox", defaultChecked: this.state.mostrarEsColeccion, name: "esColeccion", id: "esColeccion", onClick: this.cambioAColeccion }), _react["default"].createElement("span", null, _react["default"].createElement("label", { htmlFor: "esColeccion" }))))) : null, !this.state.mostrarInstruccionSQL ? _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "esObjetoFuenteDato", className: "col-form-label" }, "Tipo de Variable:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group" }, _react["default"].createElement("div", { className: "switch-button-variable switch-button-yesno", style: { margin: "0 auto", display: "block" } }, _react["default"].createElement("input", { type: "checkbox", defaultChecked: this.state.mostrarEsObjeto, name: "esObjetoFuenteDato", id: "esObjetoFuenteDato", onClick: this.cambioAObjeto }), _react["default"].createElement("span", null, _react["default"].createElement("label", { htmlFor: "esObjetoFuenteDato" }))))) : null, _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "periodicidad", className: "col-form-label" }, "Periodicidad")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group" }, _react["default"].createElement("select", { id: "periodicidad", defaultValue: this.props.periodicidadVariable, onChange: this.actualizarPeriodicidad, className: "form-control" }, _react["default"].createElement("option", { value: "-1" }, "Ninguno"), periodicidad.map(function (periodicidad, i) { return _react["default"].createElement("option", { value: periodicidad.nombre, key: periodicidad.nombre }, periodicidad.nombre); })))), this.state.valorPeriodicidad.localeCompare("-1") != 0 ? _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "esObjetoFuenteDato", className: "col-form-label" }, "Fecha de Inicio de C\xE1lculo:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group" }, _react["default"].createElement("input", { type: "text", className: "form-control", id: "fecha" }))) : null, _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "responsable", className: "col-form-label" }, "Nombre Encargado")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group" }, _react["default"].createElement("select", { id: "responsable", defaultValue: this.props.responsableVariable, onChange: this.props.actualizarNombreEncargado, className: "form-control" }, _react["default"].createElement("option", { value: "-1" }, "Ninguno"), this.state.usuarios.map(function (usuario, i) { return _react["default"].createElement("option", { value: usuario.ID, key: usuario.ID }, usuario.usuario); })))), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "categoriaVariable", className: "col-form-label" }, "Categor\xEDa de Variable")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("input", { id: "categoriaVariable", defaultValue: this.props.categoriaVariable, onKeyUp: this.props.actualizarCategoriaVariable, type: "text", className: "form-control form-control-sm" }))), _react["default"].createElement("div", { className: "row", style: { width: "100%" } }, _react["default"].createElement("div", { className: "col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3 form-group" }, _react["default"].createElement("label", { htmlFor: "guardarFuenteDato", className: "col-form-label" }, "Guardar Valores Obtenidos en Base de Datos:")), _react["default"].createElement("div", { className: "col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9 form-group" }, _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "switch-button switch-button-yesno", style: { margin: "0 auto", display: "block" } }, _react["default"].createElement("input", { type: "checkbox", defaultChecked: true, name: "guardarFuenteDato", id: "guardarFuenteDato" }), _react["default"].createElement("span", null, _react["default"].createElement("label", { htmlFor: "guardarFuenteDato" }))))), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { width: "100%", border: "1px solid #e6e6f2" } }, _react["default"].createElement(_FuenteDatoVariableAtributos["default"], { atributos: this.props.atributos, titulo: this.state.titulo, mostrarInstruccionSQL: this.state.mostrarInstruccionSQL, nombreCampoNuevoAtributosVario: this.props.nombreCampoNuevoAtributosVario, tipoNuevaVariable: this.props.tipoNuevaVariable, actualizarNombreCampoNuevoAtributosVario: this.props.actualizarNombreCampoNuevoAtributosVario, crearAtributoVariable: this.props.crearAtributoVariable, eliminarAtributoVariable: this.props.eliminarAtributoVariable, modificarNombreVariable: this.props.modificarNombreVariable, mostrarEsObjeto: this.state.mostrarEsObjeto, goToCreateConditions: this.props.goToCreateConditions, goCreateVariableFieldSQL: this.props.goCreateVariableFieldSQL, tipoVariable: this.state.tipoVariable, changeStateFirstTimeToFalse: this.props.changeStateFirstTimeToFalse })), _react["default"].createElement("br", null), _react["default"].createElement("div", { className: "row", style: { display: "flex", alignItems: "center", justifyContent: "center" } }, _react["default"].createElement("a", { href: "#", className: "btn btn-brand active", onClick: this.props.guardarVariable }, "Modificar Variable"), this.props.tipoVariableOriginal.localeCompare("variable") == 0 ? _react["default"].createElement("a", { href: "#", className: "btn btn-secondary active", style: { marginLeft: "10px" }, onClick: function onClick() { return _this31.props.eliminarVariable(true); } }, "Eliminar Variable") : null, this.props.tipoVariableOriginal.localeCompare("variable") == 0 ? _react["default"].createElement("a", { href: "#", className: "btn btn-primary active", style: { marginLeft: "10px" }, onClick: this.traerArchivosExcel }, "Realizar C\xE1lculo") : null, this.props.tipoVariableOriginal.localeCompare("variable") == 0 ? _react["default"].createElement("a", { href: "#", className: "btn btn-info active", style: { marginLeft: "10px" }, onClick: function onClick() { return _this31.goToTimeline(false); } }, "Historial de Variable") : null), _react["default"].createElement("br", null)); } }]); return FuenteDatoVariable; }(_react["default"].Component); /*<div className={"row"} style={{width: "100%", display: this.state.mostrarEsObjeto ? "" : "none"}}> <div className={"col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3"}> <label htmlFor="objetoPadreID" className="col-form-label">Variable Padre:</label> </div> <div className={"col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9"}> <select className="form-control" id="objetoPadreID"> <option value="-1">Ninguno</option> </select> </div> </div>*/ exports["default"] = FuenteDatoVariable; //# sourceMappingURL=FuenteDatoVariable.js.map
#!/usr/bin/python """ Starter code for the validation mini-project. The first step toward building your POI identifier! Start by loading/formatting the data After that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit from sklearn.tree import DecisionTreeClassifier from sklearn.cross_validation import train_test_split data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### first element is our labels, any added elements are predictor ### features. Keep this the same for the mini-project, but you'll ### have a different feature list when you do the final project. features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) labels_train, labels_test, features_train, features_test = train_test_split(labels, features, test_size=0.3, random_state=42) ### it's all yours from here forward! clf = DecisionTreeClassifier() clf.fit(features_train, labels_train)
"""Handles conversion between the sets of regions used in the `SosModel` """ from collections import namedtuple from rtree import index # type: ignore from shapely.geometry import mapping, shape # type: ignore from shapely.validation import explain_validity # type: ignore from smif.convert.adaptor import Adaptor from smif.convert.register import NDimensionalRegister, ResolutionSet __author__ = "Will Usher, Tom Russell" __copyright__ = "Will Usher, Tom Russell" __license__ = "mit" class RegionAdaptor(Adaptor): """Convert regions, assuming uniform distributions where necessary """ def generate_coefficients(self, from_spec, to_spec): """Generate conversion coefficients for spatial dimensions Assumes that the Coordinates elements contain a 'feature' key whose value corresponds to a GDAL vector feature represented as a dict, for example as returned by a `fiona` reader. """ # find dimensions to convert from_dim, to_dim = self.get_convert_dims(from_spec, to_spec) # get dimension coordinates from_coords = from_spec.dim_coords(from_dim) to_coords = to_spec.dim_coords(to_dim) # create RegionSets from Coordinates from_set = RegionSet(from_dim, from_coords.elements) to_set = RegionSet(to_dim, to_coords.elements) # register RegionSets register = NDimensionalRegister() register.register(from_set) register.register(to_set) # use NDimensionalRegister to get coefficients coefficients = register.get_coefficients(from_dim, to_dim) return coefficients NamedShape = namedtuple('NamedShape', ['name', 'shape']) class RegionSet(ResolutionSet): """Hold a set of regions, spatially indexed for ease of lookup when constructing conversion matrices. Parameters ---------- set_name : str Name to use as identifier for this set of regions elements: iterable Iterable (probably a list or a reader handle) of fiona feature records e.g. the 'features' entry of a GeoJSON collection """ def __init__(self, set_name, elements): super().__init__() self.name = set_name self._regions = [] self.data = [e['feature'] for e in elements] self._idx = index.Index() for pos, region in enumerate(self._regions): self._idx.insert(pos, region.shape.bounds) @property def data(self): return self._regions @data.setter def data(self, value): names = {} for region in value: name = region['properties']['name'] if name in names: msg = "Region set must have uniquely named regions - {} duplicated" raise AssertionError(msg.format(name)) names[name] = True self._regions.append( NamedShape( name, shape(region['geometry']) ) ) def get_entry_names(self): return [region.name for region in self.data] def as_features(self): """Get the regions as a list of feature dictionaries Returns ------- list A list of GeoJSON-style dicts """ return [ { 'type': 'Feature', 'geometry': mapping(region.shape), 'properties': { 'name': region.name } } for region in self._regions ] def centroids_as_features(self): """Get the region centroids as a list of feature dictionaries Returns ------- list A list of GeoJSON-style dicts, with Point features corresponding to region centroids """ return [ { 'type': 'Feature', 'geometry': mapping(region.shape.centroid), 'properties': { 'name': region.name } } for region in self._regions ] def intersection(self, to_entry): """Return the set of regions intersecting with the bounds of `to_entry` """ bounds = to_entry.shape.bounds return [x for x in self._idx.intersection(bounds)] def get_proportion(self, from_idx, entry_b): """Calculate the proportion of shape a that intersects with shape b """ entry_a = self.data[from_idx] if self.check_valid_shape(entry_a.shape): if self.check_valid_shape(entry_b.shape): intersection = entry_a.shape.intersection(entry_b.shape) return intersection.area / entry_a.shape.area else: raise RuntimeError("Shape {} is not valid".format(entry_b.name)) else: raise RuntimeError("Shape {} from {} is not valid".format(entry_a.name, self.name)) def check_valid_shape(self, shape): if not shape.is_valid: validity = explain_validity(shape) print("Shape is not valid. Explanation: %s", validity) return False else: return True @staticmethod def get_bounds(entry): return entry.shape.bounds @property def coverage(self): return sum([x.shape.area for x in self.data]) def __getitem__(self, key): return self._regions[key] def __len__(self): return len(self._regions)
"""Configuration file for Sphinx Documentation Generator.""" from os import path as os_path from sys import path as sys_path from toml import load as toml_load sys_path.insert(0, os_path.abspath("../src")) toml_path = "{}/pyproject.toml".format(os_path.abspath("..")) parsed_toml = toml_load(toml_path) project = parsed_toml["tool"]["poetry"]["name"] copyright = "2019, Tomer Figenblat" author = "Tomer Figenblat" version = parsed_toml["tool"]["poetry"]["version"] release = version extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", ] exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = "sphinx_rtd_theme" language = "en" show_authors = False linkcheck_anchors = True # sphinx.ext.todo configuration todo_include_todos = True
import magma as m from magma.simulator import PythonSimulator from magma.simulator.coreir_simulator import CoreIRSimulator from hwtypes import BitVector as BV def test_counter(): @m.sequential2() class Counter: def __init__(self): self.count = m.Register(m.UInt[16])() def __call__(self, inc : m.Bit) -> m.UInt[16]: if inc: self.count = self.count + 1 O = self.count return O print(repr(Counter)) sim = PythonSimulator(Counter, Counter.CLK) sim.set_value(Counter.inc, True) sim.evaluate() for i in range(4): assert sim.get_value(Counter.O) == i + 1 sim.advance_cycle() sim.set_value(Counter.inc, False) sim.evaluate() for i in range(4): assert sim.get_value(Counter.O) == 4 sim.advance_cycle() sim = CoreIRSimulator(Counter, Counter.CLK) sim.set_value(Counter.inc, 1) sim.evaluate() for i in range(4): assert sim.get_value(Counter.O) == BV[16](i + 1) sim.advance_cycle() sim.set_value(Counter.inc, 0) sim.evaluate() for i in range(4): assert sim.get_value(Counter.O) == BV[16](4) sim.advance_cycle() if __name__ == "__main__": test_counter()
/* * Copyright 2016 http://www.hswebframework.org * * 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. * */ //组件信息 var info = { groupId: "org.hswebframework.iot", artifactId: "user-server", version: "1.0-SNAPSHOT", website: "https://github.com/hs-web/hsweb-iot-cloud", author: "admin@hsweb.me", comment: "用户服务" }; var menus = [ { "u_id": "e9dc96d6b677cbae865670e6813f5e8b", "name": "系统设置", "parent_id": "-1", "permission_id": "", "path": "sOrB", "sort_index": 1, "describe": " ", "url": "", "icon": "fa fa-cogs", "status": 1 }, { "u_id": "f84b8dacb3ea07ecd811cfb869137b90", "name": "首页设置", "parent_id": "e9dc96d6b677cbae865670e6813f5e8b", "permission_id": "dashboard", "path": "sOrB-JOQv", "sort_index": 101, "describe": null, "url": "admin/dashboard/list.html", "icon": "fa fa-dashboard", "status": 1 }, { "u_id": "8db17b9ba28dd949c926b329af477a08", "name": "菜单管理", "parent_id": "e9dc96d6b677cbae865670e6813f5e8b", "permission_id": "menu", "path": "sOrB-i2ea", "sort_index": 102, "describe": null, "url": "admin/menu/list.html", "icon": "fa fa-navicon", "status": 1 }, { "u_id": "a52df62b69e21fd756523faf8f0bd986", "name": "权限管理", "parent_id": "e9dc96d6b677cbae865670e6813f5e8b", "permission_id": "permission,autz-setting", "path": "sOrB-X27v", "sort_index": 103, "describe": null, "url": "admin/permission/list.html", "icon": "fa fa-briefcase", "status": 1 }, { "u_id": "42fc4f83d12cc172e4690937eb15752a", "name": "角色管理", "parent_id": "e9dc96d6b677cbae865670e6813f5e8b", "permission_id": "role", "path": "sOrB-4ofL", "sort_index": 104, "describe": null, "url": "admin/role/list.html", "icon": "fa fa-users", "status": 1 }, { "u_id": "58eba1a4371dd3c0da24fac5da8cadc2", "name": "用户管理", "parent_id": "e9dc96d6b677cbae865670e6813f5e8b", "permission_id": "user", "path": "sOrB-Dz7b", "sort_index": 105, "describe": null, "url": "admin/user/list.html", "icon": "fa fa-user", "status": 1 }, { "u_id": "org-01", "name": "组织架构", "parent_id": "-1", "permission_id": "", "path": "a2o0", "sort_index": 2, "describe": " ", "url": "", "icon": "fa fa-sitemap", "status": 1 }, { "u_id": "org-01-01", "name": "机构管理", "parent_id": "org-01", "permission_id": "organizational", "path": "a2o0-iL0F", "sort_index": 201, "describe": null, "url": "admin/org/list.html", "icon": "fa fa-leaf", "status": 1 }, { "u_id": "org-01-02", "name": "综合设置", "parent_id": "org-01", "permission_id": "organizational,department,position,person", "path": "a2o0-A12e", "sort_index": 202, "describe": null, "url": "admin/org/manager/index.html", "icon": "fa fa-sitemap", "status": 1 }, { "u_id": "dev-01", "name": "开发人员工具", "parent_id": "-1", "permission_id": "", "path": "d010", "sort_index": 3, "describe": " ", "url": "", "icon": "fa fa-th-list", "status": 1 }, { "u_id": "code-gen", "name": "代码生成器", "parent_id": "dev-01", "permission_id": "file,database-manager,datasource", "path": "d010-jG1V", "sort_index": 301, "describe": null, "url": "admin/code-generator/index.html", "icon": "fa fa-desktop", "status": 1 }, { "u_id": "d9b7a672a63d214a1f063bbbacab89ee", "name": "人员管理", "parent_id": "org-01", "permission_id": "person", "path": "a2o0-vfXJ", "sort_index": 203, "describe": null, "url": "admin/org/person/list.html", "icon": "fa fa-vcard", "status": 1 } ]; var user = [ { "u_id": org.hswebframework.web.id.IDGenerator.MD5.generate(), "name": "超级管理员", "username": "admin", "password": "ba7a97be0609c22fa1d300691dfcd790", "salt": "HX8Hr5Yd", "status": 1, "last_login_ip": null, "last_login_time": null, "creator_id": "admin", "create_time": 1497160610259 }, { "u_id": org.hswebframework.web.id.IDGenerator.MD5.generate(), "name": "网关服务用户", "username": "gateway-server", "password": "ba7a97be0609c22fa1d300691dfcd790", "salt": "HX8Hr5Yd", "status": 1, "last_login_ip": null, "last_login_time": null, "creator_id": "admin", "create_time": 1497160610259 } ]; var autz_setting = [ { "u_id": org.hswebframework.web.id.IDGenerator.MD5.generate(), "type": "user", "setting_for": user[0].u_id, "describe": null, "status": 1 } ]; var autz_menu = []; menus.forEach(function (menu) { autz_menu.push({ u_id: org.hswebframework.web.id.IDGenerator.MD5.generate(), parent_id: "-1", menu_id: menu.u_id, status: 1, "setting_id": autz_setting[0].u_id, "path": "-" }); }); //版本更新信息 var versions = [ // { // version: "3.0.0", // upgrade: function (context) { // java.lang.System.out.println("更新到3.0.2了"); // } // } ]; var JDBCType = java.sql.JDBCType; function install(context) { var database = context.database; } function initialize(context) { var database = context.database; database.getTable("s_menu").createInsert().values(menus).exec(); database.getTable("s_autz_setting").createInsert().values(autz_setting).exec(); database.getTable("s_autz_menu").createInsert().values(autz_menu).exec(); database.getTable("s_user").createInsert().values(user).exec(); } //设置依赖 dependency.setup(info) .onInstall(install) .onUpgrade(function (context) { //更新时执行 var upgrader = context.upgrader; upgrader.filter(versions) .upgrade(function (newVer) { newVer.upgrade(context); }); }) .onUninstall(function (context) { //卸载时执行 }).onInitialize(initialize);
/* $("#vacation").inViewport(function(px){ if(px) $(this).css({ "opacity": 1, }); }); */ var open_dd = false; var temp_dd = false; var mobile = null; function dd_is_dropped() { if ( open_dd !== false ) { return true; } else { return false; } } function dd_clear_all() { open_dd = false; $(".nav-dd-playing").css({"display": "none", "opacity": 1}); $(".nav-dd-locations").css({"display": "none", "opacity": 1}); $(".nav-dd-rest").css({"display": "none", "opacity": 1}); } function dd_clear_last() { if ( ! dd_is_dropped() ) { return false; } temp_dd = open_dd $("."+open_dd).animate({ "opacity": 0 }, 500, function(){ $("."+temp_dd).css({"display": "none", "opacity": 1}); }); open_dd = false; } function ddshow(dd) { if ( is_mobile() ) { return false; } if ( dd_is_dropped() ) { dd_clear_all(); open_dd = dd; $("."+dd).css({"display": "block", "opacity": 1}); } else { open_dd = dd; $("."+dd).css({"display": "block", "opacity": 0}); $("."+dd).animate({ "opacity": 1 }, 500); } } function ddhide(dd) { open_dd = false; $("."+dd).animate({ "opacity": 0 }, 500, function(){ $("."+dd).css({"display": "none", "opacity": 1}); }); } $( document ).ready(function() { mobile = is_mobile(); $(".nav-dd-playing").mouseleave(function(e) { if ( e.relatedTarget.nodeName == "NAV" ) { return false; } ddhide('nav-dd-playing'); }); $(".nav-dd-locations").mouseleave(function(e) { if ( e.relatedTarget.nodeName == "NAV" ) { return false; } ddhide('nav-dd-locations'); }); $(".nav-dd-rest").mouseleave(function(e) { if ( e.relatedTarget.nodeName == "NAV" ) { return false; } ddhide('nav-dd-rest'); }); if ( mobile ) { $(".first-slide").attr("src", "assets/gfx/imdb/covers/predator.jpg"); $(".second-slide").attr("src", "assets/gfx/imdb/covers/house_with_a_clock_in_its_walls.jpg"); $(".third-slide").attr("src", "assets/gfx/imdb/covers/simple_favor.jpg"); $("#myCarousel").css("margin-top", $("nav").innerHeight() + "px" ); } $("#starter").css("margin-top", $("#myCarousel").height() ); $("#starter").inViewport(function(px){ if(px) $(this).animate({ "opacity": 1, }, 1000); }); $('.slicky').slick({ centerMode: true, centerPadding: '60px', slidesToShow: 5, responsive: [ { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 3 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 1 } } ] }); $("body").animate({ "opacity": 1 }); }); function is_mobile() { if ( $(window).width() < $(window).height() && $(window).width() < 800 ) { return true; } else { return false; } } $(window).resize(function(){ if ( is_mobile() === mobile ) { $("#starter").css("margin-top", $("#myCarousel").height() ); } else { $("body").css("display", "none"); location.reload(); } })
/* (c) 2007,2008 Andrei Nigmatulin */ #ifdef HAVE_TIMES #include <sys/times.h> #endif #include "fpm_config.h" #include "fpm.h" #include "fpm_php.h" #include "fpm_str.h" #include "fpm_clock.h" #include "fpm_conf.h" #include "fpm_trace.h" #include "fpm_php_trace.h" #include "fpm_process_ctl.h" #include "fpm_children.h" #include "fpm_scoreboard.h" #include "fpm_status.h" #include "fpm_stdio.h" #include "fpm_request.h" #include "fpm_log.h" #include "zlog.h" static const char *requests_stages[] = { [FPM_REQUEST_ACCEPTING] = "Idle", [FPM_REQUEST_READING_HEADERS] = "Reading headers", [FPM_REQUEST_INFO] = "Getting request informations", [FPM_REQUEST_EXECUTING] = "Running", [FPM_REQUEST_END] = "Ending", [FPM_REQUEST_FINISHED] = "Finishing", }; const char *fpm_request_get_stage_name(int stage) { return requests_stages[stage]; } void fpm_request_accepting() /* {{{ */ { struct fpm_scoreboard_proc_s *proc; struct timeval now; fpm_clock_get(&now); proc = fpm_scoreboard_proc_acquire(NULL, -1, 0); if (proc == NULL) { zlog(ZLOG_WARNING, "failed to acquire proc scoreboard"); return; } proc->request_stage = FPM_REQUEST_ACCEPTING; proc->tv = now; fpm_scoreboard_proc_release(proc); /* idle++, active-- */ fpm_scoreboard_update(1, -1, 0, 0, 0, 0, 0, FPM_SCOREBOARD_ACTION_INC, NULL); } /* }}} */ void fpm_request_reading_headers() /* {{{ */ { struct fpm_scoreboard_proc_s *proc; struct timeval now; clock_t now_epoch; #ifdef HAVE_TIMES struct tms cpu; #endif fpm_clock_get(&now); now_epoch = time(NULL); #ifdef HAVE_TIMES times(&cpu); #endif proc = fpm_scoreboard_proc_acquire(NULL, -1, 0); if (proc == NULL) { zlog(ZLOG_WARNING, "failed to acquire proc scoreboard"); return; } proc->request_stage = FPM_REQUEST_READING_HEADERS; proc->tv = now; proc->accepted = now; proc->accepted_epoch = now_epoch; #ifdef HAVE_TIMES proc->cpu_accepted = cpu; #endif proc->requests++; proc->request_uri[0] = '\0'; proc->request_method[0] = '\0'; proc->script_filename[0] = '\0'; proc->query_string[0] = '\0'; proc->auth_user[0] = '\0'; proc->content_length = 0; fpm_scoreboard_proc_release(proc); /* idle--, active++, request++ */ fpm_scoreboard_update(-1, 1, 0, 0, 1, 0, 0, FPM_SCOREBOARD_ACTION_INC, NULL); } /* }}} */ void fpm_request_info() /* {{{ */ { struct fpm_scoreboard_proc_s *proc; char *request_uri = fpm_php_request_uri(); char *request_method = fpm_php_request_method(); char *script_filename = fpm_php_script_filename(); char *query_string = fpm_php_query_string(); char *auth_user = fpm_php_auth_user(); size_t content_length = fpm_php_content_length(); struct timeval now; fpm_clock_get(&now); proc = fpm_scoreboard_proc_acquire(NULL, -1, 0); if (proc == NULL) { zlog(ZLOG_WARNING, "failed to acquire proc scoreboard"); return; } proc->request_stage = FPM_REQUEST_INFO; proc->tv = now; if (request_uri) { strlcpy(proc->request_uri, request_uri, sizeof(proc->request_uri)); } if (request_method) { strlcpy(proc->request_method, request_method, sizeof(proc->request_method)); } if (query_string) { strlcpy(proc->query_string, query_string, sizeof(proc->query_string)); } if (auth_user) { strlcpy(proc->auth_user, auth_user, sizeof(proc->auth_user)); } proc->content_length = content_length; /* if cgi.fix_pathinfo is set to "1" and script cannot be found (404) the sapi_globals.request_info.path_translated is set to NULL */ if (script_filename) { strlcpy(proc->script_filename, script_filename, sizeof(proc->script_filename)); } fpm_scoreboard_proc_release(proc); } /* }}} */ void fpm_request_executing() /* {{{ */ { struct fpm_scoreboard_proc_s *proc; struct timeval now; fpm_clock_get(&now); proc = fpm_scoreboard_proc_acquire(NULL, -1, 0); if (proc == NULL) { zlog(ZLOG_WARNING, "failed to acquire proc scoreboard"); return; } proc->request_stage = FPM_REQUEST_EXECUTING; proc->tv = now; fpm_scoreboard_proc_release(proc); } /* }}} */ void fpm_request_end(void) /* {{{ */ { struct fpm_scoreboard_proc_s *proc; struct timeval now; #ifdef HAVE_TIMES struct tms cpu; #endif size_t memory = zend_memory_peak_usage(1); fpm_clock_get(&now); #ifdef HAVE_TIMES times(&cpu); #endif proc = fpm_scoreboard_proc_acquire(NULL, -1, 0); if (proc == NULL) { zlog(ZLOG_WARNING, "failed to acquire proc scoreboard"); return; } proc->request_stage = FPM_REQUEST_FINISHED; proc->tv = now; timersub(&now, &proc->accepted, &proc->duration); #ifdef HAVE_TIMES timersub(&proc->tv, &proc->accepted, &proc->cpu_duration); proc->last_request_cpu.tms_utime = cpu.tms_utime - proc->cpu_accepted.tms_utime; proc->last_request_cpu.tms_stime = cpu.tms_stime - proc->cpu_accepted.tms_stime; proc->last_request_cpu.tms_cutime = cpu.tms_cutime - proc->cpu_accepted.tms_cutime; proc->last_request_cpu.tms_cstime = cpu.tms_cstime - proc->cpu_accepted.tms_cstime; #endif proc->memory = memory; fpm_scoreboard_proc_release(proc); fpm_stdio_flush_child(); } /* }}} */ void fpm_request_finished() /* {{{ */ { struct fpm_scoreboard_proc_s *proc; struct timeval now; fpm_clock_get(&now); proc = fpm_scoreboard_proc_acquire(NULL, -1, 0); if (proc == NULL) { zlog(ZLOG_WARNING, "failed to acquire proc scoreboard"); return; } proc->request_stage = FPM_REQUEST_FINISHED; proc->tv = now; fpm_scoreboard_proc_release(proc); } /* }}} */ void fpm_request_check_timed_out(struct fpm_child_s *child, struct timeval *now, int terminate_timeout, int slowlog_timeout) /* {{{ */ { struct fpm_scoreboard_proc_s proc, *proc_p; proc_p = fpm_scoreboard_proc_acquire(child->wp->scoreboard, child->scoreboard_i, 1); if (!proc_p) { zlog(ZLOG_WARNING, "failed to acquire scoreboard"); return; } proc = *proc_p; fpm_scoreboard_proc_release(proc_p); #if HAVE_FPM_TRACE if (child->slow_logged.tv_sec) { if (child->slow_logged.tv_sec != proc.accepted.tv_sec || child->slow_logged.tv_usec != proc.accepted.tv_usec) { child->slow_logged.tv_sec = 0; child->slow_logged.tv_usec = 0; } } #endif if (proc.request_stage > FPM_REQUEST_ACCEPTING && proc.request_stage < FPM_REQUEST_END) { char purified_script_filename[sizeof(proc.script_filename)]; struct timeval tv; timersub(now, &proc.accepted, &tv); #if HAVE_FPM_TRACE if (child->slow_logged.tv_sec == 0 && slowlog_timeout && proc.request_stage == FPM_REQUEST_EXECUTING && tv.tv_sec >= slowlog_timeout) { str_purify_filename(purified_script_filename, proc.script_filename, sizeof(proc.script_filename)); child->slow_logged = proc.accepted; child->tracer = fpm_php_trace; fpm_trace_signal(child->pid); zlog(ZLOG_WARNING, "[pool %s] child %d, script '%s' (request: \"%s %s%s%s\") executing too slow (%d.%06d sec), logging", child->wp->config->name, (int) child->pid, purified_script_filename, proc.request_method, proc.request_uri, (proc.query_string[0] ? "?" : ""), proc.query_string, (int) tv.tv_sec, (int) tv.tv_usec); } else #endif if (terminate_timeout && tv.tv_sec >= terminate_timeout) { str_purify_filename(purified_script_filename, proc.script_filename, sizeof(proc.script_filename)); fpm_pctl_kill(child->pid, FPM_PCTL_TERM); zlog(ZLOG_WARNING, "[pool %s] child %d, script '%s' (request: \"%s %s%s%s\") execution timed out (%d.%06d sec), terminating", child->wp->config->name, (int) child->pid, purified_script_filename, proc.request_method, proc.request_uri, (proc.query_string[0] ? "?" : ""), proc.query_string, (int) tv.tv_sec, (int) tv.tv_usec); } } } /* }}} */ int fpm_request_is_idle(struct fpm_child_s *child) /* {{{ */ { struct fpm_scoreboard_proc_s *proc; /* no need in atomicity here */ proc = fpm_scoreboard_proc_get(child->wp->scoreboard, child->scoreboard_i); if (!proc) { return 0; } return proc->request_stage == FPM_REQUEST_ACCEPTING; } /* }}} */ int fpm_request_last_activity(struct fpm_child_s *child, struct timeval *tv) /* {{{ */ { struct fpm_scoreboard_proc_s *proc; if (!tv) return -1; proc = fpm_scoreboard_proc_get(child->wp->scoreboard, child->scoreboard_i); if (!proc) { return -1; } *tv = proc->tv; return 1; } /* }}} */
/** * Copyright 2004-present Facebook. All Rights Reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ import type {ContextRouter} from 'react-router-dom'; import type {WifiGateway} from './WifiUtils'; import type {WithAlert} from '@fbcnms/ui/components/Alert/withAlert'; import type {WithStyles} from '@material-ui/core'; import AddIcon from '@material-ui/icons/Add'; import Button from '@material-ui/core/Button'; import ChevronRight from '@material-ui/icons/ChevronRight'; import ClipboardLink from '@fbcnms/ui/components/ClipboardLink'; import DeleteIcon from '@material-ui/icons/Delete'; import DeviceStatusCircle from '@fbcnms/ui/components/icons/DeviceStatusCircle'; import EditIcon from '@material-ui/icons/Edit'; import ExpandMore from '@material-ui/icons/ExpandMore'; import IconButton from '@material-ui/core/IconButton'; import InfoIcon from '@material-ui/icons/Info'; import LinkIcon from '@material-ui/icons/Link'; import MagmaV1API from '@fbcnms/magmalte/app/common/MagmaV1API'; import NestedRouteLink from '@fbcnms/ui/components/NestedRouteLink'; import React from 'react'; import TableCell from '@material-ui/core/TableCell'; import TableRow from '@material-ui/core/TableRow'; import Tooltip from '@material-ui/core/Tooltip'; import axios from 'axios'; import url from 'url'; import {groupBy} from 'lodash'; import WifiDeviceDetails, {InfoRow} from './WifiDeviceDetails'; import nullthrows from '@fbcnms/util/nullthrows'; import withAlert from '@fbcnms/ui/components/Alert/withAlert'; import {MagmaAPIUrls} from '@fbcnms/magmalte/app/common/MagmaAPI'; import {meshesURL} from './WifiUtils'; import {withRouter} from 'react-router-dom'; import {withStyles} from '@material-ui/core/styles'; const styles = theme => ({ actionsCell: { textAlign: 'right', }, gatewayCell: { paddingBottom: '15px', paddingLeft: '75px', paddingRight: '15px', paddingTop: '15px', }, deviceWarning: { color: 'red', paddingLeft: 40, }, iconButton: { color: theme.palette.secondary.light, padding: '5px', }, meshButton: { margin: 0, textTransform: 'none', }, meshCell: { padding: '5px', }, meshID: { color: theme.palette.primary.dark, fontWeight: 'bolder', }, meshIconButton: { color: theme.palette.primary.dark, padding: '5px', }, tableCell: { padding: '15px', }, tableRow: { height: 'auto', whiteSpace: 'nowrap', verticalAlign: 'top', }, }); type Props = ContextRouter & WithStyles<typeof styles> & WithAlert & { enableDeviceEditing?: boolean, meshID: string, gateways: WifiGateway[], onDeleteMesh: string => void, onDeleteDevice: WifiGateway => void, }; const EXPANDED_STATE_TYPES = { none: 0, device: 1, neighbors: 2, fullDump: 3, configs: 4, }; const MESH_ID_PARAM = 'meshID'; const DEVICE_ID_PARAM = 'deviceID'; const EXPANDED_STATE_PARAM = 'expandedState'; type State = { expanded: boolean, expandedGateways: {[key: string]: 0 | 1 | 2 | 3 | 4}, }; class WifiMeshRow extends React.Component<Props, State> { constructor(props) { super(props); const queryParams = new URLSearchParams(this.props.location.search); const initialState = { expanded: false, expandedGateways: {}, }; if (queryParams.get(MESH_ID_PARAM) === this.props.meshID) { initialState.expanded = true; const deviceID = queryParams.get(DEVICE_ID_PARAM); if (deviceID != null) { const expandedState = parseInt(queryParams.get(EXPANDED_STATE_PARAM)); initialState.expandedGateways = {[deviceID]: expandedState}; } } this.state = initialState; } handleToggleAllDevices = () => { const {gateways} = this.props; // determine old max state by getting max() of all the states const maxState = gateways .map(gateway => this.state.expandedGateways[gateway.id]) .reduce((max, state) => (state ? Math.max(max, state) : max), 0); // calculate next state const nextState = (maxState + 1) % Object.keys(EXPANDED_STATE_TYPES).length; // assign same next state to all gateways if (nextState === 0) { // no need to set any gateways for 0/unexpanded state this.setState({expandedGateways: {}}); } else { const expandedGateways = gateways .map(gateway => gateway.id) .reduce((expandedGateways, id) => { expandedGateways[id] = nextState; return expandedGateways; }, {}); this.setState({expandedGateways}); } }; render() { const {meshID, gateways, classes} = this.props; let gatewayRows; let gatewayVersions; if (this.state.expanded) { gatewayRows = gateways.map(gateway => ( <TableRow className={this.props.classes.tableRow} key={gateway.id}> <TableCell className={classes.gatewayCell}>{gateway.info}</TableCell> <TableCell className={classes.tableCell}> {status} <DeviceStatusCircle isGrey={!gateway.status} isActive={!!gateway.up} /> <Tooltip title="Click to toggle device info" enterDelay={400} placement={'right'}> <span onClick={() => this.expandGateway(gateway.id)}> {gateway.id} </span> </Tooltip> {gateway.coordinates.includes(NaN) && ( <span className={classes.deviceWarning}> {' '} Please configure Lat/Lng </span> )} {gateway.status && gateway.status.meta && gateway.status.meta['validation_status'] !== 'passed' && ( <span className={classes.deviceWarning}> {' '} Please check image validation status </span> )} {!!this.state.expandedGateways[gateway.id] && gateway.status && ( <WifiDeviceDetails device={gateway} hideHeader={true} showConfigs={ this.state.expandedGateways[gateway.id] === EXPANDED_STATE_TYPES.configs } showDevice={ this.state.expandedGateways[gateway.id] === EXPANDED_STATE_TYPES.device } showNeighbors={ this.state.expandedGateways[gateway.id] === EXPANDED_STATE_TYPES.neighbors } showFullDump={ this.state.expandedGateways[gateway.id] === EXPANDED_STATE_TYPES.fullDump } /> )} </TableCell> <TableCell className={classes.actionsCell}> <ClipboardLink title="Copy link to this device"> {({copyString}) => ( <IconButton className={classes.iconButton} onClick={() => copyString(this.buildLinkURL(meshID, gateway.id)) }> <LinkIcon /> </IconButton> )} </ClipboardLink> <Tooltip title="Click to toggle device info" enterDelay={400}> <IconButton className={classes.iconButton} onClick={() => this.expandGateway(gateway.id)}> <InfoIcon /> </IconButton> </Tooltip> {this.props.enableDeviceEditing && ( <NestedRouteLink to={`/${meshID}/edit_device/${gateway.id}`}> <IconButton className={classes.iconButton}> <EditIcon /> </IconButton> </NestedRouteLink> )} <IconButton className={classes.iconButton} onClick={() => this.showDeviceDeleteDialog(gateway)}> <DeleteIcon /> </IconButton> </TableCell> </TableRow> )); // construct version list per mesh const versionGroups = groupBy(gateways, device => { if (device.versionParsed) { if (device.versionParsed.fbpkg !== 'none') { return device.versionParsed.fbpkg; } else { return device.versionParsed.hash; } } return device.version || 'UNKNOWN'; }); gatewayVersions = Object.keys(versionGroups).map(version => ( <div key={version}> <Tooltip title={`${versionGroups[version].length} device(s) with ${versionGroups[version][0].version}`} enterDelay={100} key={version}> <span> {version}: <b>{versionGroups[version].length}</b> </span> </Tooltip> </div> )); } return ( <> <TableRow className={this.props.classes.tableRow}> <TableCell className={this.props.classes.meshCell}> <IconButton className={classes.meshIconButton} onClick={gateways.length == 0 ? null : this.onToggleExpand}> {this.state.expanded ? <ExpandMore /> : <ChevronRight />} </IconButton> <span className={classes.meshID}>{meshID}</span> </TableCell> <TableCell className={this.props.classes.meshCell}> {gateways.length > 0 && ( <> <InfoRow label="Up" data={`${gateways.filter(gateway => gateway.up).length} of ${ gateways.length }`} /> {this.state.expanded && ( <> <Tooltip title="Click to toggle device info" enterDelay={400} placement={'right'}> <Button size="small" className={classes.meshButton} onClick={this.handleToggleAllDevices}> toggle info </Button> </Tooltip> {gatewayVersions} </> )} </> )} </TableCell> <TableCell className={this.props.classes.actionsCell}> <ClipboardLink title="Copy link to this mesh"> {({copyString}) => ( <IconButton className={classes.iconButton} onClick={() => copyString(this.buildLinkURL(meshID))}> <LinkIcon /> </IconButton> )} </ClipboardLink> <NestedRouteLink to={`/add_device/${meshID}`}> <IconButton className={classes.meshIconButton}> <AddIcon /> </IconButton> </NestedRouteLink> <NestedRouteLink to={`/edit_mesh/${meshID}`}> <IconButton className={classes.meshIconButton}> <EditIcon /> </IconButton> </NestedRouteLink> <IconButton className={classes.meshIconButton} onClick={this.showMeshDeleteDialog}> <DeleteIcon /> </IconButton> </TableCell> </TableRow> {gatewayRows} </> ); } onToggleExpand = () => this.setState({expanded: !this.state.expanded}); expandGateway = id => { const expandedGateways = { ...this.state.expandedGateways, [id]: ((this.state.expandedGateways[id] | 0) + 1) % Object.keys(EXPANDED_STATE_TYPES).length, }; this.setState({expandedGateways}); }; showMeshDeleteDialog = () => { this.props .confirm( `Are you sure you want to delete mesh "${this.props.meshID}" and all its devices (count: ${this.props.gateways.length})?`, ) .then(async confirmed => { if (!confirmed) { return; } const requests = this.props.gateways.map(device => MagmaV1API.deleteNetworksByNetworkIdGatewaysByGatewayId({ networkId: nullthrows(this.props.match.params.networkId), gatewayId: device.id, }), ); const requestsc = this.props.gateways.map(device => axios.delete( MagmaAPIUrls.gatewayConfigsForType( this.props.match, device.id, 'wifi', ), ), ); // delete all devices and wifi configs await axios.all([...requests, ...requestsc]); // delete mesh await axios.delete( meshesURL(this.props.match) + '/' + this.props.meshID, ); this.props.onDeleteMesh(this.props.meshID); }); }; showDeviceDeleteDialog = (device: WifiGateway) => { this.props .confirm(`Are you sure you want to delete "${device.id}"?`) .then(async confirmed => { if (!confirmed) { return; } // delete all parts await axios.all([ MagmaV1API.deleteNetworksByNetworkIdGatewaysByGatewayId({ networkId: nullthrows(this.props.match.params.networkId), gatewayId: device.id, }), axios.delete( MagmaAPIUrls.gatewayConfigsForType( this.props.match, device.id, 'wifi', ), ), ]); this.props.onDeleteDevice(device); }); }; buildLinkURL = (meshID: string, deviceID: ?string = null): string => { const query: {[string]: string | number} = {[MESH_ID_PARAM]: meshID}; if (deviceID) { query[DEVICE_ID_PARAM] = deviceID; query[EXPANDED_STATE_PARAM] = this.state.expandedGateways[deviceID] ?? 1; } const {protocol, host, pathname} = window.location; return url.format({protocol, host, pathname, query}); }; } export default withStyles(styles)(withRouter(withAlert(WifiMeshRow)));
//// [tests/cases/conformance/internalModules/DeclarationMerging/TwoInternalModulesWithTheSameNameAndSameCommonRoot.ts] //// //// [part1.ts] module A { export interface Point { x: number; y: number; } export module Utils { export function mirror<T extends Point>(p: T) { return { x: p.y, y: p.x }; } } } //// [part2.ts] module A { export var Origin: Point = { x: 0, y: 0 }; export module Utils { export class Plane { constructor(public tl: Point, public br: Point) { } } } } //// [part3.ts] // test the merging actually worked var o: { x: number; y: number }; var o: A.Point; var o = A.Origin; var o = A.Utils.mirror(o); var p: { tl: A.Point; br: A.Point }; var p: A.Utils.Plane; var p = new A.Utils.Plane(o, { x: 1, y: 1 }); //// [part1.js] var A; (function (A) { var Utils; (function (Utils) { function mirror(p) { return { x: p.y, y: p.x }; } Utils.mirror = mirror; })(Utils = A.Utils || (A.Utils = {})); })(A || (A = {})); //// [part2.js] var A; (function (A) { A.Origin = { x: 0, y: 0 }; var Utils; (function (Utils) { var Plane = (function () { function Plane(tl, br) { this.tl = tl; this.br = br; } return Plane; })(); Utils.Plane = Plane; })(Utils = A.Utils || (A.Utils = {})); })(A || (A = {})); //// [part3.js] // test the merging actually worked var o; var o; var o = A.Origin; var o = A.Utils.mirror(o); var p; var p; var p = new A.Utils.Plane(o, { x: 1, y: 1 });
import hashlib import hmac import logging import os import shutil import tempfile from datetime import datetime import delegator import requests from flask import ( Blueprint, abort, current_app, flash, jsonify, make_response, redirect, request, safe_join, send_from_directory, url_for, ) from flask.views import MethodView from flask_login import current_user, login_required from packaging.version import parse as parse_version from pkg_resources import safe_name from requests.exceptions import HTTPError from sqlalchemy import desc, nullsfirst, nullslast from sqlalchemy.sql.expression import func from werkzeug.utils import secure_filename from ..account import github from ..account.forms import LeaveForm from ..auth import current_user_is_roadie from ..decorators import templated from ..exceptions import eject from ..members.decorators import member_required from ..tasks import spinach from .forms import DeleteForm, ReleaseForm, UploadForm from .models import Project, ProjectMembership, ProjectUpload from .tasks import send_new_upload_notifications, update_upload_ordering projects = Blueprint("projects", __name__, url_prefix="/projects") logger = logging.getLogger(__name__) MAX_FILESIZE = 60 * 1024 * 1024 # 60M MAX_SIGSIZE = 8 * 1024 # 8K SIGNATURE_START = b"-----BEGIN PGP SIGNATURE-----" PATH_HASHER = "sha256" DEFAULT_SORTER = func.random() SORTERS = { "uploads": Project.uploads_count, "members": Project.membership_count, "watchers": Project.subscribers_count, "stargazers": Project.stargazers_count, "forks": Project.forks_count, "issues": Project.open_issues_count, "name": Project.name, "random": DEFAULT_SORTER, } DEFAULT_ORDER = "desc" @projects.route("") @templated() def index(): requested_sorter = request.args.get("sorter", None) if requested_sorter is None or requested_sorter not in SORTERS: sorter = "random" initial_sorting = True else: sorter = requested_sorter initial_sorting = False criterion = SORTERS.get(sorter, DEFAULT_SORTER) order = request.args.get("order", None) if order == DEFAULT_ORDER: criterion = nullslast(desc(criterion)) else: criterion = nullsfirst(criterion) projects = Project.query.filter(Project.is_active.is_(True)).order_by(criterion) return { "projects": projects, "sorter": sorter, "initial_sorting": initial_sorting, "order": order, "DEFAULT_ORDER": DEFAULT_ORDER, } class ProjectMixin: def project_query(self, name): return Project.query.filter(Project.is_active.is_(True), Project.name == name) def project_name(self, *args, **kwargs): name = kwargs.get("name") if not name: abort(404) return name def redirect_to_project(self): return redirect(url_for("projects.detail", name=self.project.name)) def dispatch_request(self, *args, **kwargs): name = self.project_name(*args, **kwargs) self.project = self.project_query(name).first_or_404() return super().dispatch_request(*args, **kwargs) class DetailView(ProjectMixin, MethodView): """ A view to show the details of a project. """ methods = ["GET"] decorators = [templated()] def get(self, name): uploads = self.project.uploads.order_by( ProjectUpload.ordering.desc(), ProjectUpload.version.desc() ) versions = {upload.version for upload in uploads} return { "project": self.project, "uploads": uploads, "versions": sorted(versions, key=parse_version, reverse=True), } class JoinView(ProjectMixin, MethodView): """ A view to show the join a project team. """ methods = ["GET"] decorators = [ member_required(message="You currently can't join this project"), login_required, ] def get(self, name): response = github.join_team(self.project.team_slug, current_user.login) if response and response.status_code == 200: membership = self.project.membership.filter( ProjectMembership.user_id == current_user.id, ).first() if not membership: # create a new project membership membership = ProjectMembership( user_id=current_user.id, project_id=self.project.id ) membership.save() flash(f"You have joined the {self.project.name} team.") else: flash(f"Something went wrong while joining the {self.project.name} team.") return self.redirect_to_project() class LeaveView(ProjectMixin, MethodView): """ A view to show the join a project team. """ methods = ["GET", "POST"] decorators = [member_required(), login_required, templated()] def get(self, name): if not self.project.user_is_member(current_user): flash(f"You're not a member of {self.project.name} at the moment.") return self.redirect_to_project() return { "project": self.project, "leave_form": LeaveForm(), } def post(self, name): if not self.project.user_is_member(current_user): flash(f"You're not a member of {self.project.name} at the moment.") return self.redirect_to_project() form = LeaveForm() if form.validate_on_submit(): response = github.leave_team(self.project.team_slug, current_user.login) if response and response.status_code == 204: membership = self.project.membership.filter( ProjectMembership.user_id == current_user.id, ).first() if membership: membership.delete() flash( f"You have been removed from the {self.project.name} team. " f"See you soon!" ) else: flash( f"Leaving the {self.project.name} team failed. " f"Please try again or open a ticket for the roadies." ) return self.redirect_to_project() return { "project": self.project, "leave_form": form, } class UploadView(ProjectMixin, MethodView): """ A view to show the details of a project and also handling file uploads via Twine/distutils. """ methods = ["POST"] def check_authentication(self): """ Authenticate a request using a database lookup. """ if request.authorization is None: return False # the upload killswitch if not current_app.config["UPLOAD_ENABLED"]: return False if request.authorization.username != "jazzband": return False return self.project.credentials.filter_by( is_active=True, key=request.authorization.password ).scalar() def post(self, name): if not self.check_authentication(): response = make_response("", 401) response.headers["WWW-Authenticate"] = 'Basic realm="Jazzband"' return response # distutils "helpfully" substitutes unknown, but "required" values # with the string "UNKNOWN". This is basically never what anyone # actually wants so we'll just go ahead and delete anything whose # value is UNKNOWN. form_copy = request.form.copy() unknown_found = False for key, value in request.form.items(): if value == "UNKNOWN": unknown_found = True form_copy.pop(key) if unknown_found: request.form = form_copy form = UploadForm(meta={"csrf": False}) validation_order = ["name", "version", "content"] if not form.validate_on_submit(): for field_name in validation_order: if field_name in form.errors: break else: field_name = sorted(form.errors.keys())[0] eject( 400, description="%s: %s" % (field_name, ", ".join(form.errors[field_name])), ) # the upload FileStorage upload_data = form.content.data if upload_data is None: eject(400, description="Upload payload does not have a file.") upload_filename = secure_filename(upload_data.filename) # Make sure that our filename matches the project that it is being # uploaded to. prefix = safe_name(self.project.name).lower() if not safe_name(upload_filename).lower().startswith(prefix): eject( 400, description="The filename for %r must start with %r." % (self.project.name, prefix), ) # Fail if a project upload already exists if ProjectUpload.query.filter_by( filename=upload_filename, project_id=self.project.id ).scalar(): eject(400, description="File already exists.") # Store file uploads and calculate hashes with tempfile.TemporaryDirectory() as tmpdir: upload_path = os.path.join(tmpdir, upload_filename) upload_data.stream.seek(0) upload_data.save(upload_path) # Buffer the entire file onto disk, checking the hash of the file # as we go along. with open(upload_path, "rb") as upload_file: file_hashes = { "md5": hashlib.md5(), "sha256": hashlib.sha256(), "blake2_256": hashlib.blake2b(digest_size=256 // 8), } for chunk in iter(lambda: upload_file.read(8096), b""): for hasher in file_hashes.values(): hasher.update(chunk) # Take our hash functions and compute the final hashes for them # now. file_hashes = { method: file_hash.hexdigest().lower() for method, file_hash in file_hashes.items() } # Actually verify the digests that we've gotten. We're going to use # hmac.compare_digest even though we probably don't actually need # to because it's better safe than sorry. In the case of multiple # digests we expect them all to be given. hash_comparisons = [ hmac.compare_digest( getattr(form, "%s_digest" % digest_name).data.lower(), digest_value ) for digest_name, digest_value in file_hashes.items() if getattr(form, "%s_digest" % digest_name).data ] if not all(hash_comparisons): eject( 400, description="The digest supplied does not match a digest " "calculated from the uploaded file.", ) # Also buffer the entire signature file to disk. signature = form.gpg_signature.data signature_filename = upload_filename + ".asc" if signature: signature_path = os.path.join(tmpdir, signature_filename) signature.stream.seek(0) signature.save(signature_path) if os.path.getsize(signature_path) > MAX_SIGSIZE: eject(400, description="Signature too large.") # Check whether signature is ASCII armored with open(signature_path, "rb") as signature_file: if not signature_file.read().startswith(SIGNATURE_START): eject(400, description="PGP signature is not ASCII armored.") version = form.version.data upload = ProjectUpload( version=version, project=self.project, # e.g. acme/2coffee12345678123123123123123123 path=safe_join(self.project.name, file_hashes[PATH_HASHER]), filename=upload_filename, size=os.path.getsize(upload_path), md5_digest=file_hashes["md5"], sha256_digest=file_hashes["sha256"], blake2_256_digest=file_hashes["blake2_256"], form_data=request.form, user_agent=request.user_agent.string, remote_addr=request.remote_addr, ) # make the storage path directory /app/uploads/acme os.makedirs(os.path.dirname(upload.full_path), exist_ok=True) # move the uploaded file to storage path directory shutil.move(upload_path, upload.full_path) # copy the uploaded signature file to storage path directory if signature: shutil.move(signature_path, upload.full_path + ".asc") # write to database upload.save() spinach.schedule(send_new_upload_notifications, self.project.id) spinach.schedule(update_upload_ordering, self.project.id) return "OK" class UploadActionView(ProjectMixin, MethodView): decorators = [login_required] def dispatch_request(self, *args, **kwargs): name = self.project_name(*args, **kwargs) self.project = self.project_query(name).first_or_404() self.upload = self.project.uploads.filter_by( id=kwargs.get("upload_id") ).first_or_404() return super().dispatch_request(*args, **kwargs) class UploadMembersActionView(UploadActionView): def project_query(self, name): projects = super().project_query(name) return projects.filter(Project.membership.any(user=current_user)) class UploadLeadsActionView(UploadMembersActionView): def project_query(self, name): projects = super().project_query(name) if current_user_is_roadie(): return projects return projects.filter( Project.membership.any(is_lead=True), ) class UploadDownloadView(UploadMembersActionView): methods = ["GET"] def get(self, name, upload_id): cache_timeout = current_app.get_send_file_max_age(self.upload.full_path) path, filename = os.path.split(self.upload.full_path) return send_from_directory( path, filename, cache_timeout=cache_timeout, as_attachment=True, attachment_filename=self.upload.filename, add_etags=False, conditional=True, ) class UploadFormDataView(UploadMembersActionView): methods = ["GET"] def get(self, name, upload_id): return jsonify(self.upload.form_data) class UploadReleaseView(UploadLeadsActionView): methods = ["GET", "POST"] decorators = UploadLeadsActionView.decorators + [templated()] def validate_upload(self): errors = [] try: # check pypi if file was added, check sha256 digest, size and # filename pypi_response = requests.get(self.upload.project.pypi_json_url) pypi_response.raise_for_status() data = pypi_response.json() except HTTPError: # in case there was a network issue with getting the JSON # data from PyPI error = "Error while validating upload" logger.error(error, exc_info=True) errors.append(error) except ValueError: # or something was wrong about the returned JSON data error = "Error while parsing response from PyPI during validation" logger.error(error, exc_info=True) errors.append(error) except Exception: error = "Unknown error" logger.error(error, exc_info=True) errors.append(error) else: # next check the data for what we're looking for releases = data.get("releases", {}) release_files = releases.get(self.upload.version, []) if release_files: for release_file in release_files: release_filename = release_file.get("filename", None) if release_filename is None: error = "No file found in PyPI validation response." logger.error(error, extra={"stack": True}) if release_filename == self.upload.filename: digests = release_file.get("digests", {}) if digests: md5_digest = digests.get("md5", None) if md5_digest and md5_digest != self.upload.md5_digest: error = ( f"MD5 hash of {self.upload.filename} does " f"not match hash returned by PyPI." ) errors.append(error) logger.error(error, extra={"stack": True}) sha256_digest = digests.get("sha256", None) if ( sha256_digest and sha256_digest != self.upload.sha256_digest ): error = ( f"SHA256 hash of {self.upload.filename} " f"does not match hash returned by PyPI." ) errors.append(error) logger.error(error, extra={"stack": True}) else: error = f"No digests for file {self.upload.filename}" errors.append(error) logger.error(error, extra={"stack": True}) else: error = f"No released files found for upload " f"{self.upload.filename}" errors.append(error) logger.error(error, extra={"stack": True}) return errors def post(self, name, upload_id): if not current_app.config["RELEASE_ENABLED"]: message = "Releasing is currently out of service" flash(message) logging.info(message) if self.upload.released_at: flash( f"The upload {self.upload.filename} has already been released " f"and can't be released again." ) return self.redirect_to_project() release_form = ReleaseForm(project_name=self.project.name) context = { "release_form": release_form, "project": self.project, "upload": self.upload, } if release_form.validate_on_submit(): # copy path to new tmp directory with tempfile.TemporaryDirectory() as tmpdir: upload_path = os.path.join(tmpdir, self.upload.filename) shutil.copy(self.upload.full_path, upload_path) # run twine upload against copied upload file twine_run = delegator.run(f"twine upload {upload_path}") if twine_run.return_code == 0: errors = self.validate_upload() release_form.add_global_error(*errors) if not errors: # create ProjectRelease object with reference to project self.upload.released_at = datetime.utcnow() # write to database self.upload.save() message = f"You've successfully released {self.upload} to PyPI." flash(message) logger.info(message) return self.redirect_to_project() else: error = f"Release of {self.upload} failed." release_form.add_global_error(error) logger.error( error, extra={"data": {"out": twine_run.out, "err": twine_run.err}} ) context.update({"twine_run": twine_run, "upload": self.upload}) return context def get(self, name, upload_id): if self.upload.released_at: message = ( f"The upload {self.upload} has already been released " f"and can't be released again." ) flash(message) logger.info(message) return self.redirect_to_project() release_form = ReleaseForm(project_name=self.project.name) return { "project": self.project, "release_form": release_form, "upload": self.upload, } class UploadDeleteView(UploadLeadsActionView): methods = ["GET", "POST"] decorators = UploadLeadsActionView.decorators + [templated()] def get(self, name, upload_id): if self.upload.released_at: message = ( f"The upload {self.upload} has already been " f"released and can't be deleted." ) flash(message) logger.info(message) return self.redirect_to_project() return { "project": self.project, "upload": self.upload, "delete_form": DeleteForm(project_name=self.project.name), } def post(self, name, upload_id): if self.upload.released_at: message = ( f"The upload {self.upload} has already been " f"released and can't be deleted." ) flash(message) logger.error(message, extra={"stack": True}) return self.redirect_to_project() delete_form = DeleteForm(project_name=self.project.name) context = { "delete_form": delete_form, "project": self.project, "upload": self.upload, } if delete_form.validate_on_submit(): self.upload.delete() message = f"You've successfully deleted the upload {self.upload}." flash(message) logger.info(message) return self.redirect_to_project() else: return context # /projects/test-project/1/delete projects.add_url_rule( "/<name>/upload/<upload_id>/delete", view_func=UploadDeleteView.as_view("delete") ) # /projects/test-project/1/data projects.add_url_rule( "/<name>/upload/<upload_id>/formdata", view_func=UploadFormDataView.as_view("formdata"), ) # /projects/test-project/1/download projects.add_url_rule( "/<name>/upload/<upload_id>/download", view_func=UploadDownloadView.as_view("download"), ) # /projects/test-project/1/release projects.add_url_rule( "/<name>/upload/<upload_id>/release", view_func=UploadReleaseView.as_view("release") ) # /projects/test-project/join projects.add_url_rule("/<name>/join", view_func=JoinView.as_view("join")) # /projects/test-project/leave projects.add_url_rule("/<name>/leave", view_func=LeaveView.as_view("leave")) # /projects/test-project/upload projects.add_url_rule("/<name>/upload", view_func=UploadView.as_view("upload")) # /projects/test-project projects.add_url_rule("/<name>", view_func=DetailView.as_view("detail"))
// 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. #ifndef CONTENT_RENDERER_WEBPUBLICSUFFIXLIST_IMPL_H_ #define CONTENT_RENDERER_WEBPUBLICSUFFIXLIST_IMPL_H_ #include "base/compiler_specific.h" #include "third_party/WebKit/public/platform/WebPublicSuffixList.h" namespace content { class WebPublicSuffixListImpl : public blink::WebPublicSuffixList { public: // WebPublicSuffixList methods: virtual size_t getPublicSuffixLength(const blink::WebString& host); virtual ~WebPublicSuffixListImpl(); }; } // namespace content #endif // CONTENT_RENDERER_WEBPUBLICSUFFIXLIST_IMPL_H_
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 14, 2021 at 2:25:51 PM Mountain Standard Time * Operating System: Version 14.4 (Build 18K802) * Image Source: /System/Library/PrivateFrameworks/DataAccess.framework/DataAccess * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <DataAccess/DataAccess-Structs.h> @interface DAUserNotificationUtilities : NSObject +(void)showUserNotification:(CFUserNotificationRef)arg1 groupIdentifier:(id)arg2 callbackQueue:(id)arg3 sourceRunLoop:(id)arg4 completionBlock:(/*^block*/id)arg5 ; @end
"use strict"; /* * Copyright (C) 1998-2020 by Northwoods Software Corporation. All Rights Reserved. */ // HTML + JavaScript text editor using an HTML Select Element and HTMLInfo. // This file exposes one instance of HTMLInfo, window.TextEditorSelectBox // see /samples/customTextEditingTool.html // see also textEditorRadioButton.js for another custom editor // see also textEditor.html for a re-implementation of the default text editor (function(window) { var customEditor = new go.HTMLInfo(); var customSelectBox = document.createElement("select"); customEditor.show = function(textBlock, diagram, tool) { if (!(textBlock instanceof go.TextBlock)) return; // Populate the select box: customSelectBox.innerHTML = ""; var list = textBlock.choices; // Perhaps give some default choices if textBlock.choices is null if (list === null) list = ["Default A", "Default B", "Default C"]; var l = list.length; for (var i = 0; i < l; i++) { var op = document.createElement("option"); op.text = list[i]; op.value = list[i]; customSelectBox.add(op, null); // consider also adding the current value, if it is not in the choices list } // After the list is populated, set the value: customSelectBox.value = textBlock.text; // Do a few different things when a user presses a key customSelectBox.addEventListener("keydown", function(e) { var keynum = e.which; if (keynum == 13) { // Accept on Enter tool.acceptText(go.TextEditingTool.Enter); return; } else if (keynum == 9) { // Accept on Tab tool.acceptText(go.TextEditingTool.Tab); e.preventDefault(); return false; } else if (keynum === 27) { // Cancel on Esc tool.doCancel(); if (tool.diagram) tool.diagram.focus(); } }, false); var loc = textBlock.getDocumentPoint(go.Spot.TopLeft); var pos = diagram.transformDocToView(loc); customSelectBox.style.left = pos.x + "px"; customSelectBox.style.top = pos.y + "px"; customSelectBox.style.position = 'absolute'; customSelectBox.style.zIndex = 100; // place it in front of the Diagram diagram.div.appendChild(customSelectBox); } customEditor.hide = function(diagram, tool) { diagram.div.removeChild(customSelectBox); } customEditor.valueFunction = function() { return customSelectBox.value; } window.TextEditorSelectBox = customEditor; })(window);