prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>historyserver.py<|end_file_name|><|fim▁begin|>""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Ambari Agent """ from resource_management.libraries.script.script import Script from resource_management.libraries.resources.hdfs_resource import HdfsResource from resource_management.libraries.functions import conf_select from resource_management.libraries.functions import stack_select from resource_management.libraries.functions.check_process_status import check_process_status from resource_management.libraries.functions.copy_tarball import copy_to_hdfs from resource_management.libraries.functions.version import compare_versions, format_stack_version from resource_management.libraries.functions.format import format from resource_management.libraries.functions.security_commons import build_expectations, \ cached_kinit_executor, get_params_from_filesystem, validate_security_config_properties, \ FILE_TYPE_XML from resource_management.core.source import Template from resource_management.core.logger import Logger from yarn import yarn from service import service from ambari_commons import OSConst from ambari_commons.os_family_impl import OsFamilyImpl class HistoryServer(Script): def get_component_name(self): return "hadoop-mapreduce-historyserver" def install(self, env): self.install_packages(env) def configure(self, env): import params env.set_params(params) yarn(name="historyserver") def pre_upgrade_restart(self, env, upgrade_type=None): Logger.info("Executing Stack Upgrade pre-restart") import params env.set_params(params) if params.version and compare_versions(format_stack_version(params.version), '4.0.0.0') >= 0: conf_select.select(params.stack_name, "hadoop", params.version) stack_select.select("hadoop-mapreduce-historyserver", params.version) #Execute(format("iop-select set hadoop-mapreduce-historyserver {version}")) #copy_tarballs_to_hdfs('mapreduce', 'hadoop-mapreduce-historyserver', params.mapred_user, params.hdfs_user, params.user_group) # MC Hammer said, "Can't touch this" copy_to_hdfs("mapreduce", params.user_group, params.hdfs_user, skip=params.host_sys_prepped) copy_to_hdfs("slider", params.user_group, params.hdfs_user, skip=params.host_sys_prepped) params.HdfsResource(None, action="execute") def start(self, env, upgrade_type=None): import params env.set_params(params) self.configure(env) # FOR SECURITY # MC Hammer said, "Can't touch this" resource_created = copy_to_hdfs( "mapreduce", params.user_group, params.hdfs_user, skip=params.host_sys_prepped) resource_created = copy_to_hdfs( "slider", params.user_group, params.hdfs_user, skip=params.host_sys_prepped) or resource_created if resource_created: params.HdfsResource(None, action="execute") service('historyserver', action='start', serviceName='mapreduce') def stop(self, env, upgrade_type=None): import params env.set_params(params) service('historyserver', action='stop', serviceName='mapreduce') def status(self, env): import status_params env.set_params(status_params) check_process_status(status_params.mapred_historyserver_pid_file) def security_status(self, env): import status_params<|fim▁hole|> expectations.update(build_expectations('mapred-site', None, [ 'mapreduce.jobhistory.keytab', 'mapreduce.jobhistory.principal', 'mapreduce.jobhistory.webapp.spnego-keytab-file', 'mapreduce.jobhistory.webapp.spnego-principal' ], None)) security_params = get_params_from_filesystem(status_params.hadoop_conf_dir, {'mapred-site.xml': FILE_TYPE_XML}) result_issues = validate_security_config_properties(security_params, expectations) if not result_issues: # If all validations passed successfully try: # Double check the dict before calling execute if ( 'mapred-site' not in security_params or 'mapreduce.jobhistory.keytab' not in security_params['mapred-site'] or 'mapreduce.jobhistory.principal' not in security_params['mapred-site'] or 'mapreduce.jobhistory.webapp.spnego-keytab-file' not in security_params['mapred-site'] or 'mapreduce.jobhistory.webapp.spnego-principal' not in security_params['mapred-site']): self.put_structured_out({"securityState": "UNSECURED"}) self.put_structured_out( {"securityIssuesFound": "Keytab file or principal not set."}) return cached_kinit_executor(status_params.kinit_path_local, status_params.mapred_user, security_params['mapred-site']['mapreduce.jobhistory.keytab'], security_params['mapred-site']['mapreduce.jobhistory.principal'], status_params.hostname, status_params.tmp_dir) cached_kinit_executor(status_params.kinit_path_local, status_params.mapred_user, security_params['mapred-site']['mapreduce.jobhistory.webapp.spnego-keytab-file'], security_params['mapred-site']['mapreduce.jobhistory.webapp.spnego-principal'], status_params.hostname, status_params.tmp_dir) self.put_structured_out({"securityState": "SECURED_KERBEROS"}) except Exception as e: self.put_structured_out({"securityState": "ERROR"}) self.put_structured_out({"securityStateErrorInfo": str(e)}) else: issues = [] for cf in result_issues: issues.append("Configuration file %s did not pass the validation. Reason: %s" % (cf, result_issues[cf])) self.put_structured_out({"securityIssuesFound": ". ".join(issues)}) self.put_structured_out({"securityState": "UNSECURED"}) else: self.put_structured_out({"securityState": "UNSECURED"}) if __name__ == "__main__": HistoryServer().execute()<|fim▁end|>
env.set_params(status_params) if status_params.security_enabled: expectations = {}
<|file_name|>collect_ppa_autopkgtests_results.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import argparse import os import subprocess import tempfile ACTIVE_DISTROS = ("xenial", "artful", "bionic") def main(): parser = argparse.ArgumentParser() parser.add_argument("day", help="The day of the results, with format yyyymmdd") args = parser.parse_args() install_autopkgtest_results_formatter() with tempfile.TemporaryDirectory(dir=os.environ.get("HOME")) as temp_dir: clone_results_repo(temp_dir) format_results(temp_dir, ACTIVE_DISTROS, args.day) commit_and_push(temp_dir, args.day) def install_autopkgtest_results_formatter(): subprocess.check_call( ["sudo", "snap", "install", "autopkgtest-results-formatter", "--edge"] ) def clone_results_repo(dest_dir): subprocess.check_call( ["git", "clone", "https://github.com/elopio/autopkgtest-results.git", dest_dir] )<|fim▁hole|> [ "/snap/bin/autopkgtest-results-formatter", "--destination", dest_dir, "--distros", *distros, "--day", day, ] ) def commit_and_push(repo_dir, day): subprocess.check_call( ["git", "config", "--global", "user.email", "[email protected]"] ) subprocess.check_call(["git", "config", "--global", "user.name", "snappy-m-o"]) subprocess.check_call(["git", "-C", repo_dir, "add", "--all"]) subprocess.check_call( [ "git", "-C", repo_dir, "commit", "--message", "Add the results for {}".format(day), ] ) subprocess.check_call( [ "git", "-C", repo_dir, "push", "https://{GH_TOKEN}@github.com/elopio/autopkgtest-results.git".format( GH_TOKEN=os.environ.get("GH_TOKEN_PPA_AUTOPKGTEST_RESULTS") ), ] ) if __name__ == "__main__": main()<|fim▁end|>
def format_results(dest_dir, distros, day): subprocess.check_call(
<|file_name|>flatpickr.js<|end_file_name|><|fim▁begin|>/* flatpickr v4.6.0, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.flatpickr = factory()); }(this, function () { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var HOOKS = [ "onChange", "onClose", "onDayCreate", "onDestroy", "onKeyDown", "onMonthChange", "onOpen", "onParseConfig", "onReady", "onValueUpdate", "onYearChange", "onPreCalendarPosition", ]; var defaults = { _disable: [], _enable: [], allowInput: false, altFormat: "F j, Y", altInput: false, altInputClass: "form-control input", animate: typeof window === "object" && window.navigator.userAgent.indexOf("MSIE") === -1, ariaDateFormat: "F j, Y", clickOpens: true, closeOnSelect: true, conjunction: ", ", dateFormat: "Y-m-d", defaultHour: 12, defaultMinute: 0, defaultSeconds: 0, disable: [], disableMobile: false, enable: [], enableSeconds: false, enableTime: false, errorHandler: function (err) { return typeof console !== "undefined" && console.warn(err); }, getWeek: function (givenDate) { var date = new Date(givenDate.getTime()); date.setHours(0, 0, 0, 0); // Thursday in current week decides the year. date.setDate(date.getDate() + 3 - ((date.getDay() + 6) % 7)); // January 4 is always in week 1. var week1 = new Date(date.getFullYear(), 0, 4); // Adjust to Thursday in week 1 and count number of weeks from date to week1. return (1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + ((week1.getDay() + 6) % 7)) / 7)); }, hourIncrement: 1, ignoredFocusElements: [], inline: false, locale: "default", minuteIncrement: 5, mode: "single", nextArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>", noCalendar: false, now: new Date(), onChange: [], onClose: [], onDayCreate: [], onDestroy: [], onKeyDown: [], onMonthChange: [], onOpen: [], onParseConfig: [], onReady: [], onValueUpdate: [], onYearChange: [], onPreCalendarPosition: [], plugins: [], position: "auto", positionElement: undefined, prevArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>", shorthandCurrentMonth: false, showMonths: 1, static: false, time_24hr: false, weekNumbers: false, wrap: false }; var english = { weekdays: { shorthand: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], longhand: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ] }, months: { shorthand: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ], longhand: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ] }, daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], firstDayOfWeek: 0, ordinal: function (nth) { var s = nth % 100; if (s > 3 && s < 21) return "th"; switch (s % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; default: return "th"; } }, rangeSeparator: " to ", weekAbbreviation: "Wk", scrollTitle: "Scroll to increment", toggleTitle: "Click to toggle", amPM: ["AM", "PM"], yearAriaLabel: "Year", time_24hr: false }; var pad = function (number) { return ("0" + number).slice(-2); }; var int = function (bool) { return (bool === true ? 1 : 0); }; /* istanbul ignore next */ function debounce(func, wait, immediate) { if (immediate === void 0) { immediate = false; } var timeout; return function () { var context = this, args = arguments; timeout !== null && clearTimeout(timeout); timeout = window.setTimeout(function () { timeout = null; if (!immediate) func.apply(context, args); }, wait); if (immediate && !timeout) func.apply(context, args); }; } var arrayify = function (obj) { return obj instanceof Array ? obj : [obj]; }; function toggleClass(elem, className, bool) { if (bool === true) return elem.classList.add(className); elem.classList.remove(className); } function createElement(tag, className, content) { var e = window.document.createElement(tag); className = className || ""; content = content || ""; e.className = className; if (content !== undefined) e.textContent = content; return e; } function clearNode(node) { while (node.firstChild) node.removeChild(node.firstChild); } function findParent(node, condition) { if (condition(node)) return node; else if (node.parentNode) return findParent(node.parentNode, condition); return undefined; // nothing found } function createNumberInput(inputClassName, opts) { var wrapper = createElement("div", "numInputWrapper"), numInput = createElement("input", "numInput " + inputClassName), arrowUp = createElement("span", "arrowUp"), arrowDown = createElement("span", "arrowDown"); if (navigator.userAgent.indexOf("MSIE 9.0") === -1) { numInput.type = "number"; } else { numInput.type = "text"; numInput.pattern = "\\d*"; } if (opts !== undefined) for (var key in opts) numInput.setAttribute(key, opts[key]); wrapper.appendChild(numInput); wrapper.appendChild(arrowUp); wrapper.appendChild(arrowDown); return wrapper; } function getEventTarget(event) { if (typeof event.composedPath === "function") { var path = event.composedPath(); return path[0]; } return event.target; } var doNothing = function () { return undefined; }; var monthToStr = function (monthNumber, shorthand, locale) { return locale.months[shorthand ? "shorthand" : "longhand"][monthNumber]; }; var revFormat = { D: doNothing, F: function (dateObj, monthName, locale) { dateObj.setMonth(locale.months.longhand.indexOf(monthName)); }, G: function (dateObj, hour) { dateObj.setHours(parseFloat(hour)); }, H: function (dateObj, hour) { dateObj.setHours(parseFloat(hour)); }, J: function (dateObj, day) { dateObj.setDate(parseFloat(day)); }, K: function (dateObj, amPM, locale) { dateObj.setHours((dateObj.getHours() % 12) + 12 * int(new RegExp(locale.amPM[1], "i").test(amPM))); }, M: function (dateObj, shortMonth, locale) { dateObj.setMonth(locale.months.shorthand.indexOf(shortMonth)); }, S: function (dateObj, seconds) { dateObj.setSeconds(parseFloat(seconds)); }, U: function (_, unixSeconds) { return new Date(parseFloat(unixSeconds) * 1000); }, W: function (dateObj, weekNum, locale) { var weekNumber = parseInt(weekNum); var date = new Date(dateObj.getFullYear(), 0, 2 + (weekNumber - 1) * 7, 0, 0, 0, 0); date.setDate(date.getDate() - date.getDay() + locale.firstDayOfWeek); return date; }, Y: function (dateObj, year) { dateObj.setFullYear(parseFloat(year)); }, Z: function (_, ISODate) { return new Date(ISODate); }, d: function (dateObj, day) { dateObj.setDate(parseFloat(day)); }, h: function (dateObj, hour) { dateObj.setHours(parseFloat(hour)); }, i: function (dateObj, minutes) { dateObj.setMinutes(parseFloat(minutes)); }, j: function (dateObj, day) { dateObj.setDate(parseFloat(day)); }, l: doNothing, m: function (dateObj, month) { dateObj.setMonth(parseFloat(month) - 1); }, n: function (dateObj, month) { dateObj.setMonth(parseFloat(month) - 1); }, s: function (dateObj, seconds) { dateObj.setSeconds(parseFloat(seconds)); }, u: function (_, unixMillSeconds) { return new Date(parseFloat(unixMillSeconds)); }, w: doNothing, y: function (dateObj, year) { dateObj.setFullYear(2000 + parseFloat(year)); } }; var tokenRegex = { D: "(\\w+)", F: "(\\w+)", G: "(\\d\\d|\\d)", H: "(\\d\\d|\\d)", J: "(\\d\\d|\\d)\\w+", K: "", M: "(\\w+)", S: "(\\d\\d|\\d)", U: "(.+)", W: "(\\d\\d|\\d)", Y: "(\\d{4})", Z: "(.+)", d: "(\\d\\d|\\d)", h: "(\\d\\d|\\d)", i: "(\\d\\d|\\d)", j: "(\\d\\d|\\d)", l: "(\\w+)", m: "(\\d\\d|\\d)", n: "(\\d\\d|\\d)", s: "(\\d\\d|\\d)", u: "(.+)", w: "(\\d\\d|\\d)", y: "(\\d{2})" }; var formats = { // get the date in UTC Z: function (date) { return date.toISOString(); }, // weekday name, short, e.g. Thu D: function (date, locale, options) { return locale.weekdays.shorthand[formats.w(date, locale, options)]; }, // full month name e.g. January F: function (date, locale, options) { return monthToStr(formats.n(date, locale, options) - 1, false, locale); }, // padded hour 1-12 G: function (date, locale, options) { return pad(formats.h(date, locale, options)); }, // hours with leading zero e.g. 03 H: function (date) { return pad(date.getHours()); }, // day (1-30) with ordinal suffix e.g. 1st, 2nd J: function (date, locale) { return locale.ordinal !== undefined ? date.getDate() + locale.ordinal(date.getDate()) : date.getDate(); }, // AM/PM K: function (date, locale) { return locale.amPM[int(date.getHours() > 11)]; }, // shorthand month e.g. Jan, Sep, Oct, etc M: function (date, locale) { return monthToStr(date.getMonth(), true, locale); }, // seconds 00-59 S: function (date) { return pad(date.getSeconds()); }, // unix timestamp U: function (date) { return date.getTime() / 1000; }, W: function (date, _, options) { return options.getWeek(date); }, // full year e.g. 2016 Y: function (date) { return date.getFullYear(); }, // day in month, padded (01-30) d: function (date) { return pad(date.getDate()); }, // hour from 1-12 (am/pm) h: function (date) { return (date.getHours() % 12 ? date.getHours() % 12 : 12); }, // minutes, padded with leading zero e.g. 09 i: function (date) { return pad(date.getMinutes()); }, // day in month (1-30) j: function (date) { return date.getDate(); }, // weekday name, full, e.g. Thursday l: function (date, locale) { return locale.weekdays.longhand[date.getDay()]; }, // padded month number (01-12) m: function (date) { return pad(date.getMonth() + 1); }, // the month number (1-12) n: function (date) { return date.getMonth() + 1; }, // seconds 0-59 s: function (date) { return date.getSeconds(); }, // Unix Milliseconds u: function (date) { return date.getTime(); }, // number of the day of the week w: function (date) { return date.getDay(); }, // last two digits of year e.g. 16 for 2016 y: function (date) { return String(date.getFullYear()).substring(2); } }; var createDateFormatter = function (_a) { var _b = _a.config, config = _b === void 0 ? defaults : _b, _c = _a.l10n, l10n = _c === void 0 ? english : _c; return function (dateObj, frmt, overrideLocale) { var locale = overrideLocale || l10n; if (config.formatDate !== undefined) { return config.formatDate(dateObj, frmt, locale); } return frmt .split("") .map(function (c, i, arr) { return formats[c] && arr[i - 1] !== "\\" ? formats[c](dateObj, locale, config) : c !== "\\" ? c : ""; }) .join(""); }; }; var createDateParser = function (_a) { var _b = _a.config, config = _b === void 0 ? defaults : _b, _c = _a.l10n, l10n = _c === void 0 ? english : _c; return function (date, givenFormat, timeless, customLocale) { if (date !== 0 && !date) return undefined; var locale = customLocale || l10n; var parsedDate; var dateOrig = date; if (date instanceof Date) parsedDate = new Date(date.getTime()); else if (typeof date !== "string" && date.toFixed !== undefined // timestamp ) // create a copy parsedDate = new Date(date); else if (typeof date === "string") { // date string var format = givenFormat || (config || defaults).dateFormat; var datestr = String(date).trim(); if (datestr === "today") { parsedDate = new Date(); timeless = true; } else if (/Z$/.test(datestr) || /GMT$/.test(datestr) // datestrings w/ timezone ) parsedDate = new Date(date); else if (config && config.parseDate) parsedDate = config.parseDate(date, format); else { parsedDate = !config || !config.noCalendar ? new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0) : new Date(new Date().setHours(0, 0, 0, 0)); var matched = void 0, ops = []; for (var i = 0, matchIndex = 0, regexStr = ""; i < format.length; i++) { var token_1 = format[i]; var isBackSlash = token_1 === "\\"; var escaped = format[i - 1] === "\\" || isBackSlash; if (tokenRegex[token_1] && !escaped) { regexStr += tokenRegex[token_1]; var match = new RegExp(regexStr).exec(date); if (match && (matched = true)) { ops[token_1 !== "Y" ? "push" : "unshift"]({ fn: revFormat[token_1], val: match[++matchIndex] }); } } else if (!isBackSlash) regexStr += "."; // don't really care ops.forEach(function (_a) { var fn = _a.fn, val = _a.val; return (parsedDate = fn(parsedDate, val, locale) || parsedDate); }); } parsedDate = matched ? parsedDate : undefined; } } /* istanbul ignore next */ if (!(parsedDate instanceof Date && !isNaN(parsedDate.getTime()))) { config.errorHandler(new Error("Invalid date provided: " + dateOrig)); return undefined; } if (timeless === true) parsedDate.setHours(0, 0, 0, 0); return parsedDate; }; }; /** * Compute the difference in dates, measured in ms */ function compareDates(date1, date2, timeless) { if (timeless === void 0) { timeless = true; } if (timeless !== false) { return (new Date(date1.getTime()).setHours(0, 0, 0, 0) - new Date(date2.getTime()).setHours(0, 0, 0, 0)); } return date1.getTime() - date2.getTime(); } var isBetween = function (ts, ts1, ts2) { return ts > Math.min(ts1, ts2) && ts < Math.max(ts1, ts2); }; var duration = { DAY: 86400000 }; if (typeof Object.assign !== "function") { Object.assign = function (target) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (!target) { throw TypeError("Cannot convert undefined or null to object"); } var _loop_1 = function (source) { if (source) { Object.keys(source).forEach(function (key) { return (target[key] = source[key]); }); } }; for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { var source = args_1[_a]; _loop_1(source); } return target; }; } var DEBOUNCED_CHANGE_MS = 300; function FlatpickrInstance(element, instanceConfig) { var self = { config: __assign({}, defaults, flatpickr.defaultConfig), l10n: english }; self.parseDate = createDateParser({ config: self.config, l10n: self.l10n }); self._handlers = []; self.pluginElements = []; self.loadedPlugins = []; self._bind = bind; self._setHoursFromDate = setHoursFromDate; self._positionCalendar = positionCalendar; self.changeMonth = changeMonth; self.changeYear = changeYear; self.clear = clear; self.close = close; self._createElement = createElement; self.destroy = destroy; self.isEnabled = isEnabled; self.jumpToDate = jumpToDate; self.open = open; self.redraw = redraw; self.set = set; self.setDate = setDate; self.toggle = toggle; function setupHelperFunctions() { self.utils = { getDaysInMonth: function (month, yr) { if (month === void 0) { month = self.currentMonth; } if (yr === void 0) { yr = self.currentYear; } if (month === 1 && ((yr % 4 === 0 && yr % 100 !== 0) || yr % 400 === 0)) return 29; return self.l10n.daysInMonth[month]; } }; } function init() { self.element = self.input = element; self.isOpen = false; parseConfig(); setupLocale(); setupInputs(); setupDates(); setupHelperFunctions(); if (!self.isMobile) build(); bindEvents(); if (self.selectedDates.length || self.config.noCalendar) { if (self.config.enableTime) { setHoursFromDate(self.config.noCalendar ? self.latestSelectedDateObj || self.config.minDate : undefined); } updateValue(false); } setCalendarWidth(); self.showTimeInput = self.selectedDates.length > 0 || self.config.noCalendar; var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); /* TODO: investigate this further Currently, there is weird positioning behavior in safari causing pages to scroll up. https://github.com/chmln/flatpickr/issues/563 However, most browsers are not Safari and positioning is expensive when used in scale. https://github.com/chmln/flatpickr/issues/1096 */ if (!self.isMobile && isSafari) { positionCalendar(); } triggerEvent("onReady"); } function bindToInstance(fn) { return fn.bind(self); } function setCalendarWidth() { var config = self.config; if (config.weekNumbers === false && config.showMonths === 1) return; else if (config.noCalendar !== true) { window.requestAnimationFrame(function () { if (self.calendarContainer !== undefined) { self.calendarContainer.style.visibility = "hidden"; self.calendarContainer.style.display = "block"; } if (self.daysContainer !== undefined) { var daysWidth = (self.days.offsetWidth + 1) * config.showMonths; self.daysContainer.style.width = daysWidth + "px"; self.calendarContainer.style.width = daysWidth + (self.weekWrapper !== undefined ? self.weekWrapper.offsetWidth : 0) + "px"; self.calendarContainer.style.removeProperty("visibility"); self.calendarContainer.style.removeProperty("display"); } }); } } /** * The handler for all events targeting the time inputs */ function updateTime(e) { if (self.selectedDates.length === 0) { setDefaultTime(); } if (e !== undefined && e.type !== "blur") { timeWrapper(e); } var prevValue = self._input.value; setHoursFromInputs(); updateValue(); if (self._input.value !== prevValue) { self._debouncedChange(); } } function ampm2military(hour, amPM) { return (hour % 12) + 12 * int(amPM === self.l10n.amPM[1]); } function military2ampm(hour) { switch (hour % 24) { case 0: case 12: return 12; default: return hour % 12; } } /** * Syncs the selected date object time with user's time input */ function setHoursFromInputs() { if (self.hourElement === undefined || self.minuteElement === undefined) return; var hours = (parseInt(self.hourElement.value.slice(-2), 10) || 0) % 24, minutes = (parseInt(self.minuteElement.value, 10) || 0) % 60, seconds = self.secondElement !== undefined ? (parseInt(self.secondElement.value, 10) || 0) % 60 : 0; if (self.amPM !== undefined) { hours = ampm2military(hours, self.amPM.textContent); } var limitMinHours = self.config.minTime !== undefined || (self.config.minDate && self.minDateHasTime && self.latestSelectedDateObj && compareDates(self.latestSelectedDateObj, self.config.minDate, true) === 0); var limitMaxHours = self.config.maxTime !== undefined || (self.config.maxDate && self.maxDateHasTime && self.latestSelectedDateObj && compareDates(self.latestSelectedDateObj, self.config.maxDate, true) === 0); if (limitMaxHours) { var maxTime = self.config.maxTime !== undefined ? self.config.maxTime : self.config.maxDate; hours = Math.min(hours, maxTime.getHours()); if (hours === maxTime.getHours()) minutes = Math.min(minutes, maxTime.getMinutes()); if (minutes === maxTime.getMinutes()) seconds = Math.min(seconds, maxTime.getSeconds()); } if (limitMinHours) { var minTime = self.config.minTime !== undefined ? self.config.minTime : self.config.minDate; hours = Math.max(hours, minTime.getHours()); if (hours === minTime.getHours()) minutes = Math.max(minutes, minTime.getMinutes()); if (minutes === minTime.getMinutes()) seconds = Math.max(seconds, minTime.getSeconds()); } setHours(hours, minutes, seconds); } /** * Syncs time input values with a date */ function setHoursFromDate(dateObj) { var date = dateObj || self.latestSelectedDateObj; if (date) setHours(date.getHours(), date.getMinutes(), date.getSeconds()); } function setDefaultHours() { var hours = self.config.defaultHour; var minutes = self.config.defaultMinute; var seconds = self.config.defaultSeconds; if (self.config.minDate !== undefined) { var minHr = self.config.minDate.getHours(); var minMinutes = self.config.minDate.getMinutes(); hours = Math.max(hours, minHr); if (hours === minHr) minutes = Math.max(minMinutes, minutes); if (hours === minHr && minutes === minMinutes) seconds = self.config.minDate.getSeconds(); } if (self.config.maxDate !== undefined) { var maxHr = self.config.maxDate.getHours(); var maxMinutes = self.config.maxDate.getMinutes(); hours = Math.min(hours, maxHr); if (hours === maxHr) minutes = Math.min(maxMinutes, minutes); if (hours === maxHr && minutes === maxMinutes) seconds = self.config.maxDate.getSeconds(); } setHours(hours, minutes, seconds); } /** * Sets the hours, minutes, and optionally seconds * of the latest selected date object and the * corresponding time inputs * @param {Number} hours the hour. whether its military * or am-pm gets inferred from config * @param {Number} minutes the minutes * @param {Number} seconds the seconds (optional) */ function setHours(hours, minutes, seconds) { if (self.latestSelectedDateObj !== undefined) { self.latestSelectedDateObj.setHours(hours % 24, minutes, seconds || 0, 0); } if (!self.hourElement || !self.minuteElement || self.isMobile) return; self.hourElement.value = pad(!self.config.time_24hr ? ((12 + hours) % 12) + 12 * int(hours % 12 === 0) : hours); self.minuteElement.value = pad(minutes); if (self.amPM !== undefined) self.amPM.textContent = self.l10n.amPM[int(hours >= 12)]; if (self.secondElement !== undefined) self.secondElement.value = pad(seconds); } /** * Handles the year input and incrementing events * @param {Event} event the keyup or increment event */ function onYearInput(event) { var year = parseInt(event.target.value) + (event.delta || 0); if (year / 1000 > 1 || (event.key === "Enter" && !/[^\d]/.test(year.toString()))) { changeYear(year); } } /** * Essentially addEventListener + tracking * @param {Element} element the element to addEventListener to * @param {String} event the event name * @param {Function} handler the event handler */ function bind(element, event, handler, options) { if (event instanceof Array) return event.forEach(function (ev) { return bind(element, ev, handler, options); }); if (element instanceof Array) return element.forEach(function (el) { return bind(el, event, handler, options); }); element.addEventListener(event, handler, options); self._handlers.push({ element: element, event: event, handler: handler, options: options }); } /** * A mousedown handler which mimics click. * Minimizes latency, since we don't need to wait for mouseup in most cases. * Also, avoids handling right clicks. * * @param {Function} handler the event handler */ function onClick(handler) { return function (evt) { evt.which === 1 && handler(evt); }; } function triggerChange() { triggerEvent("onChange"); } /** * Adds all the necessary event listeners */ function bindEvents() { if (self.config.wrap) { ["open", "close", "toggle", "clear"].forEach(function (evt) { Array.prototype.forEach.call(self.element.querySelectorAll("[data-" + evt + "]"), function (el) { return bind(el, "click", self[evt]); }); }); } if (self.isMobile) { setupMobile(); return; } var debouncedResize = debounce(onResize, 50); self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS); if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent)) bind(self.daysContainer, "mouseover", function (e) { if (self.config.mode === "range") onMouseOver(e.target); }); bind(window.document.body, "keydown", onKeyDown); if (!self.config.inline && !self.config.static) bind(window, "resize", debouncedResize); if (window.ontouchstart !== undefined) bind(window.document, "touchstart", documentClick); else bind(window.document, "mousedown", onClick(documentClick)); bind(window.document, "focus", documentClick, { capture: true }); if (self.config.clickOpens === true) { bind(self._input, "focus", self.open); bind(self._input, "mousedown", onClick(self.open)); } if (self.daysContainer !== undefined) { bind(self.monthNav, "mousedown", onClick(onMonthNavClick)); bind(self.monthNav, ["keyup", "increment"], onYearInput); bind(self.daysContainer, "mousedown", onClick(selectDate)); } if (self.timeContainer !== undefined && self.minuteElement !== undefined && self.hourElement !== undefined) { var selText = function (e) { return e.target.select(); }; bind(self.timeContainer, ["increment"], updateTime); bind(self.timeContainer, "blur", updateTime, { capture: true }); bind(self.timeContainer, "mousedown", onClick(timeIncrement)); bind([self.hourElement, self.minuteElement], ["focus", "click"], selText); if (self.secondElement !== undefined) bind(self.secondElement, "focus", function () { return self.secondElement && self.secondElement.select(); }); if (self.amPM !== undefined) { bind(self.amPM, "mousedown", onClick(function (e) { updateTime(e); triggerChange(); })); } } } /** * Set the calendar view to a particular date. * @param {Date} jumpDate the date to set the view to * @param {boolean} triggerChange if change events should be triggered */ function jumpToDate(jumpDate, triggerChange) { var jumpTo = jumpDate !== undefined ? self.parseDate(jumpDate) : self.latestSelectedDateObj || (self.config.minDate && self.config.minDate > self.now ? self.config.minDate : self.config.maxDate && self.config.maxDate < self.now ? self.config.maxDate : self.now); var oldYear = self.currentYear; var oldMonth = self.currentMonth; try { if (jumpTo !== undefined) { self.currentYear = jumpTo.getFullYear(); self.currentMonth = jumpTo.getMonth(); } } catch (e) { /* istanbul ignore next */ e.message = "Invalid date supplied: " + jumpTo; self.config.errorHandler(e); } if (triggerChange && self.currentYear !== oldYear) { triggerEvent("onYearChange"); buildMonthSwitch(); } if (triggerChange && (self.currentYear !== oldYear || self.currentMonth !== oldMonth)) { triggerEvent("onMonthChange"); } self.redraw(); } /** * The up/down arrow handler for time inputs * @param {Event} e the click event */ function timeIncrement(e) { if (~e.target.className.indexOf("arrow")) incrementNumInput(e, e.target.classList.contains("arrowUp") ? 1 : -1); } /** * Increments/decrements the value of input associ- * ated with the up/down arrow by dispatching an * "increment" event on the input. * * @param {Event} e the click event * @param {Number} delta the diff (usually 1 or -1) * @param {Element} inputElem the input element */ function incrementNumInput(e, delta, inputElem) { var target = e && e.target; var input = inputElem || (target && target.parentNode && target.parentNode.firstChild); var event = createEvent("increment"); event.delta = delta; input && input.dispatchEvent(event); } function build() { var fragment = window.document.createDocumentFragment(); self.calendarContainer = createElement("div", "flatpickr-calendar"); self.calendarContainer.tabIndex = -1; if (!self.config.noCalendar) { fragment.appendChild(buildMonthNav()); self.innerContainer = createElement("div", "flatpickr-innerContainer"); if (self.config.weekNumbers) { var _a = buildWeeks(), weekWrapper = _a.weekWrapper, weekNumbers = _a.weekNumbers; self.innerContainer.appendChild(weekWrapper); self.weekNumbers = weekNumbers; self.weekWrapper = weekWrapper; } self.rContainer = createElement("div", "flatpickr-rContainer"); self.rContainer.appendChild(buildWeekdays()); if (!self.daysContainer) { self.daysContainer = createElement("div", "flatpickr-days"); self.daysContainer.tabIndex = -1; } buildDays(); self.rContainer.appendChild(self.daysContainer); self.innerContainer.appendChild(self.rContainer); fragment.appendChild(self.innerContainer); } if (self.config.enableTime) { fragment.appendChild(buildTime()); } toggleClass(self.calendarContainer, "rangeMode", self.config.mode === "range"); toggleClass(self.calendarContainer, "animate", self.config.animate === true); toggleClass(self.calendarContainer, "multiMonth", self.config.showMonths > 1); self.calendarContainer.appendChild(fragment); var customAppend = self.config.appendTo !== undefined && self.config.appendTo.nodeType !== undefined; if (self.config.inline || self.config.static) { self.calendarContainer.classList.add(self.config.inline ? "inline" : "static"); if (self.config.inline) { if (!customAppend && self.element.parentNode) self.element.parentNode.insertBefore(self.calendarContainer, self._input.nextSibling); else if (self.config.appendTo !== undefined) self.config.appendTo.appendChild(self.calendarContainer); } if (self.config.static) { var wrapper = createElement("div", "flatpickr-wrapper"); if (self.element.parentNode) self.element.parentNode.insertBefore(wrapper, self.element); wrapper.appendChild(self.element); if (self.altInput) wrapper.appendChild(self.altInput); wrapper.appendChild(self.calendarContainer); } } if (!self.config.static && !self.config.inline) (self.config.appendTo !== undefined ? self.config.appendTo : window.document.body).appendChild(self.calendarContainer); } function createDay(className, date, dayNumber, i) { var dateIsEnabled = isEnabled(date, true), dayElement = createElement("span", "flatpickr-day " + className, date.getDate().toString()); dayElement.dateObj = date; dayElement.$i = i; dayElement.setAttribute("aria-label", self.formatDate(date, self.config.ariaDateFormat)); if (className.indexOf("hidden") === -1 && compareDates(date, self.now) === 0) { self.todayDateElem = dayElement; dayElement.classList.add("today"); dayElement.setAttribute("aria-current", "date"); } if (dateIsEnabled) { dayElement.tabIndex = -1; if (isDateSelected(date)) { dayElement.classList.add("selected"); self.selectedDateElem = dayElement; if (self.config.mode === "range") { toggleClass(dayElement, "startRange", self.selectedDates[0] && compareDates(date, self.selectedDates[0], true) === 0); toggleClass(dayElement, "endRange", self.selectedDates[1] && compareDates(date, self.selectedDates[1], true) === 0); if (className === "nextMonthDay") dayElement.classList.add("inRange"); } } } else { dayElement.classList.add("flatpickr-disabled"); } if (self.config.mode === "range") { if (isDateInRange(date) && !isDateSelected(date)) dayElement.classList.add("inRange"); } if (self.weekNumbers && self.config.showMonths === 1 && className !== "prevMonthDay" && dayNumber % 7 === 1) { self.weekNumbers.insertAdjacentHTML("beforeend", "<span class='flatpickr-day'>" + self.config.getWeek(date) + "</span>"); } triggerEvent("onDayCreate", dayElement); return dayElement; } function focusOnDayElem(targetNode) { targetNode.focus(); if (self.config.mode === "range") onMouseOver(targetNode); } function getFirstAvailableDay(delta) { var startMonth = delta > 0 ? 0 : self.config.showMonths - 1; var endMonth = delta > 0 ? self.config.showMonths : -1; for (var m = startMonth; m != endMonth; m += delta) { var month = self.daysContainer.children[m]; var startIndex = delta > 0 ? 0 : month.children.length - 1; var endIndex = delta > 0 ? month.children.length : -1; for (var i = startIndex; i != endIndex; i += delta) { var c = month.children[i]; if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj)) return c; } } return undefined; } function getNextAvailableDay(current, delta) { var givenMonth = current.className.indexOf("Month") === -1 ? current.dateObj.getMonth() : self.currentMonth; var endMonth = delta > 0 ? self.config.showMonths : -1; var loopDelta = delta > 0 ? 1 : -1; for (var m = givenMonth - self.currentMonth; m != endMonth; m += loopDelta) { var month = self.daysContainer.children[m]; var startIndex = givenMonth - self.currentMonth === m ? current.$i + delta : delta < 0 ? month.children.length - 1 : 0; var numMonthDays = month.children.length; for (var i = startIndex; i >= 0 && i < numMonthDays && i != (delta > 0 ? numMonthDays : -1); i += loopDelta) { var c = month.children[i]; if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj) && Math.abs(current.$i - i) >= Math.abs(delta)) return focusOnDayElem(c); } } self.changeMonth(loopDelta); focusOnDay(getFirstAvailableDay(loopDelta), 0); return undefined; } function focusOnDay(current, offset) { var dayFocused = isInView(document.activeElement || document.body); var startElem = current !== undefined ? current : dayFocused ? document.activeElement : self.selectedDateElem !== undefined && isInView(self.selectedDateElem) ? self.selectedDateElem : self.todayDateElem !== undefined && isInView(self.todayDateElem) ? self.todayDateElem : getFirstAvailableDay(offset > 0 ? 1 : -1); if (startElem === undefined) return self._input.focus(); if (!dayFocused) return focusOnDayElem(startElem); getNextAvailableDay(startElem, offset); } function buildMonthDays(year, month) { var firstOfMonth = (new Date(year, month, 1).getDay() - self.l10n.firstDayOfWeek + 7) % 7; var prevMonthDays = self.utils.getDaysInMonth((month - 1 + 12) % 12); var daysInMonth = self.utils.getDaysInMonth(month), days = window.document.createDocumentFragment(), isMultiMonth = self.config.showMonths > 1, prevMonthDayClass = isMultiMonth ? "prevMonthDay hidden" : "prevMonthDay", nextMonthDayClass = isMultiMonth ? "nextMonthDay hidden" : "nextMonthDay"; var dayNumber = prevMonthDays + 1 - firstOfMonth, dayIndex = 0; // prepend days from the ending of previous month for (; dayNumber <= prevMonthDays; dayNumber++, dayIndex++) { days.appendChild(createDay(prevMonthDayClass, new Date(year, month - 1, dayNumber), dayNumber, dayIndex)); } // Start at 1 since there is no 0th day for (dayNumber = 1; dayNumber <= daysInMonth; dayNumber++, dayIndex++) { days.appendChild(createDay("", new Date(year, month, dayNumber), dayNumber, dayIndex)); } // append days from the next month for (var dayNum = daysInMonth + 1; dayNum <= 42 - firstOfMonth && (self.config.showMonths === 1 || dayIndex % 7 !== 0); dayNum++, dayIndex++) { days.appendChild(createDay(nextMonthDayClass, new Date(year, month + 1, dayNum % daysInMonth), dayNum, dayIndex)); } //updateNavigationCurrentMonth(); var dayContainer = createElement("div", "dayContainer"); dayContainer.appendChild(days); return dayContainer; } function buildDays() { if (self.daysContainer === undefined) { return; } clearNode(self.daysContainer); // TODO: week numbers for each month if (self.weekNumbers) clearNode(self.weekNumbers); var frag = document.createDocumentFragment(); for (var i = 0; i < self.config.showMonths; i++) { var d = new Date(self.currentYear, self.currentMonth, 1); d.setMonth(self.currentMonth + i); frag.appendChild(buildMonthDays(d.getFullYear(), d.getMonth())); } self.daysContainer.appendChild(frag); self.days = self.daysContainer.firstChild; if (self.config.mode === "range" && self.selectedDates.length === 1) { onMouseOver(); } } function buildMonthSwitch() { if (self.config.showMonths > 1) return; var shouldBuildMonth = function (month) { if (self.config.minDate !== undefined && self.currentYear === self.config.minDate.getFullYear() && month < self.config.minDate.getMonth()) { return false; } return !(self.config.maxDate !== undefined && self.currentYear === self.config.maxDate.getFullYear() && month > self.config.maxDate.getMonth()); }; self.monthsDropdownContainer.tabIndex = -1; self.monthsDropdownContainer.innerHTML = ""; for (var i = 0; i < 12; i++) { if (!shouldBuildMonth(i)) continue; var month = createElement("option", "flatpickr-monthDropdown-month"); month.value = new Date(self.currentYear, i).getMonth().toString(); month.textContent = monthToStr(i, false, self.l10n); month.tabIndex = -1; if (self.currentMonth === i) { month.selected = true; } self.monthsDropdownContainer.appendChild(month); } } function buildMonth() { var container = createElement("div", "flatpickr-month"); var monthNavFragment = window.document.createDocumentFragment(); var monthElement; if (self.config.showMonths > 1) { monthElement = createElement("span", "cur-month"); } else { self.monthsDropdownContainer = createElement("select", "flatpickr-monthDropdown-months"); bind(self.monthsDropdownContainer, "change", function (e) { var target = e.target; var selectedMonth = parseInt(target.value, 10); self.changeMonth(selectedMonth - self.currentMonth); triggerEvent("onMonthChange"); }); buildMonthSwitch(); monthElement = self.monthsDropdownContainer; } var yearInput = createNumberInput("cur-year", { tabindex: "-1" }); var yearElement = yearInput.getElementsByTagName("input")[0]; yearElement.setAttribute("aria-label", self.l10n.yearAriaLabel); if (self.config.minDate) { yearElement.setAttribute("min", self.config.minDate.getFullYear().toString()); } if (self.config.maxDate) { yearElement.setAttribute("max", self.config.maxDate.getFullYear().toString()); yearElement.disabled = !!self.config.minDate && self.config.minDate.getFullYear() === self.config.maxDate.getFullYear(); } var currentMonth = createElement("div", "flatpickr-current-month"); currentMonth.appendChild(monthElement); currentMonth.appendChild(yearInput); monthNavFragment.appendChild(currentMonth); container.appendChild(monthNavFragment); return { container: container, yearElement: yearElement, monthElement: monthElement<|fim▁hole|> } function buildMonths() { clearNode(self.monthNav); self.monthNav.appendChild(self.prevMonthNav); if (self.config.showMonths) { self.yearElements = []; self.monthElements = []; } for (var m = self.config.showMonths; m--;) { var month = buildMonth(); self.yearElements.push(month.yearElement); self.monthElements.push(month.monthElement); self.monthNav.appendChild(month.container); } self.monthNav.appendChild(self.nextMonthNav); } function buildMonthNav() { self.monthNav = createElement("div", "flatpickr-months"); self.yearElements = []; self.monthElements = []; self.prevMonthNav = createElement("span", "flatpickr-prev-month"); self.prevMonthNav.innerHTML = self.config.prevArrow; self.nextMonthNav = createElement("span", "flatpickr-next-month"); self.nextMonthNav.innerHTML = self.config.nextArrow; buildMonths(); Object.defineProperty(self, "_hidePrevMonthArrow", { get: function () { return self.__hidePrevMonthArrow; }, set: function (bool) { if (self.__hidePrevMonthArrow !== bool) { toggleClass(self.prevMonthNav, "flatpickr-disabled", bool); self.__hidePrevMonthArrow = bool; } } }); Object.defineProperty(self, "_hideNextMonthArrow", { get: function () { return self.__hideNextMonthArrow; }, set: function (bool) { if (self.__hideNextMonthArrow !== bool) { toggleClass(self.nextMonthNav, "flatpickr-disabled", bool); self.__hideNextMonthArrow = bool; } } }); self.currentYearElement = self.yearElements[0]; updateNavigationCurrentMonth(); return self.monthNav; } function buildTime() { self.calendarContainer.classList.add("hasTime"); if (self.config.noCalendar) self.calendarContainer.classList.add("noCalendar"); self.timeContainer = createElement("div", "flatpickr-time"); self.timeContainer.tabIndex = -1; var separator = createElement("span", "flatpickr-time-separator", ":"); var hourInput = createNumberInput("flatpickr-hour"); self.hourElement = hourInput.getElementsByTagName("input")[0]; var minuteInput = createNumberInput("flatpickr-minute"); self.minuteElement = minuteInput.getElementsByTagName("input")[0]; self.hourElement.tabIndex = self.minuteElement.tabIndex = -1; self.hourElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getHours() : self.config.time_24hr ? self.config.defaultHour : military2ampm(self.config.defaultHour)); self.minuteElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getMinutes() : self.config.defaultMinute); self.hourElement.setAttribute("step", self.config.hourIncrement.toString()); self.minuteElement.setAttribute("step", self.config.minuteIncrement.toString()); self.hourElement.setAttribute("min", self.config.time_24hr ? "0" : "1"); self.hourElement.setAttribute("max", self.config.time_24hr ? "23" : "12"); self.minuteElement.setAttribute("min", "0"); self.minuteElement.setAttribute("max", "59"); self.timeContainer.appendChild(hourInput); self.timeContainer.appendChild(separator); self.timeContainer.appendChild(minuteInput); if (self.config.time_24hr) self.timeContainer.classList.add("time24hr"); if (self.config.enableSeconds) { self.timeContainer.classList.add("hasSeconds"); var secondInput = createNumberInput("flatpickr-second"); self.secondElement = secondInput.getElementsByTagName("input")[0]; self.secondElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getSeconds() : self.config.defaultSeconds); self.secondElement.setAttribute("step", self.minuteElement.getAttribute("step")); self.secondElement.setAttribute("min", "0"); self.secondElement.setAttribute("max", "59"); self.timeContainer.appendChild(createElement("span", "flatpickr-time-separator", ":")); self.timeContainer.appendChild(secondInput); } if (!self.config.time_24hr) { // add self.amPM if appropriate self.amPM = createElement("span", "flatpickr-am-pm", self.l10n.amPM[int((self.latestSelectedDateObj ? self.hourElement.value : self.config.defaultHour) > 11)]); self.amPM.title = self.l10n.toggleTitle; self.amPM.tabIndex = -1; self.timeContainer.appendChild(self.amPM); } return self.timeContainer; } function buildWeekdays() { if (!self.weekdayContainer) self.weekdayContainer = createElement("div", "flatpickr-weekdays"); else clearNode(self.weekdayContainer); for (var i = self.config.showMonths; i--;) { var container = createElement("div", "flatpickr-weekdaycontainer"); self.weekdayContainer.appendChild(container); } updateWeekdays(); return self.weekdayContainer; } function updateWeekdays() { var firstDayOfWeek = self.l10n.firstDayOfWeek; var weekdays = self.l10n.weekdays.shorthand.slice(); if (firstDayOfWeek > 0 && firstDayOfWeek < weekdays.length) { weekdays = weekdays.splice(firstDayOfWeek, weekdays.length).concat(weekdays.splice(0, firstDayOfWeek)); } for (var i = self.config.showMonths; i--;) { self.weekdayContainer.children[i].innerHTML = "\n <span class='flatpickr-weekday'>\n " + weekdays.join("</span><span class='flatpickr-weekday'>") + "\n </span>\n "; } } /* istanbul ignore next */ function buildWeeks() { self.calendarContainer.classList.add("hasWeeks"); var weekWrapper = createElement("div", "flatpickr-weekwrapper"); weekWrapper.appendChild(createElement("span", "flatpickr-weekday", self.l10n.weekAbbreviation)); var weekNumbers = createElement("div", "flatpickr-weeks"); weekWrapper.appendChild(weekNumbers); return { weekWrapper: weekWrapper, weekNumbers: weekNumbers }; } function changeMonth(value, isOffset) { if (isOffset === void 0) { isOffset = true; } var delta = isOffset ? value : value - self.currentMonth; if ((delta < 0 && self._hidePrevMonthArrow === true) || (delta > 0 && self._hideNextMonthArrow === true)) return; self.currentMonth += delta; if (self.currentMonth < 0 || self.currentMonth > 11) { self.currentYear += self.currentMonth > 11 ? 1 : -1; self.currentMonth = (self.currentMonth + 12) % 12; triggerEvent("onYearChange"); buildMonthSwitch(); } buildDays(); triggerEvent("onMonthChange"); updateNavigationCurrentMonth(); } function clear(triggerChangeEvent, toInitial) { if (triggerChangeEvent === void 0) { triggerChangeEvent = true; } if (toInitial === void 0) { toInitial = true; } self.input.value = ""; if (self.altInput !== undefined) self.altInput.value = ""; if (self.mobileInput !== undefined) self.mobileInput.value = ""; self.selectedDates = []; self.latestSelectedDateObj = undefined; if (toInitial === true) { self.currentYear = self._initialDate.getFullYear(); self.currentMonth = self._initialDate.getMonth(); } self.showTimeInput = false; if (self.config.enableTime === true) { setDefaultHours(); } self.redraw(); if (triggerChangeEvent) // triggerChangeEvent is true (default) or an Event triggerEvent("onChange"); } function close() { self.isOpen = false; if (!self.isMobile) { if (self.calendarContainer !== undefined) { self.calendarContainer.classList.remove("open"); } if (self._input !== undefined) { self._input.classList.remove("active"); } } triggerEvent("onClose"); } function destroy() { if (self.config !== undefined) triggerEvent("onDestroy"); for (var i = self._handlers.length; i--;) { var h = self._handlers[i]; h.element.removeEventListener(h.event, h.handler, h.options); } self._handlers = []; if (self.mobileInput) { if (self.mobileInput.parentNode) self.mobileInput.parentNode.removeChild(self.mobileInput); self.mobileInput = undefined; } else if (self.calendarContainer && self.calendarContainer.parentNode) { if (self.config.static && self.calendarContainer.parentNode) { var wrapper = self.calendarContainer.parentNode; wrapper.lastChild && wrapper.removeChild(wrapper.lastChild); if (wrapper.parentNode) { while (wrapper.firstChild) wrapper.parentNode.insertBefore(wrapper.firstChild, wrapper); wrapper.parentNode.removeChild(wrapper); } } else self.calendarContainer.parentNode.removeChild(self.calendarContainer); } if (self.altInput) { self.input.type = "text"; if (self.altInput.parentNode) self.altInput.parentNode.removeChild(self.altInput); delete self.altInput; } if (self.input) { self.input.type = self.input._type; self.input.classList.remove("flatpickr-input"); self.input.removeAttribute("readonly"); self.input.value = ""; } [ "_showTimeInput", "latestSelectedDateObj", "_hideNextMonthArrow", "_hidePrevMonthArrow", "__hideNextMonthArrow", "__hidePrevMonthArrow", "isMobile", "isOpen", "selectedDateElem", "minDateHasTime", "maxDateHasTime", "days", "daysContainer", "_input", "_positionElement", "innerContainer", "rContainer", "monthNav", "todayDateElem", "calendarContainer", "weekdayContainer", "prevMonthNav", "nextMonthNav", "monthsDropdownContainer", "currentMonthElement", "currentYearElement", "navigationCurrentMonth", "selectedDateElem", "config", ].forEach(function (k) { try { delete self[k]; } catch (_) { } }); } function isCalendarElem(elem) { if (self.config.appendTo && self.config.appendTo.contains(elem)) return true; return self.calendarContainer.contains(elem); } function documentClick(e) { if (self.isOpen && !self.config.inline) { var eventTarget_1 = getEventTarget(e); var isCalendarElement = isCalendarElem(eventTarget_1); var isInput = eventTarget_1 === self.input || eventTarget_1 === self.altInput || self.element.contains(eventTarget_1) || // web components // e.path is not present in all browsers. circumventing typechecks (e.path && e.path.indexOf && (~e.path.indexOf(self.input) || ~e.path.indexOf(self.altInput))); var lostFocus = e.type === "blur" ? isInput && e.relatedTarget && !isCalendarElem(e.relatedTarget) : !isInput && !isCalendarElement && !isCalendarElem(e.relatedTarget); var isIgnored = !self.config.ignoredFocusElements.some(function (elem) { return elem.contains(eventTarget_1); }); if (lostFocus && isIgnored) { self.close(); if (self.config.mode === "range" && self.selectedDates.length === 1) { self.clear(false); self.redraw(); } } } } function changeYear(newYear) { if (!newYear || (self.config.minDate && newYear < self.config.minDate.getFullYear()) || (self.config.maxDate && newYear > self.config.maxDate.getFullYear())) return; var newYearNum = newYear, isNewYear = self.currentYear !== newYearNum; self.currentYear = newYearNum || self.currentYear; if (self.config.maxDate && self.currentYear === self.config.maxDate.getFullYear()) { self.currentMonth = Math.min(self.config.maxDate.getMonth(), self.currentMonth); } else if (self.config.minDate && self.currentYear === self.config.minDate.getFullYear()) { self.currentMonth = Math.max(self.config.minDate.getMonth(), self.currentMonth); } if (isNewYear) { self.redraw(); triggerEvent("onYearChange"); buildMonthSwitch(); } } function isEnabled(date, timeless) { if (timeless === void 0) { timeless = true; } var dateToCheck = self.parseDate(date, undefined, timeless); // timeless if ((self.config.minDate && dateToCheck && compareDates(dateToCheck, self.config.minDate, timeless !== undefined ? timeless : !self.minDateHasTime) < 0) || (self.config.maxDate && dateToCheck && compareDates(dateToCheck, self.config.maxDate, timeless !== undefined ? timeless : !self.maxDateHasTime) > 0)) return false; if (self.config.enable.length === 0 && self.config.disable.length === 0) return true; if (dateToCheck === undefined) return false; var bool = self.config.enable.length > 0, array = bool ? self.config.enable : self.config.disable; for (var i = 0, d = void 0; i < array.length; i++) { d = array[i]; if (typeof d === "function" && d(dateToCheck) // disabled by function ) return bool; else if (d instanceof Date && dateToCheck !== undefined && d.getTime() === dateToCheck.getTime()) // disabled by date return bool; else if (typeof d === "string" && dateToCheck !== undefined) { // disabled by date string var parsed = self.parseDate(d, undefined, true); return parsed && parsed.getTime() === dateToCheck.getTime() ? bool : !bool; } else if ( // disabled by range typeof d === "object" && dateToCheck !== undefined && d.from && d.to && dateToCheck.getTime() >= d.from.getTime() && dateToCheck.getTime() <= d.to.getTime()) return bool; } return !bool; } function isInView(elem) { if (self.daysContainer !== undefined) return (elem.className.indexOf("hidden") === -1 && self.daysContainer.contains(elem)); return false; } function onKeyDown(e) { // e.key e.keyCode // "Backspace" 8 // "Tab" 9 // "Enter" 13 // "Escape" (IE "Esc") 27 // "ArrowLeft" (IE "Left") 37 // "ArrowUp" (IE "Up") 38 // "ArrowRight" (IE "Right") 39 // "ArrowDown" (IE "Down") 40 // "Delete" (IE "Del") 46 var isInput = e.target === self._input; var allowInput = self.config.allowInput; var allowKeydown = self.isOpen && (!allowInput || !isInput); var allowInlineKeydown = self.config.inline && isInput && !allowInput; if (e.keyCode === 13 && isInput) { if (allowInput) { self.setDate(self._input.value, true, e.target === self.altInput ? self.config.altFormat : self.config.dateFormat); return e.target.blur(); } else { self.open(); } } else if (isCalendarElem(e.target) || allowKeydown || allowInlineKeydown) { var isTimeObj = !!self.timeContainer && self.timeContainer.contains(e.target); switch (e.keyCode) { case 13: if (isTimeObj) { e.preventDefault(); updateTime(); focusAndClose(); } else selectDate(e); break; case 27: // escape e.preventDefault(); focusAndClose(); break; case 8: case 46: if (isInput && !self.config.allowInput) { e.preventDefault(); self.clear(); } break; case 37: case 39: if (!isTimeObj && !isInput) { e.preventDefault(); if (self.daysContainer !== undefined && (allowInput === false || (document.activeElement && isInView(document.activeElement)))) { var delta_1 = e.keyCode === 39 ? 1 : -1; if (!e.ctrlKey) focusOnDay(undefined, delta_1); else { e.stopPropagation(); changeMonth(delta_1); focusOnDay(getFirstAvailableDay(1), 0); } } } else if (self.hourElement) self.hourElement.focus(); break; case 38: case 40: e.preventDefault(); var delta = e.keyCode === 40 ? 1 : -1; if ((self.daysContainer && e.target.$i !== undefined) || e.target === self.input) { if (e.ctrlKey) { e.stopPropagation(); changeYear(self.currentYear - delta); focusOnDay(getFirstAvailableDay(1), 0); } else if (!isTimeObj) focusOnDay(undefined, delta * 7); } else if (e.target === self.currentYearElement) { changeYear(self.currentYear - delta); } else if (self.config.enableTime) { if (!isTimeObj && self.hourElement) self.hourElement.focus(); updateTime(e); self._debouncedChange(); } break; case 9: if (isTimeObj) { var elems = [ self.hourElement, self.minuteElement, self.secondElement, self.amPM, ] .concat(self.pluginElements) .filter(function (x) { return x; }); var i = elems.indexOf(e.target); if (i !== -1) { var target = elems[i + (e.shiftKey ? -1 : 1)]; e.preventDefault(); (target || self._input).focus(); } } else if (!self.config.noCalendar && self.daysContainer && self.daysContainer.contains(e.target) && e.shiftKey) { e.preventDefault(); self._input.focus(); } break; default: break; } } if (self.amPM !== undefined && e.target === self.amPM) { switch (e.key) { case self.l10n.amPM[0].charAt(0): case self.l10n.amPM[0].charAt(0).toLowerCase(): self.amPM.textContent = self.l10n.amPM[0]; setHoursFromInputs(); updateValue(); break; case self.l10n.amPM[1].charAt(0): case self.l10n.amPM[1].charAt(0).toLowerCase(): self.amPM.textContent = self.l10n.amPM[1]; setHoursFromInputs(); updateValue(); break; } } if (isInput || isCalendarElem(e.target)) { triggerEvent("onKeyDown", e); } } function onMouseOver(elem) { if (self.selectedDates.length !== 1 || (elem && (!elem.classList.contains("flatpickr-day") || elem.classList.contains("flatpickr-disabled")))) return; var hoverDate = elem ? elem.dateObj.getTime() : self.days.firstElementChild.dateObj.getTime(), initialDate = self.parseDate(self.selectedDates[0], undefined, true).getTime(), rangeStartDate = Math.min(hoverDate, self.selectedDates[0].getTime()), rangeEndDate = Math.max(hoverDate, self.selectedDates[0].getTime()); var containsDisabled = false; var minRange = 0, maxRange = 0; for (var t = rangeStartDate; t < rangeEndDate; t += duration.DAY) { if (!isEnabled(new Date(t), true)) { containsDisabled = containsDisabled || (t > rangeStartDate && t < rangeEndDate); if (t < initialDate && (!minRange || t > minRange)) minRange = t; else if (t > initialDate && (!maxRange || t < maxRange)) maxRange = t; } } for (var m = 0; m < self.config.showMonths; m++) { var month = self.daysContainer.children[m]; var _loop_1 = function (i, l) { var dayElem = month.children[i], date = dayElem.dateObj; var timestamp = date.getTime(); var outOfRange = (minRange > 0 && timestamp < minRange) || (maxRange > 0 && timestamp > maxRange); if (outOfRange) { dayElem.classList.add("notAllowed"); ["inRange", "startRange", "endRange"].forEach(function (c) { dayElem.classList.remove(c); }); return "continue"; } else if (containsDisabled && !outOfRange) return "continue"; ["startRange", "inRange", "endRange", "notAllowed"].forEach(function (c) { dayElem.classList.remove(c); }); if (elem !== undefined) { elem.classList.add(hoverDate <= self.selectedDates[0].getTime() ? "startRange" : "endRange"); if (initialDate < hoverDate && timestamp === initialDate) dayElem.classList.add("startRange"); else if (initialDate > hoverDate && timestamp === initialDate) dayElem.classList.add("endRange"); if (timestamp >= minRange && (maxRange === 0 || timestamp <= maxRange) && isBetween(timestamp, initialDate, hoverDate)) dayElem.classList.add("inRange"); } }; for (var i = 0, l = month.children.length; i < l; i++) { _loop_1(i, l); } } } function onResize() { if (self.isOpen && !self.config.static && !self.config.inline) positionCalendar(); } function setDefaultTime() { self.setDate(self.config.minDate !== undefined ? new Date(self.config.minDate.getTime()) : new Date(), true); setDefaultHours(); updateValue(); } function open(e, positionElement) { if (positionElement === void 0) { positionElement = self._positionElement; } if (self.isMobile === true) { if (e) { e.preventDefault(); e.target && e.target.blur(); } if (self.mobileInput !== undefined) { self.mobileInput.focus(); self.mobileInput.click(); } triggerEvent("onOpen"); return; } if (self._input.disabled || self.config.inline) return; var wasOpen = self.isOpen; self.isOpen = true; if (!wasOpen) { self.calendarContainer.classList.add("open"); self._input.classList.add("active"); triggerEvent("onOpen"); positionCalendar(positionElement); } if (self.config.enableTime === true && self.config.noCalendar === true) { if (self.selectedDates.length === 0) { setDefaultTime(); } if (self.config.allowInput === false && (e === undefined || !self.timeContainer.contains(e.relatedTarget))) { setTimeout(function () { return self.hourElement.select(); }, 50); } } } function minMaxDateSetter(type) { return function (date) { var dateObj = (self.config["_" + type + "Date"] = self.parseDate(date, self.config.dateFormat)); var inverseDateObj = self.config["_" + (type === "min" ? "max" : "min") + "Date"]; if (dateObj !== undefined) { self[type === "min" ? "minDateHasTime" : "maxDateHasTime"] = dateObj.getHours() > 0 || dateObj.getMinutes() > 0 || dateObj.getSeconds() > 0; } if (self.selectedDates) { self.selectedDates = self.selectedDates.filter(function (d) { return isEnabled(d); }); if (!self.selectedDates.length && type === "min") setHoursFromDate(dateObj); updateValue(); } if (self.daysContainer) { redraw(); if (dateObj !== undefined) self.currentYearElement[type] = dateObj.getFullYear().toString(); else self.currentYearElement.removeAttribute(type); self.currentYearElement.disabled = !!inverseDateObj && dateObj !== undefined && inverseDateObj.getFullYear() === dateObj.getFullYear(); } }; } function parseConfig() { var boolOpts = [ "wrap", "weekNumbers", "allowInput", "clickOpens", "time_24hr", "enableTime", "noCalendar", "altInput", "shorthandCurrentMonth", "inline", "static", "enableSeconds", "disableMobile", ]; var userConfig = __assign({}, instanceConfig, JSON.parse(JSON.stringify(element.dataset || {}))); var formats = {}; self.config.parseDate = userConfig.parseDate; self.config.formatDate = userConfig.formatDate; Object.defineProperty(self.config, "enable", { get: function () { return self.config._enable; }, set: function (dates) { self.config._enable = parseDateRules(dates); } }); Object.defineProperty(self.config, "disable", { get: function () { return self.config._disable; }, set: function (dates) { self.config._disable = parseDateRules(dates); } }); var timeMode = userConfig.mode === "time"; if (!userConfig.dateFormat && (userConfig.enableTime || timeMode)) { var defaultDateFormat = flatpickr.defaultConfig.dateFormat || defaults.dateFormat; formats.dateFormat = userConfig.noCalendar || timeMode ? "H:i" + (userConfig.enableSeconds ? ":S" : "") : defaultDateFormat + " H:i" + (userConfig.enableSeconds ? ":S" : ""); } if (userConfig.altInput && (userConfig.enableTime || timeMode) && !userConfig.altFormat) { var defaultAltFormat = flatpickr.defaultConfig.altFormat || defaults.altFormat; formats.altFormat = userConfig.noCalendar || timeMode ? "h:i" + (userConfig.enableSeconds ? ":S K" : " K") : defaultAltFormat + (" h:i" + (userConfig.enableSeconds ? ":S" : "") + " K"); } if (!userConfig.altInputClass) { self.config.altInputClass = self.input.className + " " + self.config.altInputClass; } Object.defineProperty(self.config, "minDate", { get: function () { return self.config._minDate; }, set: minMaxDateSetter("min") }); Object.defineProperty(self.config, "maxDate", { get: function () { return self.config._maxDate; }, set: minMaxDateSetter("max") }); var minMaxTimeSetter = function (type) { return function (val) { self.config[type === "min" ? "_minTime" : "_maxTime"] = self.parseDate(val, "H:i"); }; }; Object.defineProperty(self.config, "minTime", { get: function () { return self.config._minTime; }, set: minMaxTimeSetter("min") }); Object.defineProperty(self.config, "maxTime", { get: function () { return self.config._maxTime; }, set: minMaxTimeSetter("max") }); if (userConfig.mode === "time") { self.config.noCalendar = true; self.config.enableTime = true; } Object.assign(self.config, formats, userConfig); for (var i = 0; i < boolOpts.length; i++) self.config[boolOpts[i]] = self.config[boolOpts[i]] === true || self.config[boolOpts[i]] === "true"; HOOKS.filter(function (hook) { return self.config[hook] !== undefined; }).forEach(function (hook) { self.config[hook] = arrayify(self.config[hook] || []).map(bindToInstance); }); self.isMobile = !self.config.disableMobile && !self.config.inline && self.config.mode === "single" && !self.config.disable.length && !self.config.enable.length && !self.config.weekNumbers && /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); for (var i = 0; i < self.config.plugins.length; i++) { var pluginConf = self.config.plugins[i](self) || {}; for (var key in pluginConf) { if (HOOKS.indexOf(key) > -1) { self.config[key] = arrayify(pluginConf[key]) .map(bindToInstance) .concat(self.config[key]); } else if (typeof userConfig[key] === "undefined") self.config[key] = pluginConf[key]; } } triggerEvent("onParseConfig"); } function setupLocale() { if (typeof self.config.locale !== "object" && typeof flatpickr.l10ns[self.config.locale] === "undefined") self.config.errorHandler(new Error("flatpickr: invalid locale " + self.config.locale)); self.l10n = __assign({}, flatpickr.l10ns["default"], (typeof self.config.locale === "object" ? self.config.locale : self.config.locale !== "default" ? flatpickr.l10ns[self.config.locale] : undefined)); tokenRegex.K = "(" + self.l10n.amPM[0] + "|" + self.l10n.amPM[1] + "|" + self.l10n.amPM[0].toLowerCase() + "|" + self.l10n.amPM[1].toLowerCase() + ")"; var userConfig = __assign({}, instanceConfig, JSON.parse(JSON.stringify(element.dataset || {}))); if (userConfig.time_24hr === undefined && flatpickr.defaultConfig.time_24hr === undefined) { self.config.time_24hr = self.l10n.time_24hr; } self.formatDate = createDateFormatter(self); self.parseDate = createDateParser({ config: self.config, l10n: self.l10n }); } function positionCalendar(customPositionElement) { if (self.calendarContainer === undefined) return; triggerEvent("onPreCalendarPosition"); var positionElement = customPositionElement || self._positionElement; var calendarHeight = Array.prototype.reduce.call(self.calendarContainer.children, (function (acc, child) { return acc + child.offsetHeight; }), 0), calendarWidth = self.calendarContainer.offsetWidth, configPos = self.config.position.split(" "), configPosVertical = configPos[0], configPosHorizontal = configPos.length > 1 ? configPos[1] : null, inputBounds = positionElement.getBoundingClientRect(), distanceFromBottom = window.innerHeight - inputBounds.bottom, showOnTop = configPosVertical === "above" || (configPosVertical !== "below" && distanceFromBottom < calendarHeight && inputBounds.top > calendarHeight); var top = window.pageYOffset + inputBounds.top + (!showOnTop ? positionElement.offsetHeight + 2 : -calendarHeight - 2); toggleClass(self.calendarContainer, "arrowTop", !showOnTop); toggleClass(self.calendarContainer, "arrowBottom", showOnTop); if (self.config.inline) return; var left = window.pageXOffset + inputBounds.left - (configPosHorizontal != null && configPosHorizontal === "center" ? (calendarWidth - inputBounds.width) / 2 : 0); var right = window.document.body.offsetWidth - inputBounds.right; var rightMost = left + calendarWidth > window.document.body.offsetWidth; var centerMost = right + calendarWidth > window.document.body.offsetWidth; toggleClass(self.calendarContainer, "rightMost", rightMost); if (self.config.static) return; self.calendarContainer.style.top = top + "px"; if (!rightMost) { self.calendarContainer.style.left = left + "px"; self.calendarContainer.style.right = "auto"; } else if (!centerMost) { self.calendarContainer.style.left = "auto"; self.calendarContainer.style.right = right + "px"; } else { var doc = document.styleSheets[0]; // some testing environments don't have css support if (doc === undefined) return; var bodyWidth = window.document.body.offsetWidth; var centerLeft = Math.max(0, bodyWidth / 2 - calendarWidth / 2); var centerBefore = ".flatpickr-calendar.centerMost:before"; var centerAfter = ".flatpickr-calendar.centerMost:after"; var centerIndex = doc.cssRules.length; var centerStyle = "{left:" + inputBounds.left + "px;right:auto;}"; toggleClass(self.calendarContainer, "rightMost", false); toggleClass(self.calendarContainer, "centerMost", true); doc.insertRule(centerBefore + "," + centerAfter + centerStyle, centerIndex); self.calendarContainer.style.left = centerLeft + "px"; self.calendarContainer.style.right = "auto"; } } function redraw() { if (self.config.noCalendar || self.isMobile) return; updateNavigationCurrentMonth(); buildDays(); } function focusAndClose() { self._input.focus(); if (window.navigator.userAgent.indexOf("MSIE") !== -1 || navigator.msMaxTouchPoints !== undefined) { // hack - bugs in the way IE handles focus keeps the calendar open setTimeout(self.close, 0); } else { self.close(); } } function selectDate(e) { e.preventDefault(); e.stopPropagation(); var isSelectable = function (day) { return day.classList && day.classList.contains("flatpickr-day") && !day.classList.contains("flatpickr-disabled") && !day.classList.contains("notAllowed"); }; var t = findParent(e.target, isSelectable); if (t === undefined) return; var target = t; var selectedDate = (self.latestSelectedDateObj = new Date(target.dateObj.getTime())); var shouldChangeMonth = (selectedDate.getMonth() < self.currentMonth || selectedDate.getMonth() > self.currentMonth + self.config.showMonths - 1) && self.config.mode !== "range"; self.selectedDateElem = target; if (self.config.mode === "single") self.selectedDates = [selectedDate]; else if (self.config.mode === "multiple") { var selectedIndex = isDateSelected(selectedDate); if (selectedIndex) self.selectedDates.splice(parseInt(selectedIndex), 1); else self.selectedDates.push(selectedDate); } else if (self.config.mode === "range") { if (self.selectedDates.length === 2) { self.clear(false, false); } self.latestSelectedDateObj = selectedDate; self.selectedDates.push(selectedDate); // unless selecting same date twice, sort ascendingly if (compareDates(selectedDate, self.selectedDates[0], true) !== 0) self.selectedDates.sort(function (a, b) { return a.getTime() - b.getTime(); }); } setHoursFromInputs(); if (shouldChangeMonth) { var isNewYear = self.currentYear !== selectedDate.getFullYear(); self.currentYear = selectedDate.getFullYear(); self.currentMonth = selectedDate.getMonth(); if (isNewYear) { triggerEvent("onYearChange"); buildMonthSwitch(); } triggerEvent("onMonthChange"); } updateNavigationCurrentMonth(); buildDays(); updateValue(); if (self.config.enableTime) setTimeout(function () { return (self.showTimeInput = true); }, 50); // maintain focus if (!shouldChangeMonth && self.config.mode !== "range" && self.config.showMonths === 1) focusOnDayElem(target); else if (self.selectedDateElem !== undefined && self.hourElement === undefined) { self.selectedDateElem && self.selectedDateElem.focus(); } if (self.hourElement !== undefined) self.hourElement !== undefined && self.hourElement.focus(); if (self.config.closeOnSelect) { var single = self.config.mode === "single" && !self.config.enableTime; var range = self.config.mode === "range" && self.selectedDates.length === 2 && !self.config.enableTime; if (single || range) { focusAndClose(); } } triggerChange(); } var CALLBACKS = { locale: [setupLocale, updateWeekdays], showMonths: [buildMonths, setCalendarWidth, buildWeekdays], minDate: [jumpToDate], maxDate: [jumpToDate] }; function set(option, value) { if (option !== null && typeof option === "object") { Object.assign(self.config, option); for (var key in option) { if (CALLBACKS[key] !== undefined) CALLBACKS[key].forEach(function (x) { return x(); }); } } else { self.config[option] = value; if (CALLBACKS[option] !== undefined) CALLBACKS[option].forEach(function (x) { return x(); }); else if (HOOKS.indexOf(option) > -1) self.config[option] = arrayify(value); } self.redraw(); updateValue(false); } function setSelectedDate(inputDate, format) { var dates = []; if (inputDate instanceof Array) dates = inputDate.map(function (d) { return self.parseDate(d, format); }); else if (inputDate instanceof Date || typeof inputDate === "number") dates = [self.parseDate(inputDate, format)]; else if (typeof inputDate === "string") { switch (self.config.mode) { case "single": case "time": dates = [self.parseDate(inputDate, format)]; break; case "multiple": dates = inputDate .split(self.config.conjunction) .map(function (date) { return self.parseDate(date, format); }); break; case "range": dates = inputDate .split(self.l10n.rangeSeparator) .map(function (date) { return self.parseDate(date, format); }); break; default: break; } } else self.config.errorHandler(new Error("Invalid date supplied: " + JSON.stringify(inputDate))); self.selectedDates = dates.filter(function (d) { return d instanceof Date && isEnabled(d, false); }); if (self.config.mode === "range") self.selectedDates.sort(function (a, b) { return a.getTime() - b.getTime(); }); } function setDate(date, triggerChange, format) { if (triggerChange === void 0) { triggerChange = false; } if (format === void 0) { format = self.config.dateFormat; } if ((date !== 0 && !date) || (date instanceof Array && date.length === 0)) return self.clear(triggerChange); setSelectedDate(date, format); self.showTimeInput = self.selectedDates.length > 0; self.latestSelectedDateObj = self.selectedDates[self.selectedDates.length - 1]; self.redraw(); jumpToDate(); setHoursFromDate(); if (self.selectedDates.length === 0) { self.clear(false); } updateValue(triggerChange); if (triggerChange) triggerEvent("onChange"); } function parseDateRules(arr) { return arr .slice() .map(function (rule) { if (typeof rule === "string" || typeof rule === "number" || rule instanceof Date) { return self.parseDate(rule, undefined, true); } else if (rule && typeof rule === "object" && rule.from && rule.to) return { from: self.parseDate(rule.from, undefined), to: self.parseDate(rule.to, undefined) }; return rule; }) .filter(function (x) { return x; }); // remove falsy values } function setupDates() { self.selectedDates = []; self.now = self.parseDate(self.config.now) || new Date(); // Workaround IE11 setting placeholder as the input's value var preloadedDate = self.config.defaultDate || ((self.input.nodeName === "INPUT" || self.input.nodeName === "TEXTAREA") && self.input.placeholder && self.input.value === self.input.placeholder ? null : self.input.value); if (preloadedDate) setSelectedDate(preloadedDate, self.config.dateFormat); self._initialDate = self.selectedDates.length > 0 ? self.selectedDates[0] : self.config.minDate && self.config.minDate.getTime() > self.now.getTime() ? self.config.minDate : self.config.maxDate && self.config.maxDate.getTime() < self.now.getTime() ? self.config.maxDate : self.now; self.currentYear = self._initialDate.getFullYear(); self.currentMonth = self._initialDate.getMonth(); if (self.selectedDates.length > 0) self.latestSelectedDateObj = self.selectedDates[0]; if (self.config.minTime !== undefined) self.config.minTime = self.parseDate(self.config.minTime, "H:i"); if (self.config.maxTime !== undefined) self.config.maxTime = self.parseDate(self.config.maxTime, "H:i"); self.minDateHasTime = !!self.config.minDate && (self.config.minDate.getHours() > 0 || self.config.minDate.getMinutes() > 0 || self.config.minDate.getSeconds() > 0); self.maxDateHasTime = !!self.config.maxDate && (self.config.maxDate.getHours() > 0 || self.config.maxDate.getMinutes() > 0 || self.config.maxDate.getSeconds() > 0); Object.defineProperty(self, "showTimeInput", { get: function () { return self._showTimeInput; }, set: function (bool) { self._showTimeInput = bool; if (self.calendarContainer) toggleClass(self.calendarContainer, "showTimeInput", bool); self.isOpen && positionCalendar(); } }); } function setupInputs() { self.input = self.config.wrap ? element.querySelector("[data-input]") : element; /* istanbul ignore next */ if (!self.input) { self.config.errorHandler(new Error("Invalid input element specified")); return; } // hack: store previous type to restore it after destroy() self.input._type = self.input.type; self.input.type = "text"; self.input.classList.add("flatpickr-input"); self._input = self.input; if (self.config.altInput) { // replicate self.element self.altInput = createElement(self.input.nodeName, self.config.altInputClass); self._input = self.altInput; self.altInput.placeholder = self.input.placeholder; self.altInput.disabled = self.input.disabled; self.altInput.required = self.input.required; self.altInput.tabIndex = self.input.tabIndex; self.altInput.type = "text"; self.input.setAttribute("type", "hidden"); if (!self.config.static && self.input.parentNode) self.input.parentNode.insertBefore(self.altInput, self.input.nextSibling); } if (!self.config.allowInput) self._input.setAttribute("readonly", "readonly"); self._positionElement = self.config.positionElement || self._input; } function setupMobile() { var inputType = self.config.enableTime ? self.config.noCalendar ? "time" : "datetime-local" : "date"; self.mobileInput = createElement("input", self.input.className + " flatpickr-mobile"); self.mobileInput.step = self.input.getAttribute("step") || "any"; self.mobileInput.tabIndex = 1; self.mobileInput.type = inputType; self.mobileInput.disabled = self.input.disabled; self.mobileInput.required = self.input.required; self.mobileInput.placeholder = self.input.placeholder; self.mobileFormatStr = inputType === "datetime-local" ? "Y-m-d\\TH:i:S" : inputType === "date" ? "Y-m-d" : "H:i:S"; if (self.selectedDates.length > 0) { self.mobileInput.defaultValue = self.mobileInput.value = self.formatDate(self.selectedDates[0], self.mobileFormatStr); } if (self.config.minDate) self.mobileInput.min = self.formatDate(self.config.minDate, "Y-m-d"); if (self.config.maxDate) self.mobileInput.max = self.formatDate(self.config.maxDate, "Y-m-d"); self.input.type = "hidden"; if (self.altInput !== undefined) self.altInput.type = "hidden"; try { if (self.input.parentNode) self.input.parentNode.insertBefore(self.mobileInput, self.input.nextSibling); } catch (_a) { } bind(self.mobileInput, "change", function (e) { self.setDate(e.target.value, false, self.mobileFormatStr); triggerEvent("onChange"); triggerEvent("onClose"); }); } function toggle(e) { if (self.isOpen === true) return self.close(); self.open(e); } function triggerEvent(event, data) { // If the instance has been destroyed already, all hooks have been removed if (self.config === undefined) return; var hooks = self.config[event]; if (hooks !== undefined && hooks.length > 0) { for (var i = 0; hooks[i] && i < hooks.length; i++) hooks[i](self.selectedDates, self.input.value, self, data); } if (event === "onChange") { self.input.dispatchEvent(createEvent("change")); // many front-end frameworks bind to the input event self.input.dispatchEvent(createEvent("input")); } } function createEvent(name) { var e = document.createEvent("Event"); e.initEvent(name, true, true); return e; } function isDateSelected(date) { for (var i = 0; i < self.selectedDates.length; i++) { if (compareDates(self.selectedDates[i], date) === 0) return "" + i; } return false; } function isDateInRange(date) { if (self.config.mode !== "range" || self.selectedDates.length < 2) return false; return (compareDates(date, self.selectedDates[0]) >= 0 && compareDates(date, self.selectedDates[1]) <= 0); } function updateNavigationCurrentMonth() { if (self.config.noCalendar || self.isMobile || !self.monthNav) return; self.yearElements.forEach(function (yearElement, i) { var d = new Date(self.currentYear, self.currentMonth, 1); d.setMonth(self.currentMonth + i); if (self.config.showMonths > 1) { self.monthElements[i].textContent = monthToStr(d.getMonth(), self.config.shorthandCurrentMonth, self.l10n) + " "; } else { self.monthsDropdownContainer.value = d.getMonth().toString(); } yearElement.value = d.getFullYear().toString(); }); self._hidePrevMonthArrow = self.config.minDate !== undefined && (self.currentYear === self.config.minDate.getFullYear() ? self.currentMonth <= self.config.minDate.getMonth() : self.currentYear < self.config.minDate.getFullYear()); self._hideNextMonthArrow = self.config.maxDate !== undefined && (self.currentYear === self.config.maxDate.getFullYear() ? self.currentMonth + 1 > self.config.maxDate.getMonth() : self.currentYear > self.config.maxDate.getFullYear()); } function getDateStr(format) { return self.selectedDates .map(function (dObj) { return self.formatDate(dObj, format); }) .filter(function (d, i, arr) { return self.config.mode !== "range" || self.config.enableTime || arr.indexOf(d) === i; }) .join(self.config.mode !== "range" ? self.config.conjunction : self.l10n.rangeSeparator); } /** * Updates the values of inputs associated with the calendar */ function updateValue(triggerChange) { if (triggerChange === void 0) { triggerChange = true; } if (self.mobileInput !== undefined && self.mobileFormatStr) { self.mobileInput.value = self.latestSelectedDateObj !== undefined ? self.formatDate(self.latestSelectedDateObj, self.mobileFormatStr) : ""; } self.input.value = getDateStr(self.config.dateFormat); if (self.altInput !== undefined) { self.altInput.value = getDateStr(self.config.altFormat); } if (triggerChange !== false) triggerEvent("onValueUpdate"); } function onMonthNavClick(e) { var isPrevMonth = self.prevMonthNav.contains(e.target); var isNextMonth = self.nextMonthNav.contains(e.target); if (isPrevMonth || isNextMonth) { changeMonth(isPrevMonth ? -1 : 1); } else if (self.yearElements.indexOf(e.target) >= 0) { e.target.select(); } else if (e.target.classList.contains("arrowUp")) { self.changeYear(self.currentYear + 1); } else if (e.target.classList.contains("arrowDown")) { self.changeYear(self.currentYear - 1); } } function timeWrapper(e) { e.preventDefault(); var isKeyDown = e.type === "keydown", input = e.target; if (self.amPM !== undefined && e.target === self.amPM) { self.amPM.textContent = self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])]; } var min = parseFloat(input.getAttribute("min")), max = parseFloat(input.getAttribute("max")), step = parseFloat(input.getAttribute("step")), curValue = parseInt(input.value, 10), delta = e.delta || (isKeyDown ? (e.which === 38 ? 1 : -1) : 0); var newValue = curValue + step * delta; if (typeof input.value !== "undefined" && input.value.length === 2) { var isHourElem = input === self.hourElement, isMinuteElem = input === self.minuteElement; if (newValue < min) { newValue = max + newValue + int(!isHourElem) + (int(isHourElem) && int(!self.amPM)); if (isMinuteElem) incrementNumInput(undefined, -1, self.hourElement); } else if (newValue > max) { newValue = input === self.hourElement ? newValue - max - int(!self.amPM) : min; if (isMinuteElem) incrementNumInput(undefined, 1, self.hourElement); } if (self.amPM && isHourElem && (step === 1 ? newValue + curValue === 23 : Math.abs(newValue - curValue) > step)) { self.amPM.textContent = self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])]; } input.value = pad(newValue); } } init(); return self; } /* istanbul ignore next */ function _flatpickr(nodeList, config) { // static list var nodes = Array.prototype.slice .call(nodeList) .filter(function (x) { return x instanceof HTMLElement; }); var instances = []; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; try { if (node.getAttribute("data-fp-omit") !== null) continue; if (node._flatpickr !== undefined) { node._flatpickr.destroy(); node._flatpickr = undefined; } node._flatpickr = FlatpickrInstance(node, config || {}); instances.push(node._flatpickr); } catch (e) { console.error(e); } } return instances.length === 1 ? instances[0] : instances; } /* istanbul ignore next */ if (typeof HTMLElement !== "undefined") { // browser env HTMLCollection.prototype.flatpickr = NodeList.prototype.flatpickr = function (config) { return _flatpickr(this, config); }; HTMLElement.prototype.flatpickr = function (config) { return _flatpickr([this], config); }; } /* istanbul ignore next */ var flatpickr = function (selector, config) { if (typeof selector === "string") { return _flatpickr(window.document.querySelectorAll(selector), config); } else if (selector instanceof Node) { return _flatpickr([selector], config); } else { return _flatpickr(selector, config); } }; /* istanbul ignore next */ flatpickr.defaultConfig = {}; flatpickr.l10ns = { en: __assign({}, english), "default": __assign({}, english) }; flatpickr.localize = function (l10n) { flatpickr.l10ns["default"] = __assign({}, flatpickr.l10ns["default"], l10n); }; flatpickr.setDefaults = function (config) { flatpickr.defaultConfig = __assign({}, flatpickr.defaultConfig, config); }; flatpickr.parseDate = createDateParser({}); flatpickr.formatDate = createDateFormatter({}); flatpickr.compareDates = compareDates; /* istanbul ignore next */ if (typeof jQuery !== "undefined") { jQuery.fn.flatpickr = function (config) { return _flatpickr(this, config); }; } // eslint-disable-next-line @typescript-eslint/camelcase Date.prototype.fp_incr = function (days) { return new Date(this.getFullYear(), this.getMonth(), this.getDate() + (typeof days === "string" ? parseInt(days, 10) : days)); }; if (typeof window !== "undefined") { window.flatpickr = flatpickr; } return flatpickr; }));<|fim▁end|>
};
<|file_name|>decision.py<|end_file_name|><|fim▁begin|>"""The decision module handles the three planning levels Currently, only pre-specified planning is implemented. The choices made in the three planning levels influence the set of interventions and assets available within a model run. The interventions available in a model run are stored in a dict keyed by name. """ __author__ = "Will Usher, Tom Russell" __copyright__ = "Will Usher, Tom Russell" __license__ = "mit" import itertools import os from abc import ABCMeta, abstractmethod from logging import getLogger from types import MappingProxyType from typing import Dict, List, Optional, Set, Tuple from smif.data_layer.data_handle import ResultsHandle from smif.data_layer.model_loader import ModelLoader from smif.data_layer.store import Store from smif.exception import SmifDataNotFoundError class DecisionManager(object): """A DecisionManager is initialised with one or more model run strategies that refer to DecisionModules such as pre-specified planning, a rule-based models or multi-objective optimisation. These implementations influence the combination and ordering of decision iterations and model timesteps that need to be performed by the model runner. The DecisionManager presents a simple decision loop interface to the model runner, in the form of a generator which allows the model runner to iterate over the collection of independent simulations required at each step. The DecisionManager collates the output of the decision algorithms and writes the post-decision state through a ResultsHandle. This allows Models to access a given decision state (identified uniquely by timestep and decision iteration id). The :py:meth:`get_decisions` method passes a ResultsHandle down to a DecisionModule, allowing the DecisionModule to access model results from previous timesteps and decision iterations when making decisions Arguments --------- store: smif.data_layer.store.Store """ def __init__(self, store: Store, timesteps: List[int], modelrun_name: str, sos_model): self.logger = getLogger(__name__) self._store = store self._modelrun_name = modelrun_name self._sos_model = sos_model self._timesteps = timesteps self._decision_module = None self._register = {} # type: Dict for sector_model in sos_model.sector_models: self._register.update(self._store.read_interventions(sector_model.name)) self.planned_interventions = [] # type: List strategies = self._store.read_strategies(modelrun_name) self.logger.info("%s strategies found", len(strategies)) self.pre_spec_planning = self._set_up_pre_spec_planning(modelrun_name, strategies) self._set_up_decision_modules(modelrun_name, strategies) def _set_up_pre_spec_planning(self, modelrun_name: str, strategies: List[Dict]): # Read in the historical interventions (initial conditions) directly initial_conditions = self._store.read_all_initial_conditions(modelrun_name) # Read in strategies planned_interventions = [] # type: List planned_interventions.extend(initial_conditions) for index, strategy in enumerate(strategies): # Extract pre-specified planning interventions if strategy['type'] == 'pre-specified-planning': msg = "Adding %s planned interventions to pre-specified-planning %s" self.logger.info(msg, len(strategy['interventions']), index) planned_interventions.extend(strategy['interventions']) # Create a Pre-Specified planning decision module with all # the planned interventions self.planned_interventions = self._tuplize_state(planned_interventions) def _set_up_decision_modules(self, modelrun_name, strategies): strategy_types = [x['type'] for x in strategies if x['type'] != 'pre-specified-planning'] if len(set(strategy_types)) > 1: msg = "Cannot use more the 2 type of strategy simultaneously" raise NotImplementedError(msg) for strategy in strategies: if strategy['type'] != 'pre-specified-planning': loader = ModelLoader() # absolute path to be crystal clear for ModelLoader when loading python class strategy['path'] = os.path.normpath( os.path.join(self._store.model_base_folder, strategy['path'])) strategy['timesteps'] = self._timesteps # Pass a reference to the register of interventions strategy['register'] = MappingProxyType(self.available_interventions) strategy['name'] = strategy['classname'] + '_' + strategy['type'] self.logger.debug("Trying to load strategy: %s", strategy['name']) decision_module = loader.load(strategy) self._decision_module = decision_module # type: DecisionModule @property def available_interventions(self) -> Dict[str, Dict]: """Returns a register of available interventions, i.e. those not planned """ planned_names = set(name for build_year, name in self.planned_interventions) edited_register = {name: self._register[name] for name in self._register.keys() - planned_names} return edited_register def get_intervention(self, value): try: return self._register[value] except KeyError: msg = "" raise SmifDataNotFoundError(msg.format(value)) def decision_loop(self): """Generate bundles of simulation steps to run Each call to this method returns a dict: { 'decision_iterations': list of decision iterations (int), 'timesteps': list of timesteps (int), 'decision_links': (optional) dict of { decision iteration in current bundle: decision iteration of previous bundle } } A bundle is composed differently according to the implementation of the contained DecisionModule. For example: With only pre-specified planning, there is a single step in the loop, with a single decision iteration with timesteps covering the entire model horizon. With a rule based approach, there might be many steps in the loop, each with a single decision iteration and single timestep, moving on once some threshold is satisfied. With a genetic algorithm, there might be a configurable number of steps in the loop, each with multiple decision iterations (one for each member of the algorithm's population) and timesteps covering the entire model horizon. Implicitly, if the bundle returned in an iteration contains multiple decision iterations, they can be performed in parallel. If each decision iteration contains multiple timesteps, they can also be parallelised, so long as there are no temporal dependencies. Decision links are only required if the bundle timesteps do not start from the first timestep of the model horizon. """ self.logger.debug("Calling decision loop") if self._decision_module: while True: bundle = next(self._decision_module) if bundle is None: break self.logger.debug("Bundle returned: %s", bundle) self._get_and_save_bundle_decisions(bundle) yield bundle else: bundle = { 'decision_iterations': [0], 'timesteps': [x for x in self._timesteps] } self._get_and_save_bundle_decisions(bundle) yield bundle def _get_and_save_bundle_decisions(self, bundle): """Iterate over bundle and write decisions Arguments --------- bundle : dict Returns ------- bundle : dict One definitive bundle across the decision modules """ for iteration, timestep in itertools.product( bundle['decision_iterations'], bundle['timesteps']): self.get_and_save_decisions(iteration, timestep) def get_and_save_decisions(self, iteration, timestep): """Retrieves decisions for given timestep and decision iteration from each decision module and writes them to the store as state. Calls each contained DecisionModule for the given timestep and decision iteration in the `data_handle`, retrieving a list of decision dicts (keyed by intervention name and build year). These decisions are then written to a state file using the data store. Arguments --------- timestep : int iteration : int Notes ----- State contains all intervention names which are present in the system at the given ``timestep`` for the current ``iteration``. This must include planned interventions from a previous timestep that are still within their lifetime, and interventions picked by a decision module in the previous timesteps. After loading all historical interventions, and screening them to remove interventions from the previous timestep that have reached the end of their lifetime, new decisions are added to the list of current interventions.<|fim▁hole|> Finally, the new state is written to the store. """ results_handle = ResultsHandle( store=self._store, modelrun_name=self._modelrun_name, sos_model=self._sos_model, current_timestep=timestep, timesteps=self._timesteps, decision_iteration=iteration ) # Decision module overrides pre-specified planning for obtaining state # from previous iteration pre_decision_state = set() if self._decision_module: previous_state = self._get_previous_state(self._decision_module, results_handle) pre_decision_state.update(previous_state) msg = "Pre-decision state at timestep %s and iteration %s:\n%s" self.logger.debug(msg, timestep, iteration, pre_decision_state) new_decisions = set() if self._decision_module: decisions = self._get_decisions(self._decision_module, results_handle) new_decisions.update(decisions) self.logger.debug("New decisions at timestep %s and iteration %s:\n%s", timestep, iteration, new_decisions) # Post decision state is the union of the pre decision state set, the # new decision set and the set of planned interventions post_decision_state = (pre_decision_state | new_decisions | set(self.planned_interventions)) post_decision_state = self.retire_interventions(post_decision_state, timestep) post_decision_state = self._untuplize_state(post_decision_state) self.logger.debug("Post-decision state at timestep %s and iteration %s:\n%s", timestep, iteration, post_decision_state) self._store.write_state(post_decision_state, self._modelrun_name, timestep, iteration) def retire_interventions(self, state: List[Tuple[int, str]], timestep: int) -> List[Tuple[int, str]]: alive = [] for intervention in state: build_year = int(intervention[0]) data = self._register[intervention[1]] lifetime = data['technical_lifetime']['value'] if (self.buildable(build_year, timestep) and self.within_lifetime(build_year, timestep, lifetime)): alive.append(intervention) return alive def _get_decisions(self, decision_module: 'DecisionModule', results_handle: ResultsHandle) -> List[Tuple[int, str]]: decisions = decision_module.get_decision(results_handle) return self._tuplize_state(decisions) def _get_previous_state(self, decision_module: 'DecisionModule', results_handle: ResultsHandle) -> List[Tuple[int, str]]: state_dict = decision_module.get_previous_state(results_handle) return self._tuplize_state(state_dict) @staticmethod def _tuplize_state(state: List[Dict]) -> List[Tuple[int, str]]: return [(x['build_year'], x['name']) for x in state] @staticmethod def _untuplize_state(state: List[Tuple[int, str]]) -> List[Dict]: return [{'build_year': x[0], 'name': x[1]} for x in state] def buildable(self, build_year, timestep) -> bool: """Interventions are deemed available if build_year is less than next timestep For example, if `a` is built in 2011 and timesteps are [2005, 2010, 2015, 2020] then buildable returns True for timesteps 2010, 2015 and 2020 and False for 2005. Arguments --------- build_year: int The build year of the intervention timestep: int The current timestep """ if not isinstance(build_year, (int, float)): msg = "Build Year should be an integer but is a {}" raise TypeError(msg.format(type(build_year))) if timestep not in self._timesteps: raise ValueError("Timestep not in model timesteps") index = self._timesteps.index(timestep) if index == len(self._timesteps) - 1: next_year = timestep + 1 else: next_year = self._timesteps[index + 1] if int(build_year) < next_year: return True else: return False @staticmethod def within_lifetime(build_year, timestep, lifetime) -> bool: """Interventions are deemed active if build_year + lifetime >= timestep Arguments --------- build_year : int timestep : int lifetime : int Returns ------- bool """ if not isinstance(build_year, (int, float)): msg = "Build Year should be an integer but is a {}" raise TypeError(msg.format(type(build_year))) try: build_year = int(build_year) except ValueError: raise ValueError( "A build year must be a valid integer. Received {}.".format(build_year)) try: lifetime = int(lifetime) except ValueError: lifetime = float("inf") if lifetime < 0: msg = "The value of lifetime cannot be negative" raise ValueError(msg) if timestep <= build_year + lifetime: return True else: return False class DecisionModule(metaclass=ABCMeta): """Abstract class which provides the interface to user defined decision modules. These mechanisms could include a Rule-based Approach or Multi-objective Optimisation. This class provides two main methods, ``__next__`` which is normally called implicitly as a call to the class as an iterator, and ``get_decision()`` which takes as arguments a smif.data_layer.data_handle.ResultsHandle object. Arguments --------- timesteps : list A list of planning timesteps register : dict Reference to a dict of iterventions """ """Current iteration of the decision module """ def __init__(self, timesteps: List[int], register: MappingProxyType): self.timesteps = timesteps self._register = register self.logger = getLogger(__name__) self._decisions = set() # type: Set def __next__(self) -> List[Dict]: return self._get_next_decision_iteration() @property def first_timestep(self) -> int: return min(self.timesteps) @property def last_timestep(self) -> int: return max(self.timesteps) @abstractmethod def get_previous_state(self, results_handle: ResultsHandle) -> List[Dict]: """Return the state of the previous timestep """ raise NotImplementedError def available_interventions(self, state: List[Dict]) -> List: """Return the collection of available interventions Available interventions are the subset of interventions that have not been implemented in a prior iteration or timestep Returns ------- List """ return [name for name in self._register.keys() - set([x['name'] for x in state])] def get_intervention(self, name): """Return an intervention dict Returns ------- dict """ try: return self._register[name] except KeyError: msg = "Intervention '{}' is not found in the list of available interventions" raise SmifDataNotFoundError(msg.format(name)) @abstractmethod def _get_next_decision_iteration(self) -> List[Dict]: """Implement to return the next decision iteration Within a list of decision-iteration/timestep pairs, the assumption is that all decision iterations can be run in parallel (otherwise only one will be returned) and within a decision interation, all timesteps may be run in parallel as long as there are no inter-timestep state dependencies Returns ------- dict Yields a dictionary keyed by ``decision iterations`` whose values contain a list of iteration integers, ``timesteps`` whose values contain a list of timesteps run in each decision iteration and the optional ``decision_links`` which link the decision interation of the current bundle to that of the previous bundle:: { 'decision_iterations': list of decision iterations (int), 'timesteps': list of timesteps (int), 'decision_links': (optional) dict of { decision iteration in current bundle: decision iteration of previous bundle } } """ raise NotImplementedError @abstractmethod def get_decision(self, results_handle: ResultsHandle) -> List[Dict]: """Return decisions for a given timestep and decision iteration Parameters ---------- results_handle : smif.data_layer.data_handle.ResultsHandle Returns ------- list of dict Examples -------- >>> register = {'intervention_a': {'capital_cost': {'value': 1234}}} >>> dm = DecisionModule([2010, 2015], register) >>> dm.get_decision(results_handle) [{'name': 'intervention_a', 'build_year': 2010}]) """ raise NotImplementedError class RuleBased(DecisionModule): """Rule-base decision modules """ def __init__(self, timesteps, register): super().__init__(timesteps, register) self.satisfied = False # type: bool self.current_timestep = self.first_timestep # type: int self.current_iteration = 0 # type: int # keep internal account of max iteration reached per timestep self._max_iteration_by_timestep = {self.first_timestep: 0} self.logger = getLogger(__name__) def get_previous_iteration_timestep(self) -> Optional[Tuple[int, int]]: """Returns the timestep, iteration pair that describes the previous iteration Returns ------- tuple Contains (timestep, iteration) """ if self.current_iteration > 1: iteration = self.current_iteration - 1 if self.current_timestep == self.first_timestep: timestep = self.current_timestep elif (iteration == self._max_iteration_by_timestep[self.previous_timestep]): timestep = self.previous_timestep elif (iteration >= self._max_iteration_by_timestep[self.previous_timestep]): timestep = self.current_timestep else: return None return timestep, iteration def get_previous_state(self, results_handle: ResultsHandle) -> List[Dict]: timestep_iteration = self.get_previous_iteration_timestep() if timestep_iteration: timestep, iteration = timestep_iteration return results_handle.get_state(timestep, iteration) else: return [] @property def next_timestep(self): index_current_timestep = self.timesteps.index(self.current_timestep) try: return self.timesteps[index_current_timestep + 1] except IndexError: return None @property def previous_timestep(self): index_current_timestep = self.timesteps.index(self.current_timestep) if index_current_timestep > 0: return self.timesteps[index_current_timestep - 1] else: return None def _get_next_decision_iteration(self): if self.satisfied and (self.current_timestep == self.last_timestep): return None elif self.satisfied and (self.current_timestep < self.last_timestep): self._max_iteration_by_timestep[self.current_timestep] = \ self.current_iteration self.satisfied = False self.current_timestep = self.next_timestep self.current_iteration += 1 return self._make_bundle() else: self.current_iteration += 1 return self._make_bundle() def get_previous_year_iteration(self): iteration = self._max_iteration_by_timestep[self.previous_timestep] return iteration def _make_bundle(self): bundle = {'decision_iterations': [self.current_iteration], 'timesteps': [self.current_timestep]} if self.current_timestep > self.first_timestep: bundle['decision_links'] = { self.current_iteration: self._max_iteration_by_timestep[ self.previous_timestep] } return bundle def get_decision(self, results_handle) -> List[Dict]: return []<|fim▁end|>
<|file_name|>BaseProperty.java<|end_file_name|><|fim▁begin|>/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.objects; import java.io.IOException; import java.io.Serializable; import java.io.StringWriter; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import com.xpn.xwiki.web.Utils; /** * @version $Id$ */ // TODO: shouldn't this be abstract? toFormString and toText // will never work unless getValue is overriden public class BaseProperty extends BaseElement implements PropertyInterface, Serializable, Cloneable { private BaseCollection object; private int id; /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#getObject() */ public BaseCollection getObject() { return this.object; } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#setObject(com.xpn.xwiki.objects.BaseCollection) */ public void setObject(BaseCollection object) { this.object = object; } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.BaseElement#equals(java.lang.Object) */ @Override public boolean equals(Object el) { // Same Java object, they sure are equal if (this == el) { return true; } // I hate this.. needed for hibernate to find the object // when loading the collections..<|fim▁hole|> if (!super.equals(el)) { return false; } return (getId() == ((BaseProperty) el).getId()); } public int getId() { // I hate this.. needed for hibernate to find the object // when loading the collections.. if (this.object == null) { return this.id; } else { return getObject().getId(); } } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#setId(int) */ public void setId(int id) { // I hate this.. needed for hibernate to find the object // when loading the collections.. this.id = id; } /** * {@inheritDoc} * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { // I hate this.. needed for hibernate to find the object // when loading the collections.. return ("" + getId() + getName()).hashCode(); } public String getClassType() { return getClass().getName(); } public void setClassType(String type) { } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.BaseElement#clone() */ @Override public Object clone() { BaseProperty property = (BaseProperty) super.clone(); property.setObject(getObject()); return property; } public Object getValue() { return null; } public void setValue(Object value) { } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#toXML() */ public Element toXML() { Element el = new DOMElement(getName()); Object value = getValue(); el.setText((value == null) ? "" : value.toString()); return el; } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#toFormString() */ public String toFormString() { return Utils.formEncode(toText()); } public String toText() { Object value = getValue(); return (value == null) ? "" : value.toString(); } public String toXMLString() { Document doc = new DOMDocument(); doc.setRootElement(toXML()); OutputFormat outputFormat = new OutputFormat("", true); StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, outputFormat); try { writer.write(doc); return out.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return toXMLString(); } public Object getCustomMappingValue() { return getValue(); } }<|fim▁end|>
if ((this.object == null) || ((BaseProperty) el).getObject() == null) { return (hashCode() == el.hashCode()); }
<|file_name|>bindings_serialization.cc<|end_file_name|><|fim▁begin|>// 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. #include "mojo/public/cpp/bindings/lib/bindings_serialization.h" #include "mojo/public/cpp/bindings/lib/bindings_internal.h" #include "mojo/public/cpp/bindings/lib/bounds_checker.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/environment/logging.h" namespace mojo { namespace internal { namespace { const size_t kAlignment = 8; template<typename T> T AlignImpl(T t) { return t + (kAlignment - (t % kAlignment)) % kAlignment; } } // namespace size_t Align(size_t size) { return AlignImpl(size); } char* AlignPointer(char* ptr) { return reinterpret_cast<char*>(AlignImpl(reinterpret_cast<uintptr_t>(ptr))); } bool IsAligned(const void* ptr) { return !(reinterpret_cast<uintptr_t>(ptr) % kAlignment); } void EncodePointer(const void* ptr, uint64_t* offset) { if (!ptr) { *offset = 0; return; } const char* p_obj = reinterpret_cast<const char*>(ptr); const char* p_slot = reinterpret_cast<const char*>(offset); MOJO_DCHECK(p_obj > p_slot); *offset = static_cast<uint64_t>(p_obj - p_slot); } const void* DecodePointerRaw(const uint64_t* offset) { if (!*offset) return NULL; return reinterpret_cast<const char*>(offset) + *offset; } bool ValidateEncodedPointer(const uint64_t* offset) { // Cast to uintptr_t so overflow behavior is well defined. return reinterpret_cast<uintptr_t>(offset) + *offset >= reinterpret_cast<uintptr_t>(offset); } <|fim▁hole|> if (handle->is_valid()) { handles->push_back(*handle); handle->set_value(static_cast<MojoHandle>(handles->size() - 1)); } else { handle->set_value(kEncodedInvalidHandleValue); } } void DecodeHandle(Handle* handle, std::vector<Handle>* handles) { if (handle->value() == kEncodedInvalidHandleValue) { *handle = Handle(); return; } MOJO_DCHECK(handle->value() < handles->size()); // Just leave holes in the vector so we don't screw up other indices. *handle = FetchAndReset(&handles->at(handle->value())); } bool ValidateStructHeader(const void* data, uint32_t min_num_bytes, uint32_t min_num_fields, BoundsChecker* bounds_checker) { MOJO_DCHECK(min_num_bytes >= sizeof(StructHeader)); if (!IsAligned(data)) { ReportValidationError(VALIDATION_ERROR_MISALIGNED_OBJECT); return false; } if (!bounds_checker->IsValidRange(data, sizeof(StructHeader))) { ReportValidationError(VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE); return false; } const StructHeader* header = static_cast<const StructHeader*>(data); // TODO(yzshen): Currently our binding code cannot handle structs of smaller // size or with fewer fields than the version that it sees. That needs to be // changed in order to provide backward compatibility. if (header->num_bytes < min_num_bytes || header->num_fields < min_num_fields) { ReportValidationError(VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!bounds_checker->ClaimMemory(data, header->num_bytes)) { ReportValidationError(VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE); return false; } return true; } } // namespace internal } // namespace mojo<|fim▁end|>
void EncodeHandle(Handle* handle, std::vector<Handle>* handles) {
<|file_name|>utils.js<|end_file_name|><|fim▁begin|>"use strict"; var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; <|fim▁hole|>var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; exports.alts = alts; exports.timeout = timeout; exports.pipelineAsync = pipelineAsync; // Enforces order resolution on resulting channel // This might need to be the default behavior, though that requires more thought exports.order = order; Object.defineProperty(exports, "__esModule", { value: true }); var _channelsJs = require("./channels.js"); var Channel = _channelsJs.Channel; var Transactor = _channelsJs.Transactor; var AltsTransactor = (function (_Transactor) { function AltsTransactor(offer, commitCb) { _classCallCheck(this, AltsTransactor); _get(Object.getPrototypeOf(AltsTransactor.prototype), "constructor", this).call(this, offer); this.commitCb = commitCb; } _inherits(AltsTransactor, _Transactor); _createClass(AltsTransactor, { commit: { value: function commit() { this.commitCb(); return _get(Object.getPrototypeOf(AltsTransactor.prototype), "commit", this).call(this); } } }); return AltsTransactor; })(Transactor); function alts(race) { var outCh = new Channel(); var transactors = race.map(function (cmd) { var tx = undefined; if (Array.isArray(cmd)) { var _cmd; (function () { _cmd = _slicedToArray(cmd, 2); var ch = _cmd[0]; var val = _cmd[1]; tx = new AltsTransactor(val, function () { transactors.forEach(function (h) { return h.active = false; }); }); ch.fill(val, tx).deref(function () { outCh.fill([val, ch]).deref(function () { return outCh.close(); }); }); })(); } else { tx = new AltsTransactor(true, function () { transactors.forEach(function (h) { return h.active = false; }); }); cmd.drain(tx).deref(function (val) { outCh.fill([val, cmd]).deref(function () { return outCh.close(); }); }); } return tx; }); return outCh; } function timeout(ms) { var ch = new Channel(); setTimeout(function () { ch.close(); }, ms); return ch; } function pipelineAsync(inch, converter, outch) { var shouldCloseDownstream = arguments[3] === undefined ? false : arguments[3]; function take(val) { if (val !== null) { Promise.resolve(converter(val)).then(function (converted) { outch.put(converted).then(function (didPut) { if (didPut) { inch.take().then(take); } }); }); } else if (shouldCloseDownstream) { outch.close(); } } inch.take().then(take); } function order(inch, sizeOrBuf) { var outch = new Channel(sizeOrBuf); function drain() { inch.take().then(function (val) { if (val === null) { outch.close(); } else { outch.put(val).then(drain); } }); } drain(); return outch; } //# sourceMappingURL=utils.js.map<|fim▁end|>
<|file_name|>pyHeekGame.cpp<|end_file_name|><|fim▁begin|>/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email [email protected] or by snail mail at: Cyan Worlds, Inc.<|fim▁hole|> #include "../../pyKey.h" #pragma hdrstop #include "pyHeekGame.h" #include "pfGameMgr/pfGameMgr.h" /////////////////////////////////////////////////////////////////////////////// // // Base Heek game client class // pyHeekGame::pyHeekGame(): pyGameCli() {} pyHeekGame::pyHeekGame(pfGameCli* client): pyGameCli(client) { if (client && (client->GetGameTypeId() != kGameTypeId_Heek)) gameClient = nil; // wrong type, just clear it out } bool pyHeekGame::IsHeekGame(plString& guid) { plUUID gameUuid(guid); return gameUuid == kGameTypeId_Heek; } void pyHeekGame::JoinCommonHeekGame(pyKey& callbackKey, unsigned gameID) { pfGameMgr::GetInstance()->JoinCommonGame(callbackKey.getKey(), kGameTypeId_Heek, gameID, 0, NULL); } void pyHeekGame::PlayGame(int position, uint32_t points, std::wstring name) { if (gameClient) { pfGmHeek* heek = pfGmHeek::ConvertNoRef(gameClient); heek->PlayGame((unsigned)position, (uint32_t)points, name.c_str()); } } void pyHeekGame::LeaveGame() { if (gameClient) { pfGmHeek* heek = pfGmHeek::ConvertNoRef(gameClient); heek->LeaveGame(); } } void pyHeekGame::Choose(int choice) { if (gameClient) { pfGmHeek* heek = pfGmHeek::ConvertNoRef(gameClient); heek->Choose((EHeekChoice)choice); } } void pyHeekGame::SequenceFinished(int seq) { if (gameClient) { pfGmHeek* heek = pfGmHeek::ConvertNoRef(gameClient); heek->SequenceFinished((EHeekSeqFinished)seq); } }<|fim▁end|>
14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/
<|file_name|>fact.rs<|end_file_name|><|fim▁begin|>#[allow(non_snake_case)] #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct ExprItem { pub data: Option<String>, // pub type: Option<String>, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct FactcContent { pub expr: Option<Vec<ExprItem>>,<|fim▁hole|>pub struct FactBody { pub content: FactcContent, pub meta: super::MetadataMeta, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct Fact { pub fact: FactBody, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct ObjectsFactBody { pub paging: super::MetadataPaging, pub items: Vec<Fact>, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct ObjectsFact { pub objects: ObjectsFactBody, }<|fim▁end|>
} #[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
<|file_name|>Remove _Resources.py<|end_file_name|><|fim▁begin|>import os, shutil, xbmc, xbmcgui pDialog = xbmcgui.DialogProgress() dialog = xbmcgui.Dialog() Game_Directories = [ "E:\\Games\\", "F:\\Games\\", "G:\\Games\\", "E:\\Applications\\", "F:\\Applications\\", "G:\\Applications\\", "E:\\Homebrew\\", "F:\\Homebrew\\", "G:\\Homebrew\\", "E:\\Apps\\", "F:\\Apps\\", "G:\\Apps\\", "E:\\Ports\\", "F:\\Ports\\", "G:\\Ports\\" ] for Game_Directories in Game_Directories: if os.path.isdir( Game_Directories ): pDialog.create( "PARSING XBOX GAMES","Initializing" ) pDialog.update(0,"Removing _Resources Folders","","This can take some time, please be patient.") for Items in sorted( os.listdir( Game_Directories ) ): if os.path.isdir(os.path.join( Game_Directories, Items)): Game_Directory = os.path.join( Game_Directories, Items ) _Resources = os.path.join( Game_Directory, "_Resources" ) DefaultTBN = os.path.join( Game_Directory, "default.tbn" ) FanartJPG = os.path.join( Game_Directory, "fanart.jpg" ) if os.path.isdir(_Resources): shutil.rmtree(_Resources) else: <|fim▁hole|> print "Cannot find: " + DefaultTBN if os.path.isfile(FanartJPG): os.remove(FanartJPG) else: print "Cannot find: " + FanartJPG pDialog.close() dialog.ok("COMPLETE","Done, _Resources Folders Removed.")<|fim▁end|>
print "Cannot find: " + _Resources if os.path.isfile(DefaultTBN): os.remove(DefaultTBN) else:
<|file_name|>test_reports.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """ Helper functions for reports testing. Please /do not/ import this file by default, but only explicitly call it through the code of yaml tests. """ import openerp.netsvc as netsvc import openerp.tools as tools import logging import openerp.pooler as pooler from openerp.tools.safe_eval import safe_eval from subprocess import Popen, PIPE import os import tempfile _logger = logging.getLogger(__name__) def try_report(cr, uid, rname, ids, data=None, context=None, our_module=None): """ Try to render a report <rname> with contents of ids This function should also check for common pitfalls of reports. """ if data is None: data = {} if context is None: context = {} if rname.startswith('report.'): rname_s = rname[7:] else: rname_s = rname _logger.log(netsvc.logging.TEST, " - Trying %s.create(%r)", rname, ids) res = netsvc.LocalService(rname).create(cr, uid, ids, data, context) if not isinstance(res, tuple): raise RuntimeError("Result of %s.create() should be a (data,format) tuple, now it is a %s" % \ (rname, type(res))) (res_data, res_format) = res if not res_data: raise ValueError("Report %s produced an empty result!" % rname) if tools.config['test_report_directory']: file(os.path.join(tools.config['test_report_directory'], rname+ '.'+res_format), 'wb+').write(res_data) _logger.debug("Have a %s report for %s, will examine it", res_format, rname) if res_format == 'pdf': if res_data[:5] != '%PDF-': raise ValueError("Report %s produced a non-pdf header, %r" % (rname, res_data[:10])) res_text = False try: fd, rfname = tempfile.mkstemp(suffix=res_format) os.write(fd, res_data)<|fim▁hole|> fp = Popen(['pdftotext', '-enc', 'UTF-8', '-nopgbrk', rfname, '-'], shell=False, stdout=PIPE).stdout res_text = tools.ustr(fp.read()) os.unlink(rfname) except Exception: _logger.debug("Unable to parse PDF report: install pdftotext to perform automated tests.") if res_text is not False: for line in res_text.split('\n'): if ('[[' in line) or ('[ [' in line): _logger.error("Report %s may have bad expression near: \"%s\".", rname, line[80:]) # TODO more checks, what else can be a sign of a faulty report? elif res_format == 'foobar': # TODO pass else: _logger.warning("Report %s produced a \"%s\" chunk, cannot examine it", rname, res_format) return False _logger.log(netsvc.logging.TEST, " + Report %s produced correctly.", rname) return True def try_report_action(cr, uid, action_id, active_model=None, active_ids=None, wiz_data=None, wiz_buttons=None, context=None, our_module=None): """Take an ir.action.act_window and follow it until a report is produced :param action_id: the integer id of an action, or a reference to xml id of the act_window (can search [our_module.]+xml_id :param active_model, active_ids: call the action as if it had been launched from that model+ids (tree/form view action) :param wiz_data: a dictionary of values to use in the wizard, if needed. They will override (or complete) the default values of the wizard form. :param wiz_buttons: a list of button names, or button icon strings, which should be preferred to press during the wizard. Eg. 'OK' or 'gtk-print' :param our_module: the name of the calling module (string), like 'account' """ if not our_module and isinstance(action_id, basestring): if '.' in action_id: our_module = action_id.split('.', 1)[0] if context is None: context = {} else: context = context.copy() # keep it local # TODO context fill-up pool = pooler.get_pool(cr.dbname) def log_test(msg, *args): _logger.log(netsvc.logging.TEST, " - " + msg, *args) datas = {} if active_model: datas['model'] = active_model if active_ids: datas['ids'] = active_ids if not wiz_buttons: wiz_buttons = [] if isinstance(action_id, basestring): if '.' in action_id: act_module, act_xmlid = action_id.split('.', 1) else: if not our_module: raise ValueError('You cannot only specify action_id "%s" without a module name' % action_id) act_module = our_module act_xmlid = action_id act_model, act_id = pool.get('ir.model.data').get_object_reference(cr, uid, act_module, act_xmlid) else: assert isinstance(action_id, (long, int)) act_model = 'ir.action.act_window' # assume that act_id = action_id act_xmlid = '<%s>' % act_id def _exec_action(action, datas, context): # taken from client/modules/action/main.py:84 _exec_action() if isinstance(action, bool) or 'type' not in action: return # Updating the context : Adding the context of action in order to use it on Views called from buttons if datas.get('id',False): context.update( {'active_id': datas.get('id',False), 'active_ids': datas.get('ids',[]), 'active_model': datas.get('model',False)}) context.update(safe_eval(action.get('context','{}'), context.copy())) if action['type'] in ['ir.actions.act_window', 'ir.actions.submenu']: for key in ('res_id', 'res_model', 'view_type', 'view_mode', 'limit', 'auto_refresh', 'search_view', 'auto_search', 'search_view_id'): datas[key] = action.get(key, datas.get(key, None)) view_id = False if action.get('views', []): if isinstance(action['views'],list): view_id = action['views'][0][0] datas['view_mode']= action['views'][0][1] else: if action.get('view_id', False): view_id = action['view_id'][0] elif action.get('view_id', False): view_id = action['view_id'][0] assert datas['res_model'], "Cannot use the view without a model" # Here, we have a view that we need to emulate log_test("will emulate a %s view: %s#%s", action['view_type'], datas['res_model'], view_id or '?') view_res = pool.get(datas['res_model']).fields_view_get(cr, uid, view_id, action['view_type'], context) assert view_res and view_res.get('arch'), "Did not return any arch for the view" view_data = {} if view_res.get('fields',{}).keys(): view_data = pool.get(datas['res_model']).default_get(cr, uid, view_res['fields'].keys(), context) if datas.get('form'): view_data.update(datas.get('form')) if wiz_data: view_data.update(wiz_data) _logger.debug("View data is: %r", view_data) for fk, field in view_res.get('fields',{}).items(): # Default fields returns list of int, while at create() # we need to send a [(6,0,[int,..])] if field['type'] in ('one2many', 'many2many') \ and view_data.get(fk, False) \ and isinstance(view_data[fk], list) \ and not isinstance(view_data[fk][0], tuple) : view_data[fk] = [(6, 0, view_data[fk])] action_name = action.get('name') try: from xml.dom import minidom cancel_found = False buttons = [] dom_doc = minidom.parseString(view_res['arch']) if not action_name: action_name = dom_doc.documentElement.getAttribute('name') for button in dom_doc.getElementsByTagName('button'): button_weight = 0 if button.getAttribute('special') == 'cancel': cancel_found = True continue if button.getAttribute('icon') == 'gtk-cancel': cancel_found = True continue if button.getAttribute('default_focus') == '1': button_weight += 20 if button.getAttribute('string') in wiz_buttons: button_weight += 30 elif button.getAttribute('icon') in wiz_buttons: button_weight += 10 string = button.getAttribute('string') or '?%s' % len(buttons) buttons.append( { 'name': button.getAttribute('name'), 'string': string, 'type': button.getAttribute('type'), 'weight': button_weight, }) except Exception, e: _logger.warning("Cannot resolve the view arch and locate the buttons!", exc_info=True) raise AssertionError(e.args[0]) if not datas['res_id']: # it is probably an orm_memory object, we need to create # an instance datas['res_id'] = pool.get(datas['res_model']).create(cr, uid, view_data, context) if not buttons: raise AssertionError("view form doesn't have any buttons to press!") buttons.sort(key=lambda b: b['weight']) _logger.debug('Buttons are: %s', ', '.join([ '%s: %d' % (b['string'], b['weight']) for b in buttons])) res = None while buttons and not res: b = buttons.pop() log_test("in the \"%s\" form, I will press the \"%s\" button.", action_name, b['string']) if not b['type']: log_test("the \"%s\" button has no type, cannot use it", b['string']) continue if b['type'] == 'object': #there we are! press the button! fn = getattr(pool.get(datas['res_model']), b['name']) if not fn: _logger.error("The %s model doesn't have a %s attribute!", datas['res_model'], b['name']) continue res = fn(cr, uid, [datas['res_id'],], context) break else: _logger.warning("in the \"%s\" form, the \"%s\" button has unknown type %s", action_name, b['string'], b['type']) return res elif action['type']=='ir.actions.report.xml': if 'window' in datas: del datas['window'] if not datas: datas = action.get('datas',{}) datas = datas.copy() ids = datas.get('ids') if 'ids' in datas: del datas['ids'] res = try_report(cr, uid, 'report.'+action['report_name'], ids, datas, context, our_module=our_module) return res else: raise Exception("Cannot handle action of type %s" % act_model) log_test("will be using %s action %s #%d", act_model, act_xmlid, act_id) action = pool.get(act_model).read(cr, uid, act_id, context=context) assert action, "Could not read action %s[%s]" %(act_model, act_id) loop = 0 while action: loop += 1 # This part tries to emulate the loop of the Gtk client if loop > 100: _logger.error("Passed %d loops, giving up", loop) raise Exception("Too many loops at action") log_test("it is an %s action at loop #%d", action.get('type', 'unknown'), loop) result = _exec_action(action, datas, context) if not isinstance(result, dict): break datas = result.get('datas', {}) if datas: del result['datas'] action = result return True #eof # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|>
os.close(fd)
<|file_name|>UniqueRoleNameValidator.java<|end_file_name|><|fim▁begin|>package org.carlspring.strongbox.validation; import javax.inject.Inject; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.carlspring.strongbox.authorization.service.AuthorizationConfigService; import org.springframework.util.StringUtils; /**<|fim▁hole|> * @author Pablo Tirado */ public class UniqueRoleNameValidator implements ConstraintValidator<UniqueRoleName, String> { @Inject private AuthorizationConfigService authorizationConfigService; @Override public void initialize(UniqueRoleName constraint) { // empty by design } @Override public boolean isValid(String roleName, ConstraintValidatorContext context) { return StringUtils.isEmpty(roleName) || !authorizationConfigService.get().getRoles().stream().anyMatch(r -> r.getName().equals(roleName)); } }<|fim▁end|>
<|file_name|>vpHinkley.cpp<|end_file_name|><|fim▁begin|>/**************************************************************************** * * $Id: vpHinkley.cpp 4056 2013-01-05 13:04:42Z fspindle $ * * This file is part of the ViSP software. * Copyright (C) 2005 - 2013 by INRIA. All rights reserved. * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ViSP with software that can not be combined with the GNU * GPL, please contact INRIA about acquiring a ViSP Professional * Edition License. * * See http://www.irisa.fr/lagadic/visp/visp.html for more information. * * This software was developed at: * INRIA Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * http://www.irisa.fr/lagadic * * If you have questions regarding the use of this file, please contact * INRIA at [email protected] * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * * Description: * Hinkley's cumulative sum test implementation. * * Authors: * Fabien Spindler * *****************************************************************************/ /*! \file vpHinkley.cpp \brief Definition of the vpHinkley class corresponding to the Hinkley's cumulative sum test. */ #include <visp/vpHinkley.h> #include <visp/vpDebug.h> #include <visp/vpIoTools.h> #include <visp/vpMath.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <cmath> // std::fabs #include <limits> // numeric_limits /* VP_DEBUG_MODE fixed by configure: 1: 2: 3: Print data */ /*! Constructor. Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ to default values. By default \f$ \delta = 0.2 \f$ and \f$ \alpha = 0.2\f$. Use setDelta() and setAlpha() to modify these values. */ vpHinkley::vpHinkley() { init(); setAlpha(0.2); setDelta(0.2); } /*! Constructor. Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ thresholds. \param alpha : \f$\alpha\f$ is a predefined threshold. \param delta : \f$\delta\f$ denotes the jump minimal magnitude that we want to detect. \sa setAlpha(), setDelta() */ vpHinkley::vpHinkley(double alpha, double delta) { init(); setAlpha(alpha); setDelta(delta); } /*! Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ thresholds. \param alpha : \f$\alpha\f$ is a predefined threshold. \param delta : \f$\delta\f$ denotes the jump minimal magnitude that we want to detect. \sa setAlpha(), setDelta() */ void vpHinkley::init(double alpha, double delta) { init(); setAlpha(alpha); setDelta(delta); } /*! Destructor. */ vpHinkley::~vpHinkley() { } /*! Initialise the Hinkley's test by setting the mean signal value \f$m_0\f$ to zero as well as \f$S_k, M_k, T_k, N_k\f$. */ void vpHinkley::init() { nsignal = 0; mean = 0.0; Sk = 0; Mk = 0; Tk = 0; Nk = 0; } /*! Set the value of \f$\delta\f$, the jump minimal magnetude that we want to detect. \sa setAlpha() */ void vpHinkley::setDelta(double delta) { dmin2 = delta / 2; } /*! Set the value of \f$\alpha\f$, a predefined threshold. \sa setDelta() */ void vpHinkley::setAlpha(double alpha) { this->alpha = alpha; } /*! Perform the Hinkley test. A downward jump is detected if \f$ M_k - S_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testUpwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testDownwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; // Calcul des variables cumulées computeSk(signal); computeMk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Sk: " << Sk << " Mk: " << Mk; // teste si les variables cumulées excèdent le seuil if ((Mk - Sk) > alpha) jump = downwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >=2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upwardJump " << std::endl; break; } } #endif computeMean(signal); if (jump == downwardJump) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Sk = 0; Mk = 0; nsignal = 0; } return (jump); } /*! Perform the Hinkley test. An upward jump is detected if \f$ T_k - N_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testDownwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testUpwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; // Calcul des variables cumulées computeTk(signal); computeNk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Tk: " << Tk << " Nk: " << Nk; // teste si les variables cumulées excèdent le seuil<|fim▁hole|> if (VP_DEBUG_MODE >= 2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upWardJump " << std::endl; break; } } #endif computeMean(signal); if (jump == upwardJump) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Tk = 0; Nk = 0; nsignal = 0; } return (jump); } /*! Perform the Hinkley test. A downward jump is detected if \f$ M_k - S_k > \alpha \f$. An upward jump is detected if \f$ T_k - N_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testDownwardJump(), testUpwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testDownUpwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; // Calcul des variables cumulées computeSk(signal); computeTk(signal); computeMk(); computeNk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Sk: " << Sk << " Mk: " << Mk << " Tk: " << Tk << " Nk: " << Nk << std::endl; // teste si les variables cumulées excèdent le seuil if ((Mk - Sk) > alpha) jump = downwardJump; else if ((Tk - Nk) > alpha) jump = upwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >= 2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upwardJump " << std::endl; break; } } #endif computeMean(signal); if ((jump == upwardJump) || (jump == downwardJump)) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Sk = 0; Mk = 0; Tk = 0; Nk = 0; nsignal = 0; // Debut modif FS le 03/09/2003 mean = signal; // Fin modif FS le 03/09/2003 } return (jump); } /*! Compute the mean value \f$m_0\f$ of the signal. The mean value must be computed before the jump is estimated on-line. \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeMean(double signal) { // Debut modif FS le 03/09/2003 // Lors d'une chute ou d'une remontée lente du signal, pariculièrement // après un saut, la moyenne a tendance à "dériver". Pour réduire ces // dérives de la moyenne, elle n'est remise à jour avec la valeur // courante du signal que si un début de saut potentiel n'est pas détecté. //if ( ((Mk-Sk) == 0) && ((Tk-Nk) == 0) ) if ( ( std::fabs(Mk-Sk) <= std::fabs(vpMath::maximum(Mk,Sk))*std::numeric_limits<double>::epsilon() ) && ( std::fabs(Tk-Nk) <= std::fabs(vpMath::maximum(Tk,Nk))*std::numeric_limits<double>::epsilon() ) ) // Fin modif FS le 03/09/2003 // Mise a jour de la moyenne. mean = (mean * (nsignal - 1) + signal) / (nsignal); } /*! Compute \f$S_k = \sum_{t=0}^{k} (s(t) - m_0 + \frac{\delta}{2})\f$ \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeSk(double signal) { // Calcul des variables cumulées Sk += signal - mean + dmin2; } /*! Compute \f$M_k\f$, the maximum value of \f$S_k\f$. */ void vpHinkley::computeMk() { if (Sk > Mk) Mk = Sk; } /*! Compute \f$T_k = \sum_{t=0}^{k} (s(t) - m_0 - \frac{\delta}{2})\f$ \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeTk(double signal) { // Calcul des variables cumulées Tk += signal - mean - dmin2; } /*! Compute \f$N_k\f$, the minimum value of \f$T_k\f$. */ void vpHinkley::computeNk() { if (Tk < Nk) Nk = Tk; } void vpHinkley::print(vpHinkley::vpHinkleyJumpType jump) { switch(jump) { case noJump : std::cout << " No jump detected " << std::endl ; break ; case downwardJump : std::cout << " Jump downward detected " << std::endl ; break ; case upwardJump : std::cout << " Jump upward detected " << std::endl ; break ; default: std::cout << " Jump detected " << std::endl ; break ; } }<|fim▁end|>
if ((Tk - Nk) > alpha) jump = upwardJump; #ifdef VP_DEBUG
<|file_name|>gene_enumerations.py<|end_file_name|><|fim▁begin|>#Aditya Joshi #Enumerating Oriented Gene Ordering from itertools import permutations,product from math import fabs n = int(raw_input()) def make_set(n): set = [] for x in range(1,n+1): set += [x] return set def plusAndMinusPermutations(items): for p in permutations(items,len(items)): for signs in product([-1,1], repeat=len(items)): yield [a*sign for a,sign in zip(p,signs)] def array_to_string(list): string = "" string += str(list[0]) + " " + str(list[1]) return string count = 0 <|fim▁hole|>for x in plusAndMinusPermutations(make_set(n)): print array_to_string(x) count += 1 print count<|fim▁end|>
<|file_name|>plot.py<|end_file_name|><|fim▁begin|>import scipy as sp import matplotlib import matplotlib.pyplot as plt def simple_log_qqplot(quantiles_list, png_file=None, pdf_file=None, quantile_labels=None, line_colors=None, max_val=5, title=None, text=None, plot_label=None, ax=None, **kwargs): storeFig = False if ax is None: f = plt.figure(figsize=(5.4, 5)) ax = f.add_axes([0.1, 0.09, 0.88, 0.86]) storeFig = True ax.plot([0, max_val], [0, max_val], 'k--', alpha=0.5, linewidth=2.0) num_dots = len(quantiles_list[0]) exp_quantiles = sp.arange(1, num_dots + 1, dtype='single') / (num_dots + 1) * max_val for i, quantiles in enumerate(quantiles_list): if line_colors: c = line_colors[i] else: c = 'b' if quantile_labels: ax.plot(exp_quantiles, quantiles, label=quantile_labels[i], c=c, alpha=0.5, linewidth=2.2) else: ax.plot(exp_quantiles, quantiles, c=c, alpha=0.5, linewidth=2.2) ax.set_ylabel("Observed $-log_{10}(p$-value$)$") ax.set_xlabel("Expected $-log_{10}(p$-value$)$") if title: ax.title(title) max_x = max_val max_y = max(map(max, quantiles_list)) ax.axis([-0.025 * max_x, 1.025 * max_x, -0.025 * max_y, 1.025 * max_y]) if quantile_labels: fontProp = matplotlib.font_manager.FontProperties(size=10) ax.legend(loc=2, numpoints=2, handlelength=0.05, markerscale=1, prop=fontProp, borderaxespad=0.018) y_min, y_max = plt.ylim() if text: f.text(0.05 * max_val, y_max * 0.9, text) if plot_label: f.text(-0.138 * max_val, y_max * 1.01, plot_label, fontsize=14) if storeFig == False: return if png_file != None: f.savefig(png_file) if pdf_file != None: f.savefig(pdf_file, format='pdf') <|fim▁hole|> storeFig = False if ax is None: f = plt.figure(figsize=(5.4, 5)) ax = f.add_axes([0.11, 0.09, 0.87, 0.86]) storeFig = True ax.plot([0, 1], [0, 1], 'k--', alpha=0.5, linewidth=2.0) num_dots = len(quantiles_list[0]) exp_quantiles = sp.arange(1, num_dots + 1, dtype='single') / (num_dots + 1) for i, quantiles in enumerate(quantiles_list): if line_colors: c = line_colors[i] else: c = 'b' if quantile_labels: ax.plot(exp_quantiles, quantiles, label=quantile_labels[i], c=c, alpha=0.5, linewidth=2.2) else: ax.plot(exp_quantiles, quantiles, c=c, alpha=0.5, linewidth=2.2) ax.set_ylabel("Observed $p$-value") ax.set_xlabel("Expected $p$-value") if title: ax.title(title) ax.axis([-0.025, 1.025, -0.025, 1.025]) if quantile_labels: fontProp = matplotlib.font_manager.FontProperties(size=10) ax.legend(loc=2, numpoints=2, handlelength=0.05, markerscale=1, prop=fontProp, borderaxespad=0.018) if text: f.text(0.05, 0.9, text) if plot_label: f.text(-0.151, 1.04, plot_label, fontsize=14) if storeFig == False: return if png_file != None: f.savefig(png_file) if pdf_file != None: f.savefig(pdf_file, format='pdf') def plot_simple_qqplots(png_file_prefix, results, result_labels=None, line_colors=None, num_dots=1000, title=None, max_neg_log_val=5): """ Plots both log QQ-plots and normal QQ plots. """ qs = [] log_qs = [] for res in results: pvals = res.snp_results['scores'][:] qs.append(get_quantiles(pvals, num_dots)) log_qs.append(get_log_quantiles(pvals, num_dots, max_neg_log_val)) simple_qqplot(qs, png_file_prefix + '_qq.png', quantile_labels=result_labels, line_colors=line_colors, num_dots=num_dots, title=title) simple_log_qqplot(log_qs, png_file_prefix + '_log_qq.png', quantile_labels=result_labels, line_colors=line_colors, num_dots=num_dots, title=title, max_val=max_neg_log_val) def plot_simple_qqplots_pvals(png_file_prefix, pvals_list, result_labels=None, line_colors=None, num_dots=1000, title=None, max_neg_log_val=5): """ Plots both log QQ-plots and normal QQ plots. """ qs = [] log_qs = [] for pvals in pvals_list: qs.append(get_quantiles(pvals, num_dots)) log_qs.append(get_log_quantiles(pvals, num_dots, max_neg_log_val)) simple_qqplot(qs, png_file_prefix + '_qq.png', quantile_labels=result_labels, line_colors=line_colors, num_dots=num_dots, title=title) simple_log_qqplot(log_qs, png_file_prefix + '_log_qq.png', quantile_labels=result_labels, line_colors=line_colors, num_dots=num_dots, title=title, max_val=max_neg_log_val)<|fim▁end|>
def simple_qqplot(quantiles_list, png_file=None, pdf_file=None, quantile_labels=None, line_colors=None, title=None, text=None, ax=None, plot_label=None, **kwargs):
<|file_name|>asyncGeneratorsTest.js<|end_file_name|><|fim▁begin|>const assert = require("assert"); describe("chain of iterators", function() { it("should conform to ES", function() { let finallyCalledSrc = 0; let finallyCalled1 = 0; let finallyCalled2 = 0; let cb; let p1 = new Promise(i => (cb = i)); let tasks = []; let cbtask; let p2 = { then(next) { tasks.push(next); cbtask(); } }; async function scheduler() { await new Promise(i => (cbtask = i)); tasks.pop()("t1"); } scheduler(); async function* src() { try { yield await p1; yield await p2; assert.fail("never");<|fim▁hole|> async function* a1() { try { for await (const i of src()) yield `a1:${i}`; assert.fail("never"); } finally { finallyCalled1 = true; } assert.fail("never"); } async function* a2() { try { yield* a1(); assert.fail("never"); } finally { finallyCalled2 = true; } } async function* a3() { const v = a2(); try { for (let i; !(i = await v.next()).done; ) { yield `a3:${i.value}`; } assert.fail("never"); } finally { await v.return(); } return 2; } async function a4() { const v = a3(); const i1 = await v.next(); assert.ok(!i1.done); assert.equal(i1.value, "a3:a1:hi"); const n = v.next(); const i2 = await n; assert.ok(!i2.done); assert.equal(i2.value, "a3:a1:t1"); const i3 = await v.return(4); assert.ok(i3.done); assert.equal(i3.value, 4); assert.ok(finallyCalledSrc); assert.ok(finallyCalled1); assert.ok(finallyCalled2); return 3; } const t4 = a4(); const res = t4.then(i => { assert.equal(i, 3); }); cb("hi"); return res; }); });<|fim▁end|>
} finally { finallyCalledSrc++; } }
<|file_name|>Binary Tree Inorder Traversal.py<|end_file_name|><|fim▁begin|># /** # * Definition for a binary tree node. # * public class TreeNode { # * int val; # * TreeNode left; # * TreeNode right; # * TreeNode(int x) { val = x; } # * } # */ # public class Solution { # public List<Integer> inorderTraversal(TreeNode root) { # List<Integer> list = new ArrayList<Integer>(); # # Stack<TreeNode> stack = new Stack<TreeNode>(); # TreeNode cur = root; # # while(cur!=null || !stack.empty()){ # while(cur!=null){ # stack.add(cur); # cur = cur.left; # } # cur = stack.pop(); # list.add(cur.val); # cur = cur.right; # } # # return list; # } # } # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res, stack = [], [] while True: while root: stack.append(root) root = root.left if not stack: return res<|fim▁hole|> root = node.right<|fim▁end|>
node = stack.pop() res.append(node.val)
<|file_name|>home.py<|end_file_name|><|fim▁begin|>__author__ = 'had' # The MIT License (MIT) # Copyright (c) [2015] [Houtmann Hadrien] # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the Aidez-moi), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from datetime import datetime from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django_tables2 import RequestConfig from ticket.forms.forms import TicketForm, ResponseForm, StatusForm from ticket.models import Tickets, UserProfile, Follow from ticket.tables import TicketsTables from django.contrib import messages from django.utils.translation import ugettext as _ from ticket.tasks import send_new_ticket_all_staff, incomplete_ticket from djangoticket.settings import USE_MAIL import json from django.views.decorators.cache import cache_page @login_required(login_url='login/') def home(request): if request.user.is_staff: ticket_list = Tickets\ .objects\ .select_related('create_by', 'assign_to', 'category')\ .filter()\<|fim▁hole|> else: ticket_list = Tickets.objects.filter( create_by=request.user).order_by('-created')[:10:1] ticket_incomplete = Tickets.objects.filter( create_by=request.user, complete=0).count() return render(request, 'home.html', {'ticket_list': ticket_list})<|fim▁end|>
.order_by('-created')[:10:1] ticket_incomplete = Tickets.objects.filter(complete=0).count()
<|file_name|>template_url_service_factory.cc<|end_file_name|><|fim▁begin|>// Copyright 2015 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. #include "ios/chrome/browser/search_engines/template_url_service_factory.h" #include "base/bind.h" #include "base/callback.h" #include "base/no_destructor.h" #include "components/keyed_service/core/service_access_type.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/search_engines/default_search_manager.h" #include "components/search_engines/template_url_service.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/browser_state_otr_helper.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/history/history_service_factory.h" #include "ios/chrome/browser/search_engines/template_url_service_client_impl.h" #include "ios/chrome/browser/search_engines/ui_thread_search_terms_data.h" #include "ios/chrome/browser/webdata_services/web_data_service_factory.h" #include "rlz/buildflags/buildflags.h" #if BUILDFLAG(ENABLE_RLZ) #include "components/rlz/rlz_tracker.h" // nogncheck #endif namespace ios { namespace { base::RepeatingClosure GetDefaultSearchProviderChangedCallback() { #if BUILDFLAG(ENABLE_RLZ) return base::BindRepeating( base::IgnoreResult(&rlz::RLZTracker::RecordProductEvent), rlz_lib::CHROME, rlz::RLZTracker::ChromeOmnibox(), rlz_lib::SET_TO_GOOGLE); #else return base::RepeatingClosure(); #endif } std::unique_ptr<KeyedService> BuildTemplateURLService( web::BrowserState* context) { ChromeBrowserState* browser_state = ChromeBrowserState::FromBrowserState(context); return std::make_unique<TemplateURLService>( browser_state->GetPrefs(), std::make_unique<ios::UIThreadSearchTermsData>(), ios::WebDataServiceFactory::GetKeywordWebDataForBrowserState( browser_state, ServiceAccessType::EXPLICIT_ACCESS), std::make_unique<ios::TemplateURLServiceClientImpl>( ios::HistoryServiceFactory::GetForBrowserState( browser_state, ServiceAccessType::EXPLICIT_ACCESS)), GetDefaultSearchProviderChangedCallback()); } } // namespace // static TemplateURLService* TemplateURLServiceFactory::GetForBrowserState( ChromeBrowserState* browser_state) { return static_cast<TemplateURLService*>( GetInstance()->GetServiceForBrowserState(browser_state, true)); } // static TemplateURLServiceFactory* TemplateURLServiceFactory::GetInstance() { static base::NoDestructor<TemplateURLServiceFactory> instance; return instance.get(); } // static BrowserStateKeyedServiceFactory::TestingFactory<|fim▁hole|> TemplateURLServiceFactory::TemplateURLServiceFactory() : BrowserStateKeyedServiceFactory( "TemplateURLService", BrowserStateDependencyManager::GetInstance()) { DependsOn(ios::HistoryServiceFactory::GetInstance()); DependsOn(ios::WebDataServiceFactory::GetInstance()); } TemplateURLServiceFactory::~TemplateURLServiceFactory() {} void TemplateURLServiceFactory::RegisterBrowserStatePrefs( user_prefs::PrefRegistrySyncable* registry) { DefaultSearchManager::RegisterProfilePrefs(registry); TemplateURLService::RegisterProfilePrefs(registry); } std::unique_ptr<KeyedService> TemplateURLServiceFactory::BuildServiceInstanceFor( web::BrowserState* context) const { return BuildTemplateURLService(context); } web::BrowserState* TemplateURLServiceFactory::GetBrowserStateToUse( web::BrowserState* context) const { return GetBrowserStateRedirectedInIncognito(context); } bool TemplateURLServiceFactory::ServiceIsNULLWhileTesting() const { return true; } } // namespace ios<|fim▁end|>
TemplateURLServiceFactory::GetDefaultFactory() { return base::BindRepeating(&BuildTemplateURLService); }
<|file_name|>nicovideo.js<|end_file_name|><|fim▁begin|>"use strict"; //////////////////////////////////////////////////////////////////////////////// // ニコニコ動画再生 //////////////////////////////////////////////////////////////////////////////// Contents.nicovideo = function( cp ) { var p = $( '#' + cp.id ); var cont = p.find( 'div.contents' ); cp.SetIcon( null ); //////////////////////////////////////////////////////////// // 開始処理<|fim▁hole|> cont.addClass( 'nicovideo' ) .html( OutputTPL( 'nicovideo', { id: cp.param.id } ) ); cp.SetTitle( 'Nicovideo - ' + cp.param['url'], false ); cont.activity( false ); }; //////////////////////////////////////////////////////////// // 終了処理 //////////////////////////////////////////////////////////// this.stop = function() { }; }<|fim▁end|>
//////////////////////////////////////////////////////////// this.start = function() { cont.activity( { color: '#ffffff' } );
<|file_name|>index.js<|end_file_name|><|fim▁begin|>module.exports = require("./mime-functions");<|fim▁hole|><|fim▁end|>
module.exports.contentTypes = require("./content-types");
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-<|fim▁hole|>from exceptions import DropPage, AbortProcess<|fim▁end|>
<|file_name|>vm.rs<|end_file_name|><|fim▁begin|>use crate::{builder, ffi, util, Value}; use std; use std::fmt; use libc; use std::sync::Mutex; /// A Ruby virtual machine. pub struct VM; /// We only want to be able to have one `VM` at a time. static mut VM_EXISTS: bool = false; lazy_static! { static ref ACTIVE_VM: Mutex<VM> = Mutex::new(VM::new().expect("failed to create Ruby VM")); } // TODO: // Implement hooked variables (rb_define_hooked_variable) // Allows a callback to get/set variable value #[derive(PartialEq)] /// A Ruby error pub enum ErrorKind { /// An internal VM error.<|fim▁hole|> Exception(Value), } impl VM { /// Gets the active VM. pub fn get() -> &'static Mutex<VM> { &ACTIVE_VM } /// Creates a new Ruby VM. pub fn new() -> Result<Self, ErrorKind> { unsafe { if VM_EXISTS { Err(ErrorKind::VM("can only have one Ruby VM at a time".to_owned())) } else { ffi::ruby_init(); VM_EXISTS = true; Ok(VM) } } } /// Evaluates a line of code. pub fn eval(&mut self, code: &str) -> Result<Value, ErrorKind> { self.eval_advanced(code, false) } /// Evaluates a line of code in a sandbox. /// /// Any variables defined will not be saved. pub fn eval_sandbox(&mut self, code: &str) -> Result<Value, ErrorKind> { self.eval_advanced(code, true) } /// `require`s a file. pub fn require(&self, file_name: &str) -> Value { Value::from(unsafe { ffi::rb_require(util::c_string(file_name).as_ptr()) }) } /// Creates a new class. pub fn class<S>(&mut self, name: S) -> builder::Class where S: Into<String> { builder::Class::new(name) } /// Creates a new module. pub fn module<S>(&mut self, name: S) -> builder::Module where S: Into<String> { builder::Module::new(name) } /// Sets the value of a global variable or creates a new one. pub fn set_global(&self, name: &str, value: Value) -> Value { Value::from(unsafe { ffi::rb_gv_set(util::c_string(name).as_ptr(), value.0) }) } /// Gets the value of a global variable. pub fn get_global(&self, name: &str) -> Value { Value::from(unsafe { ffi::rb_gv_get(util::c_string(name).as_ptr()) }) } /// Sets a global constant. pub fn set_global_const(&self, name: &str, value: Value) { unsafe { ffi::rb_define_global_const(util::c_string(name).as_ptr(), value.0) } } /// Defines a global function. pub fn define_global_function(&self, name: &str, f: *mut extern fn() -> Value, arg_count: u8) -> Value { unsafe { Value::from(ffi::rb_define_global_function( util::c_string(name).as_ptr(), f as *mut _, arg_count as libc::c_int, )) } } /// Gets the current receiver (can be `nil`). pub fn current_receiver(&self) -> Value { unsafe { Value::from(ffi::rb_current_receiver()) } } /// Raises an object and a message. pub fn raise(&self, value: Value, message: &str) -> ! { unsafe { ffi::rb_raise(value.0, util::c_string(message).as_ptr()) } } /// Raises a fatal error. pub fn fatal(&self, message: &str) -> ! { unsafe { ffi::rb_fatal(util::c_string(message).as_ptr()) } } /// Raises a bug. pub fn bug(&self, message: &str) -> ! { unsafe { ffi::rb_bug(util::c_string(message).as_ptr()) } } /// Logs a Ruby warning. pub fn warning(&self, message: &str) { unsafe { ffi::rb_warning(util::c_string(message).as_ptr()) } } /// Prints Ruby version info to stdout. pub fn show_ruby_version(&self) { unsafe { ffi::ruby_show_version() } } /// Prints Ruby copyright info to stdout. pub fn show_ruby_copyright(&self) { unsafe { ffi::ruby_show_copyright() } } /// Sets the script name. /// Essentially the same as `$0 = name`. pub fn set_script_name(&self, name: &str) { unsafe { ffi::ruby_script(util::c_string(name).as_ptr()) } } /// Gets the currently raised exception and clears it. pub fn consume_exception(&mut self) -> Value { let exception = self.current_exception(); unsafe { ffi::rb_set_errinfo(ffi::Qnil) }; exception } /// Gets the currently raised exception exception. /// /// Can be `nil`. pub fn current_exception(&self) -> Value { Value::from(unsafe { ffi::rb_errinfo() }) } fn eval_advanced(&mut self, code: &str, sandbox: bool) -> Result<Value, ErrorKind> { let mut state: libc::c_int = 0; let eval_fn = if sandbox { ffi::rb_eval_string_protect } else { ffi::rb_eval_string_wrap }; let result = unsafe { eval_fn(util::c_string(code).as_ptr(), &mut state) }; if state == 0 { Ok(Value::from(result)) } else { Err(ErrorKind::Exception(self.consume_exception())) } } } impl std::ops::Drop for VM { fn drop(&mut self) { unsafe { VM_EXISTS = false; ffi::ruby_cleanup(0); }; } } impl fmt::Debug for ErrorKind { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { ErrorKind::VM(ref msg) => write!(fmt, "virtual machine error: {}", msg), ErrorKind::Exception(e) => write!(fmt, "{}: {:?}", e.class_name(), e), } } }<|fim▁end|>
VM(String), /// An exception was thrown.
<|file_name|>relappro.js<|end_file_name|><|fim▁begin|>/** * Copyright 2020 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {loadScript, validateData} from '#3p/3p'; /** * @param {!Window} global * @param {!Object} data<|fim▁hole|>export function relappro(global, data) { validateData(data, [], ['slotId', 'nameAdUnit', 'requirements']); global.params = data; loadScript( global, 'https://cdn.relappro.com/adservices/amp/relappro.amp.min.js' ); }<|fim▁end|>
*/
<|file_name|>whoami.rs<|end_file_name|><|fim▁begin|>use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPlugin } pub fn get_plugin_name() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> { match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } } impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) { let privmsg; match msg.as_tymsg::<&server::Privmsg>() { Ok(p) => privmsg = p, Err(_) => return,<|fim▁hole|> } match parse_command(m) { Some(WhoAmICommandType::WhoAmI) => { m.reply(&format!("{}: you are {:?}", privmsg.source_nick(), m.source)); }, Some(WhoAmICommandType::WhereAmI) => { m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }, None => () } } }<|fim▁end|>
<|file_name|>terminal.rs<|end_file_name|><|fim▁begin|>#![macro_use] use io::display; use io::pio::*; use core::fmt; use spin::Mutex; pub struct Terminal { writer: display::Writer, color: u8, x: usize, y: usize, } pub static TERM: Mutex<Terminal> = Mutex::new(Terminal { writer: display::Writer { ptr: 0xb8000 },<|fim▁hole|> x: 0, y: 0, }); impl Terminal { pub fn new() -> Terminal { Terminal { writer: display::Writer::new(0xb8000), color: display::Color::new(display::Color::White, display::Color::Black), x: 0, y: 0, } } pub fn set_color(&mut self, color: u8) { self.color = color; } pub fn advance(&mut self) { if self.x <= display::VIDEO_WIDTH { self.x += 1; } else { self.newline(); } } pub fn newline(&mut self) { self.x = 0; self.y += 1; if self.y > display::VIDEO_HEIGHT { self.scroll(); } } pub fn clear(&mut self) { for i in 0..(display::VIDEO_WIDTH * display::VIDEO_HEIGHT) { self.writer.write_index(display::Entry::new(b' ', self.color), i); } } pub fn scroll(&mut self) { self.x = 0; self.y = 0; // for i in 0..(display::VIDEO_WIDTH * (display::VIDEO_HEIGHT - 1)) { // self.writer.write_index(self.writer.at(i + display::VIDEO_WIDTH), i); // } } pub fn backspace(&mut self) { self.writer.write_index(display::Entry::new(b' ', self.color), self.y * display::VIDEO_WIDTH + self.x - 1); if self.x == 0 { self.y -= 1; self.x = display::VIDEO_WIDTH; } else { self.x -= 1; } } pub fn update_cursor(&self) { let pos: u16 = self.y as u16 * display::VIDEO_WIDTH as u16 + self.x as u16; outb(0x3d4, 0x0f); outb(0x3d5, pos as u8 & 0xff); outb(0x3d4, 0x0e); outb(0x3d5, (pos >> 8) as u8 & 0xff); } } impl fmt::Write for Terminal { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { for byte in s.bytes() { match byte { b'\n' => self.newline(), b'\x08' => self.backspace(), byte => { self.writer.write_index(display::Entry::new(byte, self.color), self.y * display::VIDEO_WIDTH + self.x); self.advance(); } } } self.update_cursor(); Ok(()) } }<|fim▁end|>
color: display::Color::new(display::Color::White, display::Color::Black),
<|file_name|>cdecl.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------- # pycparser: cdecl.py # # Example of the CDECL tool using pycparser. CDECL "explains" C type # declarations in plain English. # # The AST generated by pycparser from the given declaration is traversed # recursively to build the explanation. Note that the declaration must be a # valid external declaration in C. All the types used in it must be defined with # typedef, or parsing will fail. The definition can be arbitrary - pycparser # doesn't really care what the type is defined to be, only that it's a type. # # For example: # # c_decl = 'typedef int Node; const Node* (*ar)[10];' # # explain_c_declaration(c_decl) # => ar is a pointer to array[10] of pointer to const Node # # struct and typedef are expanded when according arguments are set: # # explain_c_declaration(c_decl, expand_typedef=True) # => ar is a pointer to array[10] of pointer to const int # # c_decl = 'struct P {int x; int y;} p;' # # explain_c_declaration(c_decl) # => p is a struct P # # explain_c_declaration(c_decl, expand_struct=True) # => p is a struct P containing {x is a int, y is a int} # # Eli Bendersky [http://eli.thegreenplace.net] # License: BSD #----------------------------------------------------------------- import copy import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py # sys.path.extend(['.', '..']) from pycparser import c_parser, c_ast def explain_c_declaration(c_decl, expand_struct=False, expand_typedef=False): """ Parses the declaration in c_decl and returns a text explanation as a string. The last external node of the string is used, to allow earlier typedefs for used types. """ parser = c_parser.CParser() try: node = parser.parse(c_decl, filename='<stdin>') except c_parser.ParseError: e = sys.exc_info()[1] return "Parse error:" + str(e) if (not isinstance(node, c_ast.FileAST) or not isinstance(node.ext[-1], c_ast.Decl) ): return "Not a valid declaration" try: expanded = expand_struct_typedef(node.ext[-1], node, expand_struct=expand_struct, expand_typedef=expand_typedef) except Exception as e: return "Not a valid declaration: " + str(e) return _explain_decl_node(expanded) def _explain_decl_node(decl_node): """ Receives a c_ast.Decl note and returns its explanation in English. """ storage = ' '.join(decl_node.storage) + ' ' if decl_node.storage else '' return (decl_node.name + " is a " + storage + _explain_type(decl_node.type)) def _explain_type(decl): """ Recursively explains a type decl node """ typ = type(decl) if typ == c_ast.TypeDecl: quals = ' '.join(decl.quals) + ' ' if decl.quals else '' return quals + _explain_type(decl.type) elif typ == c_ast.Typename or typ == c_ast.Decl: return _explain_type(decl.type) elif typ == c_ast.IdentifierType: return ' '.join(decl.names) elif typ == c_ast.PtrDecl: quals = ' '.join(decl.quals) + ' ' if decl.quals else '' return quals + 'pointer to ' + _explain_type(decl.type) elif typ == c_ast.ArrayDecl: arr = 'array' if decl.dim: arr += '[%s]' % decl.dim.value return arr + " of " + _explain_type(decl.type) elif typ == c_ast.FuncDecl: if decl.args: params = [_explain_type(param) for param in decl.args.params] args = ', '.join(params) else: args = '' return ('function(%s) returning ' % (args) + _explain_type(decl.type)) elif typ == c_ast.Struct: decls = [_explain_decl_node(mem_decl) for mem_decl in decl.decls] members = ', '.join(decls) return ('struct%s ' % (' ' + decl.name if decl.name else '') + ('containing {%s}' % members if members else '')) def expand_struct_typedef(cdecl, file_ast, expand_struct=False, expand_typedef=False): """Expand struct & typedef in context of file_ast and return a new expanded node""" decl_copy = copy.deepcopy(cdecl) _expand_in_place(decl_copy, file_ast, expand_struct, expand_typedef) return decl_copy def _expand_in_place(decl, file_ast, expand_struct=False, expand_typedef=False): """Recursively expand struct & typedef in place, throw Exception if undeclared struct or typedef are used """ typ = type(decl) if typ in (c_ast.Decl, c_ast.TypeDecl, c_ast.PtrDecl, c_ast.ArrayDecl): decl.type = _expand_in_place(decl.type, file_ast, expand_struct, expand_typedef) elif typ == c_ast.Struct: if not decl.decls: struct = _find_struct(decl.name, file_ast) if not struct: raise Exception('using undeclared struct %s' % decl.name) decl.decls = struct.decls for i, mem_decl in enumerate(decl.decls): decl.decls[i] = _expand_in_place(mem_decl, file_ast, expand_struct, expand_typedef) if not expand_struct: decl.decls = [] elif (typ == c_ast.IdentifierType and decl.names[0] not in ('int', 'char')): typedef = _find_typedef(decl.names[0], file_ast) if not typedef: raise Exception('using undeclared type %s' % decl.names[0]) if expand_typedef: return typedef.type return decl def _find_struct(name, file_ast): """Receives a struct name and return declared struct object in file_ast """ for node in file_ast.ext: if (type(node) == c_ast.Decl and type(node.type) == c_ast.Struct and node.type.name == name): return node.type def _find_typedef(name, file_ast): """Receives a type name and return typedef object in file_ast """ for node in file_ast.ext: if type(node) == c_ast.Typedef and node.name == name: return node if __name__ == "__main__":<|fim▁hole|> c_decl = "char *(*(**foo[][8])())[];" print("Explaining the declaration: " + c_decl + "\n") print(explain_c_declaration(c_decl) + "\n")<|fim▁end|>
if len(sys.argv) > 1: c_decl = sys.argv[1] else:
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from copy import copy import json from cnxepub.utils import squash_xml_to_text from cnxml.parse import parse_metadata as parse_cnxml_metadata from cnxtransforms import cnxml_abstract_to_html from lxml import etree __all__ = ( 'convert_to_model_compat_metadata', 'scan_for_id_mapping', 'scan_for_uuid_mapping', 'build_id_to_uuid_mapping', 'id_from_metadata', )<|fim▁hole|> ('authors', 'authors'), ('licensors', 'copyright_holders'), ('maintainers', 'publishers'), ) def _format_actors(actors): """Format the actors list of usernames to a cnx-epub compatable format""" formatted_actors = [] for a in actors: formatted_actors.append({'id': a, 'type': 'cnx-id', 'name': a}) return formatted_actors def convert_to_model_compat_metadata(metadata): """\ Convert the metadata to cnx-epub model compatible metadata. This creates a copy of the metadata. It does not mutate the given metadata. :param metadata: metadata :type metadata: dict :return: metadata :rtype: dict """ md = copy(metadata) md.setdefault('cnx-archive-shortid', None) md.setdefault('cnx-archive-uri', '{}@{}'.format(md['id'], md['version'])) md.pop('id') # FIXME cnx-epub has an issue rendering and parsing license_text set to # None, so hard code it to 'CC BY' for now. md.setdefault('license_text', 'CC BY') md.setdefault('print_style', None) md['derived_from_title'] = md['derived_from']['title'] md['derived_from_uri'] = md['derived_from']['uri'] md.pop('derived_from') # Translate to a Person Info structure for lz_key, epub_key in ACTORS_MAPPING_KEYS: md[epub_key] = _format_actors(md.pop(lz_key)) md.setdefault('editors', []) md.setdefault('illustrators', []) md.setdefault('translators', []) md['summary'] = md.pop('abstract') md['summary'] = md['summary'] and md['summary'] or None if md['summary'] is not None: s = cnxml_abstract_to_html(md['summary']) s = etree.fromstring(s) md['summary'] = squash_xml_to_text(s, remove_namespaces=True) return md def id_from_metadata(metadata): """Given an model's metadata, discover the id.""" identifier = "cnx-archive-uri" return metadata.get(identifier) def scan_for_id_mapping(start_dir): """Collect a mapping of content ids to filepaths relative to the given directory (as ``start_dir``). This is necessary because the filesystem could be organized as a `book-tree`, which is a hierarchy of directories that are labeled by title rather than by id. :param start_dir: a directory to start the scan from :type start_dir: :class:`pathlib.Path` :return: mapping of content ids to the content filepath :rtype: {str: pathlib.Path, ...} """ mapping = {} for filepath in start_dir.glob('**/index.cnxml'): with filepath.open('rb') as fb: xml = etree.parse(fb) md = convert_to_model_compat_metadata(parse_cnxml_metadata(xml)) id = id_from_metadata(md) id = id.split('@')[0] mapping[id] = filepath return mapping def scan_for_uuid_mapping(start_dir): """Collect a mapping of content UUIDs to filepaths relative to the given directory (as ``start_dir``). This is similar to ``scan_for_id_mapping``, but instead of using the ID value found in CNXML as the key, we want the same mapping keyed by the UUID in the corresponding metadata.json file if it's available. :param start_dir: a directory to start the scan from :type start_dir: :class:`pathlib.Path` :return: mapping of content uuids to the content filepath :rtype: {str: pathlib.Path, ...} """ mapping = {} for filepath in start_dir.glob('**/index.cnxml'): metadata_file = filepath.parent / 'metadata.json' if metadata_file.exists(): with metadata_file.open('r') as metadata_json: metadata = json.load(metadata_json) uuid = metadata['id'] mapping[uuid] = filepath else: # Fallback to trying CNXML for UUID metadata metadata = parse_cnxml_metadata(etree.parse(filepath.open())) uuid = metadata.get('uuid') if uuid: mapping[uuid] = filepath return mapping def build_id_to_uuid_mapping(id_to_path_map, uuid_to_path_map): """Build a mapping of ID to UUID values based upon matching paths :param id_to_path_map: A mapping of IDs (m12345) to filepaths :type id_to_path_map: {str: pathlib.Path, ...} :param uuid_to_path_map: A mapping of UUIDs to filepaths :type uuid_to_path_map: {str: pathlib.Path, ...} :return: mapping of ids to uuids :rtype: {str: str, ...} """ mapping = {} path_to_uuid_map = { str(path): uuid for uuid, path in uuid_to_path_map.items() } for id, path in id_to_path_map.items(): mapping[id] = path_to_uuid_map.get(str(path)) return mapping<|fim▁end|>
ACTORS_MAPPING_KEYS = ( # (<litezip name>, <cnx-epub name>),
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python #-*- coding: utf-8 -*- from django.http import HttpResponse import service.api def api_available(request):<|fim▁hole|> return HttpResponse(service.api.get_proxy()) def hello(request): return HttpResponse("Hello world!")<|fim▁end|>
<|file_name|>test_relu.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Arm(R) Ethos(TM)-N integration relu tests""" import numpy as np import pytest import tvm from tvm import relay from tvm.testing import requires_ethosn from . import infrastructure as tei def _get_model(shape, dtype, a_min, a_max): assert a_min >= np.iinfo(dtype).min and a_max <= np.iinfo(dtype).max a = relay.var("a", shape=shape, dtype=dtype) relu = relay.clip(a, a_min=a_min, a_max=a_max) return relu @requires_ethosn @pytest.mark.parametrize("dtype", ["uint8", "int8"]) def test_relu(dtype): trials = [ ((1, 4, 4, 4), 65, 178, "uint8"), ((1, 8, 4, 2), 1, 254, "uint8"), ((1, 16), 12, 76, "uint8"), ((1, 4, 4, 4), 65, 125, "int8"), ((1, 8, 4, 2), -100, 100, "int8"), ((1, 16), -120, -20, "int8"), ] np.random.seed(0) for shape, a_min, a_max, trial_dtype in trials: if trial_dtype == dtype: inputs = { "a": tvm.nd.array( np.random.randint( low=np.iinfo(dtype).min, high=np.iinfo(dtype).max + 1, size=shape,<|fim▁hole|> ) ), } outputs = [] for npu in [False, True]: model = _get_model(inputs["a"].shape, dtype, a_min, a_max) mod = tei.make_module(model, {}) outputs.append(tei.build_and_run(mod, inputs, 1, {}, npu=npu)) tei.verify(outputs, dtype, 1) @requires_ethosn def test_relu_failure(): trials = [ ((1, 4, 4, 4, 4), "uint8", 65, 78, "dimensions=5, dimensions must be <= 4"), ((1, 8, 4, 2), "int16", 1, 254, "dtype='int16', dtype must be either uint8, int8 or int32"), ((1, 8, 4, 2), "uint8", 254, 1, "Relu has lower bound > upper bound"), ((2, 2, 2, 2), "uint8", 1, 63, "batch size=2, batch size must = 1; "), ] for shape, dtype, a_min, a_max, err_msg in trials: model = _get_model(shape, dtype, a_min, a_max) mod = tei.make_ethosn_partition(model) tei.test_error(mod, {}, err_msg)<|fim▁end|>
dtype=dtype,
<|file_name|>ipam.py<|end_file_name|><|fim▁begin|># Copyright 2015 Metaswitch Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from etcd import EtcdKeyNotFound, EtcdAlreadyExist, EtcdCompareFailed from netaddr import IPAddress, IPNetwork import socket import logging import random from pycalico.datastore_datatypes import IPPool from pycalico.datastore import DatastoreClient from pycalico.datastore import (IPAM_HOST_AFFINITY_PATH, IPAM_BLOCK_PATH, IPAM_HANDLE_PATH) from pycalico.datastore_errors import DataStoreError, PoolNotFound from pycalico.block import (AllocationBlock, get_block_cidr_for_address, BLOCK_PREFIXLEN, AlreadyAssignedError, AddressNotAssignedError, NoHostAffinityWarning) from pycalico.handle import (AllocationHandle, AddressCountTooLow) from pycalico.util import get_hostname _log = logging.getLogger(__name__) _log.addHandler(logging.NullHandler()) RETRIES = 100 KEY_ERROR_RETRIES = 3 class BlockHandleReaderWriter(DatastoreClient): """ Can read and write allocation blocks and handles to the data store, as well as related bits of state. This class keeps etcd specific code from being in the main IPAMClient class. """ def _read_block(self, block_cidr): """ Read the block from the data store. :param block_cidr: The IPNetwork identifier for a block. :return: An AllocationBlock object """ key = _block_datastore_key(block_cidr) try: # Use quorum=True to ensure we don't get stale reads. Without this # we allow many subtle race conditions, such as creating a block, # then later reading it and finding it doesn't exist. result = self.etcd_client.read(key, quorum=True) except EtcdKeyNotFound: raise KeyError(str(block_cidr)) block = AllocationBlock.from_etcd_result(result) return block def _compare_and_swap_block(self, block): """ Write the block using an atomic Compare-and-swap. """ # If the block has a db_result, CAS against that. if block.db_result is not None: _log.debug("CAS Update block %s", block) try: self.etcd_client.update(block.update_result()) except EtcdCompareFailed: raise CASError(str(block.cidr)) else: _log.debug("CAS Write new block %s", block) key = _block_datastore_key(block.cidr) value = block.to_json() try: self.etcd_client.write(key, value, prevExist=False) except EtcdAlreadyExist: raise CASError(str(block.cidr)) def _get_affine_blocks(self, host, version, pool): """ Get the blocks for which this host has affinity. :param host: The host name to get affinity for. :param version: 4 for IPv4, 6 for IPv6. :param pool: Limit blocks to a specific pool, or pass None to find all blocks for the specified version. """ # Construct the path path = IPAM_HOST_AFFINITY_PATH % {"hostname": host, "version": version} block_ids = [] try: result = self.etcd_client.read(path, quorum=True).children for child in result: packed = child.key.split("/") if len(packed) == 9: # block_ids are encoded 192.168.1.0/24 -> 192.168.1.0-24 # in etcd. block_ids.append(IPNetwork(packed[8].replace("-", "/"))) except EtcdKeyNotFound: # Means the path is empty. pass # If pool specified, filter to only include ones in the pool. if pool is not None: assert isinstance(pool, IPPool) block_ids = [cidr for cidr in block_ids if cidr in pool] return block_ids def _new_affine_block(self, host, version, pool): """ Create and register a new affine block for the host. :param host: The host name to get a block for. :param version: 4 for IPv4, 6 for IPv6. :param pool: Limit blocks to a specific pool, or pass None to find all blocks for the specified version. :return: The block CIDR of the new block. """ # Get the pools and verify we got a valid one, or none. ip_pools = self.get_ip_pools(version, ipam=True) if pool is not None: if pool not in ip_pools: raise ValueError("Requested pool %s is not configured or has" "wrong attributes" % pool) # Confine search to only the one pool. ip_pools = [pool] for pool in ip_pools: for block_cidr in pool.cidr.subnet(BLOCK_PREFIXLEN[version]): block_id = str(block_cidr) _log.debug("Checking if block %s is free.", block_id) key = _block_datastore_key(block_cidr) try: _ = self.etcd_client.read(key, quorum=True) except EtcdKeyNotFound: _log.debug("Found block %s free.", block_id) try: self._claim_block_affinity(host, block_cidr) except HostAffinityClaimedError: # Failed to claim the block because some other host # has it. _log.debug("Failed to claim block %s", block_cidr) continue # Success! return block_cidr raise NoFreeBlocksError() def _claim_block_affinity(self, host, block_cidr): """ Claim a block we think is free. """ block_id = str(block_cidr) path = IPAM_HOST_AFFINITY_PATH % {"hostname": host, "version": block_cidr.version} key = path + block_id.replace("/", "-") self.etcd_client.write(key, "") # Create the block. block = AllocationBlock(block_cidr, host) try: self._compare_and_swap_block(block) except CASError: # Block exists. Read it back to find out its host affinity block = self._read_block(block_cidr) if block.host_affinity == host: # Block is now claimed by us. Some other process on this host # must have claimed it. _log.debug("Block %s already claimed by us. Success.", block_cidr) return # Some other host beat us to claiming this block. Clean up. self.etcd_client.delete(key) # Throw a key error to let the caller know the block wasn't free # after all. raise HostAffinityClaimedError("Block %s already claimed by %s", block_id, block.host_affinity) # successfully created the block. Done. return def _random_blocks(self, excluded_ids, version, pool): """ Get an list of block CIDRs, in random order. :param excluded_ids: List of IDs that should be excluded. :param version: The IP version 4, or 6. :param pool: IPPool to get blocks from, or None to use all pools :return: An iterator of block CIDRs. """ # Get the pools and verify we got a valid one, or none. ip_pools = self.get_ip_pools(version, ipam=True) if pool is not None: if pool not in ip_pools: raise ValueError("Requested pool %s is not configured or has" "wrong attributes" % pool) # Confine search to only the one pool. ip_pools = [pool] random_blocks = [] i = 0 for pool in ip_pools: for block_cidr in pool.cidr.subnet(BLOCK_PREFIXLEN[version]): if block_cidr not in excluded_ids: # add this block. We use an "inside-out" Fisher-Yates # shuffle to randomize the list as we create it. See # http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle j = random.randint(0, i) if j != i: random_blocks.append(random_blocks[j]) random_blocks[j] = block_cidr else: random_blocks.append(block_cidr) i += 1 return random_blocks def _increment_handle(self, handle_id, block_cidr, amount): """ Increment the allocation count on the given handle for the given block by the given amount. """ for _ in xrange(RETRIES): try: handle = self._read_handle(handle_id) except KeyError: # handle doesn't exist. Create it. handle = AllocationHandle(handle_id) _ = handle.increment_block(block_cidr, amount) try: self._compare_and_swap_handle(handle) except CASError: # CAS failed. Retry. continue else: # success! return raise RuntimeError("Max retries hit.") # pragma: no cover def _decrement_handle(self, handle_id, block_cidr, amount): """ Decrement the allocation count on the given handle for the given block by the given amount. """ for _ in xrange(RETRIES): try: handle = self._read_handle(handle_id) except KeyError: # This is bad. The handle doesn't exist, which means something # really wrong has happened, like DB corruption. _log.error("Can't decrement block %s on handle %s; it doesn't " "exist.", str(block_cidr), handle_id) raise try: handle.decrement_block(block_cidr, amount) except AddressCountTooLow: # This is also bad. The handle says it has fewer than the # requested amount of addresses allocated on the block. This # means the DB is corrupted. _log.error("Can't decrement block %s on handle %s; too few " "allocated.", str(block_cidr), handle_id) raise try: self._compare_and_swap_handle(handle) except CASError: continue else: # Success! return raise RuntimeError("Max retries hit.") # pragma: no cover def _read_handle(self, handle_id): """ Read the handle with the given handle ID from the data store. :param handle_id: The handle ID to read. :return: AllocationHandle object. """ key = _handle_datastore_key(handle_id) try: result = self.etcd_client.read(key, quorum=True) except EtcdKeyNotFound: raise KeyError(handle_id) handle = AllocationHandle.from_etcd_result(result) return handle def _compare_and_swap_handle(self, handle): """ Write the handle using an atomic Compare-and-swap. """ # If the handle has a db_result, CAS against that. if handle.db_result is not None: _log.debug("Handle %s exists.", handle.handle_id) if handle.is_empty(): # Handle is now empty. Delete it instead of an update. _log.debug("Handle %s is empty.", handle.handle_id) key = _handle_datastore_key(handle.handle_id) try: self.etcd_client.delete( key, prevIndex=handle.db_result.modifiedIndex) except EtcdAlreadyExist: raise CASError(handle.handle_id) else: _log.debug("Handle %s is not empty.", handle.handle_id) try: self.etcd_client.update(handle.update_result()) except EtcdCompareFailed: raise CASError(handle.handle_id) else: _log.debug("CAS Write new handle %s", handle.handle_id) assert not handle.is_empty(), "Don't write empty handle." key = _handle_datastore_key(handle.handle_id) value = handle.to_json() try: self.etcd_client.write(key, value, prevExist=False) except EtcdAlreadyExist: raise CASError(handle.handle_id) class CASError(DataStoreError): """ Compare-and-swap atomic update failed. """ pass class NoFreeBlocksError(DataStoreError): """ Tried to get a new block but there are none available. """ pass class HostAffinityClaimedError(DataStoreError): """ Tried to set the host affinity of a block which already has a host that claims affinity. """ pass def _block_datastore_key(block_cidr): """ Translate a block_id into a datastore key. :param block_cidr: IPNetwork representing the block :return: etcd key as string. """ path = IPAM_BLOCK_PATH % {'version': block_cidr.version} return path + str(block_cidr).replace("/", "-") def _handle_datastore_key(handle_id): """ Translate a handle_id into a datastore key. :param handle_id: String key :return: etcd key as string. """ return IPAM_HANDLE_PATH + handle_id class IPAMClient(BlockHandleReaderWriter): def auto_assign_ips(self, num_v4, num_v6, handle_id, attributes, pool=(None, None), hostname=None): """ Automatically pick and assign the given number of IPv4 and IPv6 addresses. :param num_v4: Number of IPv4 addresses to request :param num_v6: Number of IPv6 addresses to request :param handle_id: allocation handle ID for this request. You can query this key using get_assignments_by_handle() or release all addresses with this key using release_by_handle(). :param attributes: Contents of this dict will be stored with the assignment and can be queried using get_assignment_attributes(). Must be JSON serializable. :param pool: (optional) tuple of (v4 pool, v6 pool); if supplied, the pool(s) to assign from, If None, automatically choose a pool. :param hostname: (optional) the hostname to use for affinity in assigning IP addresses. Defaults to the hostname returned by get_hostname(). :return: A tuple of (v4_address_list, v6_address_list). When IPs in configured pools are at or near exhaustion, this method may return fewer than requested addresses. """ assert isinstance(handle_id, str) or handle_id is None if not hostname: hostname = get_hostname() _log.info("Auto-assign %d IPv4, %d IPv6 addrs", num_v4, num_v6) v4_address_list = self._auto_assign(4, num_v4, handle_id, attributes, pool[0], hostname) _log.info("Auto-assigned IPv4s %s", [str(addr) for addr in v4_address_list]) v6_address_list = self._auto_assign(6, num_v6, handle_id, attributes, pool[1], hostname) _log.info("Auto-assigned IPv6s %s", [str(addr) for addr in v6_address_list]) return v4_address_list, v6_address_list def _auto_assign(self, ip_version, num, handle_id, attributes, pool, hostname): """ Auto assign addresses from a specific IP version. Hosts automatically register themselves as the owner of a block the first time they request an auto-assigned IP. For auto-assignment, a host will allocate from a block it owns, or if all their currently owned blocks get full, it will register itself as the owner of a new block. If all blocks are owned, and all the host's own blocks are full, it will pick blocks at random until it can fulfil the request. If you're really, really out of addresses, it will fail the request. :param ip_version: 4 or 6, the IP version number. :param num: Number of addresses to assign. :param handle_id: allocation handle ID for this request. :param attributes: Contents of this dict will be stored with the assignment and can be queried using get_assignment_attributes(). Must be JSON serializable. :param pool: (optional) if supplied, the pool to assign from, If None, automatically choose a pool. :param hostname: The hostname to use for affinity in assigning IP addresses. :return: """ assert isinstance(handle_id, str) or handle_id is None block_list = self._get_affine_blocks(hostname, ip_version, pool) block_ids = list(block_list) key_errors = 0 allocated_ips = [] num_remaining = num while num_remaining > 0: try: block_id = block_ids.pop(0) except IndexError: _log.info("Ran out of affine blocks for %s in pool %s", hostname, pool) break try: ips = self._auto_assign_block(block_id, num_remaining, handle_id, attributes) except KeyError: # In certain rare race conditions, _get_affine_blocks above # can return block_ids that don't exist (due to multiple IPAM # clients on this host running simultaneously). If that # happens, requeue the block_id for a retry, since we expect # the other IPAM client to shortly create the block. To stop # endless looping we limit the number of KeyErrors that will # generate a retry. _log.warning("Tried to auto-assign to block %s. Doesn't " "exist.", block_id) key_errors += 1 if key_errors <= KEY_ERROR_RETRIES: _log.debug("Queueing block %s for retry.", block_id) block_ids.append(block_id) else: _log.warning("Stopping retry of block %s.", block_id) continue except NoHostAffinityWarning: # In certain rare race conditions, _get_affine_blocks above # can return block_ids that don't actually have affinity to # this host (due to multiple IPAM clients on this host running # simultaneously). If that happens, just move to the next one. _log.warning("No host affinity on block %s; skipping.", block_id) continue allocated_ips.extend(ips) num_remaining = num - len(allocated_ips) # If there are still addresses to allocate, then we've run out of # blocks with affinity. Try to fullfil address request by allocating # new blocks. retries = RETRIES while num_remaining > 0 and retries > 0: retries -= 1 try: new_block = self._new_affine_block(hostname, ip_version, pool) # If successful, this creates the block and registers it to us. except NoFreeBlocksError: _log.info("Could not get new host affinity block for %s in " "pool %s", hostname, pool) break ips = self._auto_assign_block(new_block, num_remaining, handle_id, attributes) allocated_ips.extend(ips) num_remaining = num - len(allocated_ips) if retries == 0: # pragma: no cover raise RuntimeError("Hit Max Retries.") # If there are still addresses to allocate, we've now tried all blocks # with some affinity to us, and tried (and failed) to allocate new # ones. Our last option is a random hunt through any blocks we haven't # yet tried. if num_remaining > 0: random_blocks = iter(self._random_blocks(block_list, ip_version, pool)) while num_remaining > 0: try: block_id = random_blocks.next() except StopIteration: _log.warning("All addresses exhausted in pool %s", pool) break ips = self._auto_assign_block(block_id, num_remaining, handle_id, attributes, affinity_check=False) allocated_ips.extend(ips) num_remaining = num - len(allocated_ips) return allocated_ips def _auto_assign_block(self, block_cidr, num, handle_id, attributes, affinity_check=True): """ Automatically pick IPs from a block and commit them to the data store. :param block_cidr: The identifier for the block to read. :param num: The number of IPs to assign. :param handle_id: allocation handle ID for this request. :param attributes: Contents of this dict will be stored with the assignment and can be queried using get_assignment_attributes(). Must be JSON serializable. :param affinity_check: True to enable checking the host has the affinity to the block, False to disable this check, for example, while randomly searching after failure to get affine block. :return: List of assigned IPs. """ assert isinstance(handle_id, str) or handle_id is None _log.debug("Auto-assigning from block %s", block_cidr) for i in xrange(RETRIES): _log.debug("Auto-assign from %s, retry %d", block_cidr, i) block = self._read_block(block_cidr) unconfirmed_ips = block.auto_assign(num=num, handle_id=handle_id, attributes=attributes, affinity_check=affinity_check) if len(unconfirmed_ips) == 0: _log.debug("Block %s is full.", block_cidr) return [] # If using a handle, increment the handle by the number of # confirmed IPs. if handle_id is not None: self._increment_handle(handle_id, block_cidr, len(unconfirmed_ips)) try: self._compare_and_swap_block(block) except CASError: _log.debug("CAS failed on block %s", block_cidr) if handle_id is not None: self._decrement_handle(handle_id, block_cidr, len(unconfirmed_ips)) else: return unconfirmed_ips raise RuntimeError("Hit Max Retries.") def assign_ip(self, address, handle_id, attributes, hostname=None): """ Assign the given address. Throws AlreadyAssignedError if the address is taken. :param address: IPAddress to assign. :param handle_id: allocation handle ID for this request. You can query this key using get_assignments_by_handle() or release all addresses with this handle_id using release_by_handle(). :param attributes: Contents of this dict will be stored with the assignment and can be queried using get_assignment_attributes(). Must be JSON serializable. :param hostname: (optional) the hostname to use for affinity if the block containing the IP address has no host affinity. Defaults to the hostname returned by get_hostname(). :return: None. """ assert isinstance(handle_id, str) or handle_id is None assert isinstance(address, IPAddress) if not hostname: hostname = get_hostname() block_cidr = get_block_cidr_for_address(address) for _ in xrange(RETRIES): try: block = self._read_block(block_cidr) except KeyError: _log.debug("Block %s doesn't exist.", block_cidr) pools = self.get_ip_pools(address.version, ipam=True) if any([address in pool for pool in pools]): _log.debug("Create and claim block %s.", block_cidr) try: self._claim_block_affinity(hostname, block_cidr) except HostAffinityClaimedError: _log.debug("Someone else claimed block %s before us.", block_cidr) continue # Block exists now, retry writing to it. _log.debug("Claimed block %s", block_cidr) continue else: raise ValueError("%s is not in any configured pool" %<|fim▁hole|> block.assign(address, handle_id, attributes) # If using a handle, increment by one IP if handle_id is not None: self._increment_handle(handle_id, block_cidr, 1) # Try to commit. try: self._compare_and_swap_block(block) return # Success! except CASError: _log.debug("CAS failed on block %s", block_cidr) if handle_id is not None: self._decrement_handle(handle_id, block_cidr, 1) raise RuntimeError("Hit max retries.") def release_ips(self, addresses): """ Release the given addresses. :param addresses: Set of IPAddresses to release (ok to mix IPv4 and IPv6). :return: Set of addresses that were already unallocated. """ assert isinstance(addresses, (set, frozenset)) _log.info("Releasing addresses %s", [str(addr) for addr in addresses]) unallocated = set() # sort the addresses into blocks addrs_by_block = {} for address in addresses: block_cidr = get_block_cidr_for_address(address) addrs = addrs_by_block.setdefault(block_cidr, set()) addrs.add(address) # loop through blocks, CAS releasing. for block_cidr, addresses in addrs_by_block.iteritems(): unalloc_block = self._release_block(block_cidr, addresses) unallocated = unallocated.union(unalloc_block) return unallocated def _release_block(self, block_cidr, addresses): """ Release the given addresses from the block, using compare-and-swap to write the block. :param block_cidr: IPNetwork identifying the block :param addresses: List of addresses to release. :return: List of addresses that were already unallocated. """ _log.debug("Releasing %d adddresses from block %s", len(addresses), block_cidr) for _ in xrange(RETRIES): try: block = self._read_block(block_cidr) except KeyError: _log.debug("Block %s doesn't exist.", block_cidr) # OK to return, all addresses must be released already. return addresses (unallocated, handles) = block.release(addresses) assert len(unallocated) <= len(addresses) if len(unallocated) == len(addresses): # All the addresses are already unallocated. return addresses # Try to commit try: self._compare_and_swap_block(block) except CASError: continue else: # Success! Decrement handles. for handle_id, amount in handles.iteritems(): if handle_id is not None: # Skip the None handle, it's a special value meaning # the addresses were not allocated with a handle. self._decrement_handle(handle_id, block_cidr, amount) return unallocated raise RuntimeError("Hit Max retries.") # pragma: no cover def get_ip_assignments_by_handle(self, handle_id): """ Return a list of IPAddresses assigned to the key. :param handle_id: Key to query e.g. used on assign_ip() or auto_assign_ips(). :return: List of IPAddresses """ assert isinstance(handle_id, str) handle = self._read_handle(handle_id) # Can throw KeyError, let it. ip_assignments = [] for block_str in handle.block: block_cidr = IPNetwork(block_str) try: block = self._read_block(block_cidr) except KeyError: _log.warning("Couldn't read block %s referenced in handle %s.", block_str, handle_id) continue ips = block.get_ip_assignments_by_handle(handle_id) ip_assignments.extend(ips) return ip_assignments def release_ip_by_handle(self, handle_id): """ Release all addresses assigned to the key. :param handle_id: Key to query, e.g. used on assign_ip() or auto_assign_ips(). :return: None. """ assert isinstance(handle_id, str) handle = self._read_handle(handle_id) # Can throw KeyError, let it. # Loop through blocks, releasing. for block_str in handle.block: block_cidr = IPNetwork(block_str) self._release_ip_by_handle_block(handle_id, block_cidr) def _release_ip_by_handle_block(self, handle_id, block_cidr): """ Release all address in a block with the given handle ID. :param handle_id: The handle ID to find addresses with. :param block_cidr: The block to release addresses on. :return: None """ for _ in xrange(RETRIES): try: block = self._read_block(block_cidr) except KeyError: # Block doesn't exist, so all addresses are already # unallocated. This can happen if the handle is overestimating # the number of assigned addresses, which is a transient, but # expected condition. return num_release = block.release_by_handle(handle_id) if num_release == 0: # Block didn't have any addresses with this handle, so all # so all addresses are already unallocated. This can happen if # the handle is overestimating the number of assigned # addresses, which is a transient, but expected condition. return try: self._compare_and_swap_block(block) except CASError: # Failed to update, retry. continue # Successfully updated block, update the handle if necessary. if handle_id is not None: # Skip the None handle, it's a special value meaning # the addresses were not allocated with a handle. self._decrement_handle(handle_id, block_cidr, num_release) return raise RuntimeError("Hit Max retries.") # pragma: no cover def get_assignment_attributes(self, address): """ Return the attributes of a given address. :param address: IPAddress to query. :return: The attributes for the address as passed to auto_assign() or assign(). """ assert isinstance(address, IPAddress) block_cidr = get_block_cidr_for_address(address) try: block = self._read_block(block_cidr) except KeyError: _log.warning("Couldn't read block %s for requested address %s", block_cidr, address) raise AddressNotAssignedError("%s is not assigned." % address) else: _, attributes = block.get_attributes_for_ip(address) return attributes def assign_address(self, pool, address): """ Deprecated in favor of assign_ip(). Attempt to assign an IPAddress in a pool. Fails if the address is already assigned. The directory for storing assignments in this pool must already exist. :param IPPool or IPNetwork pool: The pool that the assignment is from. If pool is None, get the pool from datastore :param IPAddress address: The address to assign. :return: True if the allocation succeeds, false otherwise. An exception is thrown for any error conditions. :rtype: bool """ pool = pool or self.get_pool(address) if pool is None: raise PoolNotFound("IP address %s does not belong to any " "configured pools" % address) if isinstance(pool, IPPool): pool = pool.cidr assert isinstance(pool, IPNetwork) assert isinstance(address, IPAddress) try: self.assign_ip(address, None, {}) return True except AlreadyAssignedError: return False # Other exceptions indicate error conditions. def unassign_address(self, pool, address): """ Deprecated in favor of release_ips() Unassign an IP from a pool. :param IPPool or IPNetwork pool: The pool that the assignment is from. If the pool is None, get the pool from datastore :param IPAddress address: The address to unassign. :return: True if the address was unassigned, false otherwise. An exception is thrown for any error conditions. :rtype: bool """ pool = pool or self.get_pool(address) if pool is None: raise PoolNotFound("IP address %s does not belong to any " "configured pools" % address) if isinstance(pool, IPPool): pool = pool.cidr assert isinstance(pool, IPNetwork) assert isinstance(address, IPAddress) err = self.release_ips({address}) if err: return False else: return True<|fim▁end|>
address) # Try to assign. Throws exception if already assigned -- let it.
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate rand; use rand::{thread_rng, Rng}; use std::io::stdin; const LOWEST: isize = 1; const HIGHEST: isize = 100; fn main() { let mut rng = thread_rng(); loop { let number: isize = rng.gen_range(LOWEST, HIGHEST + 1); let mut num_guesses = 0; println!( "I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST ); loop { num_guesses += 1;<|fim▁hole|> match input { None => println!("numbers only, please"), Some(n) if n == number => { println!("you got it in {} tries!", num_guesses); break; } Some(n) if n < number => println!("too low!"), Some(n) if n > number => println!("too high!"), Some(_) => println!("something went wrong"), } } } }<|fim▁end|>
let mut line = String::new(); let res = stdin().read_line(&mut line); let input: Option<isize> = res.ok().and_then(|_| line.trim().parse().ok());
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import logging from typing import Union, cast import great_expectations.exceptions as ge_exceptions from great_expectations.data_context.store import ( CheckpointStore, ConfigurationStore, StoreBackend, ) from great_expectations.data_context.types.base import BaseYamlConfig, CheckpointConfig from great_expectations.data_context.types.resource_identifiers import ( ConfigurationIdentifier, ) from great_expectations.data_context.util import build_store_from_config logger = logging.getLogger(__name__) def build_configuration_store( class_name: str, store_name: str, store_backend: Union[StoreBackend, dict], *, module_name: str = "great_expectations.data_context.store", overwrite_existing: bool = False, **kwargs, ) -> ConfigurationStore: logger.debug( f"Starting data_context/store/util.py#build_configuration_store for store_name {store_name}" ) if store_backend is not None and issubclass(type(store_backend), StoreBackend): store_backend = store_backend.config elif not isinstance(store_backend, dict): raise ge_exceptions.DataContextError( "Invalid configuration: A store_backend needs to be a dictionary or inherit from the StoreBackend class." ) store_backend.update(**kwargs) store_config: dict = { "store_name": store_name, "module_name": module_name, "class_name": class_name, "overwrite_existing": overwrite_existing, "store_backend": store_backend, } configuration_store: ConfigurationStore = build_store_from_config( store_config=store_config, module_name=module_name, runtime_environment=None, ) return configuration_store def build_checkpoint_store_using_store_backend( store_name: str, store_backend: Union[StoreBackend, dict], overwrite_existing: bool = False, ) -> CheckpointStore: return cast( CheckpointStore, build_configuration_store( class_name="CheckpointStore", module_name="great_expectations.data_context.store", store_name=store_name, store_backend=store_backend, overwrite_existing=overwrite_existing, ), ) <|fim▁hole|> class_name: str, module_name: str, store_name: str, store_backend: Union[StoreBackend, dict], configuration_key: str, configuration: BaseYamlConfig, ): config_store: ConfigurationStore = build_configuration_store( class_name=class_name, module_name=module_name, store_name=store_name, store_backend=store_backend, overwrite_existing=True, ) key: ConfigurationIdentifier = ConfigurationIdentifier( configuration_key=configuration_key, ) config_store.set(key=key, value=configuration) def load_config_from_store_backend( class_name: str, module_name: str, store_name: str, store_backend: Union[StoreBackend, dict], configuration_key: str, ) -> BaseYamlConfig: config_store: ConfigurationStore = build_configuration_store( class_name=class_name, module_name=module_name, store_name=store_name, store_backend=store_backend, overwrite_existing=False, ) key: ConfigurationIdentifier = ConfigurationIdentifier( configuration_key=configuration_key, ) return config_store.get(key=key) def delete_config_from_store_backend( class_name: str, module_name: str, store_name: str, store_backend: Union[StoreBackend, dict], configuration_key: str, ): config_store: ConfigurationStore = build_configuration_store( class_name=class_name, module_name=module_name, store_name=store_name, store_backend=store_backend, overwrite_existing=True, ) key: ConfigurationIdentifier = ConfigurationIdentifier( configuration_key=configuration_key, ) config_store.remove_key(key=key) def save_checkpoint_config_to_store_backend( store_name: str, store_backend: Union[StoreBackend, dict], checkpoint_name: str, checkpoint_configuration: CheckpointConfig, ): config_store: CheckpointStore = build_checkpoint_store_using_store_backend( store_name=store_name, store_backend=store_backend, overwrite_existing=True, ) key: ConfigurationIdentifier = ConfigurationIdentifier( configuration_key=checkpoint_name, ) config_store.set(key=key, value=checkpoint_configuration) def load_checkpoint_config_from_store_backend( store_name: str, store_backend: Union[StoreBackend, dict], checkpoint_name: str, ) -> CheckpointConfig: config_store: CheckpointStore = build_checkpoint_store_using_store_backend( store_name=store_name, store_backend=store_backend, ) key: ConfigurationIdentifier = ConfigurationIdentifier( configuration_key=checkpoint_name, ) try: return config_store.get(key=key) except ge_exceptions.InvalidBaseYamlConfigError as exc: logger.error(exc.messages) raise ge_exceptions.InvalidCheckpointConfigError( "Error while processing DataContextConfig.", exc ) def delete_checkpoint_config_from_store_backend( store_name: str, store_backend: Union[StoreBackend, dict], checkpoint_name: str, ): config_store: CheckpointStore = build_checkpoint_store_using_store_backend( store_name=store_name, store_backend=store_backend, ) key: ConfigurationIdentifier = ConfigurationIdentifier( configuration_key=checkpoint_name, ) config_store.remove_key(key=key)<|fim▁end|>
def save_config_to_store_backend(
<|file_name|>upload.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) 2009, 2010 Google Inc. All rights reserved. # Copyright (c) 2009 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT<|fim▁hole|># OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import re import sys from optparse import make_option from webkitpy.tool import steps from webkitpy.common.checkout.changelog import parse_bug_id_from_changelog from webkitpy.common.config.committers import CommitterList from webkitpy.common.system.deprecated_logging import error, log from webkitpy.common.system.user import User from webkitpy.thirdparty.mock import Mock from webkitpy.tool.commands.abstractsequencedcommand import AbstractSequencedCommand from webkitpy.tool.comments import bug_comment_from_svn_revision from webkitpy.tool.grammar import pluralize, join_with_separators from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand class CommitMessageForCurrentDiff(AbstractDeclarativeCommand): name = "commit-message" help_text = "Print a commit message suitable for the uncommitted changes" def __init__(self): options = [ steps.Options.git_commit, ] AbstractDeclarativeCommand.__init__(self, options=options) def execute(self, options, args, tool): # This command is a useful test to make sure commit_message_for_this_commit # always returns the right value regardless of the current working directory. print "%s" % tool.checkout().commit_message_for_this_commit(options.git_commit).message() class CleanPendingCommit(AbstractDeclarativeCommand): name = "clean-pending-commit" help_text = "Clear r+ on obsolete patches so they do not appear in the pending-commit list." # NOTE: This was designed to be generic, but right now we're only processing patches from the pending-commit list, so only r+ matters. def _flags_to_clear_on_patch(self, patch): if not patch.is_obsolete(): return None what_was_cleared = [] if patch.review() == "+": if patch.reviewer(): what_was_cleared.append("%s's review+" % patch.reviewer().full_name) else: what_was_cleared.append("review+") return join_with_separators(what_was_cleared) def execute(self, options, args, tool): committers = CommitterList() for bug_id in tool.bugs.queries.fetch_bug_ids_from_pending_commit_list(): bug = self._tool.bugs.fetch_bug(bug_id) patches = bug.patches(include_obsolete=True) for patch in patches: flags_to_clear = self._flags_to_clear_on_patch(patch) if not flags_to_clear: continue message = "Cleared %s from obsolete attachment %s so that this bug does not appear in http://webkit.org/pending-commit." % (flags_to_clear, patch.id()) self._tool.bugs.obsolete_attachment(patch.id(), message) # FIXME: This should be share more logic with AssignToCommitter and CleanPendingCommit class CleanReviewQueue(AbstractDeclarativeCommand): name = "clean-review-queue" help_text = "Clear r? on obsolete patches so they do not appear in the pending-review list." def execute(self, options, args, tool): queue_url = "http://webkit.org/pending-review" # We do this inefficient dance to be more like webkit.org/pending-review # bugs.queries.fetch_bug_ids_from_review_queue() doesn't return # closed bugs, but folks using /pending-review will see them. :( for patch_id in tool.bugs.queries.fetch_attachment_ids_from_review_queue(): patch = self._tool.bugs.fetch_attachment(patch_id) if not patch.review() == "?": continue attachment_obsolete_modifier = "" if patch.is_obsolete(): attachment_obsolete_modifier = "obsolete " elif patch.bug().is_closed(): bug_closed_explanation = " If you would like this patch reviewed, please attach it to a new bug (or re-open this bug before marking it for review again)." else: # Neither the patch was obsolete or the bug was closed, next patch... continue message = "Cleared review? from %sattachment %s so that this bug does not appear in %s.%s" % (attachment_obsolete_modifier, patch.id(), queue_url, bug_closed_explanation) self._tool.bugs.obsolete_attachment(patch.id(), message) class AssignToCommitter(AbstractDeclarativeCommand): name = "assign-to-committer" help_text = "Assign bug to whoever attached the most recent r+'d patch" def _patches_have_commiters(self, reviewed_patches): for patch in reviewed_patches: if not patch.committer(): return False return True def _assign_bug_to_last_patch_attacher(self, bug_id): committers = CommitterList() bug = self._tool.bugs.fetch_bug(bug_id) if not bug.is_unassigned(): assigned_to_email = bug.assigned_to_email() log("Bug %s is already assigned to %s (%s)." % (bug_id, assigned_to_email, committers.committer_by_email(assigned_to_email))) return reviewed_patches = bug.reviewed_patches() if not reviewed_patches: log("Bug %s has no non-obsolete patches, ignoring." % bug_id) return # We only need to do anything with this bug if one of the r+'d patches does not have a valid committer (cq+ set). if self._patches_have_commiters(reviewed_patches): log("All reviewed patches on bug %s already have commit-queue+, ignoring." % bug_id) return latest_patch = reviewed_patches[-1] attacher_email = latest_patch.attacher_email() committer = committers.committer_by_email(attacher_email) if not committer: log("Attacher %s is not a committer. Bug %s likely needs commit-queue+." % (attacher_email, bug_id)) return reassign_message = "Attachment %s was posted by a committer and has review+, assigning to %s for commit." % (latest_patch.id(), committer.full_name) self._tool.bugs.reassign_bug(bug_id, committer.bugzilla_email(), reassign_message) def execute(self, options, args, tool): for bug_id in tool.bugs.queries.fetch_bug_ids_from_pending_commit_list(): self._assign_bug_to_last_patch_attacher(bug_id) class ObsoleteAttachments(AbstractSequencedCommand): name = "obsolete-attachments" help_text = "Mark all attachments on a bug as obsolete" argument_names = "BUGID" steps = [ steps.ObsoletePatches, ] def _prepare_state(self, options, args, tool): return { "bug_id" : args[0] } class AttachToBug(AbstractSequencedCommand): name = "attach-to-bug" help_text = "Attach the the file to the bug" argument_names = "BUGID FILEPATH" steps = [ steps.AttachToBug, ] def _prepare_state(self, options, args, tool): state = {} state["bug_id"] = args[0] state["filepath"] = args[1] return state class AbstractPatchUploadingCommand(AbstractSequencedCommand): def _bug_id(self, options, args, tool, state): # Perfer a bug id passed as an argument over a bug url in the diff (i.e. ChangeLogs). bug_id = args and args[0] if not bug_id: changed_files = self._tool.scm().changed_files(options.git_commit) state["changed_files"] = changed_files bug_id = tool.checkout().bug_id_for_this_commit(options.git_commit, changed_files) return bug_id def _prepare_state(self, options, args, tool): state = {} state["bug_id"] = self._bug_id(options, args, tool, state) if not state["bug_id"]: error("No bug id passed and no bug url found in ChangeLogs.") return state class Post(AbstractPatchUploadingCommand): name = "post" help_text = "Attach the current working directory diff to a bug as a patch file" argument_names = "[BUGID]" steps = [ steps.ValidateChangeLogs, steps.CheckStyle, steps.ConfirmDiff, steps.ObsoletePatches, steps.SuggestReviewers, steps.EnsureBugIsOpenAndAssigned, steps.PostDiff, ] class LandSafely(AbstractPatchUploadingCommand): name = "land-safely" help_text = "Land the current diff via the commit-queue" argument_names = "[BUGID]" long_help = """land-safely updates the ChangeLog with the reviewer listed in bugs.webkit.org for BUGID (or the bug ID detected from the ChangeLog). The command then uploads the current diff to the bug and marks it for commit by the commit-queue.""" show_in_main_help = True steps = [ steps.UpdateChangeLogsWithReviewer, steps.ValidateChangeLogs, steps.ObsoletePatches, steps.EnsureBugIsOpenAndAssigned, steps.PostDiffForCommit, ] class Prepare(AbstractSequencedCommand): name = "prepare" help_text = "Creates a bug (or prompts for an existing bug) and prepares the ChangeLogs" argument_names = "[BUGID]" steps = [ steps.PromptForBugOrTitle, steps.CreateBug, steps.PrepareChangeLog, ] def _prepare_state(self, options, args, tool): bug_id = args and args[0] return { "bug_id" : bug_id } class Upload(AbstractPatchUploadingCommand): name = "upload" help_text = "Automates the process of uploading a patch for review" argument_names = "[BUGID]" show_in_main_help = True steps = [ steps.ValidateChangeLogs, steps.CheckStyle, steps.PromptForBugOrTitle, steps.CreateBug, steps.PrepareChangeLog, steps.EditChangeLog, steps.ConfirmDiff, steps.ObsoletePatches, steps.SuggestReviewers, steps.EnsureBugIsOpenAndAssigned, steps.PostDiff, ] long_help = """upload uploads the current diff to bugs.webkit.org. If no bug id is provided, upload will create a bug. If the current diff does not have a ChangeLog, upload will prepare a ChangeLog. Once a patch is read, upload will open the ChangeLogs for editing using the command in the EDITOR environment variable and will display the diff using the command in the PAGER environment variable.""" def _prepare_state(self, options, args, tool): state = {} state["bug_id"] = self._bug_id(options, args, tool, state) return state class EditChangeLogs(AbstractSequencedCommand): name = "edit-changelogs" help_text = "Opens modified ChangeLogs in $EDITOR" show_in_main_help = True steps = [ steps.EditChangeLog, ] class PostCommits(AbstractDeclarativeCommand): name = "post-commits" help_text = "Attach a range of local commits to bugs as patch files" argument_names = "COMMITISH" def __init__(self): options = [ make_option("-b", "--bug-id", action="store", type="string", dest="bug_id", help="Specify bug id if no URL is provided in the commit log."), make_option("--add-log-as-comment", action="store_true", dest="add_log_as_comment", default=False, help="Add commit log message as a comment when uploading the patch."), make_option("-m", "--description", action="store", type="string", dest="description", help="Description string for the attachment (default: description from commit message)"), steps.Options.obsolete_patches, steps.Options.review, steps.Options.request_commit, ] AbstractDeclarativeCommand.__init__(self, options=options, requires_local_commits=True) def _comment_text_for_commit(self, options, commit_message, tool, commit_id): comment_text = None if (options.add_log_as_comment): comment_text = commit_message.body(lstrip=True) comment_text += "---\n" comment_text += tool.scm().files_changed_summary_for_commit(commit_id) return comment_text def execute(self, options, args, tool): commit_ids = tool.scm().commit_ids_from_commitish_arguments(args) if len(commit_ids) > 10: # We could lower this limit, 10 is too many for one bug as-is. error("webkit-patch does not support attaching %s at once. Are you sure you passed the right commit range?" % (pluralize("patch", len(commit_ids)))) have_obsoleted_patches = set() for commit_id in commit_ids: commit_message = tool.scm().commit_message_for_local_commit(commit_id) # Prefer --bug-id=, then a bug url in the commit message, then a bug url in the entire commit diff (i.e. ChangeLogs). bug_id = options.bug_id or parse_bug_id_from_changelog(commit_message.message()) or parse_bug_id_from_changelog(tool.scm().create_patch(git_commit=commit_id)) if not bug_id: log("Skipping %s: No bug id found in commit or specified with --bug-id." % commit_id) continue if options.obsolete_patches and bug_id not in have_obsoleted_patches: state = { "bug_id": bug_id } steps.ObsoletePatches(tool, options).run(state) have_obsoleted_patches.add(bug_id) diff = tool.scm().create_patch(git_commit=commit_id) description = options.description or commit_message.description(lstrip=True, strip_url=True) comment_text = self._comment_text_for_commit(options, commit_message, tool, commit_id) tool.bugs.add_patch_to_bug(bug_id, diff, description, comment_text, mark_for_review=options.review, mark_for_commit_queue=options.request_commit) # FIXME: This command needs to be brought into the modern age with steps and CommitInfo. class MarkBugFixed(AbstractDeclarativeCommand): name = "mark-bug-fixed" help_text = "Mark the specified bug as fixed" argument_names = "[SVN_REVISION]" def __init__(self): options = [ make_option("--bug-id", action="store", type="string", dest="bug_id", help="Specify bug id if no URL is provided in the commit log."), make_option("--comment", action="store", type="string", dest="comment", help="Text to include in bug comment."), make_option("--open", action="store_true", default=False, dest="open_bug", help="Open bug in default web browser (Mac only)."), make_option("--update-only", action="store_true", default=False, dest="update_only", help="Add comment to the bug, but do not close it."), ] AbstractDeclarativeCommand.__init__(self, options=options) # FIXME: We should be using checkout().changelog_entries_for_revision(...) instead here. def _fetch_commit_log(self, tool, svn_revision): if not svn_revision: return tool.scm().last_svn_commit_log() return tool.scm().svn_commit_log(svn_revision) def _determine_bug_id_and_svn_revision(self, tool, bug_id, svn_revision): commit_log = self._fetch_commit_log(tool, svn_revision) if not bug_id: bug_id = parse_bug_id_from_changelog(commit_log) if not svn_revision: match = re.search("^r(?P<svn_revision>\d+) \|", commit_log, re.MULTILINE) if match: svn_revision = match.group('svn_revision') if not bug_id or not svn_revision: not_found = [] if not bug_id: not_found.append("bug id") if not svn_revision: not_found.append("svn revision") error("Could not find %s on command-line or in %s." % (" or ".join(not_found), "r%s" % svn_revision if svn_revision else "last commit")) return (bug_id, svn_revision) def execute(self, options, args, tool): bug_id = options.bug_id svn_revision = args and args[0] if svn_revision: if re.match("^r[0-9]+$", svn_revision, re.IGNORECASE): svn_revision = svn_revision[1:] if not re.match("^[0-9]+$", svn_revision): error("Invalid svn revision: '%s'" % svn_revision) needs_prompt = False if not bug_id or not svn_revision: needs_prompt = True (bug_id, svn_revision) = self._determine_bug_id_and_svn_revision(tool, bug_id, svn_revision) log("Bug: <%s> %s" % (tool.bugs.bug_url_for_bug_id(bug_id), tool.bugs.fetch_bug_dictionary(bug_id)["title"])) log("Revision: %s" % svn_revision) if options.open_bug: tool.user.open_url(tool.bugs.bug_url_for_bug_id(bug_id)) if needs_prompt: if not tool.user.confirm("Is this correct?"): self._exit(1) bug_comment = bug_comment_from_svn_revision(svn_revision) if options.comment: bug_comment = "%s\n\n%s" % (options.comment, bug_comment) if options.update_only: log("Adding comment to Bug %s." % bug_id) tool.bugs.post_comment_to_bug(bug_id, bug_comment) else: log("Adding comment to Bug %s and marking as Resolved/Fixed." % bug_id) tool.bugs.close_bug_as_fixed(bug_id, bug_comment) # FIXME: Requires unit test. Blocking issue: too complex for now. class CreateBug(AbstractDeclarativeCommand): name = "create-bug" help_text = "Create a bug from local changes or local commits" argument_names = "[COMMITISH]" def __init__(self): options = [ steps.Options.cc, steps.Options.component, make_option("--no-prompt", action="store_false", dest="prompt", default=True, help="Do not prompt for bug title and comment; use commit log instead."), make_option("--no-review", action="store_false", dest="review", default=True, help="Do not mark the patch for review."), make_option("--request-commit", action="store_true", dest="request_commit", default=False, help="Mark the patch as needing auto-commit after review."), ] AbstractDeclarativeCommand.__init__(self, options=options) def create_bug_from_commit(self, options, args, tool): commit_ids = tool.scm().commit_ids_from_commitish_arguments(args) if len(commit_ids) > 3: error("Are you sure you want to create one bug with %s patches?" % len(commit_ids)) commit_id = commit_ids[0] bug_title = "" comment_text = "" if options.prompt: (bug_title, comment_text) = self.prompt_for_bug_title_and_comment() else: commit_message = tool.scm().commit_message_for_local_commit(commit_id) bug_title = commit_message.description(lstrip=True, strip_url=True) comment_text = commit_message.body(lstrip=True) comment_text += "---\n" comment_text += tool.scm().files_changed_summary_for_commit(commit_id) diff = tool.scm().create_patch(git_commit=commit_id) bug_id = tool.bugs.create_bug(bug_title, comment_text, options.component, diff, "Patch", cc=options.cc, mark_for_review=options.review, mark_for_commit_queue=options.request_commit) if bug_id and len(commit_ids) > 1: options.bug_id = bug_id options.obsolete_patches = False # FIXME: We should pass through --no-comment switch as well. PostCommits.execute(self, options, commit_ids[1:], tool) def create_bug_from_patch(self, options, args, tool): bug_title = "" comment_text = "" if options.prompt: (bug_title, comment_text) = self.prompt_for_bug_title_and_comment() else: commit_message = tool.checkout().commit_message_for_this_commit(options.git_commit) bug_title = commit_message.description(lstrip=True, strip_url=True) comment_text = commit_message.body(lstrip=True) diff = tool.scm().create_patch(options.git_commit) bug_id = tool.bugs.create_bug(bug_title, comment_text, options.component, diff, "Patch", cc=options.cc, mark_for_review=options.review, mark_for_commit_queue=options.request_commit) def prompt_for_bug_title_and_comment(self): bug_title = User.prompt("Bug title: ") # FIXME: User should provide a function for doing this multi-line prompt. print "Bug comment (hit ^D on blank line to end):" lines = sys.stdin.readlines() try: sys.stdin.seek(0, os.SEEK_END) except IOError: # Cygwin raises an Illegal Seek (errno 29) exception when the above # seek() call is made. Ignoring it seems to cause no harm. # FIXME: Figure out a way to get avoid the exception in the first # place. pass comment_text = "".join(lines) return (bug_title, comment_text) def execute(self, options, args, tool): if len(args): if (not tool.scm().supports_local_commits()): error("Extra arguments not supported; patch is taken from working directory.") self.create_bug_from_commit(options, args, tool) else: self.create_bug_from_patch(options, args, tool)<|fim▁end|>
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 Prabhu Gurumurthy <[email protected]> # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF<|fim▁hole|># OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.<|fim▁end|>
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>""" WSGI config for Texas LAN Web project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os from django.core.wsgi import get_wsgi_application # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") <|fim▁hole|># This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)<|fim▁end|>
<|file_name|>nullable.js<|end_file_name|><|fim▁begin|>const _ = require('lodash'); const en = { modifiers: require('../../res/en').modifiers }; const Types = require('../../lib/types'); const optional = { optional: true }; const repeatable = { repeatable: true }; const nullableNumber = { type: Types.NameExpression, name: 'number', nullable: true }; const nullableNumberOptional = _.extend({}, nullableNumber, optional); const nullableNumberOptionalRepeatable = _.extend({}, nullableNumber, optional, repeatable); const nullableNumberRepeatable = _.extend({}, nullableNumber, repeatable); const nonNullableObject = { type: Types.NameExpression, name: 'Object', nullable: false }; const nonNullableObjectOptional = _.extend({}, nonNullableObject, optional); const nonNullableObjectOptionalRepeatable = _.extend({}, nonNullableObject, optional, repeatable); const nonNullableObjectRepeatable = _.extend({}, nonNullableObject, repeatable); module.exports = [ { description: 'nullable number', expression: '?number', parsed: nullableNumber, described: { en: { simple: 'nullable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable }, returns: '' } } } }, { description: 'postfix nullable number', expression: 'number?', newExpression: '?number', parsed: nullableNumber, described: { en: { simple: 'nullable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable }, returns: '' } } } }, { description: 'non-nullable object', expression: '!Object', parsed: nonNullableObject, described: { en: { simple: 'non-null Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable }, returns: '' } } } }, { description: 'postfix non-nullable object', expression: 'Object!', newExpression: '!Object', parsed: nonNullableObject, described: { en: { simple: 'non-null Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable }, returns: '' } } } }, { description: 'repeatable nullable number', expression: '...?number', parsed: nullableNumberRepeatable, described: { en: { simple: 'nullable repeatable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'postfix repeatable nullable number', expression: '...number?', newExpression: '...?number', parsed: nullableNumberRepeatable, described: { en: { simple: 'nullable repeatable number', extended: {<|fim▁hole|> repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'repeatable non-nullable object', expression: '...!Object', parsed: nonNullableObjectRepeatable, described: { en: { simple: 'non-null repeatable Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'postfix repeatable non-nullable object', expression: '...Object!', newExpression: '...!Object', parsed: nonNullableObjectRepeatable, described: { en: { simple: 'non-null repeatable Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'postfix optional nullable number', expression: 'number=?', newExpression: '?number=', parsed: nullableNumberOptional, described: { en: { simple: 'optional nullable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable, optional: en.modifiers.extended.optional }, returns: '' } } } }, { description: 'postfix nullable optional number', expression: 'number?=', newExpression: '?number=', parsed: nullableNumberOptional, described: { en: { simple: 'optional nullable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable, optional: en.modifiers.extended.optional }, returns: '' } } } }, { description: 'postfix repeatable nullable optional number', expression: '...number?=', newExpression: '...?number=', parsed: nullableNumberOptionalRepeatable, described: { en: { simple: 'optional nullable repeatable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable, optional: en.modifiers.extended.optional, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'postfix optional non-nullable object', expression: 'Object=!', newExpression: '!Object=', parsed: nonNullableObjectOptional, described: { en: { simple: 'optional non-null Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, optional: en.modifiers.extended.optional }, returns: '' } } } }, { description: 'postfix non-nullable optional object', expression: 'Object!=', newExpression: '!Object=', parsed: nonNullableObjectOptional, described: { en: { simple: 'optional non-null Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, optional: en.modifiers.extended.optional }, returns: '' } } } }, { description: 'postfix repeatable non-nullable optional object', expression: '...Object!=', newExpression: '...!Object=', parsed: nonNullableObjectOptionalRepeatable, described: { en: { simple: 'optional non-null repeatable Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, optional: en.modifiers.extended.optional, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } } ];<|fim▁end|>
description: 'number', modifiers: { nullable: en.modifiers.extended.nullable,
<|file_name|>client.go<|end_file_name|><|fim▁begin|>package hdfs import ( "context" "errors" "io" "io/ioutil" "net" "os" "os/user" "strings" "github.com/colinmarc/hdfs/v2/hadoopconf" hdfs "github.com/colinmarc/hdfs/v2/internal/protocol/hadoop_hdfs" "github.com/colinmarc/hdfs/v2/internal/rpc" krb "gopkg.in/jcmturner/gokrb5.v7/client" ) // Client represents a connection to an HDFS cluster. A Client will // automatically maintain leases for any open files, preventing other clients // from modifying them, until Close is called. type Client struct { namenode *rpc.NamenodeConnection defaults *hdfs.FsServerDefaultsProto options ClientOptions } // ClientOptions represents the configurable options for a client. // The NamenodeDialFunc and DatanodeDialFunc options can be used to set // connection timeouts: // // dialFunc := (&net.Dialer{ // Timeout: 30 * time.Second, // KeepAlive: 30 * time.Second, // DualStack: true, // }).DialContext // // options := ClientOptions{ // Addresses: []string{"nn1:9000"}, // NamenodeDialFunc: dialFunc, // DatanodeDialFunc: dialFunc, // } type ClientOptions struct { // Addresses specifies the namenode(s) to connect to. Addresses []string // User specifies which HDFS user the client will act as. It is required // unless kerberos authentication is enabled, in which case it will be // determined from the provided credentials if empty. User string // UseDatanodeHostname specifies whether the client should connect to the // datanodes via hostname (which is useful in multi-homed setups) or IP // address, which may be required if DNS isn't available. UseDatanodeHostname bool // NamenodeDialFunc is used to connect to the datanodes. If nil, then // (&net.Dialer{}).DialContext is used.<|fim▁hole|> DatanodeDialFunc func(ctx context.Context, network, addr string) (net.Conn, error) // KerberosClient is used to connect to kerberized HDFS clusters. If provided, // the client will always mutually athenticate when connecting to the // namenode(s). KerberosClient *krb.Client // KerberosServicePrincipleName specifies the Service Principle Name // (<SERVICE>/<FQDN>) for the namenode(s). Like in the // dfs.namenode.kerberos.principal property of core-site.xml, the special // string '_HOST' can be substituted for the address of the namenode in a // multi-namenode setup (for example: 'nn/_HOST'). It is required if // KerberosClient is provided. KerberosServicePrincipleName string } // ClientOptionsFromConf attempts to load any relevant configuration options // from the given Hadoop configuration and create a ClientOptions struct // suitable for creating a Client. Currently this sets the following fields // on the resulting ClientOptions: // // // Determined by fs.defaultFS (or the deprecated fs.default.name), or // // fields beginning with dfs.namenode.rpc-address. // Addresses []string // // // Determined by dfs.client.use.datanode.hostname. // UseDatanodeHostname bool // // // Set to a non-nil but empty client (without credentials) if the value of // // hadoop.security.authentication is 'kerberos'. It must then be replaced // // with a credentialed Kerberos client. // KerberosClient *krb.Client // // // Determined by dfs.namenode.kerberos.principal, with the realm // // (everything after the first '@') chopped off. // KerberosServicePrincipleName string // // Because of the way Kerberos can be forced by the Hadoop configuration but not // actually configured, you should check for whether KerberosClient is set in // the resulting ClientOptions before proceeding: // // options := ClientOptionsFromConf(conf) // if options.KerberosClient != nil { // // Replace with a valid credentialed client. // options.KerberosClient = getKerberosClient() // } func ClientOptionsFromConf(conf hadoopconf.HadoopConf) ClientOptions { options := ClientOptions{Addresses: conf.Namenodes()} options.UseDatanodeHostname = (conf["dfs.client.use.datanode.hostname"] == "true") if strings.ToLower(conf["hadoop.security.authentication"]) == "kerberos" { // Set an empty KerberosClient here so that the user is forced to either // unset it (disabling kerberos altogether) or replace it with a valid // client. If the user does neither, NewClient will return an error. options.KerberosClient = &krb.Client{} } if conf["dfs.namenode.kerberos.principal"] != "" { options.KerberosServicePrincipleName = strings.Split(conf["dfs.namenode.kerberos.principal"], "@")[0] } return options } // NewClient returns a connected Client for the given options, or an error if // the client could not be created. func NewClient(options ClientOptions) (*Client, error) { var err error if options.KerberosClient != nil && options.KerberosClient.Credentials == nil { return nil, errors.New("kerberos enabled, but kerberos client is missing credentials") } if options.KerberosClient != nil && options.KerberosServicePrincipleName == "" { return nil, errors.New("kerberos enabled, but kerberos namenode SPN is not provided") } namenode, err := rpc.NewNamenodeConnection( rpc.NamenodeConnectionOptions{ Addresses: options.Addresses, User: options.User, DialFunc: options.NamenodeDialFunc, KerberosClient: options.KerberosClient, KerberosServicePrincipleName: options.KerberosServicePrincipleName, }, ) if err != nil { return nil, err } return &Client{namenode: namenode, options: options}, nil } // New returns Client connected to the namenode(s) specified by address, or an // error if it can't connect. Multiple namenodes can be specified by separating // them with commas, for example "nn1:9000,nn2:9000". // // The user will be the current system user. Any other relevant options // (including the address(es) of the namenode(s), if an empty string is passed) // will be loaded from the Hadoop configuration present at HADOOP_CONF_DIR or // HADOOP_HOME, as specified by hadoopconf.LoadFromEnvironment and // ClientOptionsFromConf. // // Note, however, that New will not attempt any Kerberos authentication; use // NewClient if you need that. func New(address string) (*Client, error) { conf, err := hadoopconf.LoadFromEnvironment() if err != nil { return nil, err } options := ClientOptionsFromConf(conf) if address != "" { options.Addresses = strings.Split(address, ",") } u, err := user.Current() if err != nil { return nil, err } options.User = u.Username return NewClient(options) } // User returns the user that the Client is acting under. This is either the // current system user or the kerberos principal. func (c *Client) User() string { return c.namenode.User } // ReadFile reads the file named by filename and returns the contents. func (c *Client) ReadFile(filename string) ([]byte, error) { f, err := c.Open(filename) if err != nil { return nil, err } defer f.Close() return ioutil.ReadAll(f) } // CopyToLocal copies the HDFS file specified by src to the local file at dst. // If dst already exists, it will be overwritten. func (c *Client) CopyToLocal(src string, dst string) error { remote, err := c.Open(src) if err != nil { return err } defer remote.Close() local, err := os.Create(dst) if err != nil { return err } defer local.Close() _, err = io.Copy(local, remote) return err } // CopyToRemote copies the local file specified by src to the HDFS file at dst. func (c *Client) CopyToRemote(src string, dst string) error { local, err := os.Open(src) if err != nil { return err } defer local.Close() remote, err := c.Create(dst) if err != nil { return err } defer remote.Close() _, err = io.Copy(remote, local) return err } func (c *Client) fetchDefaults() (*hdfs.FsServerDefaultsProto, error) { if c.defaults != nil { return c.defaults, nil } req := &hdfs.GetServerDefaultsRequestProto{} resp := &hdfs.GetServerDefaultsResponseProto{} err := c.namenode.Execute("getServerDefaults", req, resp) if err != nil { return nil, err } c.defaults = resp.GetServerDefaults() return c.defaults, nil } // Close terminates all underlying socket connections to remote server. func (c *Client) Close() error { return c.namenode.Close() }<|fim▁end|>
NamenodeDialFunc func(ctx context.Context, network, addr string) (net.Conn, error) // DatanodeDialFunc is used to connect to the datanodes. If nil, then // (&net.Dialer{}).DialContext is used.
<|file_name|>ConfirmDialog.js<|end_file_name|><|fim▁begin|>'use strict'; let {ko, Helper} = require('../common'), DialogManager = require('../DialogManager'), DEFAULT_WIDTH = 530, TEMPLATES = { DEFAULT: 'confirmDialogTpl' }, instance, getInstance = function(confirmCallback, optionalTemplateName, optionalContextVars) { Helper.assertStringOrEmpty(optionalTemplateName, 'invalid tempalte name for ConfirmDialog.getInstance()'); if (!instance) { instance = new ConfirmDialog(); } instance.setConfirmCallback(confirmCallback);<|fim▁hole|> return instance; }; /** * A simple "Möchten Sie wirklich fortfahren?" confirm dialog. * @constructor */ function ConfirmDialog() { let self = this, dialogManager = DialogManager.getInstance(), confirmCallback = null; this.settings = DialogManager.createDialogSettings({ templateName: TEMPLATES.DEFAULT, modalWidth: DEFAULT_WIDTH }); /** * Object containing properties that might be used in the template via data-bind. */ this.contextVars = null; /** * Sets the template name for this dialog or the default templateName if empty. * @param [templateName] (String) the template to set; If falsy, the {@link TEMPLATES.DEFAULT} is set * @returns (Object) this instance (chainable) */ this.setTemplateName = function(templateName) { Helper.assertStringOrEmpty(templateName, 'Invalid templateName for ConfirmDialog'); this.settings.templateName = templateName || TEMPLATES.DEFAULT; return this; }; /** * Sets the callback function called on the positive button. * @param callback (function) e.g. function(confirmDialog){..} */ this.setConfirmCallback = function(callback) { Helper.assertFunction(callback, 'Invalid confirm callback for ConfirmDialog'); confirmCallback = callback; }; this.setContextVars = function(newContextVars) { this.contextVars = newContextVars || null; }; /** * Triggered via data-bind by the template's ok button. */ this.confirm = function() { confirmCallback(self); dialogManager.reset(); return false; }; this.show = function() { dialogManager.showDialog(this); }; } module.exports = { getInstance, getInstanceForSomething: function(someInfo, onConfirm) { return getInstance(onConfirm, TEMPLATES.DEFAULT, {someInfo: someInfo}); } };<|fim▁end|>
instance.setTemplateName(optionalTemplateName); instance.setContextVars(optionalContextVars); instance.settings.modalWidth = (TEMPLATES.REVERT_ENTRY === optionalTemplateName) ? 550 : DEFAULT_WIDTH;
<|file_name|>006_counter_volume_is_float.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright 2013 eNovance SAS <[email protected]><|fim▁hole|># # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Float from sqlalchemy import MetaData from sqlalchemy import Table def upgrade(migrate_engine): meta = MetaData(bind=migrate_engine) meter = Table('meter', meta, autoload=True) meter.c.counter_volume.alter(type=Float(53))<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate protobuf; extern crate grpc; extern crate futures; extern crate futures_cpupool; pub mod message; pub mod message_grpc; <|fim▁hole|>#[test] fn it_works() {}<|fim▁end|>
<|file_name|>About_author.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt4 import QtGui,QtCore from Ui_about_author import Ui_About _IME = "<p>Author: Bojan Ili""&#263;</p>" _FAKULTET = "Faculty of Electrical Engineering, University of Belgrade - ETF" _MAIL = "[email protected]" _URL = "<a href = ""https://www.facebook.com/puzicius>Facebook link</a>" #------------------------------------------------------------------------------- class AboutWindow2(QtGui.QDialog): """ Class wrapper for about window ui """ def __init__(self): super(AboutWindow2,self).__init__() self.setupUI() #print sys.stdout.encoding def setupUI(self): #create window from ui <|fim▁hole|> self.ui.setupUi(self) self.ui.lblVersion.setText("{}".format(_IME)) self.ui.lblVersion2.setText("{}".format(_FAKULTET)) self.ui.lblVersion3.setText("E-mail: {}".format(_MAIL)) self.ui.lblURL.setText(_URL) #------------------------------------------------------------------------------- def main(): app = QtGui.QApplication(sys.argv) form = AboutWindow2() form.show() sys.exit(app.exec_()) if __name__ == "__main__": main()<|fim▁end|>
self.ui=Ui_About()
<|file_name|>setup.py<|end_file_name|><|fim▁begin|><|fim▁hole|> def readme(): with open('README.md','r') as fr: return fr.read() setup(name='docker_machinator', version='0.1', description='A tool for managing docker machines from multiple' 'workstations', long_description=readme(), entry_points={ 'console_scripts': [ 'dmachinator = docker_machinator.dmachinator:main', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Topic :: Security', ], keywords='docker machine dmachinator secure on-disk', url='https://github.com/realcr/docker_machinator', author='real', author_email='[email protected]', license='MIT', packages=['docker_machinator'], install_requires=[ 'sstash', ], setup_requires=['pytest-runner'], tests_require=['pytest'], include_package_data=True, zip_safe=False)<|fim▁end|>
from setuptools import setup # Based on # https://python-packaging.readthedocs.io/en/latest/minimal.html
<|file_name|>ScalableLinearLayout.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2015. Vin @ vinexs.com (MIT License) * * 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. */ package com.vinexs.view; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.widget.LinearLayout; @SuppressWarnings("unused") public class ScalableLinearLayout extends LinearLayout { private ScaleGestureDetector scaleDetector; private float scaleFactor = 1.f; private float maxScaleFactor = 1.5f; private float minScaleFactor = 0.5f; public ScalableLinearLayout(Context context) { super(context); scaleDetector = new ScaleGestureDetector(context, new ScaleListener()); } public ScalableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); scaleDetector = new ScaleGestureDetector(context, new ScaleListener()); } @SuppressLint("ClickableViewAccessibility") <|fim▁hole|> @Override public boolean onTouchEvent(MotionEvent event) { // Let the ScaleGestureDetector inspect all events. scaleDetector.onTouchEvent(event); return true; } @Override public void dispatchDraw(Canvas canvas) { canvas.save(); canvas.scale(scaleFactor, scaleFactor); super.dispatchDraw(canvas); canvas.restore(); } public ScalableLinearLayout setMaxScale(float scale) { maxScaleFactor = scale; return this; } public ScalableLinearLayout setMinScale(float scale) { minScaleFactor = scale; return this; } public ScaleGestureDetector getScaleGestureDetector() { return scaleDetector; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { scaleFactor *= detector.getScaleFactor(); scaleFactor = Math.max(minScaleFactor, Math.min(scaleFactor, maxScaleFactor)); invalidate(); return true; } } }<|fim▁end|>
<|file_name|>HiddenPyiImports.py<|end_file_name|><|fim▁begin|>from m1 import <error descr="Cannot find reference 'foo' in 'm1.pyi'">foo</error> from m1 import <error descr="Cannot find reference 'bar' in 'm1.pyi'">bar</error><|fim▁hole|>print(foo, bar, bar_imported, m2, m2_imported)<|fim▁end|>
from m1 import bar_imported from m1 import <error descr="Cannot find reference 'm2' in 'm1.pyi'">m2</error> from m1 import m2_imported
<|file_name|>parserMethodSignature4.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>}<|fim▁end|>
interface I { D?<T>();
<|file_name|>LinearBreadcrumb.java<|end_file_name|><|fim▁begin|>package com.afollestad.breadcrumb; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.view.ViewCompat; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author Aidan Follestad (afollestad) */ public class LinearBreadcrumb extends HorizontalScrollView implements View.OnClickListener { public static class Crumb implements Serializable { public Crumb(String path,String attachMsg) { mPath = path; mAttachMsg = attachMsg; } private final String mPath; private final String mAttachMsg; private int mScrollY; private int mScrollOffset; public int getScrollY() { return mScrollY; } public int getScrollOffset() { return mScrollOffset; } public void setScrollY(int scrollY) { this.mScrollY = scrollY; } public void setScrollOffset(int scrollOffset) { this.mScrollOffset = scrollOffset; } public String getPath() { return mPath; } public String getTitle() { return (!TextUtils.isEmpty(mAttachMsg)) ? mAttachMsg : mPath; } public String getmAttachMsg() { return mAttachMsg; } @Override public boolean equals(Object o) { return (o instanceof Crumb) && ((Crumb) o).getPath().equals(getPath()); } @Override public String toString() { return "Crumb{" + "mAttachMsg='" + mAttachMsg + '\'' + ", mPath='" + mPath + '\'' + ", mScrollY=" + mScrollY + ", mScrollOffset=" + mScrollOffset + '}'; } } public interface SelectionCallback { void onCrumbSelection(Crumb crumb, String absolutePath, int count, int index); } public LinearBreadcrumb(Context context) { super(context); init(); } public LinearBreadcrumb(Context context, AttributeSet attrs) { super(context, attrs); init(); } public LinearBreadcrumb(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private List<Crumb> mCrumbs; private List<Crumb> mOldCrumbs; private LinearLayout mChildFrame; private int mActive; private SelectionCallback mCallback; private void init() { setMinimumHeight((int) getResources().getDimension(R.dimen.breadcrumb_height)); setClipToPadding(false); mCrumbs = new ArrayList<>(); mChildFrame = new LinearLayout(getContext()); addView(mChildFrame, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void setAlpha(View view, int alpha) { if (view instanceof ImageView && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { ((ImageView) view).setImageAlpha(alpha);<|fim▁hole|> } public void addCrumb(@NonNull Crumb crumb, boolean refreshLayout) { LinearLayout view = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.bread_crumb, this, false); view.setTag(mCrumbs.size()); view.setClickable(true); view.setFocusable(true); view.setOnClickListener(this); mChildFrame.addView(view, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); mCrumbs.add(crumb); if (refreshLayout) { mActive = mCrumbs.size() - 1; requestLayout(); } invalidateActivatedAll(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); //RTL works fine like this View child = mChildFrame.getChildAt(mActive); if (child != null) smoothScrollTo(child.getLeft(), 0); } public Crumb findCrumb(@NonNull String forDir) { for (int i = 0; i < mCrumbs.size(); i++) { if (mCrumbs.get(i).getPath().equals(forDir)) return mCrumbs.get(i); } return null; } public void clearCrumbs() { try { mOldCrumbs = new ArrayList<>(mCrumbs); mCrumbs.clear(); mChildFrame.removeAllViews(); } catch (IllegalStateException e) { e.printStackTrace(); } } public Crumb getCrumb(int index) { return mCrumbs.get(index); } public void setCallback(SelectionCallback callback) { mCallback = callback; } public boolean setActive(Crumb newActive) { mActive = mCrumbs.indexOf(newActive); for(int i = size()-1;size()>mActive+1;i--){ removeCrumbAt(i); } ((LinearLayout)mChildFrame.getChildAt(mActive)).getChildAt(1).setVisibility(View.GONE); boolean success = mActive > -1; if (success) requestLayout(); return success; } private void invalidateActivatedAll() { for (int i = 0; i < mCrumbs.size(); i++) { Crumb crumb = mCrumbs.get(i); invalidateActivated(mChildFrame.getChildAt(i), mActive == mCrumbs.indexOf(crumb), i < mCrumbs.size() - 1).setText(crumb.getTitle()); } } public void removeCrumbAt(int index) { mCrumbs.remove(index); mChildFrame.removeViewAt(index); } private void updateIndices() { for (int i = 0; i < mChildFrame.getChildCount(); i++) mChildFrame.getChildAt(i).setTag(i); } private boolean isValidPath(String path) { return path == null; } public int size() { return mCrumbs.size(); } private TextView invalidateActivated(View view, boolean isActive, boolean isShowSeparator) { LinearLayout child = (LinearLayout) view; if (isShowSeparator) child.getChildAt(1).setVisibility(View.VISIBLE); return (TextView) child.getChildAt(0); } public int getActiveIndex() { return mActive; } @Override public void onClick(View v) { if (mCallback != null) { int index = (Integer) v.getTag(); if (index >= 0 && index < (size()-1)) { setActive(mCrumbs.get(index)); mCallback.onCrumbSelection(mCrumbs.get(index), getAbsolutePath(mCrumbs.get(index), "/"), mCrumbs.size(), index); } } } public static class SavedStateWrapper implements Serializable { public final int mActive; public final List<Crumb> mCrumbs; public final int mVisibility; public SavedStateWrapper(LinearBreadcrumb view) { mActive = view.mActive; mCrumbs = view.mCrumbs; mVisibility = view.getVisibility(); } } public SavedStateWrapper getStateWrapper() { return new SavedStateWrapper(this); } public void restoreFromStateWrapper(SavedStateWrapper mSavedState, Activity context) { if (mSavedState != null) { mActive = mSavedState.mActive; for (Crumb c : mSavedState.mCrumbs) { addCrumb(c, false); } requestLayout(); setVisibility(mSavedState.mVisibility); } } public String getAbsolutePath(Crumb crumb, @NonNull String separator) { StringBuilder builder = new StringBuilder(); if (size() > 1 && !crumb.equals(mCrumbs.get(0))) { List<Crumb> crumbs = mCrumbs.subList(1, size()); for (Crumb mCrumb : crumbs) { builder.append(mCrumb.getPath()); builder.append(separator); if (mCrumb.equals(crumb)) { break; } } String path = builder.toString(); return path.substring(0, path.length() -1); } else { return null; } } public String getCurAbsolutePath(@NonNull String separator){ return getAbsolutePath(getCrumb(mActive),separator); } public void addRootCrumb() { clearCrumbs(); addCrumb(new Crumb("/","root"), true); } public void addPath(@NonNull String path,@NonNull String sha, @NonNull String separator) { clearCrumbs(); addCrumb(new Crumb("",""), false); String[] paths = path.split(separator); Crumb lastCrumb = null; for (String splitPath : paths) { lastCrumb = new Crumb(splitPath,sha); addCrumb(lastCrumb, false); } if (lastCrumb != null) { setActive(lastCrumb); } } }<|fim▁end|>
} else { ViewCompat.setAlpha(view, alpha); }
<|file_name|>DecoderPro.py<|end_file_name|><|fim▁begin|>import jmri.jmrit.jython.Jynstrument as Jynstrument import jmri.jmrit.catalog.NamedIcon as NamedIcon import jmri.jmrit.symbolicprog.tabbedframe.PaneOpsProgAction as PaneOpsProgAction import javax.swing.JButton as JButton class DecoderPro(Jynstrument): def getExpectedContextClassName(self): return "javax.swing.JComponent" def init(self): jbNew = JButton( PaneOpsProgAction() )<|fim▁hole|> jbNew.setIcon( NamedIcon("resources/decoderpro.gif","resources/decoderpro.gif") ) jbNew.addMouseListener(self.getMouseListeners()[0]) # In order to get the popupmenu on the button too jbNew.setToolTipText( jbNew.getText() ) jbNew.setText( None ) self.add(jbNew) def quit(self): pass<|fim▁end|>
<|file_name|>DBPoolManager.ts<|end_file_name|><|fim▁begin|>export declare function require(name: string): any let pg = require("pg") import { CannotCreateInstanceError, SqlExecFailError, TableNotFoundError } from "../define/Error" import Table, {Record} from "../model/db/table/Table" import Column from "../model/db/column/Column" /** * DBPoolManager */ export default class DBPoolManager { private static instance: DBPoolManager private pool: any private client: any private static DB_CONF = { user: "root", database: "open_ishinomaki", password: "KsJaA4uQ", host: "localhost", port: 5432, max: 10, idleTimeoutMillis: 30000 } constructor() { if (DBPoolManager.instance) { throw new CannotCreateInstanceError(DBPoolManager.name) } this.pool = new pg.Pool(DBPoolManager.DB_CONF) } /** * @return {Promise} resolve(instance), reject(error) */ public static getInstance(): Promise<DBPoolManager> { if (this.instance == null) { this.instance = new DBPoolManager() } return new Promise((resolve, reject) => { if (this.instance.client) { resolve(this.instance) return<|fim▁hole|> this.instance.pool.connect((error, client, done) => { if (error) { reject(error) return } this.instance.client = client resolve(this.instance) }) }) } /** * @param {String} psql 実行psqlテキスト * @param {Array} varray 実行psqlテキストに付随する変数配列 * @return {Promise} resolve(result), reject(error) */ public exec(psql: string, varray?: any[]): Promise<any> { console.log("exec-psql: " + psql) return new Promise((resolve, reject) => { this.client.query(psql, varray, (error, result) => { if (error) { reject(new SqlExecFailError(error)) return } resolve(result) }) }) } } export function escape(value: any): any { if (value instanceof Array) { return value.map((value1: any) => { return escape(value1) }) } else if (value instanceof Object) { return Object.keys(value).reduce((prev: any, key: string) => { prev[key] = escape(value[key]) return prev }, {}) } else if (value == null || typeof value != String.name.toLowerCase()) { return value } return value.replace(/'/g, "''") }<|fim▁end|>
}
<|file_name|>PersistentTable.hh<|end_file_name|><|fim▁begin|>/* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __MEM_RUBY_SYSTEM_PERSISTENTTABLE_HH__ #define __MEM_RUBY_SYSTEM_PERSISTENTTABLE_HH__ #include <iostream> #include "mem/gems_common/Map.hh" #include "mem/protocol/AccessType.hh" #include "mem/ruby/common/Address.hh" #include "mem/ruby/common/Global.hh" #include "mem/ruby/common/NetDest.hh" #include "mem/ruby/system/MachineID.hh" class PersistentTableEntry { public: void print(std::ostream& out) const {} NetDest m_starving; NetDest m_marked; NetDest m_request_to_write; }; class PersistentTable<|fim▁hole|> // Constructors PersistentTable(); // Destructor ~PersistentTable(); // Public Methods void persistentRequestLock(const Address& address, MachineID locker, AccessType type); void persistentRequestUnlock(const Address& address, MachineID unlocker); bool okToIssueStarving(const Address& address, MachineID machID) const; MachineID findSmallest(const Address& address) const; AccessType typeOfSmallest(const Address& address) const; void markEntries(const Address& address); bool isLocked(const Address& addr) const; int countStarvingForAddress(const Address& addr) const; int countReadStarvingForAddress(const Address& addr) const; static void printConfig(std::ostream& out) {} void print(std::ostream& out) const; private: // Private copy constructor and assignment operator PersistentTable(const PersistentTable& obj); PersistentTable& operator=(const PersistentTable& obj); // Data Members (m_prefix) Map<Address, PersistentTableEntry>* m_map_ptr; }; inline std::ostream& operator<<(std::ostream& out, const PersistentTable& obj) { obj.print(out); out << std::flush; return out; } inline std::ostream& operator<<(std::ostream& out, const PersistentTableEntry& obj) { obj.print(out); out << std::flush; return out; } #endif // __MEM_RUBY_SYSTEM_PERSISTENTTABLE_HH__<|fim▁end|>
{ public:
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt<|fim▁hole|> def index(request): template = loader.get_template('index.html') result=10 context = RequestContext(request, { # 'result': result, }) return HttpResponse(template.render(context)) @csrf_exempt def predict(request): result=5 try: img=request.POST['img'] except KeyError: # Redisplay the question voting form. # return render(request, 'polls/detail.html', { # 'question': p, # 'error_message': "You didn't select a choice.", # }) # print "error_message" return HttpResponse("Your predict is %s." % result) else: # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. # return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) return HttpResponse("Your predict is %s." % result) # pass # name = request.POST.get('name') # return HttpResponse(json.dumps({'name': name}), content_type="application/json")<|fim▁end|>
<|file_name|>forms.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from accounts.models import Profile from django import forms from django.conf import settings from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.models import User from django.utils import formats, timezone from django.utils.translation import ugettext as _ class RegistrationForm(UserCreationForm): """Edit form for sign up""" email = forms.EmailField(label='email', required=True) code = forms.CharField(label='code', required=False)<|fim▁hole|> class Meta: """Meta for RegistrationForm""" model = User fields = {"username", "email", "code"} if settings.ENABLE_NICKNAME: fields.add("first_name") def __init__(self, *args, **kwargs): """Override maxlength""" super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['maxlength'] = settings.ID_MAX_LENGTH if settings.ENABLE_NICKNAME: self.fields['first_name'].widget.attrs['maxlength'] = settings.ID_MAX_LENGTH class SettingForm(forms.ModelForm): """Edit form for setting""" class Meta: """Meta for SettingForm""" model = Profile fields = { "alarm_interval", "alarm_board", "alarm_reply", "alarm_paper", "alarm_team", "alarm_full", "sense_client", "sense_slot" } def __init__(self, *args, **kwargs): """Init""" super(SettingForm, self).__init__(*args, **kwargs) self.fields['alarm_reply'].widget.attrs['checked'] = 'checked' self.fields['alarm_reply'].widget.attrs['disabled'] = True self.fields['alarm_full'].widget.attrs['checked'] = 'checked' self.fields['alarm_full'].widget.attrs['disabled'] = True class UserInfoForm(forms.ModelForm): """Edit form for user info""" email = forms.EmailField(label='email', required=True) code = forms.CharField(label='code', required=False) first_name = forms.CharField(max_length=12, required=False) class Meta: """Meta for UserInfoForm""" model = Profile fields = { "portrait", "email", "code", "id1", "id2", "id3", "signature" } if settings.ENABLE_NICKNAME: fields.add("first_name") def __init__(self, *args, **kwargs): """Init""" super(UserInfoForm, self).__init__(*args, **kwargs) self.fields['email'].initial = self.instance.user.email if settings.ENABLE_NICKNAME: self.fields['first_name'].initial = self.instance.user.first_name self.fields['first_name'].widget.attrs['maxlength'] = settings.ID_MAX_LENGTH class LoginForm(AuthenticationForm): """Custom login form for suspension""" def confirm_login_allowed(self, user): """Override confirm_login_allowed""" if user.is_active: pass elif not user.is_active: now = timezone.now() if now > user.profile.suspension_till: user.is_active = True user.save() else: formatted_date = formats.date_format(timezone.localtime( user.profile.suspension_till), "Y-m-d H:i:s") error = _('You have been suspended until %(date)s.') % { 'date': formatted_date } raise forms.ValidationError(error, code='suspended')<|fim▁end|>
<|file_name|>cam4.py<|end_file_name|><|fim▁begin|>''' Ultimate Whitecream Copyright (C) 2016 mortael This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import urllib, urllib2, re, cookielib, os, sys, socket import xbmc, xbmcplugin, xbmcgui, xbmcaddon import utils, sqlite3 mobileagent = {'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 9_2_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13D15 Safari/601.1'} def Main(): utils.addDir('[COLOR red]Refresh Cam4 images[/COLOR]','',283,'',Folder=False) utils.addDir('[COLOR hotpink]Featured[/COLOR]','http://www.cam4.com/featured/1',281,'',1) utils.addDir('[COLOR hotpink]Females[/COLOR]','http://www.cam4.com/female/1',281,'',1) utils.addDir('[COLOR hotpink]Couples[/COLOR]','http://www.cam4.com/couple/1',281,'',1) utils.addDir('[COLOR hotpink]Males[/COLOR]','http://www.cam4.com/male/1',281,'',1) utils.addDir('[COLOR hotpink]Transsexual[/COLOR]','http://www.cam4.com/shemale/1',281,'',1) xbmcplugin.endOfDirectory(utils.addon_handle) def clean_database(showdialog=False): conn = sqlite3.connect(xbmc.translatePath("special://database/Textures13.db")) try: with conn: list = conn.execute("SELECT id, cachedurl FROM texture WHERE url LIKE '%%%s%%';" % ".systemcdn.net") for row in list: conn.execute("DELETE FROM sizes WHERE idtexture LIKE '%s';" % row[0]) try: os.remove(xbmc.translatePath("special://thumbnails/" + row[1])) except: pass conn.execute("DELETE FROM texture WHERE url LIKE '%%%s%%';" % ".systemcdn.net") if showdialog: utils.notify('Finished','Cam4 images cleared') except: pass def List(url, page): if utils.addon.getSetting("chaturbate") == "true": clean_database() listhtml = utils.getHtml(url, url) match = re.compile('profileDataBox"> <a href="([^"]+)".*?src="([^"]+)" title="Chat Now Free with ([^"]+)"', re.DOTALL | re.IGNORECASE).findall(listhtml) for videourl, img, name in match: name = utils.cleantext(name) videourl = "http://www.cam4.com" + videourl<|fim▁hole|> if re.search('<link rel="next"', listhtml, re.DOTALL | re.IGNORECASE): npage = page + 1 url = url.replace('/'+str(page),'/'+str(npage)) utils.addDir('Next Page ('+str(npage)+')', url, 281, '', npage) xbmcplugin.endOfDirectory(utils.addon_handle) def Playvid(url, name): listhtml = utils.getHtml(url, '', mobileagent) match = re.compile('<video id=Cam4HLSPlayer class="SD" controls autoplay src="([^"]+)"> </video>', re.DOTALL | re.IGNORECASE).findall(listhtml) if match: videourl = match[0] iconimage = xbmc.getInfoImage("ListItem.Thumb") listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage) listitem.setInfo('video', {'Title': name, 'Genre': 'Porn'}) listitem.setProperty("IsPlayable","true") if int(sys.argv[1]) == -1: pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) pl.clear() pl.add(videourl, listitem) xbmc.Player().play(pl) else: listitem.setPath(str(videourl)) xbmcplugin.setResolvedUrl(utils.addon_handle, True, listitem)<|fim▁end|>
utils.addDownLink(name, videourl, 282, img, '', noDownload=True)
<|file_name|>struct_l_p_c___r_t_c___type_def.js<|end_file_name|><|fim▁begin|>var struct_l_p_c___r_t_c___type_def = [ [ "ALDOM", "struct_l_p_c___r_t_c___type_def.html#aae1199a3f1f40f90aba18aee4d6325fd", null ], [ "ALDOW", "struct_l_p_c___r_t_c___type_def.html#a5f56710f005f96878defbdb8ef1333c2", null ], [ "ALDOY", "struct_l_p_c___r_t_c___type_def.html#a4c7ceb477c4a865ae51f5052dd558667", null ], [ "ALHOUR", "struct_l_p_c___r_t_c___type_def.html#ac56690c26258c2cf9d28d09cc3447c1d", null ], [ "ALMIN", "struct_l_p_c___r_t_c___type_def.html#a7e45902fca36066b22f41d0ef60d3c36", null ], [ "ALMON", "struct_l_p_c___r_t_c___type_def.html#ad22f635b8c8b51dad2956e797a4dd9d3", null ], [ "ALSEC", "struct_l_p_c___r_t_c___type_def.html#af3ff64ab3671109971425a05194acc7c", null ], [ "ALYEAR", "struct_l_p_c___r_t_c___type_def.html#ab7f49ad885a354164adc263629d3a555", null ], [ "AMR", "struct_l_p_c___r_t_c___type_def.html#a13f4e9721184b326043e6c6596f87790", null ], [ "CALIBRATION", "struct_l_p_c___r_t_c___type_def.html#abe224f8608ae3d2c5b1036bf943b6c27", null ], [ "CCR", "struct_l_p_c___r_t_c___type_def.html#af959ddb88caef28108c2926e310a72bd", null ], [ "CIIR", "struct_l_p_c___r_t_c___type_def.html#a0df12e53986b72fbfcdceb537f7bf20e", null ],<|fim▁hole|> [ "CTIME0", "struct_l_p_c___r_t_c___type_def.html#a97fa06b91b698236cb770d9618707bef", null ], [ "CTIME1", "struct_l_p_c___r_t_c___type_def.html#a5b1a1b981a72c6d1cd482e75f1d44de4", null ], [ "CTIME2", "struct_l_p_c___r_t_c___type_def.html#a411e06dfdcddd3fc19170231aa3a98be", null ], [ "DOM", "struct_l_p_c___r_t_c___type_def.html#a7c70513eabbefbc5c5dd865a01ecc487", null ], [ "DOW", "struct_l_p_c___r_t_c___type_def.html#a61f22d3ccb1c82db258f66d7d930db35", null ], [ "DOY", "struct_l_p_c___r_t_c___type_def.html#a7b4a3d5692df3c5062ec927cedd16734", null ], [ "GPREG0", "struct_l_p_c___r_t_c___type_def.html#ac42f0d8452c678fa007f0e0b862fb0c6", null ], [ "GPREG1", "struct_l_p_c___r_t_c___type_def.html#abee4ae6eab2c33bdf38985d3b8a439f1", null ], [ "GPREG2", "struct_l_p_c___r_t_c___type_def.html#a75f852bb2980febd2af7cc583e1445ec", null ], [ "GPREG3", "struct_l_p_c___r_t_c___type_def.html#aad058be0cc120fffbbc66ad6f7c0c731", null ], [ "GPREG4", "struct_l_p_c___r_t_c___type_def.html#afcc8f7898dce77fdb1082ff681387692", null ], [ "HOUR", "struct_l_p_c___r_t_c___type_def.html#a76b8d6a8b13febe4289797f34ba73998", null ], [ "ILR", "struct_l_p_c___r_t_c___type_def.html#aba869620e961b6eb9280229dad81e458", null ], [ "MIN", "struct_l_p_c___r_t_c___type_def.html#a7a07167f54a5412387ee581fcd6dd2e0", null ], [ "MONTH", "struct_l_p_c___r_t_c___type_def.html#a28fb9798e07b54b1098e9efe96ac244a", null ], [ "RESERVED0", "struct_l_p_c___r_t_c___type_def.html#ad539ffa4484980685ca2da36b54fe61d", null ], [ "RESERVED1", "struct_l_p_c___r_t_c___type_def.html#ad9fb3ef44fb733b524dcad0dfe34290e", null ], [ "RESERVED10", "struct_l_p_c___r_t_c___type_def.html#a2d9caf1d8be9f2169521470b6ccd0377", null ], [ "RESERVED11", "struct_l_p_c___r_t_c___type_def.html#a11e504ee49142f46dcc67740ae9235e5", null ], [ "RESERVED12", "struct_l_p_c___r_t_c___type_def.html#a06137f06d699f26661c55209218bcada", null ], [ "RESERVED13", "struct_l_p_c___r_t_c___type_def.html#a17672e7a5546cef19ee778266224c193", null ], [ "RESERVED14", "struct_l_p_c___r_t_c___type_def.html#a1b9781efee5466ce7886eae907f24e60", null ], [ "RESERVED15", "struct_l_p_c___r_t_c___type_def.html#a781148146471db4cd7d04029e383d115", null ], [ "RESERVED16", "struct_l_p_c___r_t_c___type_def.html#af3ff60ce094e476f447a8046d873acb0", null ], [ "RESERVED17", "struct_l_p_c___r_t_c___type_def.html#ae98d0c41e0bb8aef875fa8b53b25af54", null ], [ "RESERVED18", "struct_l_p_c___r_t_c___type_def.html#aae0a4a7536dc03a352e8c48436b10263", null ], [ "RESERVED19", "struct_l_p_c___r_t_c___type_def.html#a5552e97d80fc1a5bd195a9c81b270ffc", null ], [ "RESERVED2", "struct_l_p_c___r_t_c___type_def.html#aff8b921ce3122ac6c22dc654a4f1b7ca", null ], [ "RESERVED20", "struct_l_p_c___r_t_c___type_def.html#af7fcad34b88077879694c020956bf69b", null ], [ "RESERVED21", "struct_l_p_c___r_t_c___type_def.html#ae26a65f4079b1f3af0490c463e6f6e90", null ], [ "RESERVED3", "struct_l_p_c___r_t_c___type_def.html#a1936698394c9e65033538255b609f5d5", null ], [ "RESERVED4", "struct_l_p_c___r_t_c___type_def.html#a23568af560875ec74b660f1860e06d3b", null ], [ "RESERVED5", "struct_l_p_c___r_t_c___type_def.html#a17b8ef27f4663f5d6b0fe9c46ab9bc3d", null ], [ "RESERVED6", "struct_l_p_c___r_t_c___type_def.html#a585b017c54971fb297a30e3927437015", null ], [ "RESERVED7", "struct_l_p_c___r_t_c___type_def.html#af2e6e355909e4223f7665881b0514716", null ], [ "RESERVED8", "struct_l_p_c___r_t_c___type_def.html#a8cb0d97b1d31d1921acc7aa587d1c60b", null ], [ "RESERVED9", "struct_l_p_c___r_t_c___type_def.html#ad8b1fadb520f7a200ee0046e110edc79", null ], [ "RTC_AUX", "struct_l_p_c___r_t_c___type_def.html#a8a91a5b909fbba65b28d972c3164a4ed", null ], [ "RTC_AUXEN", "struct_l_p_c___r_t_c___type_def.html#a4f807cc73e86fa24a247e0dce31512a4", null ], [ "SEC", "struct_l_p_c___r_t_c___type_def.html#a77f4a78b486ec068e5ced41419805802", null ], [ "YEAR", "struct_l_p_c___r_t_c___type_def.html#aaf0ddcf6e202e34e9cf7b35c584f9849", null ] ];<|fim▁end|>
<|file_name|>testeditor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Amara, universalsubtitles.org # # Copyright (C) 2013 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see # http://www.gnu.org/licenses/agpl-3.0.html. from django.core.urlresolvers import reverse import simplejson as json from utils import test_factories class TestEditor(object): """Simulates the editor widget for unit tests""" def __init__(self, client, video, original_language_code=None, base_language_code=None, mode=None): """Construct a TestEditor :param client: django TestClient object for HTTP requests :param video: Video object to edit :param original_language_code: language code for the video audio. Should be set if and only if the primary_audio_language_code hasn't been set for the video. :param base_language_code: base language code for to use for translation tasks. :param mode: one of ("review", "approve" or None) """ self.client = client self.video = video self.base_language_code = base_language_code if original_language_code is None: self.original_language_code = video.primary_audio_language_code else: if video.primary_audio_language_code is not None: raise AssertionError( "primary_audio_language_code is set (%r)" % video.primary_audio_language_code) self.original_language_code = original_language_code self.mode = mode self.task_approved = None self.task_id = None self.task_notes = None self.task_type = None def set_task_data(self, task, approved, notes): """Set data for the task that this edit is for. :param task: Task object :param approved: did the user approve the task. Should be one of the values of Task.APPROVED_IDS. :param notes: String to set for notes """ type_map = { 10: 'subtitle', 20: 'translate', 30: 'review', 40: 'approve', } self.task_id = task.id self.task_type = type_map[task.type] self.task_notes = notes self.task_approved = approved def _submit_widget_rpc(self, method, **data): """POST data to the widget:rpc view.""" url = reverse('widget:rpc', args=(method,)) post_data = dict((k, json.dumps(v)) for k, v in data.items()) response = self.client.post(url, post_data) response_data = json.loads(response.content) if 'error' in response_data: raise AssertionError("Error calling widget rpc method %s:\n%s" % (method, response_data['error'])) return response_data def run(self, language_code, completed=True, save_for_later=False): """Make the HTTP requests to simulate the editor We will use test_factories.dxfp_sample() for the subtitle data. :param language_code: code for the language of these subtitles<|fim▁hole|> """ self._submit_widget_rpc('fetch_start_dialog_contents', video_id=self.video.video_id) existing_language = self.video.subtitle_language(language_code) if existing_language is not None: subtitle_language_pk = existing_language.pk else: subtitle_language_pk = None response_data = self._submit_widget_rpc( 'start_editing', video_id=self.video.video_id, language_code=language_code, original_language_code=self.original_language_code, base_language_code=self.base_language_code, mode=self.mode, subtitle_language_pk=subtitle_language_pk) session_pk = response_data['session_pk'] self._submit_widget_rpc('finished_subtitles', completed=completed, save_for_later=save_for_later, session_pk=session_pk, subtitles=test_factories.dxfp_sample('en'), task_approved=self.task_approved, task_id=self.task_id, task_notes=self.task_notes, task_type=self.task_type)<|fim▁end|>
:param completed: simulate the completed checkbox being set :param save_for_later: simulate the save for later button
<|file_name|>man_pages.rs<|end_file_name|><|fim▁begin|>use crate::types; /// Print the given help if the -h or --help argument are found pub fn check_help(args: &[types::Str], man_page: &'static str) -> bool { for arg in args { if arg == "-h" || arg == "--help" { println!("{}", man_page); return true; } } false } // pub const MAN_FN: &str = r#"NAME // fn - print a list of all functions or create a function // // SYNOPSIS // fn // // fn example arg:int // echo $arg // end // // DESCRIPTION // fn prints a list of all functions that exist in the shell or creates a<|fim▁hole|>// The supported types in ion are, [], bool, bool[], float, float[], int, // int[], str, str[]. // // Functions are called by typing the function name and then the function // arguments, separated by a space. // // fn example arg0:int arg1:int // echo $arg // end // // example 1 //"#;<|fim▁end|>
// function when combined with the 'end' keyword. Functions can have type // hints, to tell ion to check the type of a functions arguments. An error will // occur if an argument supplied to a function is of the wrong type.
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
pub mod io; pub mod solutions;
<|file_name|>ShapefileLoader.java<|end_file_name|><|fim▁begin|>package lejos.robotics.mapping; import java.io.*; import java.util.ArrayList; import lejos.geom.Line; import lejos.geom.Rectangle; /* * WARNING: THIS CLASS IS SHARED BETWEEN THE classes AND pccomms PROJECTS. * DO NOT EDIT THE VERSION IN pccomms AS IT WILL BE OVERWRITTEN WHEN THE PROJECT IS BUILT. */ /** * <p>This class loads map data from a Shapefile and produces a LineMap object, which can * be used by the leJOS navigation package.</p> * * <p>There are many map editors which can use the Shapefile format (OpenEV, Global Mapper). Once you * have created a map, export it as Shapefile. This will produce three files ending in .shp .shx and * .dbf. The only file used by this class is .shp.</p> * * <p>NOTE: Shapefiles can only contain one type of shape data (polygon or polyline, not both). A single file can't * mix polylines with polygons.</p> * * <p>This class' code can parse points and multipoints. However, a LineMap object can't deal with * points (only lines) so points and multipoints are discarded.</p> * * @author BB * */ public class ShapefileLoader { /* OTHER POTENTIAL MAP FILE FORMATS TO ADD: * (none have really been researched yet for viability) * KML * GML * WMS? (more of a service than a file) * MIF/MID (MapInfo) * SVG (Scalable Vector Graphics) * EPS (Encapsulated Post Script) * DXF (Autodesk) * AI (Adobe Illustrator) * */ // 2D shape types types: private static final byte NULL_SHAPE = 0; private static final byte POINT = 1; private static final byte POLYLINE = 3; private static final byte POLYGON = 5; private static final byte MULTIPOINT = 8; private final int SHAPEFILE_ID = 0x0000270a; DataInputStream data_is = null; <|fim▁hole|> /** * Creates a ShapefileLoader object using an input stream. Likely you will use a FileInputStream * which points to the *.shp file containing the map data. * @param in */ public ShapefileLoader(InputStream in) { this.data_is = new DataInputStream(in); } /** * Retrieves a LineMap object from the Shapefile input stream. * @return the line map * @throws IOException */ public LineMap readLineMap() throws IOException { ArrayList <Line> lines = new ArrayList <Line> (); int fileCode = data_is.readInt(); // Big Endian if(fileCode != SHAPEFILE_ID) throw new IOException("File is not a Shapefile"); data_is.skipBytes(20); // Five int32 unused by Shapefile /*int fileLength =*/ data_is.readInt(); //System.out.println("Length: " + fileLength); // TODO: Docs say length is in 16-bit words. Unsure if this is strictly correct. Seems higher than what hex editor shows. /*int version =*/ readLEInt(); //System.out.println("Version: " + version); /*int shapeType =*/ readLEInt(); //System.out.println("Shape type: " + shapeType); // These x and y min/max values define bounding rectangle: double xMin = readLEDouble(); double yMin = readLEDouble(); double xMax = readLEDouble(); double yMax = readLEDouble(); // Create bounding rectangle: Rectangle rect = new Rectangle((float)xMin, (float)yMin, (float)(xMax - xMin), (float)(yMax - yMin)); /*double zMin =*/ readLEDouble(); /*double zMax =*/ readLEDouble(); /*double mMin =*/ readLEDouble(); /*double mMax =*/ readLEDouble(); // TODO These values seem to be rounded down to nearest 0.5. Must round them up? //System.out.println("Xmin " + xMin + " Ymin " + yMin); //System.out.println("Xmax " + xMax + " Ymax " + yMax); try { // TODO: This is a cheesy way to detect EOF condition. Not very good coding. while(2 > 1) { // TODO: Temp code to keep it looping. Should really detect EOF condition. // NOW ONTO READING INDIVIDUAL SHAPES: // Record Header (2 values): /*int recordNum =*/ data_is.readInt(); int recordLen = data_is.readInt(); // TODO: in 16-bit words. Might cause bug if number of shapes gets bigger than 16-bit short? // Record (variable length depending on shape type): int recShapeType = readLEInt(); // Now to read the actual shape data switch (recShapeType) { case NULL_SHAPE: break; case POINT: // DO WE REALLY NEED TO DEAL WITH POINT? Feature might use them possibly. /*double pointX =*/ readLEDouble(); // TODO: skip bytes instead /*double pointY =*/ readLEDouble(); break; case POLYLINE: // NOTE: Data structure for polygon/polyline is identical. Code should work for both. case POLYGON: // Polygons can contain multiple polygons, such as a donut with outer ring and inner ring for hole. // Max bounding rect: 4 doubles in a row. TODO: Discard bounding rect. values and skip instead. /*double polyxMin =*/ readLEDouble(); /*double polyyMin =*/ readLEDouble(); /*double polyxMax =*/ readLEDouble(); /*double polyyMax =*/ readLEDouble(); int numParts = readLEInt(); int numPoints = readLEInt(); // Retrieve array of indexes for each part in the polygon int [] partIndex = new int[numParts]; for(int i=0;i<numParts;i++) { partIndex[i] = readLEInt(); } // Now go through numParts times pulling out points double firstX=0; double firstY=0; for(int i=0;i<numPoints-1;i++) { // Could check here if onto new polygon (i = next index). If so, do something with line formation. for(int j=0;j<numParts;j++) { if(i == partIndex[j]) { firstX = readLEDouble(); firstY = readLEDouble(); continue; } } double secondX = readLEDouble(); double secondY = readLEDouble(); Line myLine = new Line((float)firstX, (float)firstY, (float)secondX, (float)secondY); lines.add(myLine); firstX = secondX; firstY = secondY; } break; case MULTIPOINT: // TODO: DO WE REALLY NEED TO DEAL WITH MULTIPOINT? Comment out and skip bytes? /*double multixMin = */readLEDouble(); /*double multiyMin = */readLEDouble(); /*double multixMax = */readLEDouble(); /*double multiyMax = */readLEDouble(); int multiPoints = readLEInt(); double [] xVals = new double[multiPoints]; double [] yVals = new double[multiPoints]; for(int i=0;i<multiPoints;i++) { xVals[i] = readLEDouble(); yVals[i] = readLEDouble(); } break; default: // IGNORE REST OF SHAPE TYPES and skip over data using recordLen value //System.out.println("Some other unknown shape"); data_is.skipBytes(recordLen); // TODO: Check if this works on polyline or point } } // END OF WHILE } catch(EOFException e) { // End of File, just needs to continue } Line [] arrList = new Line [lines.size()]; return new LineMap(lines.toArray(arrList), rect); } /** * Translates a little endian int into a big endian int * * @return int A big endian int */ private int readLEInt() throws IOException { int byte1, byte2, byte3, byte4; synchronized (this) { byte1 = data_is.read(); byte2 = data_is.read(); byte3 = data_is.read(); byte4 = data_is.read(); } if (byte4 == -1) { throw new EOFException(); } return (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1; } /** * Reads a little endian double into a big endian double * * @return double A big endian double */ private final double readLEDouble() throws IOException { return Double.longBitsToDouble(this.readLELong()); } /** * Translates a little endian long into a big endian long * * @return long A big endian long */ private long readLELong() throws IOException { long byte1 = data_is.read(); long byte2 = data_is.read(); long byte3 = data_is.read(); long byte4 = data_is.read(); long byte5 = data_is.read(); long byte6 = data_is.read(); long byte7 = data_is.read(); long byte8 = data_is.read(); if (byte8 == -1) { throw new EOFException(); } return (byte8 << 56) + (byte7 << 48) + (byte6 << 40) + (byte5 << 32) + (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1; } }<|fim▁end|>
<|file_name|>right_margin.py<|end_file_name|><|fim▁begin|>""" Minimal example showing the use of the AutoCompleteMode. """ import logging logging.basicConfig(level=logging.DEBUG) import sys from pyqode.qt import QtWidgets from pyqode.core.api import CodeEdit from pyqode.core.backend import server from pyqode.core.modes import RightMarginMode<|fim▁hole|> editor = CodeEdit() editor.backend.start(server.__file__) editor.resize(800, 600) margin = editor.modes.append(RightMarginMode()) margin.position = 4 editor.file.open(__file__) editor.show() app.exec_() editor.close() del editor del app<|fim▁end|>
if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv)
<|file_name|>vote.py<|end_file_name|><|fim▁begin|>""" Controller for voting related requests. """ import webapp2 from models.vote import VoteHandler from models.vote_.cast_ballot import BallotHandler from models.vote_.view_results import ResultsHandler app = webapp2.WSGIApplication([ ('/vote', VoteHandler),<|fim▁hole|> ('/vote/cast-ballot', BallotHandler), ('/vote/view-results', ResultsHandler) ], debug=True)<|fim▁end|>
<|file_name|>DictController.java<|end_file_name|><|fim▁begin|>package com.siqisoft.stone.admin.dict.controller; import java.util.List; import org.siqisource.stone.dict.model.Dict; import org.siqisource.stone.dict.service.DictService; import org.siqisource.stone.orm.condition.Condition; import org.siqisource.stone.ui.AjaxResponse; import org.siqisource.stone.ui.Notify; import org.siqisource.stone.ui.easyui.PagedRows; import org.siqisource.stone.ui.easyui.Paging; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.siqisoft.stone.admin.dict.service.DictConditionBuilder; @Controller public class DictController { @Autowired DictService service; @RequestMapping("/dict/DictList.do") public String list(Model model) { return "dict/DictList"; } @RequestMapping("/dict/dictListData.do") @ResponseBody public PagedRows<Dict> listData(DictQueryForm dictQueryForm, Paging paging) { Condition condition = DictConditionBuilder.listCondition(dictQueryForm); int count = service.count(condition); List<Dict> dictList = service.list(condition, paging.getRowBounds()); return new PagedRows<Dict>(count, dictList); } @RequestMapping("/dict/DictRead.do") public String read(String code, Model model) { Dict dict = service.read(code); model.addAttribute("dict", dict); return "dict/DictRead"; } @RequestMapping("/dict/DictAddInit.do") public String addInit(Dict dict, Model model) { return "dict/DictAdd"; } @RequestMapping("/dict/DictAdd.do") public String add(Dict dict, Model model) { service.insert(dict); return this.read(dict.getCode(), model); } <|fim▁hole|> // 判断是否被关联 if (codeList != null) { service.deleteBatch(codeList); } return new Notify("成功删除"+codeList.length+"条记录"); } @RequestMapping("/dict/DictEditInit.do") public String editInit(String code, Model model) { Dict dict = service.read(code); model.addAttribute("dict", dict); return "dict/DictEdit"; } @RequestMapping("/dict/DictEdit.do") public String edit(Dict dict, Model model) { service.update(dict); return this.read(dict.getCode(), model); } }<|fim▁end|>
@RequestMapping("/dict/dictDelete.do") @ResponseBody public AjaxResponse delete(String[] codeList, Model model) {
<|file_name|>random_trees.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from optparse import make_option import random import math from django.contrib.gis.geos import Point from treemap.models import Plot, Tree, Species from treemap.management.util import InstanceDataCommand class Command(InstanceDataCommand): option_list = InstanceDataCommand.option_list + ( make_option('-r', '--radius', action='store', type='int', dest='radius', default=5000, help='Number of meters from the center'), make_option('-n', '--number-of-trees', action='store', type='int', dest='n', default=100000, help='Number of trees to create'), make_option('-p', '--prob-of-tree', action='store', type='int', dest='ptree', default=50, help=('Probability that a given plot will ' 'have a tree (0-100)')), make_option('-s', '--prob-of-species', action='store', type='int', dest='pspecies', default=50, help=('Probability that a given tree will ' 'have a species (0-100)')), make_option('-D', '--prob-of-diameter',<|fim▁hole|> type='int', dest='pdiameter', default=10, help=('Probability that a given tree will ' 'have a diameter (0-100)'))) def handle(self, *args, **options): """ Create some seed data """ instance, user = self.setup_env(*args, **options) species_qs = instance.scope_model(Species) n = options['n'] self.stdout.write("Will create %s plots" % n) get_prob = lambda option: float(min(100, max(0, option))) / 100.0 tree_prob = get_prob(options['ptree']) species_prob = get_prob(options['pspecies']) diameter_prob = get_prob(options['pdiameter']) max_radius = options['radius'] center_x = instance.center.x center_y = instance.center.y ct = 0 cp = 0 for i in xrange(0, n): mktree = random.random() < tree_prob radius = random.gauss(0.0, max_radius) theta = random.random() * 2.0 * math.pi x = math.cos(theta) * radius + center_x y = math.sin(theta) * radius + center_y plot = Plot(instance=instance, geom=Point(x, y)) plot.save_with_user(user) cp += 1 if mktree: add_species = random.random() < species_prob if add_species: species = random.choice(species_qs) else: species = None add_diameter = random.random() < diameter_prob if add_diameter: diameter = 2 + random.random() * 18 else: diameter = None tree = Tree(plot=plot, species=species, diameter=diameter, instance=instance) tree.save_with_user(user) ct += 1 self.stdout.write("Created %s trees and %s plots" % (ct, cp))<|fim▁end|>
action='store',
<|file_name|>scripts.js<|end_file_name|><|fim▁begin|>$(function(){ $('.home .bxslider').bxSlider({ auto: true, mode: 'fade' }); /** * QUICK REFERENCE */ // check if the window bindings should be applied (only if the element is present) var $reference = $('.reference-wrap'); if($reference.length > 0){ // toggle the menu $('.reference-wrap h3').click(function() { $('.reference-content').slideToggle(300); }); // scroll to the elements $('.reference-content a').click(function(){ $('.reference-content').slideToggle(300); var id = $(this).html(); $('html, body').animate({ scrollTop: $('#' + id).offset().top - 20 }, 300); return false; }); $(window).bind('scroll resize', positionQuickReference); } // check if .reference-wrap should be sticky function positionQuickReference(){ var windowTop = $(window).scrollTop(); if(windowTop >= 112){ $reference.css({ position: 'fixed', top: 20, right: $(window).width() > 700 ? $(window).width() - ($('#primary h1').offset().left + $('#primary').width()) : 20 }); }else{ $reference.css({ position: 'absolute', top: 0, right: $(window).width() > 1040 ? 0 : 20 }); } } /** * SIDEBAR */ $('.btn-donate').click(function() { $('#frm-paypal').submit(); return false; }); $('.block-signup form').submit(function() { var email = $('#mce-EMAIL').val(); if(!isValidEmailAddress(email)){ $('.block-signup .error').show(); return false; } }); }); function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); return pattern.test(emailAddress); }; // (function(){ // var bsa = document.createElement('script'); // bsa.type = 'text/javascript'; // bsa.async = true; // bsa.src = '//s3.buysellads.com/ac/bsa.js'; // (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa); // })(); /** * Create a cookie */ function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; }; /** * Get a cookie */ function getCookie(c_name) {<|fim▁hole|> c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start, c_end)); } } return ""; };<|fim▁end|>
if (document.cookie.length > 0) {
<|file_name|>show_rack_rack.py<|end_file_name|><|fim▁begin|># -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.<|fim▁hole|># 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. """Contains the logic for `aq show rack --rack`.""" from aquilon.aqdb.model import Rack from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 class CommandShowRackRack(BrokerCommand): required_parameters = ["rack"] def render(self, session, rack, **arguments): return Rack.get_unique(session, rack, compel=True)<|fim▁end|>
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #
<|file_name|>passthrough.hpp<|end_file_name|><|fim▁begin|>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_FILTERS_IMPL_PASSTHROUGH_HPP_ #define PCL_FILTERS_IMPL_PASSTHROUGH_HPP_ #include <pcl/filters/passthrough.h> #include <pcl/common/io.h> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::PassThrough<PointT>::applyFilter (PointCloud &output) { std::vector<int> indices; if (keep_organized_) { bool temp = extract_removed_indices_; extract_removed_indices_ = true; applyFilterIndices (indices); extract_removed_indices_ = temp; output = *input_; for (int rii = 0; rii < static_cast<int> (removed_indices_->size ()); ++rii) // rii = removed indices iterator output.points[(*removed_indices_)[rii]].x = output.points[(*removed_indices_)[rii]].y = output.points[(*removed_indices_)[rii]].z = user_filter_value_; if (!pcl_isfinite (user_filter_value_)) output.is_dense = false; } else { output.is_dense = true; applyFilterIndices (indices); copyPointCloud (*input_, indices, output); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::PassThrough<PointT>::applyFilterIndices (std::vector<int> &indices) { // The arrays to be used indices.resize (indices_->size ()); removed_indices_->resize (indices_->size ()); int oii = 0, rii = 0; // oii = output indices iterator, rii = removed indices iterator // Has a field name been specified? if (filter_field_name_.empty ()) { // Only filter for non-finite entries then for (int iii = 0; iii < static_cast<int> (indices_->size ()); ++iii) // iii = input indices iterator { // Non-finite entries are always passed to removed indices if (!pcl_isfinite (input_->points[(*indices_)[iii]].x) || !pcl_isfinite (input_->points[(*indices_)[iii]].y) || !pcl_isfinite (input_->points[(*indices_)[iii]].z)) { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } indices[oii++] = (*indices_)[iii]; } } else { // Attempt to get the field name's index std::vector<pcl::PCLPointField> fields; int distance_idx = pcl::getFieldIndex (*input_, filter_field_name_, fields); if (distance_idx == -1) { PCL_WARN ("[pcl::%s::applyFilter] Unable to find field name in point type.\n", getClassName ().c_str ()); indices.clear (); removed_indices_->clear (); return; } // Filter for non-finite entries and the specified field limits for (int iii = 0; iii < static_cast<int> (indices_->size ()); ++iii) // iii = input indices iterator { // Non-finite entries are always passed to removed indices if (!pcl_isfinite (input_->points[(*indices_)[iii]].x) || !pcl_isfinite (input_->points[(*indices_)[iii]].y) || !pcl_isfinite (input_->points[(*indices_)[iii]].z)) { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } // Get the field's value const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&input_->points[(*indices_)[iii]]); float field_value = 0; memcpy (&field_value, pt_data + fields[distance_idx].offset, sizeof (float)); // Remove NAN/INF/-INF values. We expect passthrough to output clean valid data. if (!pcl_isfinite (field_value))<|fim▁hole|> { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } // Outside of the field limits are passed to removed indices if (!negative_ && (field_value < filter_limit_min_ || field_value > filter_limit_max_)) { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } // Inside of the field limits are passed to removed indices if negative was set if (negative_ && field_value > filter_limit_min_ && field_value < filter_limit_max_) { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } // Otherwise it was a normal point for output (inlier) indices[oii++] = (*indices_)[iii]; } } // Resize the output arrays indices.resize (oii); removed_indices_->resize (rii); } #define PCL_INSTANTIATE_PassThrough(T) template class PCL_EXPORTS pcl::PassThrough<T>; #endif // PCL_FILTERS_IMPL_PASSTHROUGH_HPP_<|fim▁end|>
<|file_name|>0163_auto__add_field_userinfo_avatar.py<|end_file_name|><|fim▁begin|># encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'UserInfo.avatar' db.add_column('canvas_userinfo', 'avatar', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['canvas.Content'], null=True), keep_default=False) def backwards(self, orm): # Deleting field 'UserInfo.avatar' db.delete_column('canvas_userinfo', 'avatar_id') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '254', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'canvas.apiapp': { 'Meta': {'object_name': 'APIApp'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, 'canvas.apiauthtoken': { 'Meta': {'unique_together': "(('user', 'app'),)", 'object_name': 'APIAuthToken'}, 'app': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.APIApp']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'token': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.bestof': { 'Meta': {'object_name': 'BestOf'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'best_of'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Category']"}), 'chosen_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'best_of'", 'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}) }, 'canvas.category': { 'Meta': {'object_name': 'Category'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '140'}), 'founded': ('django.db.models.fields.FloatField', [], {'default': '1298956320'}), 'founder': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'founded_groups'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderators': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'moderated_categories'", 'symmetrical': 'False', 'to': "orm['auth.User']"}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.comment': { 'Meta': {'object_name': 'Comment'}, 'anonymous': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'comments'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'comments'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Category']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15'}), 'judged': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'ot_hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'parent_comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'replies'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Comment']"}), 'parent_content': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'comments'", 'null': 'True', 'to': "orm['canvas.Content']"}), 'replied_comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['canvas.Comment']", 'null': 'True', 'blank': 'True'}), 'reply_content': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'used_in_comments'", 'null': 'True', 'to': "orm['canvas.Content']"}), 'reply_text': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'blank': 'True'}), 'score': ('django.db.models.fields.FloatField', [], {'default': '0', 'db_index': 'True'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.commentflag': { 'Meta': {'object_name': 'CommentFlag'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'type_id': ('django.db.models.fields.IntegerField', [], {}), 'undone': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': "orm['auth.User']"}) }, 'canvas.commentmoderationlog': { 'Meta': {'object_name': 'CommentModerationLog'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'note': ('django.db.models.fields.TextField', [], {}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'moderated_comments_log'", 'to': "orm['auth.User']"}), 'visibility': ('django.db.models.fields.IntegerField', [], {}) }, 'canvas.commentpin': { 'Meta': {'object_name': 'CommentPin'}, 'auto': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.commentsticker': { 'Meta': {'object_name': 'CommentSticker'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stickers'", 'to': "orm['canvas.Comment']"}), 'epic_message': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '140', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'type_id': ('django.db.models.fields.IntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'canvas.commentstickerlog': { 'Meta': {'object_name': 'CommentStickerLog'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.content': { 'Meta': {'object_name': 'Content'}, 'alpha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'animated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.CharField', [], {'max_length': '40', 'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15'}), 'remix_of': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'remixes'", 'null': 'True', 'to': "orm['canvas.Content']"}), 'remix_text': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1000', 'blank': 'True'}), 'source_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '4000', 'blank': 'True'}), 'stamps_used': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'used_as_stamp'", 'blank': 'True', 'to': "orm['canvas.Content']"}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'url_mapping': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.ContentUrlMapping']", 'null': 'True', 'blank': 'True'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.contenturlmapping': { 'Meta': {'object_name': 'ContentUrlMapping'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'canvas.emailunsubscribe': { 'Meta': {'object_name': 'EmailUnsubscribe'}, 'email': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'canvas.externalcontent': { 'Meta': {'object_name': 'ExternalContent'}, '_data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}), 'content_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parent_comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'external_content'", 'to': "orm['canvas.Comment']"}), 'source_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '4000', 'null': 'True', 'blank': 'True'}) }, 'canvas.facebookinvite': { 'Meta': {'object_name': 'FacebookInvite'}, 'fb_message_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invited_fbid': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'invitee': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'facebook_invited_from'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'inviter': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'facebook_sent_invites'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}) }, 'canvas.facebookuser': { 'Meta': {'object_name': 'FacebookUser'}, 'email': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'fb_uid': ('django.db.models.fields.BigIntegerField', [], {'unique': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'gender': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_invited': ('canvas.util.UnixTimestampField', [], {'default': '0'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, 'canvas.followcategory': { 'Meta': {'unique_together': "(('user', 'category'),)", 'object_name': 'FollowCategory'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'followers'", 'to': "orm['canvas.Category']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'following'", 'to': "orm['auth.User']"}) }, 'canvas.invitecode': { 'Meta': {'object_name': 'InviteCode'}, 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invitee': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'invited_from'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'inviter': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'sent_invites'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}) }, 'canvas.remixplugin': { 'Meta': {'object_name': 'RemixPlugin'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 's3md5': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {'default': '0'}) }, 'canvas.stashcontent': { 'Meta': {'object_name': 'StashContent'}, 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Content']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.userinfo': { 'Meta': {'object_name': 'UserInfo'}, 'avatar': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Content']", 'null': 'True'}), 'bio_text': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'blank': 'True'}), 'enable_timeline': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'enable_timeline_posts': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'facebook_id': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'free_invites': ('django.db.models.fields.IntegerField', [], {'default': '10'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invite_bypass': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), 'is_qa': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'post_anonymously': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'profile_image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']", 'null': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'canvas.usermoderationlog': { 'Meta': {'object_name': 'UserModerationLog'}, 'action': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'note': ('django.db.models.fields.TextField', [], {}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'moderation_log'", 'to': "orm['auth.User']"}) }, 'canvas.userwarning': { 'Meta': {'object_name': 'UserWarning'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['canvas.Comment']", 'null': 'True', 'blank': 'True'}), 'confirmed': ('canvas.util.UnixTimestampField', [], {'default': '0'}), 'custom_message': ('django.db.models.fields.TextField', [], {}), 'disable_user': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issued': ('canvas.util.UnixTimestampField', [], {}), 'stock_message': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_warnings'", 'to': "orm['auth.User']"}), 'viewed': ('canvas.util.UnixTimestampField', [], {'default': '0'}) }, 'canvas.welcomeemailrecipient': { 'Meta': {'object_name': 'WelcomeEmailRecipient'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'recipient': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'canvas_auth.user': { 'Meta': {'object_name': 'User', 'db_table': "'auth_user'", '_ormbases': ['auth.User'], 'proxy': 'True'} },<|fim▁hole|> 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['canvas']<|fim▁end|>
'contenttypes.contenttype': {
<|file_name|>base.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Misc stuff also needed for core imports and monkey patching """ import numpy as np from .core import (RVector3, R3Vector, RMatrix) def isScalar(v, val=None): """Check if v is scalar, i.e. int, float or complex. Optional compare with val. Examples -------- >>> import pygimli as pg >>> print(pg.isScalar(0)) True >>> print(pg.isScalar(1.0)) True >>> print(pg.isScalar(1.0, 0.0)) False >>> print(pg.isScalar(1.0, 1.0)) True >>> print(pg.isScalar(1+1j)) True >>> print(pg.isScalar([0.0, 1.0])) False """ if val is None: return isinstance(v, (int, float, complex, np.complex128)) # maybe add some tolerance check return isinstance(v, (int, float, complex, np.complex128)) and v == val def isArray(v, N=None): """Check if `v` is a 1D array or a vector, with optional size `N`. Examples -------- >>> import pygimli as pg >>> import numpy as np >>> print(pg.isArray([0, 1])) True >>> print(pg.isArray(np.ones(5))) True >>> print(pg.isArray(pg.Vector(5))) True >>> print(pg.isArray(pg.Vector(5), N=5)) True >>> print(pg.isArray(pg.Vector(5), N=2)) False >>> print(pg.isArray('foo')) False """ if N is None: if isinstance(v, (tuple, list)): return isScalar(v[0]) return (hasattr(v, '__iter__') and \ not isinstance(v, (str))) and v.ndim == 1 return isArray(v) and len(v) == N def isComplex(vals): """Check numpy or pg.Vector if have complex data type""" if isScalar(vals): if isinstance(vals, (np.complex128, complex)): return True elif isArray(vals): return isComplex(vals[0]) return False def isPos(v): """Check if v is an array of size(3), [x,y,z], or pg.Pos. Examples --------<|fim▁hole|> >>> import pygimli as pg >>> print(pg.isPos([0.0, 0.0, 1.])) True >>> print(pg.isPos(pg.Pos(0.0, 0.0, 0.0))) True >>> print(pg.isPos(np.ones(3))) True >>> print(pg.isPos(np.ones(4))) False """ return isArray(v, 2) or isArray(v, 3) or isinstance(v, RVector3) def isR3Array(v, N=None): """Check if v is an array of size(N,3), a R3Vector or a list of pg.Pos. Examples -------- >>> import pygimli as pg >>> print(pg.isR3Array([[0.0, 0.0, 1.], [1.0, 0.0, 1.]])) True >>> print(pg.isR3Array(np.ones((33, 3)), N=33)) True >>> print(pg.isR3Array(pg.meshtools.createGrid(2,2).positions())) True """ if N is None: return isinstance(v, R3Vector) or \ ( isinstance(v, list) and isPos(v[0])) or \ (not isinstance(v, list) and hasattr(v, '__iter__') and \ not isinstance(v, (str)) and v.ndim == 2 and isPos(v[0])) return isR3Array(v) and len(v) == N isPosList = isR3Array def isMatrix(v, shape=None): """Check is v has ndim=2 or is comparable list""" if shape is None: return isinstance(v, RMatrix) or \ hasattr(v, 'ndim') and v.ndim == 2 or \ isinstance(v, list) and isArray(v[0]) return isMatrix(v) and (hasattr(v, 'shape') and v.shape == shape)<|fim▁end|>
<|file_name|>rclups0.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python desc="""Report distance matrix between proteins. Dependencies: - Biopython, numpy & scipy """ epilog="""Author: [email protected] Bratislava, 28/04/2016 """ import os, sys, gzip import numpy as np from datetime import datetime from Bio import SeqIO from multiprocessing import Pool from scipy.cluster import hierarchy import matplotlib.pyplot as plt aa2i = {'A': 0, 'R': 1, 'N': 2, 'D': 3, 'C': 4, 'Q': 5, 'E': 6, 'G': 7, 'H': 8, 'I': 9, 'L': 10, 'K': 11, 'M': 12, 'F': 13, 'P': 14, 'S': 15, 'T': 16, 'W': 17, 'Y': 18, 'V': 19} dna2i = {'A': 0, 'C': 1, 'G': 2, 'T': 3, 'a': 0, 'c': 1, 'g': 2, 't': 3} a2i = aa2i a2i = dna2i bases = len(set(a2i.values())) # Grantham R (1974) Science 185:862-864. Polarity = {'A': 8.1, 'R': 10.5, 'N': 11.6, 'D': 13.0, 'C': 5.5, 'Q': 10.5, 'E': 12.3, 'G': 9.0, 'H': 10.4, 'I': 5.2, 'L': 4.9, 'K': 11.3, 'M': 5.7, 'F': 5.2, 'P': 8.0, 'S': 9.2, 'T': 8.6, 'W': 5.4, 'Y': 6.2, 'V': 5.9} Volume = {'A': 31.0, 'R': 124.0, 'N': 56.0, 'D': 54.0, 'C': 55.0, 'Q': 85.0, 'E': 83.0, 'G': 3.0, 'H': 96.0, 'I': 111.0, 'L': 111.0, 'K': 119.0, 'M': 105.0, 'F': 132.0, 'P': 32.5, 'S': 32.0, 'T': 61.0, 'W': 170.0, 'Y': 136.0, 'V': 84.0} # Zhao, G., London E (2006) Protein Sci. 15:1987-2001. Transmembrane = {'A': 0.38, 'R': -2.57, 'N': -1.62, 'D': -3.27, 'C': -0.3, 'Q': -1.84, 'E': -2.9, 'G': -0.19, 'H': -1.44, 'I': 1.97, 'L': 1.82, 'K': -3.46, 'M': 1.4, 'F': 1.98, 'P': -1.44, 'S': -0.53, 'T': -0.32, 'W': 1.53, 'Y': 0.49, 'V': 1.46} polarity = {aa: (v-np.mean(Polarity.values()))/np.std(Polarity.values()) for aa, v in Polarity.iteritems()} volume = {aa: (v-np.mean(Volume.values()))/np.std(Volume.values()) for aa, v in Volume.iteritems()} transmembrane = {aa: (v-np.mean(Transmembrane.values()))/np.std(Transmembrane.values()) for aa, v in Transmembrane.iteritems()} def get_power_spectrum(seq, features): """Return power spectrum for given feature. Consider normalisation by seq length. """ # DFT - here I'm looking only at first dimension A = np.fft.fft([features[aa] for aa in seq if aa in features]) # PS ## Get the first half of the transform (since it's symmetric) - make sure it's good PS = np.abs(A[1:(len(seq)+1)/2])**2 #PS = np.sum(PS) #/len(seq) PS = [len(seq)*np.sum(PS**j)/len(seq)**j for j in range(1,4)] return PS def get_coords0(arg): """Return x, y coordinates for given sequence""" name, seq = arg x = get_power_spectrum(seq, polarity) y = get_power_spectrum(seq, volume) z = get_power_spectrum(seq, transmembrane) return name, x + y + z def get_coords(arg): """Alternative approach Hoang (2015) A new method to cluster DNA sequences using Fourier power spectrum """ name, seq = arg a = np.zeros((bases, len(seq)), dtype=int) c = np.zeros(bases) for i, aa in enumerate(seq): if aa not in a2i: continue # update a[a2i[aa]][i] = 1 c[a2i[aa]] += 1 # DFT A = [np.fft.fft(_a) for _a in a]#; print len(A) # exclude first term # PS: only the first half : _A[1:(len(seq))/2] PS = [np.abs(_A[1:])**2 for _A in A]#; print PS[-1].shape # normalised moments MV = [] for j in range(1, 4): for i, ps in enumerate(PS): mv = c[i]*(len(seq)-c[i])*np.sum(ps**j)/(c[i]**j*(len(seq)-c[i])**j) MV.append(mv) #print MV return name, np.array(MV), len(seq) def fasta_generator_multi(files, verbose): """Return entry id and sequence""" for i, handle in enumerate(files, 1): if verbose: sys.stderr.write(' %s %s \n'%(i, handle.name)) name = ".".join(handle.name.split('.')[:-1]) if handle.name.endswith('.gz'): handle = gzip.open(handle.name) name = ".".join(handle.name.split('.')[:-2]) seqs = [] for r in SeqIO.parse(handle, 'fasta'): #yield r.description, str(r.seq) seqs.append(str(r.seq)) seq = "".join(seqs) name += "_%s"%len(seq) yield name, seq def fasta_generator(handle, verbose): """Return entry id and sequence""" if handle.name.endswith('.gz'): handle = gzip.open(handle.name) for r in SeqIO.parse(handle, 'fasta'): seq = str(r.seq) name = r.id name += "_%s"%len(seq) yield name, seq def fasta2clusters(files, out, nproc, dendrogram, verbose): """Report clusters""" if verbose: sys.stderr.write('Parsing %s input(s)...\n'%len(files)) # get iterator if len(files)>1: iterator = fasta_generator_multi(files, verbose) else: iterator = fasta_generator(files[0], verbose) # start pool of processes p = Pool(nproc) mvs, labels, seqlens = [], [], [] for i, (name, mv, seqlen) in enumerate(p.imap(get_coords, iterator), 1): #if verbose and not i%1000: sys.stderr.write(' %s %s \n'%(i, name)) #fields = name.split() #name = " ".join((fields[0].split('_')[-1], fields[1].split(':')[-1], fields[4].split(':')[-1])) # store labels.append(name) mvs.append(mv) seqlens.append(seqlen) maxlen = max(seqlens) ytdist = [1.0/maxlen*x for x in mvs] for i, mv in enumerate(ytdist): name = labels[i/3] # report j = i%3 + 1 out.write("%s\t%s\t%s\n"%(name, j, "\t".join(map(str, mv)))) # report distances dists = np.zeros((i,i)) for i1 in range(i-1): v1 = np.array(ytdist[i1])#; print len(v1) for i2 in range(i1, i): v2 = np.array(ytdist[i2]) d = np.linalg.norm(v1-v2) dists[i1][i2] = d dists[i2][i1] = d np.savetxt('out.txt', dists, delimiter='\t', header='\t'.join(labels)) if verbose: sys.stderr.write('%s entries processed!\n'%i) if dendrogram: # UPGMA http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.cluster.hierarchy.linkage.html Z = hierarchy.linkage(ytdist, method='average', metric='euclidean') plt.figure() dn = hierarchy.dendrogram(Z, labels=labels, orientation='right') plt.show() def main(): import argparse usage = "%(prog)s -v" #usage=usage, parser = argparse.ArgumentParser(description=desc, epilog=epilog, \ formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--version', action='version', version='1.0b') parser.add_argument("-v", "--verbose", default=False, action="store_true", help="verbose") parser.add_argument("-i", "--input", nargs="+", type=file, default=[sys.stdin,], help="input stream [stdin]") parser.add_argument("-o", "--output", default=sys.stdout, type=argparse.FileType('w'), help="output stream [stdout]") parser.add_argument("-d", "--dendrogram", action='store_true', default=False, help="plot dendrogram") parser.add_argument("-n", "--nproc", default=1, type=int, help="no. of processed to run [%(default)s]") o = parser.parse_args() if o.verbose: sys.stderr.write("Options: %s\n"%str(o)) fasta2clusters(o.input, o.output, o.nproc, o.dendrogram, o.verbose) if __name__=='__main__': t0 = datetime.now() try: main() except KeyboardInterrupt: sys.stderr.write("\nCtrl-C pressed! \n") except IOError as e: sys.stderr.write("I/O error({0}): {1}\n".format(e.errno, e.strerror)) dt = datetime.now()-t0 sys.stderr.write("#Time elapsed: %s\n"%dt) """ % Tung Hoang a , Changchuan Yin a , Hui Zheng a , Chenglong Yu b,c , Rong Lucy He d ,Stephen S.-T. Yau (2015) A new method to cluster DNA sequences using Fourier power spectrum function [v] = GetMomentVectorPS(seq) %UNTITLED2 Summary of this function goes here % Detailed explanation goes here n=length(seq); %Binary indicator sequences of A, C, G, T (each value will be either 1 or 0 %; 1 if that nucleotide appears in that position and 0 otherwise) uA=zeros(1, n); uC=zeros(1, n); uG=zeros(1, n); uT=zeros(1, n); %Sequences' length (of A, C, G, T respectively) nA=0; nC=0; nG=0; nT=0; %Get the binary indicator sequences and their lengths for i=1:n nu=seq(i); switch upper(nu)<|fim▁hole|> uC(i)=0; uG(i)=0; uT(i)=0; nA=nA+1; case {'C'} uC(i)=1; uA(i)=0; uG(i)=0; uT(i)=0; nC=nC+1; case {'G'} uG(i)=1; uA(i)=0; uC(i)=0; uT(i)=0; nG=nG+1; case {'T'} uT(i)=1; uA(i)=0; uC(i)=0; uG(i)=0; nT=nT+1; end end %Discrete Fourier Transforms UA=fft(uA); UC=fft(uC); UG=fft(uG); UT=fft(uT); %Exclude the first term UA(1)=[]; UC(1)=[]; UG(1)=[]; UT(1)=[]; % Get the first half of the transform (since it's symmetric) m=floor((n-1)/2); UA1=UA(1:m); UC1=UC(1:m); UG1=UG(1:m); UT1=UT(1:m); %Power spectrums PSA=abs(UA).^2; PSC=abs(UC).^2; PSG=abs(UG).^2; PST=abs(UT).^2; %Normalized moments MA=zeros(1,3); MC=zeros(1,3); MG=zeros(1,3); MT=zeros(1,3); %Moment vector for j=1:3 MA(j)=(nA*(n-nA))*sum(PSA.^j)/(nA^(j)*(n-nA)^(j)); MC(j)=(nC*(n-nC))*sum(PSC.^j)/(nC^(j)*(n-nC)^(j)); MG(j)=(nG*(n-nG))*sum(PSG.^j)/(nG^(j)*(n-nG)^(j)); MT(j)=(nT*(n-nT))*sum(PST.^j)/(nT^(j)*(n-nT)^(j)); end v=[MA(1), MC(1), MG(1), MT(1), MA(2), MC(2), MG(2), MT(2), MA(3), MC(3), MG(3), MT(3)]; end """<|fim▁end|>
case {'A'} uA(i)=1;
<|file_name|>swagger-oauth.js<|end_file_name|><|fim▁begin|>var appName; var popupMask; var popupDialog; var clientId; var realm; var redirect_uri; var clientSecret; var scopeSeparator; var additionalQueryStringParams; function handleLogin() { var scopes = []; var auths = window.swaggerUi.api.authSchemes || window.swaggerUi.api.securityDefinitions; if(auths) { var key; var defs = auths; for(key in defs) { var auth = defs[key]; if(auth.type === 'oauth2' && auth.scopes) { var scope; if(Array.isArray(auth.scopes)) { // 1.2 support var i; for(i = 0; i < auth.scopes.length; i++) { scopes.push(auth.scopes[i]); } } else { // 2.0 support for(scope in auth.scopes) { scopes.push({scope: scope, description: auth.scopes[scope], OAuthSchemeKey: key}); } } } } } if(window.swaggerUi.api && window.swaggerUi.api.info) { appName = window.swaggerUi.api.info.title; } $('.api-popup-dialog').remove(); popupDialog = $( [ '<div class="api-popup-dialog">', '<div class="api-popup-title">Select OAuth2.0 Scopes</div>', '<div class="api-popup-content">', '<p>Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes.', '<a href="#">Learn how to use</a>', '</p>', '<p><strong>' + appName + '</strong> API requires the following scopes. Select which ones you want to grant to Swagger UI.</p>', '<ul class="api-popup-scopes">', '</ul>', '<p class="error-msg"></p>', '<div class="api-popup-actions"><button class="api-popup-authbtn api-button green" type="button">Authorize</button><button class="api-popup-cancel api-button gray" type="button">Cancel</button></div>', '</div>', '</div>'].join('')); $(document.body).append(popupDialog); //TODO: only display applicable scopes (will need to pass them into handleLogin) popup = popupDialog.find('ul.api-popup-scopes').empty(); for (i = 0; i < scopes.length; i ++) { scope = scopes[i]; str = '<li><input type="checkbox" id="scope_' + i + '" scope="' + scope.scope + '"' +'" oauthtype="' + scope.OAuthSchemeKey +'"/>' + '<label for="scope_' + i + '">' + scope.scope ; if (scope.description) { if ($.map(auths, function(n, i) { return i; }).length > 1) //if we have more than one scheme, display schemes str += '<br/><span class="api-scope-desc">' + scope.description + ' ('+ scope.OAuthSchemeKey+')' +'</span>'; else str += '<br/><span class="api-scope-desc">' + scope.description + '</span>'; } str += '</label></li>'; popup.append(str); } var $win = $(window), dw = $win.width(), dh = $win.height(), st = $win.scrollTop(), dlgWd = popupDialog.outerWidth(), dlgHt = popupDialog.outerHeight(), top = (dh -dlgHt)/2 + st, left = (dw - dlgWd)/2; popupDialog.css({ top: (top < 0? 0 : top) + 'px', left: (left < 0? 0 : left) + 'px' }); popupDialog.find('button.api-popup-cancel').click(function() { popupMask.hide(); popupDialog.hide(); popupDialog.empty(); popupDialog = []; }); $('button.api-popup-authbtn').unbind(); popupDialog.find('button.api-popup-authbtn').click(function() { popupMask.hide(); popupDialog.hide(); var authSchemes = window.swaggerUi.api.authSchemes; var host = window.location; var pathname = location.pathname.substring(0, location.pathname.lastIndexOf("/")); var defaultRedirectUrl = host.protocol + '//' + host.host + pathname + '/o2c-html'; var redirectUrl = window.oAuthRedirectUrl || defaultRedirectUrl; var url = null; var scopes = [] var o = popup.find('input:checked'); var OAuthSchemeKeys = []; var state; for(k =0; k < o.length; k++) { var scope = $(o[k]).attr('scope'); if (scopes.indexOf(scope) === -1) scopes.push(scope); var OAuthSchemeKey = $(o[k]).attr('oauthtype'); if (OAuthSchemeKeys.indexOf(OAuthSchemeKey) === -1) OAuthSchemeKeys.push(OAuthSchemeKey); } //TODO: merge not replace if scheme is different from any existing //(needs to be aware of schemes to do so correctly) window.enabledScopes=scopes; for (var key in authSchemes) { if (authSchemes.hasOwnProperty(key) && OAuthSchemeKeys.indexOf(key) != -1) { //only look at keys that match this scope. var flow = authSchemes[key].flow; if(authSchemes[key].type === 'oauth2' && flow && (flow === 'implicit' || flow === 'accessCode')) { var dets = authSchemes[key]; url = dets.authorizationUrl + '?response_type=' + (flow === 'implicit' ? 'token' : 'code'); window.swaggerUi.tokenName = dets.tokenName || 'access_token'; window.swaggerUi.tokenUrl = (flow === 'accessCode' ? dets.tokenUrl : null); state = key; } else if(authSchemes[key].type === 'oauth2' && flow && (flow === 'application')) { var dets = authSchemes[key]; window.swaggerUi.tokenName = dets.tokenName || 'access_token'; clientCredentialsFlow(scopes, dets.tokenUrl, key); return; } else if(authSchemes[key].grantTypes) { // 1.2 support var o = authSchemes[key].grantTypes; for(var t in o) { if(o.hasOwnProperty(t) && t === 'implicit') { var dets = o[t]; var ep = dets.loginEndpoint.url; url = dets.loginEndpoint.url + '?response_type=token'; window.swaggerUi.tokenName = dets.tokenName; } else if (o.hasOwnProperty(t) && t === 'accessCode') { var dets = o[t]; var ep = dets.tokenRequestEndpoint.url; url = dets.tokenRequestEndpoint.url + '?response_type=code'; window.swaggerUi.tokenName = dets.tokenName; } } } } } redirect_uri = redirectUrl; url += '&redirect_uri=' + encodeURIComponent(redirectUrl); url += '&realm=' + encodeURIComponent(realm); url += '&client_id=' + encodeURIComponent(clientId); url += '&scope=' + encodeURIComponent(scopes.join(scopeSeparator)); url += '&state=' + encodeURIComponent(state); for (var key in additionalQueryStringParams) { url += '&' + key + '=' + encodeURIComponent(additionalQueryStringParams[key]); } window.open(url); }); popupMask.show(); popupDialog.show(); return; } function handleLogout() { for(key in window.swaggerUi.api.clientAuthorizations.authz){ window.swaggerUi.api.clientAuthorizations.remove(key) } window.enabledScopes = null; $('.api-ic.ic-on').addClass('ic-off'); $('.api-ic.ic-on').removeClass('ic-on'); // set the info box $('.api-ic.ic-warning').addClass('ic-error'); $('.api-ic.ic-warning').removeClass('ic-warning'); } function initOAuth(opts) { var o = (opts||{}); var errors = []; appName = (o.appName||errors.push('missing appName')); popupMask = (o.popupMask||$('#api-common-mask')); popupDialog = (o.popupDialog||$('.api-popup-dialog')); clientId = (o.clientId||errors.push('missing client id')); clientSecret = (o.clientSecret||null); realm = (o.realm||errors.push('missing realm')); scopeSeparator = (o.scopeSeparator||' '); additionalQueryStringParams = (o.additionalQueryStringParams||{}); if(errors.length > 0){ log('auth unable initialize oauth: ' + errors); return; } $('pre code').each(function(i, e) {hljs.highlightBlock(e)}); $('.api-ic').unbind(); $('.api-ic').click(function(s) { if($(s.target).hasClass('ic-off')) handleLogin(); else { handleLogout(); } false; }); } function clientCredentialsFlow(scopes, tokenUrl, OAuthSchemeKey) { var params = { 'client_id': clientId, 'client_secret': clientSecret, 'scope': scopes.join(' '), 'grant_type': 'client_credentials' } $.ajax( { url : tokenUrl, type: "POST", data: params, success:function(data, textStatus, jqXHR) { onOAuthComplete(data,OAuthSchemeKey); }, error: function(jqXHR, textStatus, errorThrown) { onOAuthComplete(""); } }); } window.processOAuthCode = function processOAuthCode(data) { var OAuthSchemeKey = data.state; var params = { 'client_id': clientId, 'code': data.code, 'grant_type': 'authorization_code', 'redirect_uri': redirect_uri }; if (clientSecret) { params.client_secret = clientSecret; } $.ajax( { url : window.swaggerUi.tokenUrl, type: "POST", data: params, success:function(data, textStatus, jqXHR) { onOAuthComplete(data, OAuthSchemeKey); }, error: function(jqXHR, textStatus, errorThrown) { onOAuthComplete(""); } }); }; window.onOAuthComplete = function onOAuthComplete(token,OAuthSchemeKey) { if(token) { if(token.error) { var checkbox = $('input[type=checkbox],.secured') checkbox.each(function(pos){ checkbox[pos].checked = false; }); alert(token.error); } else { var b = token[window.swaggerUi.tokenName]; if (!OAuthSchemeKey){ OAuthSchemeKey = token.state; } if(b){ // if all roles are satisfied var o = null; $.each($('.auth .api-ic .api_information_panel'), function(k, v) { var children = v; if(children && children.childNodes) { var requiredScopes = []; $.each((children.childNodes), function (k1, v1){ var inner = v1.innerHTML; if(inner) requiredScopes.push(inner); }); var diff = []; for(var i=0; i < requiredScopes.length; i++) { var s = requiredScopes[i]; if(window.enabledScopes && window.enabledScopes.indexOf(s) == -1) { diff.push(s); } } if(diff.length > 0){ o = v.parentNode.parentNode; $(o.parentNode).find('.api-ic.ic-on').addClass('ic-off'); $(o.parentNode).find('.api-ic.ic-on').removeClass('ic-on'); // sorry, not all scopes are satisfied $(o).find('.api-ic').addClass('ic-warning'); $(o).find('.api-ic').removeClass('ic-error'); } else { o = v.parentNode.parentNode; $(o.parentNode).find('.api-ic.ic-off').addClass('ic-on'); $(o.parentNode).find('.api-ic.ic-off').removeClass('ic-off'); // all scopes are satisfied $(o).find('.api-ic').addClass('ic-info'); $(o).find('.api-ic').removeClass('ic-warning'); $(o).find('.api-ic').removeClass('ic-error');<|fim▁hole|> window.swaggerUi.api.clientAuthorizations.add(OAuthSchemeKey, new SwaggerClient.ApiKeyAuthorization('Authorization', 'Bearer ' + b, 'header')); } } } };<|fim▁end|>
} } });
<|file_name|>issue46.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2010-2021 Google LLC # 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. """Code for issue 46 in or-tools.""" from ortools.constraint_solver import pywrapcp class AssignToStartMin(pywrapcp.PyDecisionBuilder): def __init__(self, intervals): pywrapcp.PyDecisionBuilder.__init__(self) self.__intervals = intervals <|fim▁hole|> interval.SetStartMax(interval.StartMin()) return None def DebugString(self): return 'CustomDecisionBuilder' def NoSequence(): print('NoSequence') solver = pywrapcp.Solver('Ordo') tasks = [] [ tasks.append( solver.FixedDurationIntervalVar(0, 25, 5, False, 'Tasks%i' % i)) for i in range(3) ] print(tasks) disj = solver.DisjunctiveConstraint(tasks, 'Disjunctive') solver.Add(disj) collector = solver.AllSolutionCollector() collector.Add(tasks) intervalPhase = solver.Phase(tasks, solver.INTERVAL_DEFAULT) solver.Solve(intervalPhase, [collector]) print(collector.SolutionCount()) for i in range(collector.SolutionCount()): print("Solution ", i) print(collector.ObjectiveValue(i)) print([collector.StartValue(i, tasks[j]) for j in range(3)]) print([collector.EndValue(i, tasks[j]) for j in range(3)]) def Sequence(): print('Sequence') solver = pywrapcp.Solver('Ordo') tasks = [] [ tasks.append( solver.FixedDurationIntervalVar(0, 25, 5, False, 'Tasks%i' % i)) for i in range(3) ] print(tasks) disj = solver.DisjunctiveConstraint(tasks, 'Disjunctive') solver.Add(disj) sequence = [] sequence.append(disj.SequenceVar()) sequence[0].RankFirst(0) collector = solver.AllSolutionCollector() collector.Add(sequence) collector.Add(tasks) sequencePhase = solver.Phase(sequence, solver.SEQUENCE_DEFAULT) intervalPhase = AssignToStartMin(tasks) # intervalPhase = solver.Phase(tasks, solver.INTERVAL_DEFAULT) mainPhase = solver.Compose([sequencePhase, intervalPhase]) solver.Solve(mainPhase, [collector]) print(collector.SolutionCount()) for i in range(collector.SolutionCount()): print("Solution ", i) print(collector.ObjectiveValue(i)) print([collector.StartValue(i, tasks[j]) for j in range(3)]) print([collector.EndValue(i, tasks[j]) for j in range(3)]) def main(): NoSequence() Sequence() if __name__ == '__main__': main()<|fim▁end|>
def Next(self, solver): for interval in self.__intervals:
<|file_name|>devdiv.js<|end_file_name|><|fim▁begin|>"use strict"; devdiv.directive('devDiv', [function () { return { restrict: 'E', link: function (scope, iElement, iAttrs) {<|fim▁hole|> iElement.addClass("row"); } }; }]) devdiv.controller('NameCtrl', function ($scope, $watch) { });<|fim▁end|>
iElement.addClass("dev-div");
<|file_name|>msgpack_protocol.go<|end_file_name|><|fim▁begin|>package protocol import ( "context" "github.com/coffeehc/logger" "github.com/coffeehc/netx" "github.com/ugorji/go/codec" ) type msgpackProtocol struct { hander *codec.MsgpackHandle interf func() interface{} } //NewMsgpackProcotol cteate a Msgpack Protocol implement func NewMsgpackProcotol(interfFunc func() interface{}) netx.Protocol { p := &msgpackProtocol{hander: new(codec.MsgpackHandle)} p.interf = interfFunc if p.interf == nil { p.interf = func() interface{} { var i interface{} return &i } } return p } func (mp *msgpackProtocol) Encode(cxt context.Context, connContext netx.ConnContext, chain netx.ProtocolChain, data interface{}) { var b []byte encode := codec.NewEncoderBytes(&b, mp.hander) err := encode.Encode(data) if err != nil { logger.Error("Msgpack序列化错误:%s", err) return } chain.Fire(cxt, connContext, b) } func (mp *msgpackProtocol) Decode(cxt context.Context, connContext netx.ConnContext, chain netx.ProtocolChain, data interface{}) { if v, ok := data.([]byte); ok { obj := mp.interf() decode := codec.NewDecoderBytes(v, mp.hander) err := decode.Decode(obj) if err != nil { logger.Error("Msgpack反序列化失败:%s", err) return } data = obj } chain.Fire(cxt, connContext, data) } func (mp *msgpackProtocol) EncodeDestroy() {} <|fim▁hole|><|fim▁end|>
func (mp *msgpackProtocol) DecodeDestroy() {}
<|file_name|>Composite.d.ts<|end_file_name|><|fim▁begin|>import Layer from '../layer/Layer'; import { Pixel } from '../pixel';<|fim▁hole|> export default class CompositeMapRenderer extends MapRenderer { constructor(map: PluggableMap); dispatchRenderEvent(type: EventType, frameState: FrameState): void; forEachLayerAtPixel<T>( pixel: Pixel, frameState: FrameState, hitTolerance: number, callback: (p0: Layer<Source>, p1: Uint8ClampedArray | Uint8Array) => T, layerFilter: (p0: Layer<Source>) => boolean, ): T | undefined; /** * Render. */ renderFrame(frameState: FrameState): void; }<|fim▁end|>
import PluggableMap, { FrameState } from '../PluggableMap'; import EventType from '../render/EventType'; import Source from '../source/Source'; import MapRenderer from './Map';
<|file_name|>dir_2e0ad737c5a35fd799870b9d14d04fcf.js<|end_file_name|><|fim▁begin|>var dir_2e0ad737c5a35fd799870b9d14d04fcf =<|fim▁hole|> [ "main.cpp", "TestOpenGl_2TestOpenGl_2main_8cpp.html", "TestOpenGl_2TestOpenGl_2main_8cpp" ], [ "objloader.cpp", "objloader_8cpp.html", null ], [ "objloader.h", "objloader_8h.html", [ [ "coordinate", "structcoordinate.html", "structcoordinate" ], [ "face", "structface.html", "structface" ], [ "material", "structmaterial.html", "structmaterial" ], [ "texcoord", "structtexcoord.html", "structtexcoord" ], [ "objloader", "classobjloader.html", "classobjloader" ] ] ] ];<|fim▁end|>
[
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import unittest import logging import logging.config import sys import argparse DESCRIPTION=""" Harness for tests in the cloaca/tests/ directory. Run all tests with '--all' or provide a list dotted names of specific tests (eg. legionary.TestLegionary.test_legionary). """ # Set up logging. See logging.json for config def setup_logging( default_path='test_logging.json', default_level=logging.INFO): """Setup logging configuration """ import sys, os, json path = default_path if os.path.exists(path): with open(path, 'rt') as f: config = json.load(f) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level) def main(): parser = argparse.ArgumentParser( description=DESCRIPTION, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--all', action='store_true', help='Run all tests instead of matching pattern.') parser.add_argument('pattern', nargs='*', help=('pattern(s) to match against, eg. "buildings" or ' '"architect.TestArchitect.test_lead_architect".')) parser.add_argument('-v', '--verbose', action='store_true', help='Use verbose test result reporting.') parser.add_argument('-q', '--quiet', action='store_true', help=('Suppress individual test result reporting. Still reports ' 'summary information. Overrides --verbose.')) parser.add_argument('--log-level', default='WARNING', help=('Set app log level during tests. Valid arguments are: ' 'DEBUG, INFO, WARNING, ERROR, CRITICAL. See logging module ' 'documentation.')) args = parser.parse_args() setup_logging() numeric_level = getattr(logging, args.log_level.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: {0!s}'.format(args.log_level)) # This catches the children loggers like cloaca.game logging.getLogger('cloaca').setLevel(numeric_level) loader = unittest.defaultTestLoader if args.all: sys.stderr.write('Running all tests.\n') suites = loader.discover('.', pattern='*.py') else: if len(args.pattern) == 0: sys.stderr.write('ERROR: No tests specified.\n\n') parser.print_help(file=sys.stderr) return sys.stderr.write('Running all tests matching the patterns (' + ', '.join(args.pattern) + ')\n') suites = loader.loadTestsFromNames(args.pattern) test_suite = unittest.TestSuite(suites) # TextTestRunner takes verbosity that can be 0 (quiet), 1 (default), # or 2 (verbose). Quiet overrides verbose. if args.quiet: verbosity = 0 elif args.verbose: verbosity = 2 else: verbosity=1 test_runner = unittest.TextTestRunner(verbosity=verbosity).run(test_suite) <|fim▁hole|> main()<|fim▁end|>
if __name__ == '__main__':
<|file_name|>loader.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from asyncore import write import serial import sys import time import strutils from datafile import DataFile __author__ = 'Trol' # Установка: # python -m pip install pyserial def _bytes(i): return divmod(i, 0x100) class Bootloader: CMD_SYNC = 0 CMD_ABOUT = 1 CMD_READ_FLASH = 2 CMD_READ_EEPROM = 3 CMD_READ_FUSES = 4 CMD_START_APP = 5 CMD_ERASE_PAGE = 6 CMD_WRITE_FLASH_PAGE = 7 CMD_TRANSFER_PAGE = 8 def __init__(self, port_name, bauds): self.serial = serial.serial_for_url(port_name, baudrate=bauds, timeout=1.0) res1 = self.sync(1) if res1 != 1 and res1 > 0: cnt = 1 while True: try: self._read() cnt += 1 except: break print 'skip', cnt, 'bytes' self.sync(100) def close(self): self.serial.close() def sync(self, val): self._cmd(Bootloader.CMD_SYNC, val) try: return self._read() except: return -1 def get_about(self): self._cmd(Bootloader.CMD_ABOUT) info = { 'signature': self._read_char() + self._read_char() + self._read_char() + self._read_char(), 'version': self._read_word(), 'bootloader_start': self._read_dword(), 'bootloader_size': self._read_word(), 'page_size': self._read_word(), 'device_signature': (self._read() << 16) + (self._read() << 8) + self._read() } return info def read_flash(self, addr_in_16_byte_pages, size16): self._cmd(Bootloader.CMD_READ_FLASH, _bytes(addr_in_16_byte_pages), _bytes(size16)) result = [] for i in range(0, size16): v = self._read() result.append(v) return result def read_eeprom(self, addr16, size16): self._cmd(Bootloader.CMD_READ_EEPROM, _bytes(addr16), _bytes(size16)) result = [] for i in range(0, size16): v = self._read() result.append(v) return result def read_fuses(self): pass def start_app(self): self._cmd(Bootloader.CMD_START_APP) def erase_page(self, page_number): self._cmd(Bootloader.CMD_ERASE_PAGE, _bytes(page_number)) def write_flash_page(self, page_number): self._cmd(Bootloader.CMD_WRITE_FLASH_PAGE, _bytes(page_number)) self._read() # TODO == 0 ??? def transfer_page(self, page_data): self._cmd(Bootloader.CMD_TRANSFER_PAGE, page_data) def _read_all(self): while True: try: self.serial.read() return except: return def _write(self, b): self.serial.write(chr(b)) def _cmd(self, *args): for a in args: if type(a) is tuple: for v in a: self._write(v) elif type(a) is list: for v in a: self._write(v) else: self._write(a) def _read(self): b = ord(self.serial.read()) return b def _read_char(self): return self.serial.read() def _read_word(self): return (self._read() << 8) + self._read() def _read_dword(self): return (self._read_word() << 16) + self._read_word() class Loader: def __init__(self, port, baudrate): self.dev = Bootloader(port, baudrate) if self.dev.sync(123) != 123:<|fim▁hole|> if about['signature'] != 'TSBL': print "Wrong bootloader signature" sys.exit(-1) self.page_size = about['page_size'] self.bootloader_size = about['bootloader_size'] self.bootloader_start = about['bootloader_start'] self.firmware_pages = self.bootloader_start / self.page_size print 'page sizes', self.page_size print 'pages', self.firmware_pages def read_all_flash(self, with_loader): start = time.time() size = self.bootloader_start if with_loader: size += self.bootloader_size #return self.read_flash(0, size) ret = self.read_flash(0, size) tm = time.time() - start print 'read flash time', tm, 'speed=', 1e6*tm/size, 'us/byte' return ret def read_flash(self, offset, size): result = [] while size > 0: read_size = size if size < 0xffff else 0xffff dt = self.dev.read_flash(offset >> 4, read_size) result.extend(dt) offset += read_size size -= read_size return result def _find_changed_pages(self, data): if len(data) > self.bootloader_start: data = data[0:self.bootloader_start] pages_in_data = len(data) / self.page_size if pages_in_data*self.page_size < len(data): pages_in_data += 1 print 'pages_in_data', pages_in_data read = self.read_flash(0, pages_in_data*self.page_size) changed_pages = pages_in_data*[False] changes_count = 0 # TODO detect if page is empty !!! for page in range(0, pages_in_data): data_page_is_empty = True for o in range(0, self.page_size): if data[page * self.page_size + o] != 0xff: data_page_is_empty = False break if data_page_is_empty: continue for o in range(0, self.page_size): if data[page * self.page_size + o] != read[page * self.page_size + o]: changed_pages[page] = True print '! offset', o, 'page', page, '->', hex(page * self.page_size + o), ' data =', hex(data[page * self.page_size + o]), 'vs readed =', hex(read[page * self.page_size + o]) changes_count += 1 break if changes_count == 0: print 'No changes' else: print 'changed pages', changes_count, 'from', len(changed_pages) # print changed_pages return changed_pages def write_flash(self, data): while len(data) < self.firmware_pages * self.page_size: data.append(0xff) changed_pages = self._find_changed_pages(data) start = time.time() write_counter = 0 for page in range(0, len(changed_pages)): if not changed_pages[page]: continue self.dev.transfer_page(data[page*self.page_size:page*self.page_size + self.page_size]) #print 'erase', page self.dev.erase_page(page) #print 'write', page self.dev.write_flash_page(page) write_counter += 1 tm = time.time() - start if write_counter > 0: print 'write flash time', tm, 1e6*tm/write_counter/self.page_size, 'us/byte' def read_and_save_flash(self, filename, with_bootloader): _df = DataFile([]) _df.data = self.read_all_flash(with_bootloader) print 'Read', len(_df.data), 'bytes' _df.save(filename) def print_dump(lst): s = '' i = 0 for v in lst: vs = hex(v)[2:] i += 1 if len(vs) == 1: vs = '0' + vs s += vs + ' ' if (i % 16) == 0: print s s = '' #fw = DataFile('/Users/trol/Projects/radio/avr-lcd-module-128x128/build/avr-lcd-module-128x128.hex') fw = DataFile('/Users/trol/Projects/radio/avr-ic-tester-v2/firmware/tester/build/ic-tester-main.hex') # read 230400 44.0383300884 us/byte #write 234000 256.21552423 us/byte # 255.434597666 us/byte #l = Loader('/dev/tty.wchusbserial14230', 57600) #l = Loader('/dev/tty.wchusbserial14230', 230400) l = Loader('/dev/tty.wchusbserial14220', 153600) print l.dev.get_about() l.read_and_save_flash('flash_with_loader.hex', True) l.read_and_save_flash('flash_without_loader.hex', False) l.write_flash(fw.data) l.dev.start_app() 1/0 # df = DataFile([]) # # df.load('flash.hex') # df.save('flash2.hex') dev = Bootloader('/dev/tty.wchusbserial14230', 57600) print dev.sync(10) print dev.get_about() eeprom = dev.read_eeprom(0, 1024) # flash = dev.read_flash(0x7000, 0x1000) flash = dev.read_flash(0x0000, 32*1024) # print_dump(flash) print_dump(flash) df = DataFile(flash) df.save('flash.hex') dev.start_app()<|fim▁end|>
print "Can't connect to bootloader" sys.exit(-1) about = self.dev.get_about()
<|file_name|>declarations.d.ts<|end_file_name|><|fim▁begin|>/* Declaration files are how the Typescript compiler knows about the type information(or shape) of an object. They're what make intellisense work and make Typescript know all about your code. A wildcard module is declared below to allow third party libraries to be used in an app even if they don't provide their own type declarations. To learn more about using third party libraries in an Ionic app, check out the docs here: http://ionicframework.com/docs/v2/resources/third-party-libs/ For more info on type definition files, check out the Typescript docs here: https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html<|fim▁hole|><|fim▁end|>
*/
<|file_name|>store.js<|end_file_name|><|fim▁begin|>import { compose, combineReducers, createStore } from 'redux'; import { devTools } from 'redux-devtools'; import twist from './reducers/twist'; import form from './reducers/form'; const twister = combineReducers({ twist, form });<|fim▁hole|><|fim▁end|>
const finalCreateStore = compose(devTools())(createStore); export default finalCreateStore(twister);
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import family_aux_mass_edit from . import family_associate_to_family_aux<|fim▁hole|>from . import family_aux_associate_to_address_aux<|fim▁end|>
<|file_name|>images.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # encoding: utf-8 import argparse import cmd import os import shlex import sys from tabulate import tabulate import time from talus_client.cmds import TalusCmdBase import talus_client.api import talus_client.errors as errors from talus_client.models import Image,Field class ImageCmd(TalusCmdBase): """The Talus images command processor """ command_name = "image" def do_list(self, args): """List existing images in Talus image list Examples: List all images in Talus: image list """ parts = shlex.split(args) search = self._search_terms(parts, user_default_filter=False) if "sort" not in search: search["sort"] = "timestamps.created" if "--all" not in parts and "num" not in search: search["num"] = 20 self.out("showing first 20 results, use --all to see everything") fields = [] for image in self._talus_client.image_iter(**search): fields.append([ image.id, image.name, image.status["name"], image.tags, self._nice_name(image, "base_image") if image.base_image is not None else None, self._nice_name(image, "os"), image.md5, ]) print(tabulate(fields, headers=Image.headers())) def do_info(self, args): """List detailed information about an image info ID_OR_NAME Examples: List info about the image named "Win 7 Pro" image info "Win 7 Pro" """ pass def do_import(self, args): """Import an image into Talus import FILE -n NAME -o OSID [-d DESC] [-t TAG1,TAG2,..] [-u USER] [-p PASS] [-i] FILE The file to import -o,--os ID or name of the operating system model -n,--name The name of the resulting image (default: basename(FILE)) -d,--desc A description of the image (default: "") -t,--tags Tags associated with the image (default: []) -f,--file-id The id of an already-uploaded file (NOT A NORMAL USE CASE) -u,--username The username to be used in the image (default: user) -p,--password The password to be used in the image (default: password) -i,--interactive To interact with the imported image for setup (default: False) Examples: To import an image from VMWare at ``~/images/win7pro.vmdk`` named "win 7 pro test" and to be given a chance to perform some manual setup/checks: image import ~/images/win7pro.vmdk -n "win 7 pro test" -i -o "win7pro" -t windows7,x64,IE8 """ parser = argparse.ArgumentParser() parser.add_argument("file", type=str) parser.add_argument("--os", "-o") parser.add_argument("--name", "-n") parser.add_argument("--desc", "-d", default="desc") parser.add_argument("--file-id", "-f", default=None) parser.add_argument("--tags", "-t", default="") parser.add_argument("--username", "-u", default="user") parser.add_argument("--password", "-p", default="password") parser.add_argument("--interactive", "-i", action="store_true", default=False) args = parser.parse_args(shlex.split(args)) args.tags = args.tags.split(",") if args.name is None: args.name = os.path.basename(args.file) image = self._talus_client.image_import( image_path = args.file, image_name = args.name, os_id = args.os, desc = args.desc, tags = args.tags, file_id = args.file_id, username = args.username, password = args.password ) self._wait_for_image(image, args.interactive) def do_edit(self, args): """Edit an existing image. Interactive mode only """ if args.strip() == "": raise errors.TalusApiError("you must provide a name/id of an image to edit it") parts = shlex.split(args) leftover = [] image_id_or_name = None search = self._search_terms(parts, out_leftover=leftover) if len(leftover) > 0: image_id_or_name = leftover[0] image = self._resolve_one_model(image_id_or_name, Image, search) if image is None: raise errors.TalusApiError("could not find talus image with id {!r}".format(image_id_or_name)) while True: model_cmd = self._make_model_cmd(image) cancelled = model_cmd.cmdloop() if cancelled: break error = False if image.os is None:<|fim▁hole|> if image.name is None or image.name == "": self.err("You must specify a name for the image") error = True if image.base_image is None: self.err("You must specify the base_image for your new image") error = True if error: continue try: image.timestamps = {"modified": time.time()} image.save() self.ok("edited image {}".format(image.id)) self.ok("note that this DOES NOT start the image for configuring!") except errors.TalusApiError as e: self.err(e.message) return def do_create(self, args): """Create a new image in talus using an existing base image. Anything not explicitly specified will be inherited from the base image, except for the name, which is required. create -n NAME -b BASEID_NAME [-d DESC] [-t TAG1,TAG2,..] [-u USER] [-p PASS] [-o OSID] [-i] -o,--os ID or name of the operating system model -b,--base ID or name of the base image -n,--name The name of the resulting image (default: basename(FILE)) -d,--desc A description of the image (default: "") -t,--tags Tags associated with the image (default: []) --shell Forcefully drop into an interactive shell -v,--vagrantfile A vagrant file that will be used to congfigure the image -i,--interactive To interact with the imported image for setup (default: False) Examples: To create a new image based on the image with id 222222222222222222222222 and adding a new description and allowing for manual user setup: image create -b 222222222222222222222222 -d "some new description" -i """ args = shlex.split(args) if self._go_interactive(args): image = Image() self._prep_model(image) image.username = "user" image.password = "password" image.md5 = " " image.desc = "some description" image.status = { "name": "create", "vagrantfile": None, "user_interaction": True } while True: model_cmd = self._make_model_cmd(image) model_cmd.add_field( "interactive", Field(True), lambda x,v: x.status.update({"user_interaction": v}), lambda x: x.status["user_interaction"], desc="If the image requires user interaction for configuration", ) model_cmd.add_field( "vagrantfile", Field(str), lambda x,v: x.status.update({"vagrantfile": open(v).read()}), lambda x: x.status["vagrantfile"], desc="The path to the vagrantfile that will configure the image" ) cancelled = model_cmd.cmdloop() if cancelled: break error = False if image.os is None: self.err("You must specify the os") error = True if image.name is None or image.name == "": self.err("You must specify a name for the image") error = True if image.base_image is None: self.err("You must specify the base_image for your new image") error = True if error: continue try: image.timestamps = {"created": time.time()} image.save() self.ok("created new image {}".format(image.id)) except errors.TalusApiError as e: self.err(e.message) else: self._wait_for_image(image, image.status["user_interaction"]) return parser = self._argparser() parser.add_argument("--os", "-o", default=None) parser.add_argument("--base", "-b", default=None) parser.add_argument("--name", "-n", default=None) parser.add_argument("--desc", "-d", default="") parser.add_argument("--tags", "-t", default="") parser.add_argument("--vagrantfile", "-v", default=None, type=argparse.FileType("rb")) parser.add_argument("--interactive", "-i", action="store_true", default=False) args = parser.parse_args(args) if args.name is None: raise errors.TalusApiError("You must specify an image name") vagrantfile_contents = None if args.vagrantfile is not None: vagrantfile_contents = args.vagrantfile.read() if args.tags is not None: args.tags = args.tags.split(",") error = False validation = { "os" : "You must set the os", "base" : "You must set the base", "name" : "You must set the name", } error = False for k,v in validation.iteritems(): if getattr(args, k) is None: self.err(v) error = True if error: parser.print_help() return image = self._talus_client.image_create( image_name = args.name, base_image_id_or_name = args.base, os_id = args.os, desc = args.desc, tags = args.tags, vagrantfile = vagrantfile_contents, user_interaction = args.interactive ) self._wait_for_image(image, args.interactive) def do_configure(self, args): """Configure an existing image in talus configure ID_OR_NAME [-v PATH_TO_VAGRANTFILE] [-i] id_or_name The ID or name of the image that is to be configured (required) -i,--interactive To interact with the imported image for setup (default: False) -v,--vagrantfile The path to the vagrantfile that should be used to configure the image (default=None) Examples: To configure an image named "Windows 7 x64 Test", using a vagrantfile found at `~/vagrantfiles/UpdateIE` with no interaction: configure "Windows 7 x64 Test" --vagrantfile ~/vagrantfiles/UpdateIE """ parser = self._argparser() parser.add_argument("image_id_or_name", type=str) parser.add_argument("--interactive", "-i", action="store_true", default=False) parser.add_argument("--vagrantfile", "-v", default=None, type=argparse.FileType("rb")) args = parser.parse_args(shlex.split(args)) vagrantfile_contents = None if args.vagrantfile is not None: vagrantfile_contents = args.vagrantfile.read() image = self._talus_client.image_configure( args.image_id_or_name, vagrantfile=vagrantfile_contents, user_interaction=args.interactive ) if image is None: return self._wait_for_image(image, args.interactive) def do_delete(self, args): """Attempt to delete the specified image. This may fail if the image is the base image for another image. delete id_or_name id_or_name The ID or name of the image that is to be deleted """ args = shlex.split(args) image = self._talus_client.image_delete(args[0]) if image is None: return try: while image.status["name"] == "delete": time.sleep(1) image.refresh() if "error" in image.status: self.err("could not delete image due to: " + image.status["error"]) else: self.ok("image succesfully deleted") except: self.err("could not delete image") # ---------------------------- # UTILITY # ---------------------------- def _wait_for_image(self, image, interactive): """Wait for the image to be ready, either for interactive interaction or to enter the ready state""" if interactive: while image.status["name"] != "configuring": time.sleep(1) image.refresh() self.ok("Image is up and running at {}".format(image.status["vnc"]["vnc"]["uri"])) self.ok("Shutdown (yes, nicely shut it down) to save your changes") else: while image.status["name"] != "ready": time.sleep(1) image.refresh() self.ok("image {!r} is ready for use".format(image.name))<|fim▁end|>
self.err("You must specify the os") error = True
<|file_name|>footy.py<|end_file_name|><|fim▁begin|>T = input() while(T): T -= 1 buff = [] a,b = [int(i) for i in raw_input().split()] buff.append(b) pt = 0 while(a): a -= 1 c = [i for i in raw_input().split()]<|fim▁hole|> buff.append(c[1]) #pt = len(buff)-1 k = len(buff)-1 l = len(buff)-2 #print buff[k] if c[0] == "B": k,l = l,k #print k print buff,buff[k] print "Player " + str(buff[k])<|fim▁end|>
if len(c)==2: c[1] = int(c[1]) if c[0] == "P":
<|file_name|>packagetools.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # JDownloader/src/jd/controlling/LinkGrabberPackager.java import re from urlparse import urlparse def matchFirst(string, *args): """ matches against list of regexp and returns first match""" for patternlist in args: for pattern in patternlist: r = pattern.search(string) if r is not None: name = r.group(1) return name return string def parseNames(files): """ Generates packages names from name, data lists :param files: list of (name, data) :return: packagenames mapt to data lists (eg. urls) """ packs = {} endings = "\\.(3gp|7zip|7z|abr|ac3|aiff|aifc|aif|ai|au|avi|bin|bz2|cbr|cbz|ccf|cue|cvd|chm|dta|deb|divx|djvu|dlc|dmg|doc|docx|dot|eps|exe|ff|flv|f4v|gsd|gif|gz|iwd|iso|ipsw|java|jar|jpg|jpeg|jdeatme|load|mws|mw|m4v|m4a|mkv|mp2|mp3|mp4|mov|movie|mpeg|mpe|mpg|msi|msu|msp|nfo|npk|oga|ogg|ogv|otrkey|pkg|png|pdf|pptx|ppt|pps|ppz|pot|psd|qt|rmvb|rm|rar|ram|ra|rev|rnd|r\\d+|rpm|run|rsdf|rtf|sh(!?tml)|srt|snd|sfv|swf|tar|tif|tiff|ts|txt|viv|vivo|vob|wav|wmv|xla|xls|xpi|zeno|zip|z\\d+|_[_a-z]{2}|\\d+$)" rarPats = [re.compile("(.*)(\\.|_|-)pa?r?t?\\.?[0-9]+.(rar|exe)$", re.I), re.compile("(.*)(\\.|_|-)part\\.?[0]*[1].(rar|exe)$", re.I), re.compile("(.*)\\.rar$", re.I), re.compile("(.*)\\.r\\d+$", re.I), re.compile("(.*)(\\.|_|-)\\d+$", re.I)] zipPats = [re.compile("(.*)\\.zip$", re.I), re.compile("(.*)\\.z\\d+$", re.I), re.compile("(?is).*\\.7z\\.[\\d]+$", re.I), re.compile("(.*)\\.a.$", re.I)] ffsjPats = [re.compile("(.*)\\._((_[a-z])|([a-z]{2}))(\\.|$)"), re.compile("(.*)(\\.|_|-)[\\d]+(" + endings + "$)", re.I)] iszPats = [re.compile("(.*)\\.isz$", re.I), re.compile("(.*)\\.i\\d{2}$", re.I)] pat1 = re.compile("(\\.?CD\\d+)", re.I) pat2 = re.compile("(\\.?part\\d+)", re.I) pat3 = re.compile("(.+)[\\.\\-_]+$") pat4 = re.compile("(.+)\\.\\d+\\.xtm$") for file, url in files: patternMatch = False if file is None: continue # remove trailing / name = file.rstrip('/') # extract last path part .. if there is a path split = name.rsplit("/", 1) if len(split) > 1: name = split.pop(1) #check if a already existing package may be ok for this file # found = False # for pack in packs: # if pack in file: # packs[pack].append(url) # found = True # break # # if found: continue # unrar pattern, 7zip/zip and hjmerge pattern, isz pattern, FFSJ pattern before = name name = matchFirst(name, rarPats, zipPats, iszPats, ffsjPats) if before != name: patternMatch = True # xtremsplit pattern r = pat4.search(name)<|fim▁hole|> r = pat1.search(name) if r is not None: name = name.replace(r.group(0), "") patternMatch = True r = pat2.search(name) if r is not None: name = name.replace(r.group(0), "") patternMatch = True # additional checks if extension pattern matched if patternMatch: # remove extension index = name.rfind(".") if index <= 0: index = name.rfind("_") if index > 0: length = len(name) - index if length <= 4: name = name[:-length] # remove endings like . _ - r = pat3.search(name) if r is not None: name = r.group(1) # replace . and _ with space name = name.replace(".", " ") name = name.replace("_", " ") name = name.strip() else: name = "" # fallback: package by hoster if not name: name = urlparse(file).hostname if name: name = name.replace("www.", "") # fallback : default name if not name: name = "unknown" # build mapping if name in packs: packs[name].append(url) else: packs[name] = [url] return packs if __name__ == "__main__": from os.path import join from pprint import pprint f = open(join("..", "..", "testlinks2.txt"), "rb") urls = [(x.strip(), x.strip()) for x in f.readlines() if x.strip()] f.close() print "Having %d urls." % len(urls) packs = parseNames(urls) pprint(packs) print "Got %d urls." % sum([len(x) for x in packs.itervalues()])<|fim▁end|>
if r is not None: name = r.group(1) # remove part and cd pattern
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE" def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity)<|fim▁hole|> from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value)<|fim▁end|>
DBSESSION().merge(line) def downgrade():
<|file_name|>issue-3556.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[deriving(Show)] enum Token { Text(String), ETag(Vec<String>, String), UTag(Vec<String>, String), Section(Vec<String>, bool, Vec<Token>, String, String, String, String, String), IncompleteSection(Vec<String>, bool, String, bool),<|fim▁hole|>} fn check_strs(actual: &str, expected: &str) -> bool { if actual != expected { println!("Found {}, but expected {}", actual, expected); return false; } return true; } pub fn main() { // assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")")); // assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())), // "ETag(@~[ ~\"foo\" ], @~\"bar\")")); let t = Text("foo".to_string()); let u = Section(vec!["alpha".to_string()], true, vec![t], "foo".to_string(), "foo".to_string(), "foo".to_string(), "foo".to_string(), "foo".to_string()); let v = format!("{}", u); // this is the line that causes the seg fault assert!(v.len() > 0); }<|fim▁end|>
Partial(String, String, String),
<|file_name|>LatestNoYoYoValidatedPonderationRule.java<|end_file_name|><|fim▁begin|>/** * Premium Markets is an automated stock market analysis system. * It implements a graphical environment for monitoring stock markets technical analysis * major indicators, for portfolio management and historical data charting. * In its advanced packaging -not provided under this license- it also includes : * Screening of financial web sites to pick up the best market shares, * Price trend prediction based on stock markets technical analysis and indices rotation, * Back testing, Automated buy sell email notifications on trend signals calculated over * markets and user defined portfolios. * With in mind beating the buy and hold strategy. * Type 'Premium Markets FORECAST' in your favourite search engine for a free workable demo. * * Copyright (C) 2008-2014 Guillaume Thoreton * * This file is part of Premium Markets. * * Premium Markets is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by <|fim▁hole|> * 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 Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.finance.pms.events.pounderationrules; import java.util.HashMap; import com.finance.pms.admin.install.logging.MyLogger; import com.finance.pms.datasources.shares.Stock; import com.finance.pms.events.SymbolEvents; import com.finance.pms.events.Validity; public class LatestNoYoYoValidatedPonderationRule extends LatestEventsPonderationRule { private static final long serialVersionUID = 573802685420097964L; private static MyLogger LOGGER = MyLogger.getLogger(LatestNoYoYoValidatedPonderationRule.class); private HashMap<Stock, Validity> tuningValidityList; public LatestNoYoYoValidatedPonderationRule(Integer sellThreshold, Integer buyThreshold, HashMap<Stock, Validity> tuningValidityList) { super(sellThreshold, buyThreshold); this.tuningValidityList = tuningValidityList; } @Override public int compare(SymbolEvents o1, SymbolEvents o2) { SymbolEvents se1 = o1; SymbolEvents se2 = o2; PonderationRule p1 = new LatestNoYoYoValidatedPonderationRule(sellThreshold, buyThreshold, tuningValidityList); PonderationRule p2 = new LatestNoYoYoValidatedPonderationRule(sellThreshold, buyThreshold, tuningValidityList); return compareCal(se1, se2, p1, p2); } @Override public Float finalWeight(SymbolEvents symbolEvents) { Validity validity = tuningValidityList.get(symbolEvents.getStock()); boolean isValid = false; if (validity != null) { isValid = validity.equals(Validity.SUCCESS); } else { LOGGER.warn("No validity information found for " + symbolEvents.getStock() + " while parsing events " + symbolEvents + ". Neural trend was not calculated for that stock."); } if (isValid) { return super.finalWeight(symbolEvents); } else { return 0.0f; } } @Override public Signal initSignal(SymbolEvents symbolEvents) { return new LatestNoYoYoValidatedSignal(symbolEvents.getEventDefList()); } @Override protected void postCondition(Signal signal) { LatestNoYoYoValidatedSignal LVSignal = (LatestNoYoYoValidatedSignal) signal; //Updating cumulative event signal with Bull Bear neural events. switch (LVSignal.getNbTrendChange()) { case 0 : //No event detected break; case 1 : //One Type of Event, no yoyo : weight = sum(cumulative events) + bullish - bearish signal.setSignalWeight(signal.getSignalWeight() + LVSignal.getNbBullish() - LVSignal.getNbBearish()); break; default : //Yoyo, Bull/Bear, we ignore the signal LOGGER.warn("Yo yo trend detected."); break; } } }<|fim▁end|>
* the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. *
<|file_name|>doc.go<|end_file_name|><|fim▁begin|><|fim▁hole|>// +k8s:defaulter-gen=TypeMeta // +k8s:defaulter-gen-input=../../../../../../../../github.com/openshift/api/template/v1 // +groupName=template.openshift.io // Package v1 is the v1 version of the API. package v1<|fim▁end|>
// +k8s:conversion-gen=github.com/openshift/openshift-apiserver/pkg/template/apis/template // +k8s:conversion-gen-external-types=github.com/openshift/api/template/v1
<|file_name|>volunteer.app.js<|end_file_name|><|fim▁begin|>/***************************************************** * Copyright (c) 2014 Colby Brown * * This program is released under the MIT license. * * For more information about the MIT license, * * visit http://opensource.org/licenses/MIT * *****************************************************/ var app = angular.module('volunteer', [ 'ajoslin.promise-tracker', 'cn.offCanvas', 'ncy-angular-breadcrumb', 'ngCookies', 'ui.bootstrap', 'ui.router', 'accentbows.controller', 'alerts.controller', 'bears.controller', 'configure.controller', 'confirm.controller', 'home.volunteer.controller', 'letters.controller', 'mums.volunteer.controller', 'mumtypes.controller', 'accessoriesAdd.controller', 'accessoriesAll.controller', 'accessoriesEdit.controller', 'accentbows.service', 'alerts.service', 'bears.service', 'confirm.service', 'letters.service', 'mum.service', 'mumtypes.service', 'pay.service', 'accessories.service', 'volunteer.service']); app.config(function($stateProvider, $urlRouterProvider, $httpProvider) { $urlRouterProvider.otherwise('/home'); $stateProvider .state('home', { url: '/home', templateUrl: 'public/views/volunteer/home/index.html', controller: 'homeController' }) .state('home.logout', { url: '/logout', onEnter: function($cookieStore, $rootScope, $state) { $cookieStore.remove('volunteerToken'); $rootScope.updateHeader(); $state.go('home'); } }) .state('configure', { url: '/configure', templateUrl: 'public/views/volunteer/configure/index.html', controller: 'configureController' }) .state('configure.accentbows', { url: '/accentbows', templateUrl: 'public/views/volunteer/accentbows/index.html', controller: 'accentbowsController' }) .state('configure.bears', { url: '/bears', templateUrl: 'public/views/volunteer/bears/index.html', controller: 'bearsController' }) .state('configure.letters', { url: '/letters', templateUrl: 'public/views/volunteer/letters/index.html', controller: 'lettersController' }) .state('configure.volunteers', { url: '/volunteers', templateUrl: 'public/views/volunteer/configure/volunteers.html', controller: 'configureVolunteerController' }) .state('configure.yearly', { url: '/yearly', templateUrl: 'public/views/volunteer/configure/yearly.html', controller: 'configureYearlyController' }) .state('mums', { url: '/mums', templateUrl: 'public/views/volunteer/mums/index.html', controller: 'mumsController', abstract: true }) .state('mums.all', { url: '', templateUrl: 'public/views/volunteer/mums/all.html', controller: 'mumsAllController' }) .state('mums.view', { url: '/view/:mumId', templateUrl: 'public/views/volunteer/mums/view.html', controller: 'mumsViewController' }) .state('configure.mumtypes', { url: '/mumtypes', templateUrl: 'public/views/volunteer/mumtypes/index.html', controller: 'mumtypesController', abstract: true }) .state('configure.mumtypes.grade', { url: '', templateUrl: 'public/views/volunteer/mumtypes/grade.html', controller: 'mumtypesItemsController', resolve: { itemDetails: function(MumtypesService) { return { formController: 'mumtypesEditGradeController', service: MumtypesService.grades, fetch: [] }; } } }) .state('configure.mumtypes.product', { url: '/:gradeId', templateUrl: 'public/views/volunteer/mumtypes/product.html', controller: 'mumtypesItemsController', resolve: { itemDetails: function($stateParams, MumtypesService) { return { formController: 'mumtypesEditProductController', service: MumtypesService.products, fetch: [ function($scope) { return MumtypesService.grades.fetch($stateParams.gradeId) .success(function(data) { $scope.grade = data; }); } ] }; } } }) .state('configure.mumtypes.size', { url: '/:gradeId/:productId', templateUrl: 'public/views/volunteer/mumtypes/size.html', controller: 'mumtypesItemsController', resolve: { itemDetails: function($stateParams, MumtypesService) { return { formController: 'mumtypesEditSizeController', service: MumtypesService.sizes, fetch: [ function($scope) { return MumtypesService.grades.fetch($stateParams.gradeId) .success(function(data) { $scope.grade = data; }); }, function($scope) { return MumtypesService.products.fetch($stateParams.productId) .success(function(data) { $scope.product = data; }); } ] }; } } }) .state('configure.mumtypes.backing', { url: '/:gradeId/:productId/:sizeId', templateUrl: 'public/views/volunteer/mumtypes/backing.html', controller: 'mumtypesItemsController', resolve: { itemDetails: function($stateParams, MumtypesService) { return { formController: 'mumtypesEditBackingController', service: MumtypesService.backings, fetch: [ function($scope) { return MumtypesService.grades.fetch($stateParams.gradeId) .success(function(data) { $scope.grade = data; }); }, function($scope) { return MumtypesService.products.fetch($stateParams.productId) .success(function(data) { $scope.product = data; }); }, function($scope) { return MumtypesService.sizes.fetch($stateParams.sizeId) .success(function(data) { $scope.size = data; }); } ] } } } }) .state('configure.accessories', { url: '/accessories', template: '<ui-view />', abstract: true }) .state('configure.accessories.all', { url: '', templateUrl: 'public/views/volunteer/accessories/all.html', controller: 'accessoriesAllController' }) .state('configure.accessories.add', { url: '/add', templateUrl: 'public/views/volunteer/accessories/edit.html', controller: 'accessoriesAddController' }) .state('configure.accessories.edit', { url: '/edit/:accessoryId', templateUrl: 'public/views/volunteer/accessories/edit.html', controller: 'accessoriesEditController' }); $httpProvider.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'}; $httpProvider.defaults.headers.put = {'Content-Type': 'application/x-www-form-urlencoded'}; //PHP does not play nice with this feature. It's no big deal. //$locationProvider.html5Mode(true); }); app.run(['$cookieStore', '$injector', function($cookieStore, $injector) { $injector.get("$http").defaults.transformRequest.unshift(function(data, headersGetter) { var token = $cookieStore.get('volunteerToken'); if (token) { headersGetter()['Authentication'] = token.jwt; } if (data === undefined) { return data; } // If this is not an object, defer to native stringification. if ( ! angular.isObject( data ) ) { return( ( data == null ) ? "" : data.toString() ); } var buffer = []; // Serialize each key in the object. for ( var name in data ) { if ( ! data.hasOwnProperty( name ) ) { continue; } var value = data[ name ]; buffer.push( encodeURIComponent( name ) + "=" + encodeURIComponent( ( value == null ) ? "" : value ) ); } // Serialize the buffer and clean it up for transportation. var source = buffer.join( "&" ).replace( /%20/g, "+" ); return( source ); });<|fim▁hole|> }]); app.controller('headerController', function($rootScope, $cookieStore) { $rootScope.updateHeader = function() { $rootScope.volunteer = $cookieStore.get('volunteerToken'); }; $rootScope.updateHeader(); }); //This filter is used to convert MySQL datetimes into AngularJS a readable ISO format. app.filter('dateToISO', function() { return function(badTime) { if (!badTime) return ""; if (badTime.date) { return badTime.date.replace(/(.+) (.+)/, "$1T$2Z"); } else { return badTime.replace(/(.+) (.+)/, "$1T$2Z"); } }; });<|fim▁end|>
<|file_name|>js_kJRR2EPkdTyr2CIdeTvE1Z1h-ltSkNI_HTuwHAsTNDE.js<|end_file_name|><|fim▁begin|>(function($) { Drupal.wysiwyg.editor.init.ckeditor = function(settings) { window.CKEDITOR_BASEPATH = settings.global.editorBasePath + '/'; CKEDITOR.basePath = window.CKEDITOR_BASEPATH; // Drupal.wysiwyg.editor['initialized']['ckeditor'] = true; // Plugins must only be loaded once. Only the settings from the first format // will be used but they're identical anyway. var registeredPlugins = {}; for (var format in settings) { if (Drupal.settings.wysiwyg.plugins[format]) { // Register native external plugins. // Array syntax required; 'native' is a predefined token in JavaScript. for (var pluginName in Drupal.settings.wysiwyg.plugins[format]['native']) { if (!registeredPlugins[pluginName]) { var plugin = Drupal.settings.wysiwyg.plugins[format]['native'][pluginName]; CKEDITOR.plugins.addExternal(pluginName, plugin.path, plugin.fileName); registeredPlugins[pluginName] = true; } } // Register Drupal plugins. for (var pluginName in Drupal.settings.wysiwyg.plugins[format].drupal) { if (!registeredPlugins[pluginName]) { Drupal.wysiwyg.editor.instance.ckeditor.addPlugin(pluginName, Drupal.settings.wysiwyg.plugins[format].drupal[pluginName], Drupal.settings.wysiwyg.plugins.drupal[pluginName]); registeredPlugins[pluginName] = true; } } } } }; /** * Attach this editor to a target element. */ Drupal.wysiwyg.editor.attach.ckeditor = function(context, params, settings) { // Apply editor instance settings. CKEDITOR.config.customConfig = ''; settings.on = { instanceReady: function(ev) { var editor = ev.editor; // Get a list of block, list and table tags from CKEditor's XHTML DTD. // @see http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Output_Formatting. var dtd = CKEDITOR.dtd; var tags = CKEDITOR.tools.extend({}, dtd.$block, dtd.$listItem, dtd.$tableContent); // Set source formatting rules for each listed tag except <pre>. // Linebreaks can be inserted before or after opening and closing tags. if (settings.apply_source_formatting) { // Mimic FCKeditor output, by breaking lines between tags. for (var tag in tags) { if (tag == 'pre') { continue; } this.dataProcessor.writer.setRules(tag, { indent: true, breakBeforeOpen: true, breakAfterOpen: false, breakBeforeClose: false, breakAfterClose: true }); } } else { // CKEditor adds default formatting to <br>, so we want to remove that // here too. tags.br = 1; // No indents or linebreaks; for (var tag in tags) { if (tag == 'pre') { continue; } this.dataProcessor.writer.setRules(tag, { indent: false, breakBeforeOpen: false, breakAfterOpen: false, breakBeforeClose: false, breakAfterClose: false }); } } }, pluginsLoaded: function(ev) { // Override the conversion methods to let Drupal plugins modify the data. var editor = ev.editor; if (editor.dataProcessor && Drupal.settings.wysiwyg.plugins[params.format]) { editor.dataProcessor.toHtml = CKEDITOR.tools.override(editor.dataProcessor.toHtml, function(originalToHtml) { // Convert raw data for display in WYSIWYG mode. return function(data, fixForBody) { for (var plugin in Drupal.settings.wysiwyg.plugins[params.format].drupal) { if (typeof Drupal.wysiwyg.plugins[plugin].attach == 'function') { data = Drupal.wysiwyg.plugins[plugin].attach(data, Drupal.settings.wysiwyg.plugins.drupal[plugin], editor.name); data = Drupal.wysiwyg.instances[params.field].prepareContent(data); } } return originalToHtml.call(this, data, fixForBody); }; }); editor.dataProcessor.toDataFormat = CKEDITOR.tools.override(editor.dataProcessor.toDataFormat, function(originalToDataFormat) { // Convert WYSIWYG mode content to raw data. return function(data, fixForBody) { data = originalToDataFormat.call(this, data, fixForBody); for (var plugin in Drupal.settings.wysiwyg.plugins[params.format].drupal) { if (typeof Drupal.wysiwyg.plugins[plugin].detach == 'function') { data = Drupal.wysiwyg.plugins[plugin].detach(data, Drupal.settings.wysiwyg.plugins.drupal[plugin], editor.name); } } return data; }; }); } }, selectionChange: function (event) { var pluginSettings = Drupal.settings.wysiwyg.plugins[params.format]; if (pluginSettings && pluginSettings.drupal) { $.each(pluginSettings.drupal, function (name) { var plugin = Drupal.wysiwyg.plugins[name]; if ($.isFunction(plugin.isNode)) { var node = event.data.selection.getSelectedElement(); var state = plugin.isNode(node ? node.$ : null) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF; event.editor.getCommand(name).setState(state); } }); } }, focus: function(ev) { Drupal.wysiwyg.activeId = ev.editor.name; } }; // Attach editor. CKEDITOR.replace(params.field, settings); }; /** * Detach a single or all editors. * * @todo 3.x: editor.prototype.getInstances() should always return an array * containing all instances or the passed in params.field instance, but * always return an array to simplify all detach functions. */ Drupal.wysiwyg.editor.detach.ckeditor = function(context, params) { if (typeof params != 'undefined') { var instance = CKEDITOR.instances[params.field]; if (instance) { instance.destroy(); } } else { for (var instanceName in CKEDITOR.instances) { CKEDITOR.instances[instanceName].destroy(); } } }; Drupal.wysiwyg.editor.instance.ckeditor = { addPlugin: function(pluginName, settings, pluginSettings) { CKEDITOR.plugins.add(pluginName, { // Wrap Drupal plugin in a proxy pluygin. init: function(editor) { if (settings.css) { editor.on('mode', function(ev) { if (ev.editor.mode == 'wysiwyg') { // Inject CSS files directly into the editing area head tag. $('head', $('#cke_contents_' + ev.editor.name + ' iframe').eq(0).contents()).append('<link rel="stylesheet" href="' + settings.css + '" type="text/css" >'); } }); } if (typeof Drupal.wysiwyg.plugins[pluginName].invoke == 'function') { var pluginCommand = { exec: function (editor) { var data = { format: 'html', node: null, content: '' }; var selection = editor.getSelection(); if (selection) { data.node = selection.getSelectedElement(); if (data.node) { data.node = data.node.$; } if (selection.getType() == CKEDITOR.SELECTION_TEXT) { if (CKEDITOR.env.ie) { data.content = selection.getNative().createRange().text; } else { data.content = selection.getNative().toString(); } } else if (data.node) { // content is supposed to contain the "outerHTML". data.content = data.node.parentNode.innerHTML; } } Drupal.wysiwyg.plugins[pluginName].invoke(data, pluginSettings, editor.name); } }; editor.addCommand(pluginName, pluginCommand); } editor.ui.addButton(pluginName, { label: settings.iconTitle, command: pluginName, icon: settings.icon }); // @todo Add button state handling. } }); }, prepareContent: function(content) { // @todo Don't know if we need this yet. return content; }, insert: function(content) { content = this.prepareContent(content); CKEDITOR.instances[this.field].insertHtml(content); } }; })(jQuery); ; (function($) { /** * Attach this editor to a target element. * * @param context * A DOM element, supplied by Drupal.attachBehaviors(). * @param params * An object containing input format parameters. Default parameters are: * - editor: The internal editor name. * - theme: The name/key of the editor theme/profile to use. * - field: The CSS id of the target element. * @param settings * An object containing editor settings for all enabled editor themes. */ Drupal.wysiwyg.editor.attach.none = function(context, params, settings) { if (params.resizable) { var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first'); $wrapper.addClass('resizable'); if (Drupal.behaviors.textarea.attach) { Drupal.behaviors.textarea.attach(); } } }; /** * Detach a single or all editors. * * @param context * A DOM element, supplied by Drupal.attachBehaviors(). * @param params * (optional) An object containing input format parameters. If defined, * only the editor instance in params.field should be detached. Otherwise, * all editors should be detached and saved, so they can be submitted in * AJAX/AHAH applications. */ Drupal.wysiwyg.editor.detach.none = function(context, params) { if (typeof params != 'undefined') { var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first'); $wrapper.removeOnce('textarea').removeClass('.resizable-textarea') .find('.grippie').remove(); } }; /** * Instance methods for plain text areas. */ Drupal.wysiwyg.editor.instance.none = { insert: function(content) { var editor = document.getElementById(this.field); // IE support. if (document.selection) { editor.focus(); var sel = document.selection.createRange(); sel.text = content; } // Mozilla/Firefox/Netscape 7+ support. else if (editor.selectionStart || editor.selectionStart == '0') { var startPos = editor.selectionStart; var endPos = editor.selectionEnd; editor.value = editor.value.substring(0, startPos) + content + editor.value.substring(endPos, editor.value.length); } // Fallback, just add to the end of the content. else { editor.value += content; } } }; })(jQuery); ; (function($) { //Global container. window.imce = {tree: {}, findex: [], fids: {}, selected: {}, selcount: 0, ops: {}, cache: {}, urlId: {}, vars: {previewImages: 1, cache: 1}, hooks: {load: [], list: [], navigate: [], cache: []}, //initiate imce. initiate: function() { imce.conf = Drupal.settings.imce || {}; if (imce.conf.error != false) return; imce.FLW = imce.el('file-list-wrapper'), imce.SBW = imce.el('sub-browse-wrapper'); imce.NW = imce.el('navigation-wrapper'), imce.BW = imce.el('browse-wrapper'); imce.PW = imce.el('preview-wrapper'), imce.FW = imce.el('forms-wrapper'); imce.updateUI(); imce.prepareMsgs();//process initial status messages imce.initiateTree();//build directory tree imce.hooks.list.unshift(imce.processRow);//set the default list-hook. imce.initiateList();//process file list imce.initiateOps();//prepare operation tabs imce.refreshOps(); imce.invoke('load', window);//run functions set by external applications. }, //process navigation tree initiateTree: function() { $('#navigation-tree li').each(function(i) { var a = this.firstChild, txt = a.firstChild; txt && (txt.data = imce.decode(txt.data)); var branch = imce.tree[a.title] = {'a': a, li: this, ul: this.lastChild.tagName == 'UL' ? this.lastChild : null}; if (a.href) imce.dirClickable(branch); imce.dirCollapsible(branch); }); }, //Add a dir to the tree under parent dirAdd: function(dir, parent, clickable) { if (imce.tree[dir]) return clickable ? imce.dirClickable(imce.tree[dir]) : imce.tree[dir]; var parent = parent || imce.tree['.']; parent.ul = parent.ul ? parent.ul : parent.li.appendChild(imce.newEl('ul')); var branch = imce.dirCreate(dir, imce.decode(dir.substr(dir.lastIndexOf('/')+1)), clickable); parent.ul.appendChild(branch.li); return branch; }, //create list item for navigation tree dirCreate: function(dir, text, clickable) { if (imce.tree[dir]) return imce.tree[dir]; var branch = imce.tree[dir] = {li: imce.newEl('li'), a: imce.newEl('a')}; $(branch.a).addClass('folder').text(text).attr('title', dir).appendTo(branch.li); imce.dirCollapsible(branch); return clickable ? imce.dirClickable(branch) : branch; }, //change currently active directory dirActivate: function(dir) { if (dir != imce.conf.dir) { if (imce.tree[imce.conf.dir]){ $(imce.tree[imce.conf.dir].a).removeClass('active'); } $(imce.tree[dir].a).addClass('active'); imce.conf.dir = dir; } return imce.tree[imce.conf.dir]; }, //make a dir accessible dirClickable: function(branch) { if (branch.clkbl) return branch; $(branch.a).attr('href', '#').removeClass('disabled').click(function() {imce.navigate(this.title); return false;}); branch.clkbl = true; return branch; }, //sub-directories expand-collapse ability dirCollapsible: function (branch) { if (branch.clpsbl) return branch; $(imce.newEl('span')).addClass('expander').html('&nbsp;').click(function() { if (branch.ul) { $(branch.ul).toggle(); $(branch.li).toggleClass('expanded'); $.browser.msie && $('#navigation-header').css('top', imce.NW.scrollTop); } else if (branch.clkbl){ $(branch.a).click(); } }).prependTo(branch.li); branch.clpsbl = true; return branch; }, //update navigation tree after getting subdirectories. dirSubdirs: function(dir, subdirs) { var branch = imce.tree[dir]; if (subdirs && subdirs.length) { var prefix = dir == '.' ? '' : dir +'/'; for (var i in subdirs) {//add subdirectories imce.dirAdd(prefix + subdirs[i], branch, true); } $(branch.li).removeClass('leaf').addClass('expanded'); $(branch.ul).show(); } else if (!branch.ul){//no subdirs->leaf $(branch.li).removeClass('expanded').addClass('leaf'); } }, //process file list initiateList: function(cached) { var L = imce.hooks.list, dir = imce.conf.dir, token = {'%dir': dir == '.' ? $(imce.tree['.'].a).text() : imce.decode(dir)} imce.findex = [], imce.fids = {}, imce.selected = {}, imce.selcount = 0, imce.vars.lastfid = null; imce.tbody = imce.el('file-list').tBodies[0]; if (imce.tbody.rows.length) { for (var row, i = 0; row = imce.tbody.rows[i]; i++) { var fid = row.id; imce.findex[i] = imce.fids[fid] = row; if (cached) { if (imce.hasC(row, 'selected')) { imce.selected[imce.vars.lastfid = fid] = row; imce.selcount++; } } else { for (var func, j = 0; func = L[j]; j++) func(row);//invoke list-hook } } } if (!imce.conf.perm.browse) { imce.setMessage(Drupal.t('File browsing is disabled in directory %dir.', token), 'error'); } }, //add a file to the list. (having properties name,size,formatted size,width,height,date,formatted date) fileAdd: function(file) { var row, fid = file.name, i = imce.findex.length, attr = ['name', 'size', 'width', 'height', 'date']; if (!(row = imce.fids[fid])) { row = imce.findex[i] = imce.fids[fid] = imce.tbody.insertRow(i); for (var i in attr) row.insertCell(i).className = attr[i]; } row.cells[0].innerHTML = row.id = fid; row.cells[1].innerHTML = file.fsize; row.cells[1].id = file.size; row.cells[2].innerHTML = file.width; row.cells[3].innerHTML = file.height; row.cells[4].innerHTML = file.fdate; row.cells[4].id = file.date; imce.invoke('list', row); if (imce.vars.prvfid == fid) imce.setPreview(fid); if (file.id) imce.urlId[imce.getURL(fid)] = file.id; }, //remove a file from the list fileRemove: function(fid) { if (!(row = imce.fids[fid])) return; imce.fileDeSelect(fid); imce.findex.splice(row.rowIndex, 1); $(row).remove(); delete imce.fids[fid]; if (imce.vars.prvfid == fid) imce.setPreview(); }, //return a file object containing all properties. fileGet: function (fid) { var row = imce.fids[fid]; var url = imce.getURL(fid); return row ? { name: imce.decode(fid), url: url, size: row.cells[1].innerHTML, bytes: row.cells[1].id * 1, width: row.cells[2].innerHTML * 1, height: row.cells[3].innerHTML * 1, date: row.cells[4].innerHTML, time: row.cells[4].id * 1, id: imce.urlId[url] || 0, //file id for newly uploaded files relpath: (imce.conf.dir == '.' ? '' : imce.conf.dir +'/') + fid //rawurlencoded path relative to file directory path. } : null; }, //simulate row click. selection-highlighting fileClick: function(row, ctrl, shft) { if (!row) return; var fid = typeof(row) == 'string' ? row : row.id; if (ctrl || fid == imce.vars.prvfid) { imce.fileToggleSelect(fid); } else if (shft) { var last = imce.lastFid(); var start = last ? imce.fids[last].rowIndex : -1; var end = imce.fids[fid].rowIndex; var step = start > end ? -1 : 1; while (start != end) { start += step; imce.fileSelect(imce.findex[start].id); } } else { for (var fname in imce.selected) { imce.fileDeSelect(fname); } imce.fileSelect(fid); } //set preview imce.setPreview(imce.selcount == 1 ? imce.lastFid() : null); }, //file select/deselect functions fileSelect: function (fid) { if (imce.selected[fid] || !imce.fids[fid]) return; imce.selected[fid] = imce.fids[imce.vars.lastfid=fid]; $(imce.selected[fid]).addClass('selected'); imce.selcount++; }, fileDeSelect: function (fid) { if (!imce.selected[fid] || !imce.fids[fid]) return; if (imce.vars.lastfid == fid) imce.vars.lastfid = null; $(imce.selected[fid]).removeClass('selected'); delete imce.selected[fid]; imce.selcount--; }, fileToggleSelect: function (fid) { imce['file'+ (imce.selected[fid] ? 'De' : '') +'Select'](fid); }, //process file operation form and create operation tabs. initiateOps: function() { imce.setHtmlOps(); imce.setUploadOp();//upload imce.setFileOps();//thumb, delete, resize }, //process existing html ops. setHtmlOps: function () { $(imce.el('ops-list')).children('li').each(function() { if (!this.firstChild) return $(this).remove(); var name = this.id.substr(8); var Op = imce.ops[name] = {div: imce.el('op-content-'+ name), li: imce.el('op-item-'+ name)}; Op.a = Op.li.firstChild; Op.title = Op.a.innerHTML; $(Op.a).click(function() {imce.opClick(name); return false;}); }); }, //convert upload form to an op. setUploadOp: function () { var form = imce.el('imce-upload-form'); if (!form) return; $(form).ajaxForm(imce.uploadSettings()).find('fieldset').each(function() {//clean up fieldsets this.removeChild(this.firstChild); $(this).after(this.childNodes); }).remove(); imce.opAdd({name: 'upload', title: Drupal.t('Upload'), content: form});//add op }, //convert fileop form submit buttons to ops. setFileOps: function () { var form = imce.el('imce-fileop-form'); if (!form) return; $(form.elements.filenames).parent().remove(); $(form).find('fieldset').each(function() {//remove fieldsets var $sbmt = $('input:submit', this); if (!$sbmt.size()) return; var Op = {name: $sbmt.attr('id').substr(5)}; var func = function() {imce.fopSubmit(Op.name); return false;}; $sbmt.click(func); Op.title = $(this).children('legend').remove().text() || $sbmt.val(); Op.name == 'delete' ? (Op.func = func) : (Op.content = this.childNodes); imce.opAdd(Op); }).remove(); imce.vars.opform = $(form).serialize();//serialize remaining parts. }, //refresh ops states. enable/disable refreshOps: function() { for (var p in imce.conf.perm) { if (imce.conf.perm[p]) imce.opEnable(p); else imce.opDisable(p); } }, //add a new file operation opAdd: function (op) { var oplist = imce.el('ops-list'), opcons = imce.el('op-contents'); var name = op.name || ('op-'+ $(oplist).children('li').size()); var title = op.title || 'Untitled'; var Op = imce.ops[name] = {title: title}; if (op.content) { Op.div = imce.newEl('div'); $(Op.div).attr({id: 'op-content-'+ name, 'class': 'op-content'}).appendTo(opcons).append(op.content); } Op.a = imce.newEl('a'); Op.li = imce.newEl('li'); $(Op.a).attr({href: '#', name: name, title: title}).html('<span>' + title +'</span>').click(imce.opClickEvent); $(Op.li).attr('id', 'op-item-'+ name).append(Op.a).appendTo(oplist); Op.func = op.func || imce.opVoid; return Op; }, //click event for file operations opClickEvent: function(e) { imce.opClick(this.name); return false; }, //void operation function opVoid: function() {}, //perform op click opClick: function(name) { var Op = imce.ops[name], oldop = imce.vars.op; if (!Op || Op.disabled) { return imce.setMessage(Drupal.t('You can not perform this operation.'), 'error'); } if (Op.div) { if (oldop) { var toggle = oldop == name; imce.opShrink(oldop, toggle ? 'fadeOut' : 'hide'); if (toggle) return false; } var left = Op.li.offsetLeft; var $opcon = $('#op-contents').css({left: 0}); $(Op.div).fadeIn('normal', function() { setTimeout(function() { if (imce.vars.op) { var $inputs = $('input', imce.ops[imce.vars.op].div); $inputs.eq(0).focus(); //form inputs become invisible in IE. Solution is as stupid as the behavior. $('html').is('.ie') && $inputs.addClass('dummyie').removeClass('dummyie'); } }); }); var diff = left + $opcon.width() - $('#imce-content').width(); $opcon.css({left: diff > 0 ? left - diff - 1 : left}); $(Op.li).addClass('active'); $(imce.opCloseLink).fadeIn(300); imce.vars.op = name; } Op.func(true); return true; }, //enable a file operation opEnable: function(name) { var Op = imce.ops[name]; if (Op && Op.disabled) { Op.disabled = false; $(Op.li).show(); } }, //disable a file operation opDisable: function(name) { var Op = imce.ops[name]; if (Op && !Op.disabled) { Op.div && imce.opShrink(name); $(Op.li).hide(); Op.disabled = true; } }, //hide contents of a file operation opShrink: function(name, effect) { if (imce.vars.op != name) return; var Op = imce.ops[name]; $(Op.div).stop(true, true)[effect || 'hide'](); $(Op.li).removeClass('active'); $(imce.opCloseLink).hide(); Op.func(false); imce.vars.op = null; }, //navigate to dir navigate: function(dir) { if (imce.vars.navbusy || (dir == imce.conf.dir && !confirm(Drupal.t('Do you want to refresh the current directory?')))) return; var cache = imce.vars.cache && dir != imce.conf.dir; var set = imce.navSet(dir, cache); if (cache && imce.cache[dir]) {//load from the cache set.success({data: imce.cache[dir]}); set.complete(); } else $.ajax(set);//live load }, //ajax navigation settings navSet: function (dir, cache) { $(imce.tree[dir].li).addClass('loading'); imce.vars.navbusy = dir; return {url: imce.ajaxURL('navigate', dir), type: 'GET', dataType: 'json', success: function(response) { if (response.data && !response.data.error) { if (cache) imce.navCache(imce.conf.dir, dir);//cache the current dir imce.navUpdate(response.data, dir); } imce.processResponse(response); }, complete: function () { $(imce.tree[dir].li).removeClass('loading'); imce.vars.navbusy = null; } }; }, //update directory using the given data navUpdate: function(data, dir) { var cached = data == imce.cache[dir], olddir = imce.conf.dir; if (cached) data.files.id = 'file-list'; $(imce.FLW).html(data.files); imce.dirActivate(dir); imce.dirSubdirs(dir, data.subdirectories); $.extend(imce.conf.perm, data.perm); imce.refreshOps(); imce.initiateList(cached); imce.setPreview(imce.selcount == 1 ? imce.lastFid() : null); imce.SBW.scrollTop = 0; imce.invoke('navigate', data, olddir, cached); }, //set cache navCache: function (dir, newdir) { var C = imce.cache[dir] = {'dir': dir, files: imce.el('file-list'), dirsize: imce.el('dir-size').innerHTML, perm: $.extend({}, imce.conf.perm)}; C.files.id = 'cached-list-'+ dir; imce.FW.appendChild(C.files); imce.invoke('cache', C, newdir); }, //validate upload form uploadValidate: function (data, form, options) { var path = data[0].value; if (!path) return false; if (imce.conf.extensions != '*') { var ext = path.substr(path.lastIndexOf('.') + 1); if ((' '+ imce.conf.extensions +' ').indexOf(' '+ ext.toLowerCase() +' ') == -1) { return imce.setMessage(Drupal.t('Only files with the following extensions are allowed: %files-allowed.', {'%files-allowed': imce.conf.extensions}), 'error'); } } var sep = path.indexOf('/') == -1 ? '\\' : '/'; options.url = imce.ajaxURL('upload');//make url contain current dir. imce.fopLoading('upload', true); return true; }, //settings for upload uploadSettings: function () { return {beforeSubmit: imce.uploadValidate, success: function (response) {imce.processResponse($.parseJSON(response));}, complete: function () {imce.fopLoading('upload', false);}, resetForm: true}; }, //validate default ops(delete, thumb, resize) fopValidate: function(fop) { if (!imce.validateSelCount(1, imce.conf.filenum)) return false; switch (fop) { case 'delete': return confirm(Drupal.t('Delete selected files?')); case 'thumb': if (!$('input:checked', imce.ops['thumb'].div).size()) { return imce.setMessage(Drupal.t('Please select a thumbnail.'), 'error'); } return imce.validateImage(); case 'resize': var w = imce.el('edit-width').value, h = imce.el('edit-height').value; var maxDim = imce.conf.dimensions.split('x'); var maxW = maxDim[0]*1, maxH = maxW ? maxDim[1]*1 : 0; if (!(/^[1-9][0-9]*$/).test(w) || !(/^[1-9][0-9]*$/).test(h) || (maxW && (maxW < w*1 || maxH < h*1))) { return imce.setMessage(Drupal.t('Please specify dimensions within the allowed range that is from 1x1 to @dimensions.', {'@dimensions': maxW ? imce.conf.dimensions : Drupal.t('unlimited')}), 'error'); } return imce.validateImage(); } var func = fop +'OpValidate'; if (imce[func]) return imce[func](fop); return true; }, //submit wrapper for default ops fopSubmit: function(fop) { switch (fop) { case 'thumb': case 'delete': case 'resize': return imce.commonSubmit(fop); } var func = fop +'OpSubmit'; if (imce[func]) return imce[func](fop); }, //common submit function shared by default ops commonSubmit: function(fop) { if (!imce.fopValidate(fop)) return false; imce.fopLoading(fop, true); $.ajax(imce.fopSettings(fop)); }, //settings for default file operations fopSettings: function (fop) { return {url: imce.ajaxURL(fop), type: 'POST', dataType: 'json', success: imce.processResponse, complete: function (response) {imce.fopLoading(fop, false);}, data: imce.vars.opform +'&filenames='+ imce.serialNames() +'&jsop='+ fop + (imce.ops[fop].div ? '&'+ $('input, select, textarea', imce.ops[fop].div).serialize() : '')}; }, //toggle loading state fopLoading: function(fop, state) { var el = imce.el('edit-'+ fop), func = state ? 'addClass' : 'removeClass' if (el) { $(el)[func]('loading').attr('disabled', state); } else { $(imce.ops[fop].li)[func]('loading'); imce.ops[fop].disabled = state; } }, //preview a file. setPreview: function (fid) { var row, html = ''; imce.vars.prvfid = fid; if (fid && (row = imce.fids[fid])) { var width = row.cells[2].innerHTML * 1; html = imce.vars.previewImages && width ? imce.imgHtml(fid, width, row.cells[3].innerHTML) : imce.decodePlain(fid); html = '<a href="#" onclick="imce.send(\''+ fid +'\'); return false;" title="'+ (imce.vars.prvtitle||'') +'">'+ html +'</a>'; } imce.el('file-preview').innerHTML = html; }, //default file send function. sends the file to the new window. send: function (fid) { fid && window.open(imce.getURL(fid)); }, //add an operation for an external application to which the files are send. setSendTo: function (title, func) { imce.send = function (fid) { fid && func(imce.fileGet(fid), window);}; var opFunc = function () { if (imce.selcount != 1) return imce.setMessage(Drupal.t('Please select a file.'), 'error'); imce.send(imce.vars.prvfid); }; imce.vars.prvtitle = title; return imce.opAdd({name: 'sendto', title: title, func: opFunc}); }, //move initial page messages into log prepareMsgs: function () { var msgs; if (msgs = imce.el('imce-messages')) { $('>div', msgs).each(function (){ var type = this.className.split(' ')[1]; var li = $('>ul li', this); if (li.size()) li.each(function () {imce.setMessage(this.innerHTML, type);}); else imce.setMessage(this.innerHTML, type); }); $(msgs).remove(); } }, //insert log message setMessage: function (msg, type) { var $box = $(imce.msgBox); var logs = imce.el('log-messages') || $(imce.newEl('div')).appendTo('#help-box-content').before('<h4>'+ Drupal.t('Log messages') +':</h4>').attr('id', 'log-messages')[0]; var msg = '<div class="message '+ (type || 'status') +'">'+ msg +'</div>'; $box.queue(function() { $box.css({opacity: 0, display: 'block'}).html(msg); $box.dequeue(); }); var q = $box.queue().length, t = imce.vars.msgT || 1000; q = q < 2 ? 1 : q < 3 ? 0.8 : q < 4 ? 0.7 : 0.4;//adjust speed with respect to queue length $box.fadeTo(600 * q, 1).fadeTo(t * q, 1).fadeOut(400 * q); $(logs).append(msg); return false; }, //invoke hooks invoke: function (hook) { var i, args, func, funcs; if ((funcs = imce.hooks[hook]) && funcs.length) { (args = $.makeArray(arguments)).shift(); for (i = 0; func = funcs[i]; i++) func.apply(this, args); } }, //process response processResponse: function (response) { if (response.data) imce.resData(response.data); if (response.messages) imce.resMsgs(response.messages); }, //process response data resData: function (data) { var i, added, removed; if (added = data.added) { var cnt = imce.findex.length; for (i in added) {//add new files or update existing imce.fileAdd(added[i]); } if (added.length == 1) {//if it is a single file operation imce.highlight(added[0].name);//highlight } if (imce.findex.length != cnt) {//if new files added, scroll to bottom. $(imce.SBW).animate({scrollTop: imce.SBW.scrollHeight}).focus(); } } if (removed = data.removed) for (i in removed) { imce.fileRemove(removed[i]); } imce.conf.dirsize = data.dirsize; imce.updateStat(); }, //set response messages resMsgs: function (msgs) { for (var type in msgs) for (var i in msgs[type]) { imce.setMessage(msgs[type][i], type); } }, //return img markup imgHtml: function (fid, width, height) { return '<img src="'+ imce.getURL(fid) +'" width="'+ width +'" height="'+ height +'" alt="'+ imce.decodePlain(fid) +'">'; }, //check if the file is an image isImage: function (fid) { return imce.fids[fid].cells[2].innerHTML * 1; }, //find the first non-image in the selection getNonImage: function (selected) { for (var fid in selected) { if (!imce.isImage(fid)) return fid; } return false; }, //validate current selection for images validateImage: function () { var nonImg = imce.getNonImage(imce.selected); return nonImg ? imce.setMessage(Drupal.t('%filename is not an image.', {'%filename': imce.decode(nonImg)}), 'error') : true; }, //validate number of selected files validateSelCount: function (Min, Max) { if (Min && imce.selcount < Min) { return imce.setMessage(Min == 1 ? Drupal.t('Please select a file.') : Drupal.t('You must select at least %num files.', {'%num': Min}), 'error'); } if (Max && Max < imce.selcount) { return imce.setMessage(Drupal.t('You are not allowed to operate on more than %num files.', {'%num': Max}), 'error'); } return true; }, //update file count and dir size updateStat: function () { imce.el('file-count').innerHTML = imce.findex.length; imce.el('dir-size').innerHTML = imce.conf.dirsize; }, //serialize selected files. return fids with a colon between them serialNames: function () { var str = ''; for (var fid in imce.selected) { str += ':'+ fid; } return str.substr(1); }, //get file url. re-encode & and # for mod rewrite getURL: function (fid) { var path = (imce.conf.dir == '.' ? '' : imce.conf.dir +'/') + fid; return imce.conf.furl + (imce.conf.modfix ? path.replace(/%(23|26)/g, '%25$1') : path); }, //el. by id el: function (id) { return document.getElementById(id); }, //find the latest selected fid lastFid: function () { if (imce.vars.lastfid) return imce.vars.lastfid; for (var fid in imce.selected); return fid; }, //create ajax url ajaxURL: function (op, dir) { return imce.conf.url + (imce.conf.clean ? '?' :'&') +'jsop='+ op +'&dir='+ (dir||imce.conf.dir); }, //fast class check hasC: function (el, name) { return el.className && (' '+ el.className +' ').indexOf(' '+ name +' ') != -1; }, //highlight a single file highlight: function (fid) { if (imce.vars.prvfid) imce.fileClick(imce.vars.prvfid); imce.fileClick(fid); }, //process a row processRow: function (row) { row.cells[0].innerHTML = '<span>' + imce.decodePlain(row.id) + '</span>'; row.onmousedown = function(e) { var e = e||window.event; imce.fileClick(this, e.ctrlKey, e.shiftKey); return !(e.ctrlKey || e.shiftKey); }; row.ondblclick = function(e) { imce.send(this.id); return false; }; }, //decode urls. uses unescape. can be overridden to use decodeURIComponent decode: function (str) { return unescape(str); }, //decode and convert to plain text decodePlain: function (str) { return Drupal.checkPlain(imce.decode(str)); }, //global ajax error function ajaxError: function (e, response, settings, thrown) { imce.setMessage(Drupal.ajaxError(response, settings.url).replace(/\n/g, '<br />'), 'error'); }, //convert button elements to standard input buttons convertButtons: function(form) { $('button:submit', form).each(function(){ $(this).replaceWith('<input type="submit" value="'+ $(this).text() +'" name="'+ this.name +'" class="form-submit" id="'+ this.id +'" />'); }); }, //create element newEl: function(name) { return document.createElement(name); }, //scroll syncronization for section headers syncScroll: function(scrlEl, fixEl, bottom) { var $fixEl = $(fixEl); var prop = bottom ? 'bottom' : 'top'; var factor = bottom ? -1 : 1; var syncScrl = function(el) { $fixEl.css(prop, factor * el.scrollTop); } $(scrlEl).scroll(function() { var el = this; syncScrl(el); setTimeout(function() { syncScrl(el); }); }); }, //get UI ready. provide backward compatibility. updateUI: function() { //file urls. var furl = imce.conf.furl, isabs = furl.indexOf('://') > -1; var absurls = imce.conf.absurls = imce.vars.absurls || imce.conf.absurls; var host = location.host; var baseurl = location.protocol + '//' + host; if (furl.charAt(furl.length - 1) != '/') { furl = imce.conf.furl = furl + '/'; } imce.conf.modfix = imce.conf.clean && furl.indexOf(host + '/system/') > -1; if (absurls && !isabs) { imce.conf.furl = baseurl + furl; } else if (!absurls && isabs && furl.indexOf(baseurl) == 0) { imce.conf.furl = furl.substr(baseurl.length); } //convert button elements to input elements. imce.convertButtons(imce.FW); //ops-list $('#ops-list').removeClass('tabs secondary').addClass('clear-block clearfix'); imce.opCloseLink = $(imce.newEl('a')).attr({id: 'op-close-link', href: '#', title: Drupal.t('Close')}).click(function() { imce.vars.op && imce.opClick(imce.vars.op); return false; }).appendTo('#op-contents')[0]; //navigation-header if (!$('#navigation-header').size()) { $(imce.NW).children('.navigation-text').attr('id', 'navigation-header').wrapInner('<span></span>'); } //log $('#log-prv-wrapper').before($('#log-prv-wrapper > #preview-wrapper')).remove(); $('#log-clearer').remove(); //content resizer $('#content-resizer').remove(); //message-box imce.msgBox = imce.el('message-box') || $(imce.newEl('div')).attr('id', 'message-box').prependTo('#imce-content')[0]; //create help tab var $hbox = $('#help-box'); $hbox.is('a') && $hbox.replaceWith($(imce.newEl('div')).attr('id', 'help-box').append($hbox.children())); imce.hooks.load.push(function() { imce.opAdd({name: 'help', title: $('#help-box-title').remove().text(), content: $('#help-box').show()}); }); //add ie classes $.browser.msie && $('html').addClass('ie') && parseFloat($.browser.version) < 8 && $('html').addClass('ie-7'); // enable box view for file list imce.vars.boxW && imce.boxView(); //scrolling file list imce.syncScroll(imce.SBW, '#file-header-wrapper'); imce.syncScroll(imce.SBW, '#dir-stat', true); //scrolling directory tree imce.syncScroll(imce.NW, '#navigation-header'); } }; //initiate $(document).ready(imce.initiate).ajaxError(imce.ajaxError); })(jQuery);; /* * IMCE Integration by URL * Ex-1: http://example.com/imce?app=XEditor|url@urlFieldId|width@widthFieldId|height@heightFieldId * Creates "Insert file" operation tab, which fills the specified fields with url, width, height properties * of the selected file in the parent window * Ex-2: http://example.com/imce?app=XEditor|sendto@functionName * "Insert file" operation calls parent window's functionName(file, imceWindow) * Ex-3: http://example.com/imce?app=XEditor|imceload@functionName * Parent window's functionName(imceWindow) is called as soon as IMCE UI is ready. Send to operation * needs to be set manually. See imce.setSendTo() method in imce.js */ (function($) { var appFields = {}, appWindow = (top.appiFrm||window).opener || parent; // Execute when imce loads. imce.hooks.load.push(function(win) { var index = location.href.lastIndexOf('app='); if (index == -1) return; var data = decodeURIComponent(location.href.substr(index + 4)).split('|'); var arr, prop, str, func, appName = data.shift(); // Extract fields for (var i = 0, len = data.length; i < len; i++) { str = data[i]; if (!str.length) continue; if (str.indexOf('&') != -1) str = str.split('&')[0]; arr = str.split('@'); if (arr.length > 1) { prop = arr.shift(); appFields[prop] = arr.join('@'); } } // Run custom onload function if available if (appFields.imceload && (func = isFunc(appFields.imceload))) { func(win); delete appFields.imceload; } // Set custom sendto function. appFinish is the default. var sendtoFunc = appFields.url ? appFinish : false; //check sendto@funcName syntax in URL if (appFields.sendto && (func = isFunc(appFields.sendto))) { sendtoFunc = func; delete appFields.sendto; } // Check old method windowname+ImceFinish. else if (win.name && (func = isFunc(win.name +'ImceFinish'))) { sendtoFunc = func; } // Highlight file if (appFields.url) { // Support multiple url fields url@field1,field2.. if (appFields.url.indexOf(',') > -1) { var arr = appFields.url.split(','); for (var i in arr) { if ($('#'+ arr[i], appWindow.document).size()) { appFields.url = arr[i]; break; } } } var filename = $('#'+ appFields.url, appWindow.document).val() || ''; imce.highlight(filename.substr(filename.lastIndexOf('/')+1)); } // Set send to sendtoFunc && imce.setSendTo(Drupal.t('Insert file'), sendtoFunc); }); // Default sendTo function var appFinish = function(file, win) { var $doc = $(appWindow.document); for (var i in appFields) { $doc.find('#'+ appFields[i]).val(file[i]); } if (appFields.url) { try{ $doc.find('#'+ appFields.url).blur().change().focus(); }catch(e){ try{ $doc.find('#'+ appFields.url).trigger('onblur').trigger('onchange').trigger('onfocus');//inline events for IE }catch(e){} } } appWindow.focus(); win.close(); }; // Checks if a string is a function name in the given scope. // Returns function reference. Supports x.y.z notation. var isFunc = function(str, scope) { var obj = scope || appWindow; var parts = str.split('.'), len = parts.length; for (var i = 0; i < len && (obj = obj[parts[i]]); i++); return obj && i == len && (typeof obj == 'function' || typeof obj != 'string' && !obj.nodeName && obj.constructor != Array && /^[\s[]?function/.test(obj.toString())) ? obj : false; } })(jQuery);; /** * Wysiwyg API integration helper function. */ function imceImageBrowser(field_name, url, type, win) { // TinyMCE. if (win !== 'undefined') { win.open(Drupal.settings.imce.url + encodeURIComponent(field_name), '', 'width=760,height=560,resizable=1'); } } /** * CKeditor integration. */ var imceCkeditSendTo = function (file, win) { var parts = /\?(?:.*&)?CKEditorFuncNum=(\d+)(?:&|$)/.exec(win.location.href); if (parts && parts.length > 1) { CKEDITOR.tools.callFunction(parts[1], file.url); win.close(); } else { throw 'CKEditorFuncNum parameter not found or invalid: ' + win.location.href;<|fim▁hole|> } }; ; /** * @file: Popup dialog interfaces for the media project. * * Drupal.media.popups.mediaBrowser * Launches the media browser which allows users to pick a piece of media. * * Drupal.media.popups.mediaStyleSelector * Launches the style selection form where the user can choose * what format / style they want their media in. * */ (function ($) { namespace('Drupal.media.popups'); /** * Media browser popup. Creates a media browser dialog. * * @param {function} * onSelect Callback for when dialog is closed, received (Array * media, Object extra); * @param {Object} * globalOptions Global options that will get passed upon initialization of the browser. * @see Drupal.media.popups.mediaBrowser.getDefaults(); * * @param {Object} * pluginOptions Options for specific plugins. These are passed * to the plugin upon initialization. If a function is passed here as * a callback, it is obviously not passed, but is accessible to the plugin * in Drupal.settings.variables. * * Example * pluginOptions = {library: {url_include_patterns:'/foo/bar'}}; * * @param {Object} * widgetOptions Options controlling the appearance and behavior of the * modal dialog. * @see Drupal.media.popups.mediaBrowser.getDefaults(); */ Drupal.media.popups.mediaBrowser = function (onSelect, globalOptions, pluginOptions, widgetOptions) { var options = Drupal.media.popups.mediaBrowser.getDefaults(); options.global = $.extend({}, options.global, globalOptions); options.plugins = pluginOptions; options.widget = $.extend({}, options.widget, widgetOptions); // Create it as a modal window. var browserSrc = options.widget.src; if ($.isArray(browserSrc) && browserSrc.length) { browserSrc = browserSrc[browserSrc.length - 1]; } // Params to send along to the iframe. WIP. var params = {}; $.extend(params, options.global); params.plugins = options.plugins; browserSrc += '&' + $.param(params); var mediaIframe = Drupal.media.popups.getPopupIframe(browserSrc, 'mediaBrowser'); // Attach the onLoad event mediaIframe.bind('load', options, options.widget.onLoad); /** * Setting up the modal dialog */ var ok = 'OK'; var cancel = 'Cancel'; var notSelected = 'You have not selected anything!'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); cancel = Drupal.t(cancel); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = options.dialog; dialogOptions.buttons[ok] = function () { var selected = this.contentWindow.Drupal.media.browser.selectedMedia; if (selected.length < 1) { alert(notSelected); return; } onSelect(selected); $(this).dialog("destroy"); $(this).remove(); }; dialogOptions.buttons[cancel] = function () { $(this).dialog("destroy"); $(this).remove(); }; Drupal.media.popups.setDialogPadding(mediaIframe.dialog(dialogOptions)); // Remove the title bar. mediaIframe.parents(".ui-dialog").find(".ui-dialog-titlebar").remove(); Drupal.media.popups.overlayDisplace(mediaIframe.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad = function (e) { var options = e.data; if (this.contentWindow.Drupal.media.browser.selectedMedia.length > 0) { var ok = $(this).dialog('option', 'buttons')['OK']; ok.call(this); return; } }; Drupal.media.popups.mediaBrowser.getDefaults = function () { return { global: { types: [], // Types to allow, defaults to all. activePlugins: [] // If provided, a list of plugins which should be enabled. }, widget: { // Settings for the actual iFrame which is launched. src: Drupal.settings.media.browserUrl, // Src of the media browser (if you want to totally override it) onLoad: Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad // Onload function when iFrame loads. }, dialog: Drupal.media.popups.getDialogOptions() }; }; Drupal.media.popups.mediaBrowser.finalizeSelection = function () { var selected = this.contentWindow.Drupal.media.browser.selectedMedia; if (selected.length < 1) { alert(notSelected); return; } onSelect(selected); $(this).dialog("destroy"); $(this).remove(); } /** * Style chooser Popup. Creates a dialog for a user to choose a media style. * * @param mediaFile * The mediaFile you are requesting this formatting form for. * @todo: should this be fid? That's actually all we need now. * * @param Function * onSubmit Function to be called when the user chooses a media * style. Takes one parameter (Object formattedMedia). * * @param Object * options Options for the mediaStyleChooser dialog. */ Drupal.media.popups.mediaStyleSelector = function (mediaFile, onSelect, options) { var defaults = Drupal.media.popups.mediaStyleSelector.getDefaults(); // @todo: remove this awful hack :( defaults.src = defaults.src.replace('-media_id-', mediaFile.fid); options = $.extend({}, defaults, options); // Create it as a modal window. var mediaIframe = Drupal.media.popups.getPopupIframe(options.src, 'mediaStyleSelector'); // Attach the onLoad event mediaIframe.bind('load', options, options.onLoad); /** * Set up the button text */ var ok = 'OK'; var cancel = 'Cancel'; var notSelected = 'Very sorry, there was an unknown error embedding media.'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); cancel = Drupal.t(cancel); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = Drupal.media.popups.getDialogOptions(); dialogOptions.buttons[ok] = function () { var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia(); if (!formattedMedia) { alert(notSelected); return; } onSelect(formattedMedia); $(this).dialog("destroy"); $(this).remove(); }; dialogOptions.buttons[cancel] = function () { $(this).dialog("destroy"); $(this).remove(); }; Drupal.media.popups.setDialogPadding(mediaIframe.dialog(dialogOptions)); // Remove the title bar. mediaIframe.parents(".ui-dialog").find(".ui-dialog-titlebar").remove(); Drupal.media.popups.overlayDisplace(mediaIframe.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaStyleSelector.mediaBrowserOnLoad = function (e) { }; Drupal.media.popups.mediaStyleSelector.getDefaults = function () { return { src: Drupal.settings.media.styleSelectorUrl, onLoad: Drupal.media.popups.mediaStyleSelector.mediaBrowserOnLoad }; }; /** * Style chooser Popup. Creates a dialog for a user to choose a media style. * * @param mediaFile * The mediaFile you are requesting this formatting form for. * @todo: should this be fid? That's actually all we need now. * * @param Function * onSubmit Function to be called when the user chooses a media * style. Takes one parameter (Object formattedMedia). * * @param Object * options Options for the mediaStyleChooser dialog. */ Drupal.media.popups.mediaFieldEditor = function (fid, onSelect, options) { var defaults = Drupal.media.popups.mediaFieldEditor.getDefaults(); // @todo: remove this awful hack :( defaults.src = defaults.src.replace('-media_id-', fid); options = $.extend({}, defaults, options); // Create it as a modal window. var mediaIframe = Drupal.media.popups.getPopupIframe(options.src, 'mediaFieldEditor'); // Attach the onLoad event // @TODO - This event is firing too early in IE on Windows 7, // - so the height being calculated is too short for the content. mediaIframe.bind('load', options, options.onLoad); /** * Set up the button text */ var ok = 'OK'; var cancel = 'Cancel'; var notSelected = 'Very sorry, there was an unknown error embedding media.'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); cancel = Drupal.t(cancel); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = Drupal.media.popups.getDialogOptions(); dialogOptions.buttons[ok] = function () { alert('hell yeah'); return "poo"; var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia(); if (!formattedMedia) { alert(notSelected); return; } onSelect(formattedMedia); $(this).dialog("destroy"); $(this).remove(); }; dialogOptions.buttons[cancel] = function () { $(this).dialog("destroy"); $(this).remove(); }; Drupal.media.popups.setDialogPadding(mediaIframe.dialog(dialogOptions)); // Remove the title bar. mediaIframe.parents(".ui-dialog").find(".ui-dialog-titlebar").remove(); Drupal.media.popups.overlayDisplace(mediaIframe.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaFieldEditor.mediaBrowserOnLoad = function (e) { }; Drupal.media.popups.mediaFieldEditor.getDefaults = function () { return { // @todo: do this for real src: '/media/-media_id-/edit?render=media-popup', onLoad: Drupal.media.popups.mediaFieldEditor.mediaBrowserOnLoad }; }; /** * Generic functions to both the media-browser and style selector */ /** * Returns the commonly used options for the dialog. */ Drupal.media.popups.getDialogOptions = function () { return { buttons: {}, dialogClass: 'media-wrapper', modal: true, draggable: false, resizable: false, minWidth: 600, width: 800, height: 550, position: 'center', overlay: { backgroundColor: '#000000', opacity: 0.4 } }; }; /** * Created padding on a dialog * * @param jQuery dialogElement * The element which has .dialog() attached to it. */ Drupal.media.popups.setDialogPadding = function (dialogElement) { // @TODO: Perhaps remove this hardcoded reference to height. // - It's included to make IE on Windows 7 display the dialog without // collapsing. 550 is the height that displays all of the tab panes // within the Add Media overlay. This is either a bug in the jQuery // UI library, a bug in IE on Windows 7 or a bug in the way the // dialog is instantiated. Or a combo of the three. // All browsers except IE on Win7 ignore these defaults and adjust // the height of the iframe correctly to match the content in the panes dialogElement.height(dialogElement.dialog('option', 'height')); dialogElement.width(dialogElement.dialog('option', 'width')); }; /** * Get an iframe to serve as the dialog's contents. Common to both plugins. */ Drupal.media.popups.getPopupIframe = function (src, id, options) { var defaults = {width: '800px', scrolling: 'no'}; var options = $.extend({}, defaults, options); return $('<iframe class="media-modal-frame"/>') .attr('src', src) .attr('width', options.width) .attr('id', id) .attr('scrolling', options.scrolling); }; Drupal.media.popups.overlayDisplace = function (dialog) { if (parent.window.Drupal.overlay) { var overlayDisplace = parent.window.Drupal.overlay.getDisplacement('top'); if (dialog.offset().top < overlayDisplace) { dialog.css('top', overlayDisplace); } } } })(jQuery); ; /** * @file * Attach Media WYSIWYG behaviors. */ (function ($) { Drupal.media = Drupal.media || {}; // Define the behavior. Drupal.wysiwyg.plugins.media = { /** * Initializes the tag map. */ initializeTagMap: function () { if (typeof Drupal.settings.tagmap == 'undefined') { Drupal.settings.tagmap = { }; } }, /** * Execute the button. * @TODO: Debug calls from this are never called. What's its function? */ invoke: function (data, settings, instanceId) { if (data.format == 'html') { Drupal.media.popups.mediaBrowser(function (mediaFiles) { Drupal.wysiwyg.plugins.media.mediaBrowserOnSelect(mediaFiles, instanceId); }, settings['global']); } }, /** * Respond to the mediaBrowser's onSelect event. * @TODO: Debug calls from this are never called. What's its function? */ mediaBrowserOnSelect: function (mediaFiles, instanceId) { var mediaFile = mediaFiles[0]; var options = {}; Drupal.media.popups.mediaStyleSelector(mediaFile, function (formattedMedia) { Drupal.wysiwyg.plugins.media.insertMediaFile(mediaFile, formattedMedia.type, formattedMedia.html, formattedMedia.options, Drupal.wysiwyg.instances[instanceId]); }, options); return; }, insertMediaFile: function (mediaFile, viewMode, formattedMedia, options, wysiwygInstance) { this.initializeTagMap(); // @TODO: the folks @ ckeditor have told us that there is no way // to reliably add wrapper divs via normal HTML. // There is some method of adding a "fake element" // But until then, we're just going to embed to img. // This is pretty hacked for now. // var imgElement = $(this.stripDivs(formattedMedia)); this.addImageAttributes(imgElement, mediaFile.fid, viewMode, options); var toInsert = this.outerHTML(imgElement); // Create an inline tag var inlineTag = Drupal.wysiwyg.plugins.media.createTag(imgElement); // Add it to the tag map in case the user switches input formats Drupal.settings.tagmap[inlineTag] = toInsert; wysiwygInstance.insert(toInsert); }, /** * Gets the HTML content of an element * * @param jQuery element */ outerHTML: function (element) { return $('<div>').append( element.eq(0).clone() ).html(); }, addImageAttributes: function (imgElement, fid, view_mode, additional) { // imgElement.attr('fid', fid); // imgElement.attr('view_mode', view_mode); // Class so we can find this image later. imgElement.addClass('media-image'); this.forceAttributesIntoClass(imgElement, fid, view_mode, additional); if (additional) { for (k in additional) { if (additional.hasOwnProperty(k)) { if (k === 'attr') { imgElement.attr(k, additional[k]); } } } } }, /** * Due to problems handling wrapping divs in ckeditor, this is needed. * * Going forward, if we don't care about supporting other editors * we can use the fakeobjects plugin to ckeditor to provide cleaner * transparency between what Drupal will output <div class="field..."><img></div> * instead of just <img>, for now though, we're going to remove all the stuff surrounding the images. * * @param String formattedMedia * Element containing the image * * @return HTML of <img> tag inside formattedMedia */ stripDivs: function (formattedMedia) { // Check to see if the image tag has divs to strip var stripped = null; if ($(formattedMedia).is('img')) { stripped = this.outerHTML($(formattedMedia)); } else { stripped = this.outerHTML($('img', $(formattedMedia))); } // This will fail if we pass the img tag without anything wrapping it, like we do when re-enabling WYSIWYG return stripped; }, /** * Attach function, called when a rich text editor loads. * This finds all [[tags]] and replaces them with the html * that needs to show in the editor. * */ attach: function (content, settings, instanceId) { var matches = content.match(/\[\[.*?\]\]/g); this.initializeTagMap(); var tagmap = Drupal.settings.tagmap; if (matches) { var inlineTag = ""; for (i = 0; i < matches.length; i++) { inlineTag = matches[i]; if (tagmap[inlineTag]) { // This probably needs some work... // We need to somehow get the fid propogated here. // We really want to var tagContent = tagmap[inlineTag]; var mediaMarkup = this.stripDivs(tagContent); // THis is <div>..<img> var _tag = inlineTag; _tag = _tag.replace('[[',''); _tag = _tag.replace(']]',''); try { mediaObj = JSON.parse(_tag); } catch(err) { mediaObj = null; } if(mediaObj) { var imgElement = $(mediaMarkup); this.addImageAttributes(imgElement, mediaObj.fid, mediaObj.view_mode); var toInsert = this.outerHTML(imgElement); content = content.replace(inlineTag, toInsert); } } else { debug.debug("Could not find content for " + inlineTag); } } } return content; }, /** * Detach function, called when a rich text editor detaches */ detach: function (content, settings, instanceId) { // Replace all Media placeholder images with the appropriate inline json // string. Using a regular expression instead of jQuery manipulation to // prevent <script> tags from being displaced. // @see http://drupal.org/node/1280758. if (matches = content.match(/<img[^>]+class=([\'"])media-image[^>]*>/gi)) { for (var i = 0; i < matches.length; i++) { var imageTag = matches[i]; var inlineTag = Drupal.wysiwyg.plugins.media.createTag($(imageTag)); Drupal.settings.tagmap[inlineTag] = imageTag; content = content.replace(imageTag, inlineTag); } } return content; }, /** * @param jQuery imgNode * Image node to create tag from */ createTag: function (imgNode) { // Currently this is the <img> itself // Collect all attribs to be stashed into tagContent var mediaAttributes = {}; var imgElement = imgNode[0]; var sorter = []; // @todo: this does not work in IE, width and height are always 0. for (i=0; i< imgElement.attributes.length; i++) { var attr = imgElement.attributes[i]; if (attr.specified == true) { if (attr.name !== 'class') { sorter.push(attr); } else { // Exctract expando properties from the class field. var attributes = this.getAttributesFromClass(attr.value); for (var name in attributes) { if (attributes.hasOwnProperty(name)) { var value = attributes[name]; if (value.type && value.type === 'attr') { sorter.push(value); } } } } } } sorter.sort(this.sortAttributes); for (var prop in sorter) { mediaAttributes[sorter[prop].name] = sorter[prop].value; } // The following 5 ifs are dedicated to IE7 // If the style is null, it is because IE7 can't read values from itself if (jQuery.browser.msie && jQuery.browser.version == '7.0') { if (mediaAttributes.style === "null") { var imgHeight = imgNode.css('height'); var imgWidth = imgNode.css('width'); mediaAttributes.style = { height: imgHeight, width: imgWidth } if (!mediaAttributes['width']) { mediaAttributes['width'] = imgWidth; } if (!mediaAttributes['height']) { mediaAttributes['height'] = imgHeight; } } // If the attribute width is zero, get the CSS width if (Number(mediaAttributes['width']) === 0) { mediaAttributes['width'] = imgNode.css('width'); } // IE7 does support 'auto' as a value of the width attribute. It will not // display the image if this value is allowed to pass through if (mediaAttributes['width'] === 'auto') { delete mediaAttributes['width']; } // If the attribute height is zero, get the CSS height if (Number(mediaAttributes['height']) === 0) { mediaAttributes['height'] = imgNode.css('height'); } // IE7 does support 'auto' as a value of the height attribute. It will not // display the image if this value is allowed to pass through if (mediaAttributes['height'] === 'auto') { delete mediaAttributes['height']; } } // Remove elements from attribs using the blacklist for (var blackList in Drupal.settings.media.blacklist) { delete mediaAttributes[Drupal.settings.media.blacklist[blackList]]; } tagContent = { "type": 'media', // @todo: This will be selected from the format form "view_mode": attributes['view_mode'].value, "fid" : attributes['fid'].value, "attributes": mediaAttributes }; return '[[' + JSON.stringify(tagContent) + ']]'; }, /** * Forces custom attributes into the class field of the specified image. * * Due to a bug in some versions of Firefox * (http://forums.mozillazine.org/viewtopic.php?f=9&t=1991855), the * custom attributes used to share information about the image are * being stripped as the image markup is set into the rich text * editor. Here we encode these attributes into the class field so * the data survives. * * @param imgElement * The image * @fid * The file id. * @param view_mode * The view mode. * @param additional * Additional attributes to add to the image. */ forceAttributesIntoClass: function (imgElement, fid, view_mode, additional) { var wysiwyg = imgElement.attr('wysiwyg'); if (wysiwyg) { imgElement.addClass('attr__wysiwyg__' + wysiwyg); } var format = imgElement.attr('format'); if (format) { imgElement.addClass('attr__format__' + format); } var typeOf = imgElement.attr('typeof'); if (typeOf) { imgElement.addClass('attr__typeof__' + typeOf); } if (fid) { imgElement.addClass('img__fid__' + fid); } if (view_mode) { imgElement.addClass('img__view_mode__' + view_mode); } if (additional) { for (var name in additional) { if (additional.hasOwnProperty(name)) { if (name !== 'alt') { imgElement.addClass('attr__' + name + '__' + additional[name]); } } } } }, /** * Retrieves encoded attributes from the specified class string. * * @param classString * A string containing the value of the class attribute. * @return * An array containing the attribute names as keys, and an object * with the name, value, and attribute type (either 'attr' or * 'img', depending on whether it is an image attribute or should * be it the attributes section) */ getAttributesFromClass: function (classString) { var actualClasses = []; var otherAttributes = []; var classes = classString.split(' '); var regexp = new RegExp('^(attr|img)__([^\S]*)__([^\S]*)$'); for (var index = 0; index < classes.length; index++) { var matches = classes[index].match(regexp); if (matches && matches.length === 4) { otherAttributes[matches[2]] = {name: matches[2], value: matches[3], type: matches[1]}; } else { actualClasses.push(classes[index]); } } if (actualClasses.length > 0) { otherAttributes['class'] = {name: 'class', value: actualClasses.join(' '), type: 'attr'}; } return otherAttributes; }, /* * */ sortAttributes: function (a, b) { var nameA = a.name.toLowerCase(); var nameB = b.name.toLowerCase(); if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } return 0; } }; })(jQuery); ; (function ($) { // @todo Array syntax required; 'break' is a predefined token in JavaScript. Drupal.wysiwyg.plugins['break'] = { /** * Return whether the passed node belongs to this plugin. */ isNode: function(node) { return ($(node).is('img.wysiwyg-break')); }, /** * Execute the button. */ invoke: function(data, settings, instanceId) { if (data.format == 'html') { // Prevent duplicating a teaser break. if ($(data.node).is('img.wysiwyg-break')) { return; } var content = this._getPlaceholder(settings); } else { // Prevent duplicating a teaser break. // @todo data.content is the selection only; needs access to complete content. if (data.content.match(/<!--break-->/)) { return; } var content = '<!--break-->'; } if (typeof content != 'undefined') { Drupal.wysiwyg.instances[instanceId].insert(content); } }, /** * Replace all <!--break--> tags with images. */ attach: function(content, settings, instanceId) { content = content.replace(/<!--break-->/g, this._getPlaceholder(settings)); return content; }, /** * Replace images with <!--break--> tags in content upon detaching editor. */ detach: function(content, settings, instanceId) { var $content = $('<div>' + content + '</div>'); // No .outerHTML() in jQuery :( // #404532: document.createComment() required or IE will strip the comment. // #474908: IE 8 breaks when using jQuery methods to replace the elements. // @todo Add a generic implementation for all Drupal plugins for this. $.each($('img.wysiwyg-break', $content), function (i, elem) { elem.parentNode.insertBefore(document.createComment('break'), elem); elem.parentNode.removeChild(elem); }); return $content.html(); }, /** * Helper function to return a HTML placeholder. */ _getPlaceholder: function (settings) { return '<img src="' + settings.path + '/images/spacer.gif" alt="&lt;--break-&gt;" title="&lt;--break--&gt;" class="wysiwyg-break drupal-content" />'; } }; })(jQuery); ; (function ($) { /** * Auto-hide summary textarea if empty and show hide and unhide links. */ Drupal.behaviors.textSummary = { attach: function (context, settings) { $('.text-summary', context).once('text-summary', function () { var $widget = $(this).closest('div.field-type-text-with-summary'); var $summaries = $widget.find('div.text-summary-wrapper'); $summaries.once('text-summary-wrapper').each(function(index) { var $summary = $(this); var $summaryLabel = $summary.find('label'); var $full = $widget.find('.text-full').eq(index).closest('.form-item'); var $fullLabel = $full.find('label'); // Create a placeholder label when the field cardinality is // unlimited or greater than 1. if ($fullLabel.length == 0) { $fullLabel = $('<label></label>').prependTo($full); } // Setup the edit/hide summary link. var $link = $('<span class="field-edit-link">(<a class="link-edit-summary" href="#">' + Drupal.t('Hide summary') + '</a>)</span>').toggle( function () { $summary.hide(); $(this).find('a').html(Drupal.t('Edit summary')).end().appendTo($fullLabel); return false; }, function () { $summary.show(); $(this).find('a').html(Drupal.t('Hide summary')).end().appendTo($summaryLabel); return false; } ).appendTo($summaryLabel); // If no summary is set, hide the summary field. if ($(this).find('.text-summary').val() == '') { $link.click(); } return; }); }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.textarea = { attach: function (context, settings) { $('.form-textarea-wrapper.resizable', context).once('textarea', function () { var staticOffset = null; var textarea = $(this).addClass('resizable-textarea').find('textarea'); var grippie = $('<div class="grippie"></div>').mousedown(startDrag); grippie.insertAfter(textarea); function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag); textarea.css('opacity', 1); } }); } }; })(jQuery); ; (function ($) { /** * Automatically display the guidelines of the selected text format. */ Drupal.behaviors.filterGuidelines = { attach: function (context) { $('.filter-guidelines', context).once('filter-guidelines') .find(':header').hide() .parents('.filter-wrapper').find('select.filter-list') .bind('change', function () { $(this).parents('.filter-wrapper') .find('.filter-guidelines-item').hide() .siblings('.filter-guidelines-' + this.value).show(); }) .change(); } }; })(jQuery); ; (function ($) { /** * Toggle the visibility of a fieldset using smooth animations. */ Drupal.toggleFieldset = function (fieldset) { var $fieldset = $(fieldset); if ($fieldset.is('.collapsed')) { var $content = $('> .fieldset-wrapper', fieldset).hide(); $fieldset .removeClass('collapsed') .trigger({ type: 'collapsed', value: false }) .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide')); $content.slideDown({ duration: 'fast', easing: 'linear', complete: function () { Drupal.collapseScrollIntoView(fieldset); fieldset.animating = false; }, step: function () { // Scroll the fieldset into view. Drupal.collapseScrollIntoView(fieldset); } }); } else { $fieldset.trigger({ type: 'collapsed', value: true }); $('> .fieldset-wrapper', fieldset).slideUp('fast', function () { $fieldset .addClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show')); fieldset.animating = false; }); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = document.documentElement.clientHeight || document.body.clientHeight || 0; var offset = document.documentElement.scrollTop || document.body.scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = { attach: function (context, settings) { $('fieldset.collapsible', context).once('collapse', function () { var $fieldset = $(this); // Expand fieldset if there are errors inside, or if it contains an // element that is targeted by the uri fragment identifier. var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : ''; if ($('.error' + anchor, $fieldset).length) { $fieldset.removeClass('collapsed'); } var summary = $('<span class="summary"></span>'); $fieldset. bind('summaryUpdated', function () { var text = $.trim($fieldset.drupalGetSummary()); summary.html(text ? ' (' + text + ')' : ''); }) .trigger('summaryUpdated'); // Turn the legend into a clickable link, but retain span.fieldset-legend // for CSS positioning. var $legend = $('> legend .fieldset-legend', this); $('<span class="fieldset-legend-prefix element-invisible"></span>') .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide')) .prependTo($legend) .after(' '); // .wrapInner() does not retain bound events. var $link = $('<a class="fieldset-title" href="#"></a>') .prepend($legend.contents()) .appendTo($legend) .click(function () { var fieldset = $fieldset.get(0); // Don't animate multiple times. if (!fieldset.animating) { fieldset.animating = true; Drupal.toggleFieldset(fieldset); } return false; }); $legend.append(summary); }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.menuFieldsetSummaries = { attach: function (context) { $('fieldset.menu-link-form', context).drupalSetSummary(function (context) { if ($('.form-item-menu-enabled input', context).is(':checked')) { return Drupal.checkPlain($('.form-item-menu-link-title input', context).val()); } else { return Drupal.t('Not in menu'); } }); } }; /** * Automatically fill in a menu link title, if possible. */ Drupal.behaviors.menuLinkAutomaticTitle = { attach: function (context) { $('fieldset.menu-link-form', context).each(function () { // Try to find menu settings widget elements as well as a 'title' field in // the form, but play nicely with user permissions and form alterations. var $checkbox = $('.form-item-menu-enabled input', this); var $link_title = $('.form-item-menu-link-title input', context); var $title = $(this).closest('form').find('.form-item-title input'); // Bail out if we do not have all required fields. if (!($checkbox.length && $link_title.length && $title.length)) { return; } // If there is a link title already, mark it as overridden. The user expects // that toggling the checkbox twice will take over the node's title. if ($checkbox.is(':checked') && $link_title.val().length) { $link_title.data('menuLinkAutomaticTitleOveridden', true); } // Whenever the value is changed manually, disable this behavior. $link_title.keyup(function () { $link_title.data('menuLinkAutomaticTitleOveridden', true); }); // Global trigger on checkbox (do not fill-in a value when disabled). $checkbox.change(function () { if ($checkbox.is(':checked')) { if (!$link_title.data('menuLinkAutomaticTitleOveridden')) { $link_title.val($title.val()); } } else { $link_title.val(''); $link_title.removeData('menuLinkAutomaticTitleOveridden'); } $checkbox.closest('fieldset.vertical-tabs-pane').trigger('summaryUpdated'); $checkbox.trigger('formUpdated'); }); // Take over any title change. $title.keyup(function () { if (!$link_title.data('menuLinkAutomaticTitleOveridden') && $checkbox.is(':checked')) { $link_title.val($title.val()); $link_title.val($title.val()).trigger('formUpdated'); } }); }); } }; })(jQuery); ; (function ($) { /** * Attaches sticky table headers. */ Drupal.behaviors.tableHeader = { attach: function (context, settings) { if (!$.support.positionFixed) { return; } $('table.sticky-enabled', context).once('tableheader', function () { $(this).data("drupal-tableheader", new Drupal.tableHeader(this)); }); } }; /** * Constructor for the tableHeader object. Provides sticky table headers. * * @param table * DOM object for the table to add a sticky header to. */ Drupal.tableHeader = function (table) { var self = this; this.originalTable = $(table); this.originalHeader = $(table).children('thead'); this.originalHeaderCells = this.originalHeader.find('> tr > th'); // Clone the table header so it inherits original jQuery properties. Hide // the table to avoid a flash of the header clone upon page load. this.stickyTable = $('<table class="sticky-header"/>') .insertBefore(this.originalTable) .css({ position: 'fixed', top: '0px' }); this.stickyHeader = this.originalHeader.clone(true) .hide() .appendTo(this.stickyTable); this.stickyHeaderCells = this.stickyHeader.find('> tr > th'); this.originalTable.addClass('sticky-table'); $(window) .bind('scroll.drupal-tableheader', $.proxy(this, 'eventhandlerRecalculateStickyHeader')) .bind('resize.drupal-tableheader', { calculateWidth: true }, $.proxy(this, 'eventhandlerRecalculateStickyHeader')) // Make sure the anchor being scrolled into view is not hidden beneath the // sticky table header. Adjust the scrollTop if it does. .bind('drupalDisplaceAnchor.drupal-tableheader', function () { window.scrollBy(0, -self.stickyTable.outerHeight()); }) // Make sure the element being focused is not hidden beneath the sticky // table header. Adjust the scrollTop if it does. .bind('drupalDisplaceFocus.drupal-tableheader', function (event) { if (self.stickyVisible && event.clientY < (self.stickyOffsetTop + self.stickyTable.outerHeight()) && event.$target.closest('sticky-header').length === 0) { window.scrollBy(0, -self.stickyTable.outerHeight()); } }) .triggerHandler('resize.drupal-tableheader'); // We hid the header to avoid it showing up erroneously on page load; // we need to unhide it now so that it will show up when expected. this.stickyHeader.show(); }; /** * Event handler: recalculates position of the sticky table header. * * @param event * Event being triggered. */ Drupal.tableHeader.prototype.eventhandlerRecalculateStickyHeader = function (event) { var self = this; var calculateWidth = event.data && event.data.calculateWidth; // Reset top position of sticky table headers to the current top offset. this.stickyOffsetTop = Drupal.settings.tableHeaderOffset ? eval(Drupal.settings.tableHeaderOffset + '()') : 0; this.stickyTable.css('top', this.stickyOffsetTop + 'px'); // Save positioning data. var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight; if (calculateWidth || this.viewHeight !== viewHeight) { this.viewHeight = viewHeight; this.vPosition = this.originalTable.offset().top - 4 - this.stickyOffsetTop; this.hPosition = this.originalTable.offset().left; this.vLength = this.originalTable[0].clientHeight - 100; calculateWidth = true; } // Track horizontal positioning relative to the viewport and set visibility. var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft; var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition; this.stickyVisible = vOffset > 0 && vOffset < this.vLength; this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' }); // Only perform expensive calculations if the sticky header is actually // visible or when forced. if (this.stickyVisible && (calculateWidth || !this.widthCalculated)) { this.widthCalculated = true; // Resize header and its cell widths. this.stickyHeaderCells.each(function (index) { var cellWidth = self.originalHeaderCells.eq(index).css('width'); // Exception for IE7. if (cellWidth == 'auto') { cellWidth = self.originalHeaderCells.get(index).clientWidth + 'px'; } $(this).css('width', cellWidth); }); this.stickyTable.css('width', this.originalTable.css('width')); } }; })(jQuery); ; (function ($) { Drupal.behaviors.tokenTree = { attach: function (context, settings) { $('table.token-tree', context).once('token-tree', function () { $(this).treeTable(); }); } }; Drupal.behaviors.tokenInsert = { attach: function (context, settings) { // Keep track of which textfield was last selected/focused. $('textarea, input[type="text"]', context).focus(function() { Drupal.settings.tokenFocusedField = this; }); $('.token-click-insert .token-key', context).once('token-click-insert', function() { var newThis = $('<a href="javascript:void(0);" title="' + Drupal.t('Insert this token into your form') + '">' + $(this).html() + '</a>').click(function(){ if (typeof Drupal.settings.tokenFocusedField == 'undefined') { alert(Drupal.t('First click a text field to insert your tokens into.')); } else { var myField = Drupal.settings.tokenFocusedField; var myValue = $(this).text(); //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); } else { myField.value += myValue; } $('html,body').animate({scrollTop: $(myField).offset().top}, 500); } return false; }); $(this).html(newThis); }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.metatagFieldsetSummaries = { attach: function (context) { $('fieldset.metatags-form', context).drupalSetSummary(function (context) { var vals = []; $("input[type='text'], select, textarea", context).each(function() { var default_name = $(this).attr('name').replace(/\[value\]/, '[default]'); var default_value = $("input[type='hidden'][name='" + default_name + "']", context); if (default_value.length && default_value.val() == $(this).val()) { // Meta tag has a default value and form value matches default value. return true; } else if (!default_value.length && !$(this).val().length) { // Meta tag has no default value and form value is empty. return true; } var label = $("label[for='" + $(this).attr('id') + "']").text(); vals.push(Drupal.t('@label: @value', { '@label': label.trim(), '@value': Drupal.truncate($(this).val(), 25) || Drupal.t('None') })); }); if (vals.length === 0) { return Drupal.t('Using defaults'); } else { return vals.join('<br />'); } }); } }; /** * Encode special characters in a plain-text string for display as HTML. */ Drupal.truncate = function (str, limit) { if (str.length > limit) { return str.substr(0, limit) + '...'; } else { return str; } }; })(jQuery); ; (function ($) { Drupal.behaviors.pathFieldsetSummaries = { attach: function (context) { $('fieldset.path-form', context).drupalSetSummary(function (context) { var path = $('.form-item-path-alias input').val(); var automatic = $('.form-item-path-pathauto input').attr('checked'); if (automatic) { return Drupal.t('Automatic alias'); } if (path) { return Drupal.t('Alias: @alias', { '@alias': path }); } else { return Drupal.t('No alias'); } }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.commentFieldsetSummaries = { attach: function (context) { $('fieldset.comment-node-settings-form', context).drupalSetSummary(function (context) { return Drupal.checkPlain($('.form-item-comment input:checked', context).next('label').text()); }); // Provide the summary for the node type form. $('fieldset.comment-node-type-settings-form', context).drupalSetSummary(function(context) { var vals = []; // Default comment setting. vals.push($(".form-item-comment select option:selected", context).text()); // Threading. var threading = $(".form-item-comment-default-mode input:checked", context).next('label').text(); if (threading) { vals.push(threading); } // Comments per page. var number = $(".form-item-comment-default-per-page select option:selected", context).val(); vals.push(Drupal.t('@number comments per page', {'@number': number})); return Drupal.checkPlain(vals.join(', ')); }); } }; })(jQuery); ; (function ($) { /** * Attaches the autocomplete behavior to all required fields. */ Drupal.behaviors.autocomplete = { attach: function (context, settings) { var acdb = []; $('input.autocomplete', context).once('autocomplete', function () { var uri = this.value; if (!acdb[uri]) { acdb[uri] = new Drupal.ACDB(uri); } var $input = $('#' + this.id.substr(0, this.id.length - 13)) .attr('autocomplete', 'OFF') .attr('aria-autocomplete', 'list'); $($input[0].form).submit(Drupal.autocompleteSubmit); $input.parent() .attr('role', 'application') .append($('<span class="element-invisible" aria-live="assertive"></span>') .attr('id', $input.attr('id') + '-autocomplete-aria-live') ); new Drupal.jsAC($input, acdb[uri]); }); } }; /** * Prevents the form from submitting if the suggestions popup is open * and closes the suggestions popup when doing so. */ Drupal.autocompleteSubmit = function () { return $('#autocomplete').each(function () { this.owner.hidePopup(); }).size() == 0; }; /** * An AutoComplete object. */ Drupal.jsAC = function ($input, db) { var ac = this; this.input = $input[0]; this.ariaLive = $('#' + this.input.id + '-autocomplete-aria-live'); this.db = db; $input .keydown(function (event) { return ac.onkeydown(this, event); }) .keyup(function (event) { ac.onkeyup(this, event); }) .blur(function () { ac.hidePopup(); ac.db.cancel(); }); }; /** * Handler for the "keydown" event. */ Drupal.jsAC.prototype.onkeydown = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 40: // down arrow. this.selectDown(); return false; case 38: // up arrow. this.selectUp(); return false; default: // All other keys. return true; } }; /** * Handler for the "keyup" event. */ Drupal.jsAC.prototype.onkeyup = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 16: // Shift. case 17: // Ctrl. case 18: // Alt. case 20: // Caps lock. case 33: // Page up. case 34: // Page down. case 35: // End. case 36: // Home. case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return true; case 9: // Tab. case 13: // Enter. case 27: // Esc. this.hidePopup(e.keyCode); return true; default: // All other keys. if (input.value.length > 0) this.populatePopup(); else this.hidePopup(e.keyCode); return true; } }; /** * Puts the currently highlighted suggestion into the autocomplete field. */ Drupal.jsAC.prototype.select = function (node) { this.input.value = $(node).data('autocompleteValue'); }; /** * Highlights the next suggestion. */ Drupal.jsAC.prototype.selectDown = function () { if (this.selected && this.selected.nextSibling) { this.highlight(this.selected.nextSibling); } else if (this.popup) { var lis = $('li', this.popup); if (lis.size() > 0) { this.highlight(lis.get(0)); } } }; /** * Highlights the previous suggestion. */ Drupal.jsAC.prototype.selectUp = function () { if (this.selected && this.selected.previousSibling) { this.highlight(this.selected.previousSibling); } }; /** * Highlights a suggestion. */ Drupal.jsAC.prototype.highlight = function (node) { if (this.selected) { $(this.selected).removeClass('selected'); } $(node).addClass('selected'); this.selected = node; $(this.ariaLive).html($(this.selected).html()); }; /** * Unhighlights a suggestion. */ Drupal.jsAC.prototype.unhighlight = function (node) { $(node).removeClass('selected'); this.selected = false; $(this.ariaLive).empty(); }; /** * Hides the autocomplete suggestions. */ Drupal.jsAC.prototype.hidePopup = function (keycode) { // Select item if the right key or mousebutton was pressed. if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) { this.input.value = $(this.selected).data('autocompleteValue'); } // Hide popup. var popup = this.popup; if (popup) { this.popup = null; $(popup).fadeOut('fast', function () { $(popup).remove(); }); } this.selected = false; $(this.ariaLive).empty(); }; /** * Positions the suggestions popup and starts a search. */ Drupal.jsAC.prototype.populatePopup = function () { var $input = $(this.input); var position = $input.position(); // Show popup. if (this.popup) { $(this.popup).remove(); } this.selected = false; this.popup = $('<div id="autocomplete"></div>')[0]; this.popup.owner = this; $(this.popup).css({ top: parseInt(position.top + this.input.offsetHeight, 10) + 'px', left: parseInt(position.left, 10) + 'px', width: $input.innerWidth() + 'px', display: 'none' }); $input.before(this.popup); // Do search. this.db.owner = this; this.db.search(this.input.value); }; /** * Fills the suggestion popup with any matches received. */ Drupal.jsAC.prototype.found = function (matches) { // If no value in the textfield, do not show the popup. if (!this.input.value.length) { return false; } // Prepare matches. var ul = $('<ul></ul>'); var ac = this; for (key in matches) { $('<li></li>') .html($('<div></div>').html(matches[key])) .mousedown(function () { ac.select(this); }) .mouseover(function () { ac.highlight(this); }) .mouseout(function () { ac.unhighlight(this); }) .data('autocompleteValue', key) .appendTo(ul); } // Show popup with matches, if any. if (this.popup) { if (ul.children().size()) { $(this.popup).empty().append(ul).show(); $(this.ariaLive).html(Drupal.t('Autocomplete popup')); } else { $(this.popup).css({ visibility: 'hidden' }); this.hidePopup(); } } }; Drupal.jsAC.prototype.setStatus = function (status) { switch (status) { case 'begin': $(this.input).addClass('throbbing'); $(this.ariaLive).html(Drupal.t('Searching for matches...')); break; case 'cancel': case 'error': case 'found': $(this.input).removeClass('throbbing'); break; } }; /** * An AutoComplete DataBase object. */ Drupal.ACDB = function (uri) { this.uri = uri; this.delay = 300; this.cache = {}; }; /** * Performs a cached and delayed search. */ Drupal.ACDB.prototype.search = function (searchString) { var db = this; this.searchString = searchString; // See if this string needs to be searched for anyway. searchString = searchString.replace(/^\s+|\s+$/, ''); if (searchString.length <= 0 || searchString.charAt(searchString.length - 1) == ',') { return; } // See if this key has been searched for before. if (this.cache[searchString]) { return this.owner.found(this.cache[searchString]); } // Initiate delayed search. if (this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(function () { db.owner.setStatus('begin'); // Ajax GET request for autocompletion. $.ajax({ type: 'GET', url: db.uri + '/' + encodeURIComponent(searchString), dataType: 'json', success: function (matches) { if (typeof matches.status == 'undefined' || matches.status != 0) { db.cache[searchString] = matches; // Verify if these are still the matches the user wants to see. if (db.searchString == searchString) { db.owner.found(matches); } db.owner.setStatus('found'); } }, error: function (xmlhttp) { alert(Drupal.ajaxError(xmlhttp, db.uri)); } }); }, this.delay); }; /** * Cancels the current autocomplete request. */ Drupal.ACDB.prototype.cancel = function () { if (this.owner) this.owner.setStatus('cancel'); if (this.timer) clearTimeout(this.timer); this.searchString = ''; }; })(jQuery); ; (function ($) { Drupal.behaviors.nodeFieldsetSummaries = { attach: function (context) { $('fieldset.node-form-revision-information', context).drupalSetSummary(function (context) { var revisionCheckbox = $('.form-item-revision input', context); // Return 'New revision' if the 'Create new revision' checkbox is checked, // or if the checkbox doesn't exist, but the revision log does. For users // without the "Administer content" permission the checkbox won't appear, // but the revision log will if the content type is set to auto-revision. if (revisionCheckbox.is(':checked') || (!revisionCheckbox.length && $('.form-item-log textarea', context).length)) { return Drupal.t('New revision'); } return Drupal.t('No revision'); }); $('fieldset.node-form-author', context).drupalSetSummary(function (context) { var name = $('.form-item-name input', context).val() || Drupal.settings.anonymous, date = $('.form-item-date input', context).val(); return date ? Drupal.t('By @name on @date', { '@name': name, '@date': date }) : Drupal.t('By @name', { '@name': name }); }); $('fieldset.node-form-options', context).drupalSetSummary(function (context) { var vals = []; $('input:checked', context).parent().each(function () { vals.push(Drupal.checkPlain($.trim($(this).text()))); }); if (!$('.form-item-status input', context).is(':checked')) { vals.unshift(Drupal.t('Not published')); } return vals.join(', '); }); } }; })(jQuery); ;<|fim▁end|>
<|file_name|>typescript.rs<|end_file_name|><|fim▁begin|>// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::common; use diem_types::transaction::{ArgumentABI, ScriptABI, TypeArgumentABI}; use move_core_types::language_storage::TypeTag; use serde_generate::{ indent::{IndentConfig, IndentedWriter}, typescript, CodeGeneratorConfig, }; use heck::{CamelCase, MixedCase, ShoutySnakeCase}; use std::{ collections::BTreeMap, io::{Result, Write}, path::PathBuf, }; /// Output transaction builders and decoders in TypeScript for the given ABIs. pub fn output(out: &mut dyn Write, abis: &[ScriptABI]) -> Result<()> { write_script_calls(out, abis)?; write_helpers(out, abis) } fn write_stdlib_helper_interfaces(emitter: &mut TypeScriptEmitter<&mut dyn Write>) -> Result<()> { writeln!( emitter.out, r#" export interface TypeTagDef {{ type: Types; arrayType?: TypeTagDef; name?: string; module?: string; address?: string; typeParams?: TypeTagDef[]; }} export interface ArgDef {{ readonly name: string; readonly type: TypeTagDef; readonly choices?: string[]; readonly mandatory?: boolean; }} export interface ScriptDef {{ readonly stdlibEncodeFunction: (...args: any[]) => DiemTypes.Script; readonly stdlibDecodeFunction: (script: DiemTypes.Script) => ScriptCall; readonly codeName: string; readonly description: string; readonly typeArgs: string[]; readonly args: ArgDef[]; }} export enum Types {{ Boolean, U8, U64, U128, Address, Array, Struct }} "# )?; Ok(()) } /// Output transaction helper functions for the given ABIs. fn write_helpers(out: &mut dyn Write, abis: &[ScriptABI]) -> Result<()> { let mut emitter = TypeScriptEmitter { out: IndentedWriter::new(out, IndentConfig::Space(2)), }; emitter.output_preamble()?; write_stdlib_helper_interfaces(&mut emitter)?; writeln!(emitter.out, "\nexport class Stdlib {{")?; emitter.out.indent(); writeln!(emitter.out, "private static fromHexString(hexString: string): Uint8Array {{ return new Uint8Array(hexString.match(/.{{1,2}}/g)!.map((byte) => parseInt(byte, 16)));}}")?; for abi in abis { emitter.output_script_encoder_function(abi)?; } for abi in abis { emitter.output_script_decoder_function(abi)?; } for abi in abis { emitter.output_code_constant(abi)?; } writeln!( emitter.out, "\nstatic ScriptArgs: {{[name: string]: ScriptDef}} = {{" )?; emitter.out.indent(); for abi in abis { emitter.output_script_args_definition(abi)?; } emitter.out.unindent(); writeln!(emitter.out, "}}")?; emitter.out.unindent(); writeln!(emitter.out, "\n}}\n")?; writeln!(emitter.out, "\nexport type ScriptDecoders = {{")?; emitter.out.indent(); writeln!(emitter.out, "User: {{")?; emitter.out.indent(); for abi in abis { emitter.output_script_args_callbacks(abi)?; } writeln!( emitter.out, "default: (type: keyof ScriptDecoders['User']) => void;" )?; emitter.out.unindent(); writeln!(emitter.out, "}};")?; emitter.out.unindent(); writeln!(emitter.out, "}};") } fn write_script_calls(out: &mut dyn Write, abis: &[ScriptABI]) -> Result<()> { let external_definitions = crate::common::get_external_definitions("diemTypes"); let script_registry: BTreeMap<_, _> = vec![( "ScriptCall".to_string(), common::make_abi_enum_container(abis), )] .into_iter() .collect(); let mut comments: BTreeMap<_, _> = abis .iter() .map(|abi| { let mut paths = Vec::new(); paths.push("ScriptCall".to_string()); paths.push(abi.name().to_camel_case()); (paths, crate::common::prepare_doc_string(abi.doc())) }) .collect(); comments.insert( vec!["ScriptCall".to_string()], "Structured representation of a call into a known Move script.".into(), ); let config = CodeGeneratorConfig::new("StdLib".to_string()) .with_comments(comments) .with_external_definitions(external_definitions) .with_serialization(false); typescript::CodeGenerator::new(&config) .output(out, &script_registry) .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, format!("{}", err)))?; Ok(()) } /// Shared state for the TypeScript code generator. struct TypeScriptEmitter<T> { /// Writer. out: IndentedWriter<T>, } impl<T> TypeScriptEmitter<T> where T: Write, { fn output_preamble(&mut self) -> Result<()> { writeln!( self.out, r#" import {{ BcsSerializer }} from '../bcs/bcsSerializer'; "#, )?; Ok(()) } fn output_script_encoder_function(&mut self, abi: &ScriptABI) -> Result<()> { writeln!( self.out, "\n{}static encode{}Script({}): DiemTypes.Script {{", Self::quote_doc(abi.doc()), abi.name().to_camel_case(), [ Self::quote_type_parameters(abi.ty_args()), Self::quote_parameters(abi.args()), ] .concat() .join(", ") )?; self.out.indent(); writeln!( self.out, r#"const code = Stdlib.{}_CODE; const tyArgs: Seq<DiemTypes.TypeTag> = [{}]; const args: Seq<DiemTypes.TransactionArgument> = [{}]; return new DiemTypes.Script(code, tyArgs, args);"#, abi.name().to_shouty_snake_case(), Self::quote_type_arguments(abi.ty_args()), Self::quote_arguments(abi.args()), )?; self.out.unindent(); writeln!(self.out, "}}") } fn output_script_decoder_function(&mut self, abi: &ScriptABI) -> Result<()> { writeln!( self.out, "\nstatic decode{}Script({}script: DiemTypes.Script): ScriptCallVariant{0} {{", abi.name().to_camel_case(), // prevent warning "unused variable" if abi.ty_args().is_empty() && abi.args().is_empty() { "_" } else { "" } )?; let mut all_args: Vec<String> = Vec::new(); all_args.extend( abi.ty_args() .iter() .enumerate() .map(|(idx, _)| format!("script.ty_args[{}]", idx)) .collect::<Vec<_>>(), ); all_args.extend( abi.args() .iter() .enumerate() .map(|(idx, arg)| { format!( "(script.args[{}] as {}).value", idx, Self::quote_transaction_argument_type(arg.type_tag()) ) }) .collect::<Vec<_>>(), ); self.out.indent(); writeln!( self.out, "return new ScriptCallVariant{}(", abi.name().to_camel_case() )?; self.out.indent(); writeln!(self.out, "{}", all_args.join(",\n"))?;<|fim▁hole|> self.out.unindent(); writeln!(self.out, ");",)?; self.out.unindent(); writeln!(self.out, "}}")?; Ok(()) } fn output_code_constant(&mut self, abi: &ScriptABI) -> Result<()> { writeln!( self.out, "\nstatic {}_CODE = Stdlib.fromHexString('{}');", abi.name().to_shouty_snake_case(), abi.code() .iter() .map(|x| format!("{:02x}", *x as i8)) .collect::<Vec<_>>() .join("") )?; Ok(()) } fn output_script_args_definition(&mut self, abi: &ScriptABI) -> Result<()> { writeln!(self.out, "{}: {{", abi.name().to_camel_case())?; writeln!( self.out, " stdlibEncodeFunction: Stdlib.encode{}Script,", abi.name().to_camel_case() )?; writeln!( self.out, " stdlibDecodeFunction: Stdlib.decode{}Script,", abi.name().to_camel_case() )?; writeln!( self.out, " codeName: '{}',", abi.name().to_shouty_snake_case() )?; writeln!( self.out, " description: \"{}\",", abi.doc().replace("\"", "\\\"").replace("\n", "\" + \n \"") )?; writeln!( self.out, " typeArgs: [{}],", abi.ty_args() .iter() .map(|ty_arg| format!("\"{}\"", ty_arg.name())) .collect::<Vec<_>>() .join(", ") )?; writeln!(self.out, " args: [")?; writeln!( self.out, "{}", abi.args() .iter() .map(|arg| format!( "{{name: \"{}\", type: {}}}", arg.name(), Self::quote_script_arg_type(arg.type_tag()) )) .collect::<Vec<_>>() .join(", ") )?; writeln!(self.out, " ]")?; writeln!(self.out, "}},")?; Ok(()) } fn output_script_args_callbacks(&mut self, abi: &ScriptABI) -> Result<()> { let mut args_with_types = abi .ty_args() .iter() .map(|ty_arg| { format!( "{}: DiemTypes.TypeTagVariantStruct", ty_arg.name().to_mixed_case() ) }) .collect::<Vec<_>>(); args_with_types.extend( abi.args() .iter() .map(|arg| { format!( "{}: {}", arg.name().to_mixed_case(), Self::quote_transaction_argument_type(arg.type_tag()) ) }) .collect::<Vec<_>>(), ); writeln!( self.out, "{}: (type: string, {}) => void;", abi.name().to_camel_case(), args_with_types.join(", ") )?; Ok(()) } fn quote_doc(doc: &str) -> String { let doc = crate::common::prepare_doc_string(doc); let text = textwrap::indent(&doc, " * ").replace("\n\n", "\n *\n"); format!("/**\n{}\n */\n", text) } fn quote_type_parameters(ty_args: &[TypeArgumentABI]) -> Vec<String> { ty_args .iter() .map(|ty_arg| format!("{}: DiemTypes.TypeTag", ty_arg.name())) .collect() } fn quote_parameters(args: &[ArgumentABI]) -> Vec<String> { args.iter() .map(|arg| format!("{}: {}", arg.name(), Self::quote_type(arg.type_tag()))) .collect() } fn quote_type_arguments(ty_args: &[TypeArgumentABI]) -> String { ty_args .iter() .map(|ty_arg| ty_arg.name().to_string()) .collect::<Vec<_>>() .join(", ") } fn quote_arguments(args: &[ArgumentABI]) -> String { args.iter() .map(|arg| Self::quote_transaction_argument(arg.type_tag(), arg.name())) .collect::<Vec<_>>() .join(", ") } fn quote_type(type_tag: &TypeTag) -> String { use TypeTag::*; match type_tag { Bool => "boolean".into(), U8 => "number".into(), U64 => "BigInt".into(), U128 => "BigInt".into(), Address => "DiemTypes.AccountAddress".into(), Vector(type_tag) => match type_tag.as_ref() { U8 => "Uint8Array".into(), _ => common::type_not_allowed(type_tag), }, Struct(_) | Signer => common::type_not_allowed(type_tag), } } fn quote_transaction_argument_type(type_tag: &TypeTag) -> String { use TypeTag::*; match type_tag { Bool => "DiemTypes.TransactionArgumentVariantBool".to_string(), U8 => "DiemTypes.TransactionArgumentVariantU8".to_string(), U64 => "DiemTypes.TransactionArgumentVariantU64".to_string(), U128 => "DiemTypes.TransactionArgumentVariantU128".to_string(), Address => "DiemTypes.TransactionArgumentVariantAddress".to_string(), Vector(type_tag) => match type_tag.as_ref() { U8 => "DiemTypes.TransactionArgumentVariantU8Vector".to_string(), _ => common::type_not_allowed(type_tag), }, Struct(_) | Signer => common::type_not_allowed(type_tag), } } fn quote_transaction_argument(type_tag: &TypeTag, name: &str) -> String { format!( "new {}({})", Self::quote_transaction_argument_type(type_tag), name ) } fn quote_script_arg_type(type_tag: &TypeTag) -> String { use TypeTag::*; match type_tag { Bool => "{type: Types.Boolean}".to_string(), U8 => "{type: Types.U8}".to_string(), U64 => "{type: Types.U64}".to_string(), U128 => "{type: Types.U128}".to_string(), Address => "{type: Types.Address}".to_string(), Vector(type_tag) => format!("{{type: Types.Array, arrayType: {}}}", Self::quote_script_arg_type(type_tag)), Struct(struct_tag) => format!("{{type: Types.Struct, name: \"{}\", module: \"{}\", address: \"{}\", typeParams: [{}]}}", struct_tag.name, struct_tag.module, struct_tag.address, struct_tag.type_params.iter().map(|tt| Self::quote_script_arg_type(tt)).collect::<Vec<_>>().join(", ")), Signer => common::type_not_allowed(type_tag), } } } pub struct Installer { install_dir: PathBuf, } impl Installer { pub fn new(install_dir: PathBuf) -> Self { Installer { install_dir } } } impl crate::SourceInstaller for Installer { type Error = Box<dyn std::error::Error>; fn install_transaction_builders( &self, name: &str, abis: &[ScriptABI], ) -> std::result::Result<(), Self::Error> { let dir_path = self.install_dir.join(name); std::fs::create_dir_all(&dir_path)?; let mut file = std::fs::File::create(dir_path.join("index.ts"))?; output(&mut file, abis)?; Ok(()) } }<|fim▁end|>
<|file_name|>test_fd.py<|end_file_name|><|fim▁begin|>import facedetect import cv2 def test_fd(): image = cv2.imread('abba.jpg') print image.shape<|fim▁hole|> print FD.features if __name__ == '__main__': test_fd()<|fim▁end|>
FD = facedetect.FeatureDetect(image) FD.detectEyes() FD.detectFace()
<|file_name|>karma.conf.js<|end_file_name|><|fim▁begin|>// Karma configuration // Generated on Wed Feb 17 2016 10:45:47 GMT+0100 (CET) <|fim▁hole|> // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['systemjs', 'jasmine'], // list of files / patterns to load in the browser files: [ 'app/**/*spec.js' ], systemjs: { // Point out where the SystemJS config file is configFile: 'app/systemjs.config.js', serveFiles: [ 'app/**/*.js' ] }, plugins: [ 'karma-systemjs', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-phantomjs-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-coverage' ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'app/**/!(*spec).js': ['coverage'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage'], coverageReporter: { reporters:[ {type: 'lcov', subdir: 'report-lcov'}, {type: 'json', subdir: 'report-json', file: 'coverage-final.json'}, ] }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }) }<|fim▁end|>
module.exports = function(config) { config.set({
<|file_name|>places_item.js<|end_file_name|><|fim▁begin|>/** * Created by lee on 10/13/17. */ import React, { Component } from 'react'; export default class PlacesItem extends Component { constructor(props) { super(props); this.config = this.config.bind(this); this.rateStars = this.rateStars.bind(this); this.startBounce = this.startBounce.bind(this); this.endBounce = this.endBounce.bind(this); } config() { return { itemPhotoSize : { maxWidth: 80, maxHeight: 91 } } } startBounce() { this.props.place.marker.setAnimation(google.maps.Animation.BOUNCE); } endBounce() { this.props.place.marker.setAnimation(null); } // build rate starts rateStars(num) { let stars = []; for(let i = 0; i < num; i++) { stars.push( <span><img key={i} src='./assets/star.png' /></span> ) } return stars } render() { const {place} = this.props.place; const img = place.photos ? place.photos[0].getUrl(this.config().itemPhotoSize) : './assets/no_image.png'; <|fim▁hole|> return( <div className="item-box" onMouseOver = {this.startBounce} onMouseOut={this.endBounce}> <div className="item-text"> <strong>{place.name}</strong> { place.rating ?<p>{this.rateStars(place.rating)}<span>&nbsp;&nbsp;&nbsp;{'$'.repeat(place.price_level)}</span></p> : <p>{'$'.repeat(place.price_level)}</p> } <p id="item-address">{place.formatted_address}</p> <p>{place.opening_hours && place.opening_hours.open_now ? "Open" :"Closed"}</p> </div> <img className='item-image' src={img} /> </div> ) } }<|fim▁end|>
<|file_name|>malwebsites.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python import subprocess import sys, threading, Queue import os import string from time import gmtime, strftime import urllib2 import urllib import re, time import urlparse import os.path import logging #from google import search import scan import executemechanize import extraction import mechanize from BeautifulSoup import BeautifulSoup def domaindownload():# this function downloads domain and website links from multible blacklisted website databases. if os.path.isfile("list/list1.txt")==True: print "Malicious website database from https://spyeyetracker.abuse.ch exists!\n" print "Continuing with the next list." else: print "Fetching list from: https://spyeyetracker.abuse.ch" command1="wget https://zeustracker.abuse.ch/blocklist.php?download=domainblocklist -O list/list1.txt" os.system(command1) #--proxy-user=username --proxy-password=password if os.path.isfile("list/list2.txt")==True: print "Malicious website database from https://zeustracker.abuse.ch/ exists!\n" print "Continuing with the next list." else: print "Fetching list from: https://zeustracker.abuse.ch/" command2="wget https://zeustracker.abuse.ch/blocklist.php?download=domainblocklist -O list/list2.txt" os.system(command2) if os.path.isfile("list/list3.txt")==True: print "Malicious website database 3 exists!\n" else: print "Fetching list 3" command3="wget http://hosts-file.net/hphosts-partial.asp -O list/list3.txt" os.system(command3) print "*****\nThis May Take a While\n" mainfile=open("list/malwebsites.txt", 'w') file1=open("list/list1.txt", 'r') mainfile.write(file1.read()) file2=open("list/list2.txt", 'r') mainfile.write(file2.read()) file3=open("list/list3.txt", 'r') mainfile.write(file3.read()) mainfile.close()<|fim▁hole|> file2.close() file3.close() def duplicateremover(): mylist=list() fopen2=open("list/malwebsites.txt","r") for line in fopen2: line=line.strip() if line.startswith("127.0.0.1"): line=line[10:] pass if line.startswith("#"): continue if line.find('#') == 1: continue # if line=="invalid": # continue if not line: continue if line in mylist: continue if not (line.startswith("http://")) and not (line.startswith("https://")): line="http://"+line pass # print line mylist.append(line) fopen2.close() fopen3=open("list/malwebsites.txt","w") for line in mylist: fopen3.write(line+"\n") fopen3.close() print "List of Malicious websites were downloaded from three databases."<|fim▁end|>
file1.close()
<|file_name|>debug_events_monitors_test.py<|end_file_name|><|fim▁begin|># Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for the debug events writer Python class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.core.protobuf import debug_event_pb2 from tensorflow.python.debug.lib import debug_events_monitors from tensorflow.python.debug.lib import debug_events_reader from tensorflow.python.debug.lib import dumping_callback from tensorflow.python.debug.lib import dumping_callback_test_lib from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import googletest from tensorflow.python.platform import test class TestMonitor(debug_events_monitors.BaseMonitor): def __init__(self, debug_data_reader): super(TestMonitor, self).__init__(debug_data_reader) # Mapping execution index to Execution data objects. self.executions = dict() # Mapping graph execution trace index to GraphExecutionTrace data objects. self.graph_execution_traces = dict() def on_execution(self, execution_index, execution): if execution_index in self.executions: raise ValueError("Duplicate execution index: %d" % execution_index) self.executions[execution_index] = execution def on_graph_execution_trace(self, graph_execution_trace_index, graph_execution_trace): if graph_execution_trace_index in self.graph_execution_traces: raise ValueError("Duplicate graph-execution-trace index: %d" % graph_execution_trace_index) self.graph_execution_traces[ graph_execution_trace_index] = graph_execution_trace class DebugEventsMonitorTest(dumping_callback_test_lib.DumpingCallbackTestBase, parameterized.TestCase): @parameterized.named_parameters( ("NoTensor", "NO_TENSOR"), ("ConciseHealth", "CONCISE_HEALTH"), ("FullTensor", "FULL_TENSOR"), ) def testOnExecutionIsCalled(self, tensor_debug_mode): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) x = constant_op.constant([[1, 2], [3, 4]], dtype=dtypes.float32) y = constant_op.constant([[-1], [1]], dtype=dtypes.float32) math_ops.matmul(x, y) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: test_monitor = TestMonitor(reader) reader.update() self.assertLen(test_monitor.executions, 1) self.assertEmpty(test_monitor.graph_execution_traces) execution = test_monitor.executions[0] self.assertTrue(execution.wall_time) self.assertEqual(execution.op_type, "MatMul") self.assertLen(execution.output_tensor_device_ids, 1) self.assertLen(execution.input_tensor_ids, 2) self.assertLen(execution.output_tensor_ids, 1) self.assertEqual(execution.num_outputs, 1) self.assertEqual(execution.graph_id, "") if tensor_debug_mode == "NO_TENSOR": self.assertIsNone(execution.debug_tensor_values) elif tensor_debug_mode == "CONCISE_HEALTH": self.assertLen(execution.debug_tensor_values, 1) # [tensor_id, element_count, neg_inf_count, pos_inf_count, nan_count]. self.assertLen(execution.debug_tensor_values[0], 5) elif tensor_debug_mode == "FULL_TENSOR": # Full tensor values are not stored in the debug_tensor_values field. self.assertIsNone(execution.debug_tensor_values) self.assertAllClose( reader.execution_to_tensor_values(execution), [[[1.], [1.]]]) @parameterized.named_parameters( ("ConciseHealth", "CONCISE_HEALTH"), ("FullTensor", "FULL_TENSOR"), ) def testOnGraphExecutionTraceIsCalled(self, tensor_debug_mode): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) @def_function.function def unique_sum(xs): """Sum over the unique values, for testing.""" unique_xs, indices = array_ops.unique(xs) return math_ops.reduce_sum(unique_xs), indices xs = constant_op.constant([2., 6., 8., 1., 2.], dtype=dtypes.float32) unique_sum(xs) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: test_monitor = TestMonitor(reader) reader.update() self.assertLen(test_monitor.executions, 1) execution = test_monitor.executions[0] self.assertTrue(execution.wall_time) self.assertStartsWith(execution.op_type, "__inference_unique_sum") self.assertLen(execution.output_tensor_device_ids, 2) self.assertLen(execution.input_tensor_ids, 1) self.assertLen(execution.output_tensor_ids, 2) self.assertEqual(execution.num_outputs, 2) self.assertTrue(execution.graph_id) traces = test_monitor.graph_execution_traces if tensor_debug_mode == "CONCISE_HEALTH": self.assertLen(traces, 3) # [Placeholder:0, Unique:0 , Sum:0]. self.assertEqual(traces[0].op_type, "Placeholder") self.assertEqual(traces[0].output_slot, 0) self.assertEqual(traces[1].op_type, "Unique") self.assertEqual(traces[1].output_slot, 0) # Unique:1 is not traced under CONCISE_HEALTH mode, as it's int-dtype. self.assertEqual(traces[2].op_type, "Sum") self.assertEqual(traces[2].output_slot, 0) # [tensor_id, element_count, neg_inf_count, pos_inf_count, nan_count]. self.assertLen(traces[0].debug_tensor_value, 5) self.assertLen(traces[1].debug_tensor_value, 5) self.assertLen(traces[2].debug_tensor_value, 5) elif tensor_debug_mode == "FULL_TENSOR": self.assertLen(traces, 4) # [Placeholder:0, Unique:0, Unique:1, Sum:0]. self.assertEqual(traces[0].op_type, "Placeholder") self.assertEqual(traces[0].output_slot, 0) self.assertIsNone(traces[0].debug_tensor_value) self.assertAllEqual( reader.graph_execution_trace_to_tensor_value(traces[0]), [2., 6., 8., 1., 2.]) self.assertEqual(traces[1].op_type, "Unique") self.assertEqual(traces[1].output_slot, 0) self.assertIsNone(traces[1].debug_tensor_value) self.assertAllEqual( reader.graph_execution_trace_to_tensor_value(traces[1]), [2., 6., 8., 1.]) self.assertEqual(traces[2].op_type, "Unique") self.assertEqual(traces[2].output_slot, 1) self.assertIsNone(traces[2].debug_tensor_value) self.assertAllEqual( reader.graph_execution_trace_to_tensor_value(traces[2]), [0, 1, 2, 3, 0]) self.assertEqual(traces[3].op_type, "Sum") self.assertEqual(traces[3].output_slot, 0) self.assertIsNone(traces[3].debug_tensor_value) self.assertAllClose( reader.graph_execution_trace_to_tensor_value(traces[3]), 17.) class AlertDataObjectsTest(test_util.TensorFlowTestCase): """Unit tests for alert-class objects.""" def testInfNanMonitor(self): alert = debug_events_monitors.InfNanAlert( 1234, "FooOp", 1, size=1000, num_neg_inf=5, num_pos_inf=10, num_nan=20, execution_index=777, graph_execution_trace_index=888) self.assertEqual(alert.wall_time, 1234) self.assertEqual(alert.op_type, "FooOp") self.assertEqual(alert.output_slot, 1) self.assertEqual(alert.size, 1000) self.assertEqual(alert.num_neg_inf, 5) self.assertEqual(alert.num_pos_inf, 10) self.assertEqual(alert.num_nan, 20) self.assertEqual(alert.execution_index, 777) self.assertEqual(alert.graph_execution_trace_index, 888) class InfNanMonitorTest(test_util.TensorFlowTestCase, parameterized.TestCase): def testInfNanMonitorStartsWithEmptyAlerts(self): mock_reader = test.mock.MagicMock() monitor = debug_events_monitors.InfNanMonitor(mock_reader) self.assertEmpty(monitor.alerts()) def testInfNanMonitorOnExecutionUnderCurtHealthMode(self): mock_reader = test.mock.MagicMock() monitor = debug_events_monitors.InfNanMonitor(mock_reader) execution_digest = debug_events_reader.ExecutionDigest( 1234, 1, "FooOp", output_tensor_device_ids=[0, 1])<|fim▁hole|> execution_digest, "worker01", ["a1", "b2", "e3"], debug_event_pb2.TensorDebugMode.CURT_HEALTH, graph_id=None, input_tensor_ids=[12, 34], output_tensor_ids=[56, 78], debug_tensor_values=[[-1, 0], [-1, 1]]) # [tensor_id, any_inf_nan]. monitor.on_execution(50, execution) self.assertLen(monitor.alerts(), 1) alert = monitor.alerts()[0] self.assertEqual(alert.wall_time, 1234) self.assertEqual(alert.op_type, "FooOp") self.assertEqual(alert.output_slot, 1) # The four fields below are unavailable under CURT_HEALTH mode by design. self.assertIsNone(alert.size) self.assertIsNone(alert.num_neg_inf) self.assertIsNone(alert.num_pos_inf) self.assertIsNone(alert.num_nan) self.assertEqual(alert.execution_index, 50) self.assertIsNone(alert.graph_execution_trace_index) def testInfNanMonitorOnExecutionUnderConciseHealthMode(self): mock_reader = test.mock.MagicMock() monitor = debug_events_monitors.InfNanMonitor(mock_reader) execution_digest = debug_events_reader.ExecutionDigest( 1234, 1, "BarOp", output_tensor_device_ids=[0, 1]) execution = debug_events_reader.Execution( execution_digest, "worker01", ["a1", "b2", "e3"], debug_event_pb2.TensorDebugMode.CONCISE_HEALTH, graph_id=None, input_tensor_ids=[12, 34], output_tensor_ids=[56, 78], # [tensor_id, size, num_neg_inf, num_pos_inf, num_nan]. debug_tensor_values=[[-1, 10, 1, 2, 3], [-1, 100, 0, 0, 0]]) monitor.on_execution(60, execution) self.assertLen(monitor.alerts(), 1) alert = monitor.alerts()[0] self.assertEqual(alert.wall_time, 1234) self.assertEqual(alert.op_type, "BarOp") self.assertEqual(alert.output_slot, 0) self.assertEqual(alert.size, 10) self.assertEqual(alert.num_neg_inf, 1) self.assertEqual(alert.num_pos_inf, 2) self.assertEqual(alert.num_nan, 3) self.assertEqual(alert.execution_index, 60) self.assertIsNone(alert.graph_execution_trace_index) @parameterized.named_parameters( ("FloatsScalarWithInfAndNan", np.inf, np.float32, 1, 0, 1, 0), ("Floats2DWithInfAndNan", [[0, np.nan, np.nan, -np.inf] ], np.float32, 4, 1, 0, 2), ("Floats1DWithoutInfOrNan", [0, -1e6, 1e6, 9e5], np.float32, 4, 0, 0, 0), ("Integers", [[0, 1000, -200, -300]], np.int32, 4, 0, 0, 0), ("Booleans", [False, True, False, False], np.int32, 4, 0, 0, 0), ) def testInfNanMonitorOnExecutionUnderFullTensorModeWorks( self, tensor_value, dtype, expected_size, expected_num_neg_inf, expected_num_pos_inf, expected_num_nan): mock_reader = test.mock.MagicMock() mock_reader.execution_to_tensor_values.return_value = [ np.array([[0.0, -1.0, 1.0]]), np.array(tensor_value, dtype=dtype) ] monitor = debug_events_monitors.InfNanMonitor(mock_reader) execution_digest = debug_events_reader.ExecutionDigest( 1234, 1, "__inference_bar_function_1234", output_tensor_device_ids=[0, 1]) execution = debug_events_reader.Execution( execution_digest, "worker01", ["a1", "b2", "e3"], debug_event_pb2.TensorDebugMode.FULL_TENSOR, graph_id=None, input_tensor_ids=[12, 34], output_tensor_ids=[56, 78]) monitor.on_execution(70, execution) if expected_num_neg_inf or expected_num_pos_inf or expected_num_nan: self.assertLen(monitor.alerts(), 1) alert = monitor.alerts()[0] self.assertEqual(alert.wall_time, 1234) self.assertEqual(alert.op_type, "__inference_bar_function_1234") self.assertEqual(alert.output_slot, 1) self.assertEqual(alert.size, expected_size) self.assertEqual(alert.num_neg_inf, expected_num_neg_inf) self.assertEqual(alert.num_pos_inf, expected_num_pos_inf) self.assertEqual(alert.num_nan, expected_num_nan) self.assertEqual(alert.execution_index, 70) self.assertIsNone(alert.graph_execution_trace_index, 70) else: self.assertEmpty(monitor.alerts()) def testInfNaNMonitorOnGraphExecutionTraceCurtHealthMode(self): mock_reader = test.mock.MagicMock() monitor = debug_events_monitors.InfNanMonitor(mock_reader) trace_digest = debug_events_reader.GraphExecutionTraceDigest( 1234, 1, "FooOp", "FooOp_1", 2, "g1") trace = debug_events_reader.GraphExecutionTrace( trace_digest, ["g0", "g1"], debug_event_pb2.TensorDebugMode.CURT_HEALTH, debug_tensor_value=[9, 1]) # [tensor_id, any_inf_nan]. monitor.on_graph_execution_trace(55, trace) self.assertLen(monitor.alerts(), 1) alert = monitor.alerts()[0] self.assertEqual(alert.wall_time, 1234) self.assertEqual(alert.op_type, "FooOp") self.assertEqual(alert.output_slot, 2) # The four fields below are unavailable under CURT_HEALTH mode by design. self.assertIsNone(alert.size) self.assertIsNone(alert.num_neg_inf) self.assertIsNone(alert.num_pos_inf) self.assertIsNone(alert.num_nan) self.assertIsNone(alert.execution_index) self.assertEqual(alert.graph_execution_trace_index, 55) def testInfNaNMonitorOnGraphExecutionTraceConciseHealthMode(self): mock_reader = test.mock.MagicMock() monitor = debug_events_monitors.InfNanMonitor(mock_reader) trace_digest = debug_events_reader.GraphExecutionTraceDigest( 1234, 1, "FooOp", "FooOp_1", 2, "g1") trace = debug_events_reader.GraphExecutionTrace( trace_digest, ["g0", "g1"], debug_event_pb2.TensorDebugMode.CONCISE_HEALTH, # [tensor_id, size, num_neg_inf, num_pos_inf, num_nan]. debug_tensor_value=[9, 100, 3, 2, 1]) monitor.on_graph_execution_trace(55, trace) self.assertLen(monitor.alerts(), 1) alert = monitor.alerts()[0] self.assertEqual(alert.wall_time, 1234) self.assertEqual(alert.op_type, "FooOp") self.assertEqual(alert.output_slot, 2) self.assertEqual(alert.size, 100) self.assertEqual(alert.num_neg_inf, 3) self.assertEqual(alert.num_pos_inf, 2) self.assertEqual(alert.num_nan, 1) self.assertEqual(alert.graph_execution_trace_index, 55) @parameterized.named_parameters( ("FloatsScalarWithInfAndNan", np.inf, np.float32, 1, 0, 1, 0), ("Floats2DWithInfAndNan", [[0, np.nan, np.nan, -np.inf] ], np.float32, 4, 1, 0, 2), ("Floats1DWithoutInfOrNan", [0, -1e6, 1e6, 9e5], np.float32, 4, 0, 0, 0), ("Integers", [[0, 1000, -200, -300]], np.int32, 4, 0, 0, 0), ("Booleans", [False, True, False, False], np.int32, 4, 0, 0, 0), ) def testInfNanMonitorOnGraphExecutionTraceUnderFullTensorModeWorks( self, tensor_value, dtype, expected_size, expected_num_neg_inf, expected_num_pos_inf, expected_num_nan): mock_reader = test.mock.MagicMock() mock_reader.graph_execution_trace_to_tensor_value.return_value = np.array( tensor_value, dtype=dtype) monitor = debug_events_monitors.InfNanMonitor(mock_reader) trace_digest = debug_events_reader.GraphExecutionTraceDigest( 1234, 1, "BazOp", "name_scope_3/BazOp_1", 2, "g1") trace = debug_events_reader.GraphExecutionTrace( trace_digest, ["g0", "g1"], debug_event_pb2.TensorDebugMode.FULL_TENSOR) monitor.on_graph_execution_trace(80, trace) if expected_num_neg_inf or expected_num_pos_inf or expected_num_nan: self.assertLen(monitor.alerts(), 1) alert = monitor.alerts()[0] self.assertEqual(alert.wall_time, 1234) self.assertEqual(alert.op_type, "BazOp") self.assertEqual(alert.output_slot, 2) self.assertEqual(alert.size, expected_size) self.assertEqual(alert.num_neg_inf, expected_num_neg_inf) self.assertEqual(alert.num_pos_inf, expected_num_pos_inf) self.assertEqual(alert.num_nan, expected_num_nan) self.assertIsNone(alert.execution_index) self.assertEqual(alert.graph_execution_trace_index, 80) else: self.assertEmpty(monitor.alerts()) def testLimitingInfNanMonitorAlertCountWorks(self): mock_reader = test.mock.MagicMock() monitor = debug_events_monitors.InfNanMonitor(mock_reader, limit=3) for i in range(10): execution_digest = debug_events_reader.ExecutionDigest( i * 1000, 1, "FooOp", output_tensor_device_ids=[0, 1]) execution = debug_events_reader.Execution( execution_digest, "worker01", ["a1", "b2", "e3"], debug_event_pb2.TensorDebugMode.CURT_HEALTH, graph_id=None, input_tensor_ids=[12, 34], output_tensor_ids=[56, 78], debug_tensor_values=[[-1, 0], [-1, 1]]) # [tensor_id, any_inf_nan]. monitor.on_execution(i, execution) alerts = monitor.alerts() self.assertLen(alerts, 3) for i, alert in enumerate(alerts): self.assertEqual(alert.wall_time, i * 1000) self.assertEqual(alert.op_type, "FooOp") self.assertEqual(alert.output_slot, 1) # The four fields below are unavailable under CURT_HEALTH mode by design. self.assertIsNone(alert.size) self.assertIsNone(alert.num_neg_inf) self.assertIsNone(alert.num_pos_inf) self.assertIsNone(alert.num_nan) self.assertEqual(alert.execution_index, i) self.assertIsNone(alert.graph_execution_trace_index) if __name__ == "__main__": ops.enable_eager_execution() googletest.main()<|fim▁end|>
execution = debug_events_reader.Execution(
<|file_name|>content_view.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright 2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated<|fim▁hole|># in this software or its documentation. from katello.client.api.base import KatelloAPI from katello.client.lib.utils.data import update_dict_unless_none class ContentViewAPI(KatelloAPI): """ Connection class to access content_view calls """ def content_views_by_org(self, org_id, env=None): path = "/api/organizations/%s/content_views" % org_id params = {"environment_id": env["id"]} if env else {} views = self.server.GET(path, params)[1] return views def views_by_label_name_or_id(self, org_id, label=None, name=None, vid=None): params = {} update_dict_unless_none(params, "name", name) update_dict_unless_none(params, "label", label) update_dict_unless_none(params, "id", vid) path = "/api/organizations/%s/content_views" % org_id views = self.server.GET(path, params)[1] return views def show(self, org_name, view_id, environment_id=None): path = "/api/organizations/%s/content_views/%s" % (org_name, view_id) params = {"environment_id": environment_id} view = self.server.GET(path, params)[1] return view def content_view_by_label(self, org_id, view_label): path = "/api/organizations/%s/content_views/" % (org_id) views = self.server.GET(path, {"label": view_label})[1] if len(views) > 0: return views[0] else: return None def update(self, org_id, cv_id, label, description): view = {} view = update_dict_unless_none(view, "label", label) view = update_dict_unless_none(view, "description", description) path = "/api/organizations/%s/content_views/%s" % (org_id, cv_id) return self.server.PUT(path, {"content_view": view})[1] def delete(self, org_id, cv_id): path = "/api/organizations/%s/content_views/%s" % (org_id, cv_id) return self.server.DELETE(path)[1] def promote(self, cv_id, env_id): path = "/api/content_views/%s/promote" % cv_id params = {"environment_id": env_id} return self.server.POST(path, params)[1] def refresh(self, cv_id): path = "/api/content_views/%s/refresh" % cv_id return self.server.POST(path, {})[1]<|fim▁end|>
<|file_name|>notify.py<|end_file_name|><|fim▁begin|>"""Support for Matrix notifications.""" import voluptuous as vol from homeassistant.components.notify import ( ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService, ) import homeassistant.helpers.config_validation as cv<|fim▁hole|> from .const import DOMAIN, SERVICE_SEND_MESSAGE CONF_DEFAULT_ROOM = "default_room" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_DEFAULT_ROOM): cv.string}) def get_service(hass, config, discovery_info=None): """Get the Matrix notification service.""" return MatrixNotificationService(config[CONF_DEFAULT_ROOM]) class MatrixNotificationService(BaseNotificationService): """Send notifications to a Matrix room.""" def __init__(self, default_room): """Set up the Matrix notification service.""" self._default_room = default_room def send_message(self, message="", **kwargs): """Send the message to the Matrix server.""" target_rooms = kwargs.get(ATTR_TARGET) or [self._default_room] service_data = {ATTR_TARGET: target_rooms, ATTR_MESSAGE: message} if (data := kwargs.get(ATTR_DATA)) is not None: service_data[ATTR_DATA] = data return self.hass.services.call( DOMAIN, SERVICE_SEND_MESSAGE, service_data=service_data )<|fim▁end|>
<|file_name|>event-debug.js<|end_file_name|><|fim▁begin|>/* Copyright (c) 2008, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 2.5.0 */ /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires * @param {Object} oScope The context the event will fire from. "this" will * refer to this object in the callback. Default value: * the window object. The listener can override this. * @param {boolean} silent pass true to prevent the event from writing to * the debugsystem * @param {int} signature the signature that the custom event subscriber * will receive. YAHOO.util.CustomEvent.LIST or * YAHOO.util.CustomEvent.FLAT. The default is * YAHOO.util.CustomEvent.LIST. * @namespace YAHOO.util * @class CustomEvent * @constructor */ YAHOO.util.CustomEvent = function(type, oScope, silent, signature) { /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The scope the the event will fire from by default. Defaults to the window * obj * @property scope * @type object */ this.scope = oScope || window; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = silent; /** * Custom events support two styles of arguments provided to the event * subscribers. * <ul> * <li>YAHOO.util.CustomEvent.LIST: * <ul> * <li>param1: event name</li> * <li>param2: array of arguments sent to fire</li> * <li>param3: <optional> a custom object supplied by the subscriber</li> * </ul> * </li> * <li>YAHOO.util.CustomEvent.FLAT * <ul> * <li>param1: the first argument passed to fire. If you need to * pass multiple parameters, use and array or object literal</li> * <li>param2: <optional> a custom object supplied by the subscriber</li> * </ul> * </li> * </ul> * @property signature * @type int */ this.signature = signature || YAHOO.util.CustomEvent.LIST; /** * The subscribers to this event * @property subscribers * @type Subscriber[] */ this.subscribers = []; if (!this.silent) { YAHOO.log( "Creating " + this, "info", "Event" ); } var onsubscribeType = "_YUICEOnSubscribe"; // Only add subscribe events for events that are not generated by // CustomEvent if (type !== onsubscribeType) { /** * Custom events provide a custom event that fires whenever there is * a new subscriber to the event. This provides an opportunity to * handle the case where there is a non-repeating event that has * already fired has a new subscriber. * * @event subscribeEvent * @type YAHOO.util.CustomEvent * @param {Function} fn The function to execute * @param {Object} obj An object to be passed along when the event * fires * @param {boolean|Object} override If true, the obj passed in becomes * the execution scope of the listener. * if an object, that object becomes the * the execution scope. */ this.subscribeEvent = new YAHOO.util.CustomEvent(onsubscribeType, this, true); } /** * In order to make it possible to execute the rest of the subscriber * stack when one thows an exception, the subscribers exceptions are * caught. The most recent exception is stored in this property * @property lastError * @type Error */ this.lastError = null; }; /** * Subscriber listener sigature constant. The LIST type returns three * parameters: the event type, the array of args passed to fire, and * the optional custom object * @property YAHOO.util.CustomEvent.LIST * @static * @type int */ YAHOO.util.CustomEvent.LIST = 0; /** * Subscriber listener sigature constant. The FLAT type returns two * parameters: the first argument passed to fire and the optional * custom object * @property YAHOO.util.CustomEvent.FLAT * @static * @type int */ YAHOO.util.CustomEvent.FLAT = 1; YAHOO.util.CustomEvent.prototype = { /** * Subscribes the caller to this event * @method subscribe * @param {Function} fn The function to execute * @param {Object} obj An object to be passed along when the event * fires * @param {boolean|Object} override If true, the obj passed in becomes * the execution scope of the listener. * if an object, that object becomes the * the execution scope. */ subscribe: function(fn, obj, override) { if (!fn) { throw new Error("Invalid callback for subscriber to '" + this.type + "'"); } if (this.subscribeEvent) { this.subscribeEvent.fire(fn, obj, override); } this.subscribers.push( new YAHOO.util.Subscriber(fn, obj, override) ); }, /** * Unsubscribes subscribers. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} obj The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {boolean} True if the subscriber was found and detached. */ unsubscribe: function(fn, obj) { if (!fn) { return this.unsubscribeAll(); } var found = false; for (var i=0, len=this.subscribers.length; i<len; ++i) { var s = this.subscribers[i]; if (s && s.contains(fn, obj)) { this._delete(i); found = true; } } return found; }, /** * Notifies the subscribers. The callback functions will be executed * from the scope specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise */ fire: function() { var len=this.subscribers.length; if (!len && this.silent) { return true; } var args=[], ret=true, i, rebuild=false; for (i=0; i<arguments.length; ++i) { args.push(arguments[i]); } if (!this.silent) { YAHOO.log( "Firing " + this + ", " + "args: " + args + ", " + "subscribers: " + len, "info", "Event" ); } for (i=0; i<len; ++i) { var s = this.subscribers[i]; if (!s) { rebuild=true; } else { if (!this.silent) { YAHOO.log( this.type + "->" + (i+1) + ": " + s, "info", "Event" ); } var scope = s.getScope(this.scope); if (this.signature == YAHOO.util.CustomEvent.FLAT) { var param = null; if (args.length > 0) { param = args[0]; } try { ret = s.fn.call(scope, param, s.obj); } catch(e) { this.lastError = e; YAHOO.log(this + " subscriber exception: " + e, "error", "Event"); } } else { try { ret = s.fn.call(scope, this.type, args, s.obj); } catch(ex) { this.lastError = ex; YAHOO.log(this + " subscriber exception: " + ex, "error", "Event"); } } if (false === ret) { if (!this.silent) { YAHOO.log("Event cancelled, subscriber " + i + " of " + len, "info", "Event"); } //break; return false; } } } if (rebuild) { var newlist=[],subs=this.subscribers; for (i=0,len=subs.length; i<len; i=i+1) { newlist.push(subs[i]); } this.subscribers=newlist; } return true; }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed */ unsubscribeAll: function() { for (var i=0, len=this.subscribers.length; i<len; ++i) { this._delete(len - 1 - i); } this.subscribers=[]; return i; }, /** * @method _delete * @private */ _delete: function(index) { var s = this.subscribers[index]; if (s) { delete s.fn; delete s.obj; } this.subscribers[index]=null; }, /** * @method toString */ toString: function() { return "CustomEvent: " + "'" + this.type + "', " + "scope: " + this.scope; } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The function to execute * @param {Object} obj An object to be passed along when the event fires * @param {boolean} override If true, the obj passed in becomes the execution * scope of the listener * @class Subscriber * @constructor */ YAHOO.util.Subscriber = function(fn, obj, override) { /** * The callback that will be execute when the event fires * @property fn * @type function */ this.fn = fn; /** * An optional custom object that will passed to the callback when * the event fires * @property obj * @type object */ this.obj = YAHOO.lang.isUndefined(obj) ? null : obj; /** * The default execution scope for the event listener is defined when the * event is created (usually the object which contains the event). * By setting override to true, the execution scope becomes the custom * object passed in by the subscriber. If override is an object, that * object becomes the scope. * @property override * @type boolean|object */ this.override = override; }; /** * Returns the execution scope for this listener. If override was set to true * the custom obj will be the scope. If override is an object, that is the * scope, otherwise the default scope will be used. * @method getScope * @param {Object} defaultScope the scope to use if this listener does not * override it. */ YAHOO.util.Subscriber.prototype.getScope = function(defaultScope) { if (this.override) { if (this.override === true) { return this.obj; } else { return this.override; } } return defaultScope; }; /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute * @param {Object} obj an object to be passed along when the event fires * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ YAHOO.util.Subscriber.prototype.contains = function(fn, obj) { if (obj) { return (this.fn == fn && this.obj == obj); } else { return (this.fn == fn); } }; /** * @method toString */ YAHOO.util.Subscriber.prototype.toString = function() { return "Subscriber { obj: " + this.obj + ", override: " + (this.override || "no") + " }"; }; /** * The Event Utility provides utilities for managing DOM Events and tools * for building event systems * * @module event * @title Event Utility * @namespace YAHOO.util * @requires yahoo */ // The first instance of Event will win if it is loaded more than once. // @TODO this needs to be changed so that only the state data that needs to // be preserved is kept, while methods are overwritten/added as needed. // This means that the module pattern can't be used. if (!YAHOO.util.Event) { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ YAHOO.util.Event = function() { /** * True after the onload event has fired * @property loadComplete * @type boolean * @static * @private */ var loadComplete = false; /** * Cache of wrapped listeners * @property listeners * @type array * @static * @private */ var listeners = []; /** * User-defined unload function that will be fired before all events * are detached * @property unloadListeners * @type array * @static * @private */ var unloadListeners = []; /** * Cache of DOM0 event handlers to work around issues with DOM2 events * in Safari * @property legacyEvents * @static * @private */ var legacyEvents = []; /** * Listener stack for DOM0 events * @property legacyHandlers * @static * @private */ var legacyHandlers = []; /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property retryCount * @static * @private */ var retryCount = 0; /** * onAvailable listeners * @property onAvailStack * @static * @private */ var onAvailStack = []; /** * Lookup table for legacy events * @property legacyMap * @static * @private */ var legacyMap = []; /** * Counter for auto id generation * @property counter * @static * @private */ var counter = 0; /** * Normalized keycodes for webkit/safari * @property webkitKeymap * @type {int: int} * @private * @static * @final */ var webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9 // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) }; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 2000@amp;20 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 2000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 20, /** * Element to bind, int constant * @property EL * @type int * @static * @final */ EL: 0, /** * Type of event, int constant * @property TYPE * @type int * @static * @final */ TYPE: 1, /** * Function to execute, int constant * @property FN * @type int * @static * @final */ FN: 2, /** * Function wrapped for scope correction and cleanup, int constant * @property WFN * @type int * @static * @final */ WFN: 3, /** * Object passed in by the user that will be returned as a * parameter to the callback, int constant. Specific to * unload listeners * @property OBJ * @type int * @static * @final */ UNLOAD_OBJ: 3, /** * Adjusted scope, either the element we are registering the event * on or the custom object passed in by the listener, int constant * @property ADJ_SCOPE * @type int * @static * @final */ ADJ_SCOPE: 4, /** * The original obj passed into addListener * @property OBJ * @type int * @static * @final */ OBJ: 5, /** * The original scope parameter passed into addListener * @property OVERRIDE * @type int * @static * @final */ OVERRIDE: 6, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * Safari detection * @property isSafari * @private * @static * @deprecated use YAHOO.env.ua.webkit */ isSafari: YAHOO.env.ua.webkit, /** * webkit version * @property webkit * @type string * @private * @static * @deprecated use YAHOO.env.ua.webkit */ webkit: YAHOO.env.ua.webkit, /** * IE detection * @property isIE * @private * @static * @deprecated use YAHOO.env.ua.ie */ isIE: YAHOO.env.ua.ie, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!this._interval) { var self = this; var callback = function() { self._tryPreloadAttach(); }; this._interval = setInterval(callback, this.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} p_id the id of the element, or an array * of ids to look for. * @param {function} p_fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to p_fn. * @param {boolean|object} p_override If set to true, p_fn will execute * in the scope of p_obj, if set to an object it * will execute in the scope of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static */ onAvailable: function(p_id, p_fn, p_obj, p_override, checkContent) { var a = (YAHOO.lang.isString(p_id)) ? [p_id] : p_id; for (var i=0; i<a.length; i=i+1) { onAvailStack.push({id: a[i], fn: p_fn, obj: p_obj, override: p_override, checkReady: checkContent }); } retryCount = this.POLL_RETRYS; this.startInterval(); }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} p_id the id of the element to look for. * @param {function} p_fn what to execute when the element is ready. * @param {object} p_obj an optional object to be passed back as * a parameter to p_fn. * @param {boolean|object} p_override If set to true, p_fn will execute * in the scope of p_obj. If an object, p_fn will * exectute in the scope of that object * * @static */ onContentReady: function(p_id, p_fn, p_obj, p_override) { this.onAvailable(p_id, p_fn, p_obj, p_override, true); }, /** * Executes the supplied callback when the DOM is first usable. This * will execute immediately if called after the DOMReady event has * fired. @todo the DOMContentReady event does not fire when the * script is dynamically injected into the page. This means the * DOMReady custom event will never fire in FireFox or Opera when the * library is injected. It _will_ fire in Safari, and the IE * implementation would allow for us to fire it if the defered script * is not available. We want this to behave the same in all browsers. * Is there a way to identify when the script has been injected * instead of included inline? Is there a way to know whether the * window onload event has fired without having had a listener attached * to it when it did so? * * <p>The callback is a CustomEvent, so the signature is:</p> * <p>type &lt;string&gt;, args &lt;array&gt;, customobject &lt;object&gt;</p> * <p>For DOMReady events, there are no fire argments, so the * signature is:</p> * <p>"DOMReady", [], obj</p> * * * @method onDOMReady * * @param {function} p_fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to p_fn. * @param {boolean|object} p_scope If set to true, p_fn will execute * in the scope of p_obj, if set to an object it * will execute in the scope of that object * * @static */ onDOMReady: function(p_fn, p_obj, p_override) { if (this.DOMReady) { setTimeout(function() { var s = window; if (p_override) { if (p_override === true) { s = p_obj; } else { s = p_override; } } p_fn.call(s, "DOMReady", [], p_obj); }, 0); } else { this.DOMReadyEvent.subscribe(p_fn, p_obj, p_override); } }, /** * Appends an event handler * * @method addListener * * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {String} sType The type of event to append * @param {Function} fn The method the event invokes * @param {Object} obj An arbitrary object that will be * passed as a parameter to the handler * @param {Boolean|object} override If true, the obj passed in becomes * the execution scope of the listener. If an * object, this object becomes the execution * scope. * @return {Boolean} True if the action was successful or defered, * false if one or more of the elements * could not have the listener attached, * or if the operation throws an exception. * @static */ addListener: function(el, sType, fn, obj, override) { if (!fn || !fn.call) { // throw new TypeError(sType + " addListener call failed, callback undefined"); YAHOO.log(sType + " addListener call failed, invalid callback", "error", "Event"); return false; } // The el argument can be an array of elements or element ids. if ( this._isValidCollection(el)) { var ok = true; for (var i=0,len=el.length; i<len; ++i) { ok = this.on(el[i], sType, fn, obj, override) && ok; } return ok; } else if (YAHOO.lang.isString(el)) { var oEl = this.getEl(el); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until onload event fires // check to see if we need to delay hooking up the event // until after the page loads. if (oEl) { el = oEl; } else { // defer adding the event until the element is available this.onAvailable(el, function() { YAHOO.util.Event.on(el, sType, fn, obj, override); }); return true; } } // Element should be an html element or an array if we get // here. if (!el) { // this.logger.debug("unable to attach event " + sType); return false; } // we need to make sure we fire registered unload events // prior to automatically unhooking them. So we hang on to // these instead of attaching them to the window and fire the // handles explicitly during our one unload event. if ("unload" == sType && obj !== this) { unloadListeners[unloadListeners.length] = [el, sType, fn, obj, override]; return true; } // this.logger.debug("Adding handler: " + el + ", " + sType); // if the user chooses to override the scope, we use the custom // object passed in, otherwise the executing scope will be the // HTML element that the event is registered on var scope = el; if (override) { if (override === true) { scope = obj; } else { scope = override; } } // wrap the function so we can return the obj object when // the event fires; var wrappedFn = function(e) { return fn.call(scope, YAHOO.util.Event.getEvent(e, el), obj); }; var li = [el, sType, fn, wrappedFn, scope, obj, override]; var index = listeners.length; // cache the listener so we can try to automatically unload listeners[index] = li; if (this.useLegacyEvent(el, sType)) { var legacyIndex = this.getLegacyIndex(el, sType); // Add a new dom0 wrapper if one is not detected for this // element if ( legacyIndex == -1 || el != legacyEvents[legacyIndex][0] ) { legacyIndex = legacyEvents.length; legacyMap[el.id + sType] = legacyIndex; // cache the signature for the DOM0 event, and // include the existing handler for the event, if any legacyEvents[legacyIndex] = [el, sType, el["on" + sType]]; legacyHandlers[legacyIndex] = []; el["on" + sType] = function(e) { YAHOO.util.Event.fireLegacyEvent( YAHOO.util.Event.getEvent(e), legacyIndex); }; } // add a reference to the wrapped listener to our custom // stack of events //legacyHandlers[legacyIndex].push(index); legacyHandlers[legacyIndex].push(li); } else { try { this._simpleAdd(el, sType, wrappedFn, false); } catch(ex) { // handle an error trying to attach an event. If it fails // we need to clean up the cache this.lastError = ex; this.removeListener(el, sType, fn); return false; } } return true; }, /** * When using legacy events, the handler is routed to this object * so we can fire our custom listener stack. * @method fireLegacyEvent * @static * @private */ fireLegacyEvent: function(e, legacyIndex) { // this.logger.debug("fireLegacyEvent " + legacyIndex); var ok=true,le,lh,li,scope,ret; lh = legacyHandlers[legacyIndex]; for (var i=0,len=lh.length; i<len; ++i) { li = lh[i]; if ( li && li[this.WFN] ) { scope = li[this.ADJ_SCOPE]; ret = li[this.WFN].call(scope, e); ok = (ok && ret); } } // Fire the original handler if we replaced one. We fire this // after the other events to keep stopPropagation/preventDefault // that happened in the DOM0 handler from touching our DOM2 // substitute le = legacyEvents[legacyIndex]; if (le && le[2]) { le[2](e); } return ok; }, /** * Returns the legacy event index that matches the supplied * signature * @method getLegacyIndex * @static * @private */ getLegacyIndex: function(el, sType) { var key = this.generateId(el) + sType; if (typeof legacyMap[key] == "undefined") { return -1; } else { return legacyMap[key]; } }, /** * Logic that determines when we should automatically use legacy * events instead of DOM2 events. Currently this is limited to old * Safari browsers with a broken preventDefault * @method useLegacyEvent * @static * @private */ useLegacyEvent: function(el, sType) { if (this.webkit && ("click"==sType || "dblclick"==sType)) { var v = parseInt(this.webkit, 10); if (!isNaN(v) && v<418) { return true; } } return false; }, /** * Removes an event listener * * @method removeListener * * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to remove * the listener from. * @param {String} sType the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @return {boolean} true if the unbind was successful, false * otherwise. * @static */ removeListener: function(el, sType, fn) { var i, len, li; // The el argument can be a string if (typeof el == "string") { el = this.getEl(el); // The el argument can be an array of elements or element ids. } else if ( this._isValidCollection(el)) { var ok = true; for (i=0,len=el.length; i<len; ++i) { ok = ( this.removeListener(el[i], sType, fn) && ok ); } return ok; } if (!fn || !fn.call) { // this.logger.debug("Error, function is not valid " + fn); //return false; return this.purgeElement(el, false, sType); } if ("unload" == sType) { for (i=0, len=unloadListeners.length; i<len; i++) { li = unloadListeners[i]; if (li && li[0] == el && li[1] == sType && li[2] == fn) { //unloadListeners.splice(i, 1); unloadListeners[i]=null; return true; } } return false; } var cacheItem = null; // The index is a hidden parameter; needed to remove it from // the method signature because it was tempting users to // try and take advantage of it, which is not possible. var index = arguments[3]; if ("undefined" === typeof index) { index = this._getCacheIndex(el, sType, fn); } if (index >= 0) { cacheItem = listeners[index]; } if (!el || !cacheItem) { // this.logger.debug("cached listener not found"); return false; } // this.logger.debug("Removing handler: " + el + ", " + sType); if (this.useLegacyEvent(el, sType)) { var legacyIndex = this.getLegacyIndex(el, sType); var llist = legacyHandlers[legacyIndex]; if (llist) { for (i=0, len=llist.length; i<len; ++i) { li = llist[i]; if (li && li[this.EL] == el && li[this.TYPE] == sType && li[this.FN] == fn) { //llist.splice(i, 1); llist[i]=null; break; } } } } else { try { this._simpleRemove(el, sType, cacheItem[this.WFN], false); } catch(ex) { this.lastError = ex; return false; } } // removed the wrapped handler delete listeners[index][this.WFN]; delete listeners[index][this.FN]; //listeners.splice(index, 1); listeners[index]=null; return true; }, /** * Returns the event's target element. Safari sometimes provides * a text node, and this is automatically resolved to the text * node's parent so that it behaves like other browsers. * @method getTarget * @param {Event} ev the event * @param {boolean} resolveTextNode when set to true the target's * parent will be returned if the target is a * text node. @deprecated, the text node is * now resolved automatically * @return {HTMLElement} the event's target * @static */ getTarget: function(ev, resolveTextNode) { var t = ev.target || ev.srcElement; return this.resolveTextNode(t); }, /** * In some cases, some browsers will return a text node inside * the actual element that was targeted. This normalizes the * return value for getTarget and getRelatedTarget. * @method resolveTextNode * @param {HTMLElement} node node to resolve * @return {HTMLElement} the normized node * @static */ resolveTextNode: function(n) { try { if (n && 3 == n.nodeType) { return n.parentNode; } } catch(e) { } return n; }, /** * Returns the event's pageX * @method getPageX * @param {Event} ev the event * @return {int} the event's pageX * @static */ getPageX: function(ev) { var x = ev.pageX; if (!x && 0 !== x) { x = ev.clientX || 0; if ( this.isIE ) { x += this._getScrollLeft(); } } return x; }, /** * Returns the event's pageY * @method getPageY * @param {Event} ev the event * @return {int} the event's pageY * @static */ getPageY: function(ev) { var y = ev.pageY; if (!y && 0 !== y) { y = ev.clientY || 0; if ( this.isIE ) { y += this._getScrollTop(); } } return y; }, /** * Returns the pageX and pageY properties as an indexed array. * @method getXY * @param {Event} ev the event * @return {[x, y]} the pageX and pageY properties of the event * @static */ getXY: function(ev) { return [this.getPageX(ev), this.getPageY(ev)]; }, /** * Returns the event's related target * @method getRelatedTarget * @param {Event} ev the event * @return {HTMLElement} the event's relatedTarget * @static */ getRelatedTarget: function(ev) { var t = ev.relatedTarget; if (!t) { if (ev.type == "mouseout") { t = ev.toElement; } else if (ev.type == "mouseover") { t = ev.fromElement; } } return this.resolveTextNode(t); }, /** * Returns the time of the event. If the time is not included, the * event is modified using the current time. * @method getTime * @param {Event} ev the event * @return {Date} the time of the event * @static */ getTime: function(ev) { if (!ev.time) { var t = new Date().getTime(); try { ev.time = t; } catch(ex) { this.lastError = ex; return t; } } return ev.time; }, /** * Convenience method for stopPropagation + preventDefault * @method stopEvent * @param {Event} ev the event * @static */ stopEvent: function(ev) { this.stopPropagation(ev); this.preventDefault(ev); }, /** * Stops event propagation * @method stopPropagation * @param {Event} ev the event * @static */ stopPropagation: function(ev) { if (ev.stopPropagation) { ev.stopPropagation(); } else { ev.cancelBubble = true; } }, /** * Prevents the default behavior of the event * @method preventDefault * @param {Event} ev the event * @static */ preventDefault: function(ev) { if (ev.preventDefault) { ev.preventDefault(); } else { ev.returnValue = false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} boundEl the element the listener is attached to * @return {Event} the event * @static */ getEvent: function(e, boundEl) { var ev = e || window.event; if (!ev) { var c = this.getEvent.caller; while (c) { ev = c.arguments[0]; if (ev && Event == ev.constructor) { break; } c = c.caller; } } return ev; }, /** * Returns the charcode for an event * @method getCharCode * @param {Event} ev the event * @return {int} the event's charCode * @static */ getCharCode: function(ev) { var code = ev.keyCode || ev.charCode || 0; // webkit key normalization if (YAHOO.env.ua.webkit && (code in webkitKeymap)) { code = webkitKeymap[code]; } return code; }, /** * Locating the saved event handler data by function ref * * @method _getCacheIndex * @static * @private */ _getCacheIndex: function(el, sType, fn) { for (var i=0,len=listeners.length; i<len; ++i) { var li = listeners[i]; if ( li && li[this.FN] == fn && li[this.EL] == el && li[this.TYPE] == sType ) { return i; } } return -1; }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { var id = el.id; if (!id) { id = "yuievtautoid-" + counter; ++counter; el.id = id; } return id; }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @static * @private */ _isValidCollection: function(o) { try { return ( o && // o is something typeof o !== "string" && // o is not a string o.length && // o is indexed !o.tagName && // o is not an HTML element !o.alert && // o is not a window typeof o[0] !== "undefined" ); } catch(ex) { YAHOO.log("_isValidCollection error, assuming that " + " this is a cross frame problem and not a collection", "warn"); return false; } }, /** * @private * @property elCache * DOM element cache * @static * @deprecated Elements are not cached due to issues that arise when * elements are removed and re-added */ elCache: {}, /** * We cache elements bound by id because when the unload event * fires, we can no longer use document.getElementById * @method getEl * @static * @private * @deprecated Elements are not cached any longer */ getEl: function(id) { return (typeof id === "string") ? document.getElementById(id) : id; }, /** * Clears the element cache * @deprecated Elements are not cached any longer * @method clearCache * @static * @private */ clearCache: function() { }, /** * Custom event the fires when the dom is initially usable * @event DOMReadyEvent */ DOMReadyEvent: new YAHOO.util.CustomEvent("DOMReady", this), /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!loadComplete) { loadComplete = true; var EU = YAHOO.util.Event; // Just in case DOMReady did not go off for some reason EU._ready(); // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification EU._tryPreloadAttach(); } }, /** * Fires the DOMReady event listeners the first time the document is * usable. * @method _ready * @static * @private */ _ready: function(e) { var EU = YAHOO.util.Event; if (!EU.DOMReady) { EU.DOMReady=true; // Fire the content ready custom event EU.DOMReadyEvent.fire(); // Remove the DOMContentLoaded (FF/Opera) EU._simpleRemove(document, "DOMContentLoaded", EU._ready); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _tryPreloadAttach * @static * @private */ _tryPreloadAttach: function() { if (this.locked) { return false; } if (this.isIE) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. if (!this.DOMReady) { this.startInterval(); return false; } } this.locked = true; // this.logger.debug("tryPreloadAttach"); // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var tryAgain = !loadComplete; if (!tryAgain) { tryAgain = (retryCount > 0); } // onAvailable var notAvail = []; var executeItem = function (el, item) { var scope = el; if (item.override) { if (item.override === true) { scope = item.obj; } else { scope = item.override; } } item.fn.call(scope, item.obj); }; var i,len,item,el; // onAvailable for (i=0,len=onAvailStack.length; i<len; ++i) { item = onAvailStack[i]; if (item && !item.checkReady) { el = this.getEl(item.id); if (el) { executeItem(el, item); onAvailStack[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=onAvailStack.length; i<len; ++i) { item = onAvailStack[i]; if (item && item.checkReady) { el = this.getEl(item.id); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (loadComplete || el.nextSibling) { executeItem(el, item); onAvailStack[i] = null; } } else { notAvail.push(item); } } } retryCount = (notAvail.length === 0) ? 0 : retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here this.startInterval(); } else { clearInterval(this._interval); this._interval = null; } this.locked = false; return true; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} sType optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, sType) { var oEl = (YAHOO.lang.isString(el)) ? this.getEl(el) : el; var elListeners = this.getListeners(oEl, sType), i, len; if (elListeners) { for (i=0,len=elListeners.length; i<len ; ++i) { var l = elListeners[i]; this.removeListener(oEl, l.type, l.fn, l.index); } } if (recurse && oEl && oEl.childNodes) { for (i=0,len=oEl.childNodes.length; i<len ; ++i) { this.purgeElement(oEl.childNodes[i], recurse, sType); } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param sType {string} optional type of listener to return. If * left out, all listeners will be returned * @return {Object} the listener. Contains the following fields: * &nbsp;&nbsp;type: (string) the type of event * &nbsp;&nbsp;fn: (function) the callback supplied to addListener * &nbsp;&nbsp;obj: (object) the custom object supplied to addListener * &nbsp;&nbsp;adjust: (boolean|object) whether or not to adjust the default scope * &nbsp;&nbsp;scope: (boolean) the derived scope based on the adjust parameter * &nbsp;&nbsp;index: (int) its position in the Event util listener cache * @static */ getListeners: function(el, sType) { var results=[], searchLists; if (!sType) { searchLists = [listeners, unloadListeners]; } else if (sType === "unload") { searchLists = [unloadListeners]; } else { searchLists = [listeners]; } var oEl = (YAHOO.lang.isString(el)) ? this.getEl(el) : el; for (var j=0;j<searchLists.length; j=j+1) { var searchList = searchLists[j]; if (searchList && searchList.length > 0) { for (var i=0,len=searchList.length; i<len ; ++i) { var l = searchList[i]; if ( l && l[this.EL] === oEl && (!sType || sType === l[this.TYPE]) ) { results.push({ type: l[this.TYPE], fn: l[this.FN], obj: l[this.OBJ], adjust: l[this.OVERRIDE], scope: l[this.ADJ_SCOPE], index: i }); } } } } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { var EU = YAHOO.util.Event, i, j, l, len, index; // execute and clear stored unload listeners for (i=0,len=unloadListeners.length; i<len; ++i) { l = unloadListeners[i]; if (l) { var scope = window; if (l[EU.ADJ_SCOPE]) { if (l[EU.ADJ_SCOPE] === true) { scope = l[EU.UNLOAD_OBJ]; } else { scope = l[EU.ADJ_SCOPE]; } } l[EU.FN].call(scope, EU.getEvent(e, l[EU.EL]), l[EU.UNLOAD_OBJ] ); unloadListeners[i] = null; l=null; scope=null; } } unloadListeners = null; // Remove listeners to handle IE memory leaks //if (YAHOO.env.ua.ie && listeners && listeners.length > 0) { // 2.5.0 listeners are removed for all browsers again. FireFox preserves // at least some listeners between page refreshes, potentially causing // errors during page load (mouseover listeners firing before they // should if the user moves the mouse at the correct moment). if (listeners && listeners.length > 0) { j = listeners.length; while (j) { index = j-1; l = listeners[index]; if (l) { EU.removeListener(l[EU.EL], l[EU.TYPE], l[EU.FN], index); } j--; } l=null; } legacyEvents = null; EU._simpleRemove(window, "unload", EU._unload); }, /** * Returns scrollLeft * @method _getScrollLeft * @static * @private */ _getScrollLeft: function() { return this._getScroll()[1]; }, /** * Returns scrollTop * @method _getScrollTop * @static * @private */ _getScrollTop: function() { return this._getScroll()[0]; }, /** * Returns the scrollTop and scrollLeft. Used to calculate the * pageX and pageY in Internet Explorer * @method _getScroll * @static * @private */ _getScroll: function() { var dd = document.documentElement, db = document.body; if (dd && (dd.scrollTop || dd.scrollLeft)) { return [dd.scrollTop, dd.scrollLeft]; } else if (db) { return [db.scrollTop, db.scrollLeft]; } else { return [0, 0]; } }, /** * Used by old versions of CustomEvent, restored for backwards * compatibility * @method regCE * @private * @static * @deprecated still here for backwards compatibility */ regCE: function() { // does nothing }, /** * Adds a DOM event directly without the caching, cleanup, scope adj, etc * * @method _simpleAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} sType the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ _simpleAdd: function () { if (window.addEventListener) { return function(el, sType, fn, capture) { el.addEventListener(sType, fn, (capture)); }; } else if (window.attachEvent) { return function(el, sType, fn, capture) { el.attachEvent("on" + sType, fn); }; } else { return function(){}; } }(), /** * Basic remove listener * * @method _simpleRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} sType the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ _simpleRemove: function() { if (window.removeEventListener) { return function (el, sType, fn, capture) { el.removeEventListener(sType, fn, (capture)); }; } else if (window.detachEvent) { return function (el, sType, fn) { el.detachEvent("on" + sType, fn); }; } else { return function(){}; } }() }; }(); (function() { var EU = YAHOO.util.Event; /** * YAHOO.util.Event.on is an alias for addListener * @method on * @see addListener * @static */ EU.on = EU.addListener; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */ // Internet Explorer: use the readyState of a defered script. // This isolates what appears to be a safe moment to manipulate // the DOM prior to when the document's readyState suggests // it is safe to do so. if (EU.isIE) { // Process onAvailable/onContentReady items when when the // DOM is ready. YAHOO.util.Event.onDOMReady( YAHOO.util.Event._tryPreloadAttach, YAHOO.util.Event, true); EU._dri = setInterval(function() { var n = document.createElement('p'); try { // throws an error if doc is not ready<|fim▁hole|> EU._dri = null; EU._ready(); n = null; } catch (ex) { n = null; } }, EU.POLL_INTERVAL); // The document's readyState in Safari currently will // change to loaded/complete before images are loaded. } else if (EU.webkit && EU.webkit < 525) { EU._dri = setInterval(function() { var rs=document.readyState; if ("loaded" == rs || "complete" == rs) { clearInterval(EU._dri); EU._dri = null; EU._ready(); } }, EU.POLL_INTERVAL); // FireFox and Opera: These browsers provide a event for this // moment. The latest WebKit releases now support this event. } else { EU._simpleAdd(document, "DOMContentLoaded", EU._ready); } ///////////////////////////////////////////////////////////// EU._simpleAdd(window, "load", EU._load); EU._simpleAdd(window, "unload", EU._unload); EU._tryPreloadAttach(); })(); } /** * EventProvider is designed to be used with YAHOO.augment to wrap * CustomEvents in an interface that allows events to be subscribed to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * * @Class EventProvider */ YAHOO.util.EventProvider = function() { }; YAHOO.util.EventProvider.prototype = { /** * Private storage of custom events * @property __yui_events * @type Object[] * @private */ __yui_events: null, /** * Private storage of custom event subscribers * @property __yui_subscribers * @type Object[] * @private */ __yui_subscribers: null, /** * Subscribe to a CustomEvent by event type * * @method subscribe * @param p_type {string} the type, or name of the event * @param p_fn {function} the function to exectute when the event fires * @param p_obj {Object} An object to be passed along when the event * fires * @param p_override {boolean} If true, the obj passed in becomes the * execution scope of the listener */ subscribe: function(p_type, p_fn, p_obj, p_override) { this.__yui_events = this.__yui_events || {}; var ce = this.__yui_events[p_type]; if (ce) { ce.subscribe(p_fn, p_obj, p_override); } else { this.__yui_subscribers = this.__yui_subscribers || {}; var subs = this.__yui_subscribers; if (!subs[p_type]) { subs[p_type] = []; } subs[p_type].push( { fn: p_fn, obj: p_obj, override: p_override } ); } }, /** * Unsubscribes one or more listeners the from the specified event * @method unsubscribe * @param p_type {string} The type, or name of the event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param p_fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param p_obj {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {boolean} true if the subscriber was found and detached. */ unsubscribe: function(p_type, p_fn, p_obj) { this.__yui_events = this.__yui_events || {}; var evts = this.__yui_events; if (p_type) { var ce = evts[p_type]; if (ce) { return ce.unsubscribe(p_fn, p_obj); } } else { var ret = true; for (var i in evts) { if (YAHOO.lang.hasOwnProperty(evts, i)) { ret = ret && evts[i].unsubscribe(p_fn, p_obj); } } return ret; } return false; }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param p_type {string} The type, or name of the event */ unsubscribeAll: function(p_type) { return this.unsubscribe(p_type); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method createEvent * * @param p_type {string} the type, or name of the event * @param p_config {object} optional config params. Valid properties are: * * <ul> * <li> * scope: defines the default execution scope. If not defined * the default scope will be this instance. * </li> * <li> * silent: if true, the custom event will not generate log messages. * This is false by default. * </li> * <li> * onSubscribeCallback: specifies a callback to execute when the * event has a new subscriber. This will fire immediately for * each queued subscriber if any exist prior to the creation of * the event. * </li> * </ul> * * @return {CustomEvent} the custom event * */ createEvent: function(p_type, p_config) { this.__yui_events = this.__yui_events || {}; var opts = p_config || {}; var events = this.__yui_events; if (events[p_type]) { YAHOO.log("EventProvider createEvent skipped: '"+p_type+"' already exists"); } else { var scope = opts.scope || this; var silent = (opts.silent); var ce = new YAHOO.util.CustomEvent(p_type, scope, silent, YAHOO.util.CustomEvent.FLAT); events[p_type] = ce; if (opts.onSubscribeCallback) { ce.subscribeEvent.subscribe(opts.onSubscribeCallback); } this.__yui_subscribers = this.__yui_subscribers || {}; var qs = this.__yui_subscribers[p_type]; if (qs) { for (var i=0; i<qs.length; ++i) { ce.subscribe(qs[i].fn, qs[i].obj, qs[i].override); } } } return events[p_type]; }, /** * Fire a custom event by name. The callback functions will be executed * from the scope specified when the event was created, and with the * following parameters: * <ul> * <li>The first argument fire() was executed with</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * If the custom event has not been explicitly created, it will be * created now with the default config, scoped to the host object * @method fireEvent * @param p_type {string} the type, or name of the event * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. * @return {boolean} the return value from CustomEvent.fire * */ fireEvent: function(p_type, arg1, arg2, etc) { this.__yui_events = this.__yui_events || {}; var ce = this.__yui_events[p_type]; if (!ce) { YAHOO.log(p_type + "event fired before it was created."); return null; } var args = []; for (var i=1; i<arguments.length; ++i) { args.push(arguments[i]); } return ce.fire.apply(ce, args); }, /** * Returns true if the custom event of the provided type has been created * with createEvent. * @method hasEvent * @param type {string} the type, or name of the event */ hasEvent: function(type) { if (this.__yui_events) { if (this.__yui_events[type]) { return true; } } return false; } }; /** * KeyListener is a utility that provides an easy interface for listening for * keydown/keyup events fired against DOM elements. * @namespace YAHOO.util * @class KeyListener * @constructor * @param {HTMLElement} attachTo The element or element ID to which the key * event should be attached * @param {String} attachTo The element or element ID to which the key * event should be attached * @param {Object} keyData The object literal representing the key(s) * to detect. Possible attributes are * shift(boolean), alt(boolean), ctrl(boolean) * and keys(either an int or an array of ints * representing keycodes). * @param {Function} handler The CustomEvent handler to fire when the * key event is detected * @param {Object} handler An object literal representing the handler. * @param {String} event Optional. The event (keydown or keyup) to * listen for. Defaults automatically to keydown. * * @knownissue the "keypress" event is completely broken in Safari 2.x and below. * the workaround is use "keydown" for key listening. However, if * it is desired to prevent the default behavior of the keystroke, * that can only be done on the keypress event. This makes key * handling quite ugly. * @knownissue keydown is also broken in Safari 2.x and below for the ESC key. * There currently is no workaround other than choosing another * key to listen for. */ YAHOO.util.KeyListener = function(attachTo, keyData, handler, event) { if (!attachTo) { YAHOO.log("No attachTo element specified", "error"); } else if (!keyData) { YAHOO.log("No keyData specified", "error"); } else if (!handler) { YAHOO.log("No handler specified", "error"); } if (!event) { event = YAHOO.util.KeyListener.KEYDOWN; } /** * The CustomEvent fired internally when a key is pressed * @event keyEvent * @private * @param {Object} keyData The object literal representing the key(s) to * detect. Possible attributes are shift(boolean), * alt(boolean), ctrl(boolean) and keys(either an * int or an array of ints representing keycodes). */ var keyEvent = new YAHOO.util.CustomEvent("keyPressed"); /** * The CustomEvent fired when the KeyListener is enabled via the enable() * function * @event enabledEvent * @param {Object} keyData The object literal representing the key(s) to * detect. Possible attributes are shift(boolean), * alt(boolean), ctrl(boolean) and keys(either an * int or an array of ints representing keycodes). */ this.enabledEvent = new YAHOO.util.CustomEvent("enabled"); /** * The CustomEvent fired when the KeyListener is disabled via the * disable() function * @event disabledEvent * @param {Object} keyData The object literal representing the key(s) to * detect. Possible attributes are shift(boolean), * alt(boolean), ctrl(boolean) and keys(either an * int or an array of ints representing keycodes). */ this.disabledEvent = new YAHOO.util.CustomEvent("disabled"); if (typeof attachTo == 'string') { attachTo = document.getElementById(attachTo); } if (typeof handler == 'function') { keyEvent.subscribe(handler); } else { keyEvent.subscribe(handler.fn, handler.scope, handler.correctScope); } /** * Handles the key event when a key is pressed. * @method handleKeyPress * @param {DOMEvent} e The keypress DOM event * @param {Object} obj The DOM event scope object * @private */ function handleKeyPress(e, obj) { if (! keyData.shift) { keyData.shift = false; } if (! keyData.alt) { keyData.alt = false; } if (! keyData.ctrl) { keyData.ctrl = false; } // check held down modifying keys first if (e.shiftKey == keyData.shift && e.altKey == keyData.alt && e.ctrlKey == keyData.ctrl) { // if we pass this, all modifiers match var dataItem; if (keyData.keys instanceof Array) { for (var i=0;i<keyData.keys.length;i++) { dataItem = keyData.keys[i]; if (dataItem == e.charCode ) { keyEvent.fire(e.charCode, e); break; } else if (dataItem == e.keyCode) { keyEvent.fire(e.keyCode, e); break; } } } else { dataItem = keyData.keys; if (dataItem == e.charCode ) { keyEvent.fire(e.charCode, e); } else if (dataItem == e.keyCode) { keyEvent.fire(e.keyCode, e); } } } } /** * Enables the KeyListener by attaching the DOM event listeners to the * target DOM element * @method enable */ this.enable = function() { if (! this.enabled) { YAHOO.util.Event.addListener(attachTo, event, handleKeyPress); this.enabledEvent.fire(keyData); } /** * Boolean indicating the enabled/disabled state of the Tooltip * @property enabled * @type Boolean */ this.enabled = true; }; /** * Disables the KeyListener by removing the DOM event listeners from the * target DOM element * @method disable */ this.disable = function() { if (this.enabled) { YAHOO.util.Event.removeListener(attachTo, event, handleKeyPress); this.disabledEvent.fire(keyData); } this.enabled = false; }; /** * Returns a String representation of the object. * @method toString * @return {String} The string representation of the KeyListener */ this.toString = function() { return "KeyListener [" + keyData.keys + "] " + attachTo.tagName + (attachTo.id ? "[" + attachTo.id + "]" : ""); }; }; /** * Constant representing the DOM "keydown" event. * @property YAHOO.util.KeyListener.KEYDOWN * @static * @final * @type String */ YAHOO.util.KeyListener.KEYDOWN = "keydown"; /** * Constant representing the DOM "keyup" event. * @property YAHOO.util.KeyListener.KEYUP * @static * @final * @type String */ YAHOO.util.KeyListener.KEYUP = "keyup"; /** * keycode constants for a subset of the special keys * @property KEY * @static * @final */ YAHOO.util.KeyListener.KEY = { ALT : 18, BACK_SPACE : 8, CAPS_LOCK : 20, CONTROL : 17, DELETE : 46, DOWN : 40, END : 35, ENTER : 13, ESCAPE : 27, HOME : 36, LEFT : 37, META : 224, NUM_LOCK : 144, PAGE_DOWN : 34, PAGE_UP : 33, PAUSE : 19, PRINTSCREEN : 44, RIGHT : 39, SCROLL_LOCK : 145, SHIFT : 16, SPACE : 32, TAB : 9, UP : 38 }; YAHOO.register("event", YAHOO.util.Event, {version: "2.5.0", build: "895"});<|fim▁end|>
n.doScroll('left'); clearInterval(EU._dri);
<|file_name|>frames.rs<|end_file_name|><|fim▁begin|>/* Copyright (C) 2017-2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use crate::applayer::StreamSlice; use crate::core::Flow;<|fim▁hole|>struct CFrame { _private: [u8; 0], } // Defined in app-layer-register.h extern { fn AppLayerFrameNewByRelativeOffset( flow: *const Flow, stream_slice: *const StreamSlice, frame_start_rel: u32, len: i64, dir: i32, frame_type: u8, ) -> *const CFrame; fn AppLayerFrameAddEventById(flow: *const Flow, dir: i32, id: i64, event: u8); fn AppLayerFrameSetLengthById(flow: *const Flow, dir: i32, id: i64, len: i64); fn AppLayerFrameSetTxIdById(flow: *const Flow, dir: i32, id: i64, tx_id: u64); fn AppLayerFrameGetId(frame: *const CFrame) -> i64; } pub struct Frame { pub id: i64, } impl std::fmt::Debug for Frame { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "frame: {}", self.id) } } impl Frame { pub fn new( flow: *const Flow, stream_slice: &StreamSlice, frame_start: &[u8], frame_len: i64, dir: i32, frame_type: u8, ) -> Option<Self> { let offset = frame_start.as_ptr() as usize - stream_slice.as_slice().as_ptr() as usize; SCLogDebug!("offset {} stream_slice.len() {} frame_start.len() {}", offset, stream_slice.len(), frame_start.len()); let frame = unsafe { AppLayerFrameNewByRelativeOffset( flow, stream_slice, offset as u32, frame_len, dir, frame_type, ) }; let id = unsafe { AppLayerFrameGetId(frame) }; if id > 0 { Some(Self { id }) } else { None } } pub fn new_ts( flow: *const Flow, stream_slice: &StreamSlice, frame_start: &[u8], frame_len: i64, frame_type: u8, ) -> Option<Self> { Self::new(flow, stream_slice, frame_start, frame_len, 0, frame_type) } pub fn new_tc( flow: *const Flow, stream_slice: &StreamSlice, frame_start: &[u8], frame_len: i64, frame_type: u8, ) -> Option<Self> { Self::new(flow, stream_slice, frame_start, frame_len, 1, frame_type) } pub fn set_len(&self, flow: *const Flow, dir: i32, len: i64) { unsafe { AppLayerFrameSetLengthById(flow, dir, self.id, len); }; } pub fn set_tx(&self, flow: *const Flow, dir: i32, tx_id: u64) { unsafe { AppLayerFrameSetTxIdById(flow, dir, self.id, tx_id); }; } pub fn add_event(&self, flow: *const Flow, dir: i32, event: u8) { unsafe { AppLayerFrameAddEventById(flow, dir, self.id, event); }; } }<|fim▁end|>
#[repr(C)]
<|file_name|>examples-curves-surfaces.py<|end_file_name|><|fim▁begin|># Name: Examples for using conditioning number finders for curves and surfaces # Description: Contains some examples with descriptions of how to use the functions # Created: 2016-08-18 # Author: Janis Lazovskis # Navigate to the conditioning directory # Run Python 2 # Example (curve) execfile('curves.py') x = variety() x0,x1,x2 = sp.var('x0,x1,x2') x.varlist = [x0,x1,x2] x.func = x0*x0 + x1*x2 - x1*x0 x.points = [[1,1,0], [2,1,-2]] cnumcurve(x) # Non-example (curve) # Use the above, but instead, put: x.points = [[1,1,0], [2,1,-2], [0,0,0]] # Then cnumcurve will return an empty list saying the last point isn't in P^2 cnumcurve(x) # Non-example (curve) # Use the above, but instead, put: x.points = [[1,1,0], [2,1,-2], [1,1,1]] # Then cnumcurve will return an empty list saying the last point isn't on the curve cnumcurve(x) # Example surface execfile('surfaces.py') x = variety() x0,x1,x2,x3 = sp.var('x0,x1,x2,x3') x.varlist = [x0,x1,x2,x3] x.func = x0*x1 - x2*x3 x.points = [[1,1,1,1], [0,1,1,0], [0,1,0,1], [2,1,1,2]] cnumsurface(x) # Non-example (surface) execfile('surfaces.py') x = variety() x0,x1,x2,x3 = sp.var('x0,x1,x2,x3') x.varlist = [x0,x1,x2,x3] x.func = x0*x0*x1 - x2*x3*x3 + x0*x1*x2 +x2*x2*x2 x.points = [[0,1,1,1], [1,0,1,1], [1,0,2,2], [1,1,-1,1]]<|fim▁hole|><|fim▁end|>
# This will raise an error because the curve is not smooth cnumsurface(x)
<|file_name|>PrairieDraw.js<|end_file_name|><|fim▁begin|>define(['sylvester', 'sha1', 'PrairieGeom'], function (Sylvester, Sha1, PrairieGeom) { var $V = Sylvester.Vector.create; var Vector = Sylvester.Vector; var Matrix = Sylvester.Matrix; /*****************************************************************************/ /** Creates a PrairieDraw object. @constructor @this {PrairieDraw} @param {HTMLCanvasElement or string} canvas The canvas element to draw on or the ID of the canvas elemnt. @param {Function} drawfcn An optional function that draws on the canvas. */ function PrairieDraw(canvas, drawFcn) { if (canvas) { if (canvas instanceof HTMLCanvasElement) { this._canvas = canvas; } else if (canvas instanceof String || typeof canvas === 'string') { this._canvas = document.getElementById(canvas); } else { //throw new Error("PrairieDraw: unknown object type for constructor") this._canvas = undefined; } if (this._canvas) { this._canvas.prairieDraw = this; this._ctx = this._canvas.getContext('2d'); if (this._ctx.setLineDash === undefined) { this._ctx.setLineDash = function () {}; } this._width = this._canvas.width; this._height = this._canvas.height; this._trans = Matrix.I(3); this._transStack = []; this._initViewAngleX3D = (-Math.PI / 2) * 0.75; this._initViewAngleY3D = 0; this._initViewAngleZ3D = (-Math.PI / 2) * 1.25; this._viewAngleX3D = this._initViewAngleX3D; this._viewAngleY3D = this._initViewAngleY3D; this._viewAngleZ3D = this._initViewAngleZ3D; this._trans3D = PrairieGeom.rotateTransform3D( Matrix.I(4), this._initViewAngleX3D, this._initViewAngleY3D, this._initViewAngleZ3D ); this._trans3DStack = []; this._props = {}; this._initProps(); this._propStack = []; this._options = {}; this._history = {}; this._images = {}; this._redrawCallbacks = []; if (drawFcn) { this.draw = drawFcn.bind(this); } this.save(); this.draw(); this.restoreAll(); } } } /** Creates a new PrairieDraw from a canvas ID. @param {string} id The ID of the canvas element to draw on. @return {PrairieDraw} The new PrairieDraw object. */ PrairieDraw.fromCanvasId = function (id) { var canvas = document.getElementById(id); if (!canvas) { throw new Error('PrairieDraw: unable to find canvas ID: ' + id); } return new PrairieDraw(canvas); }; /** Prototype function to draw on the canvas, should be implemented by children. */ PrairieDraw.prototype.draw = function () {}; /** Redraw the drawing. */ PrairieDraw.prototype.redraw = function () { this.save(); this.draw(); this.restoreAll(); for (var i = 0; i < this._redrawCallbacks.length; i++) { this._redrawCallbacks[i](); } }; /** Add a callback on redraw() calls. */ PrairieDraw.prototype.registerRedrawCallback = function (callback) { this._redrawCallbacks.push(callback.bind(this)); }; /** @private Initialize properties. */ PrairieDraw.prototype._initProps = function () { this._props.viewAngleXMin = -Math.PI / 2 + 1e-6; this._props.viewAngleXMax = -1e-6; this._props.viewAngleYMin = -Infinity; this._props.viewAngleYMax = Infinity; this._props.viewAngleZMin = -Infinity; this._props.viewAngleZMax = Infinity; this._props.arrowLineWidthPx = 2; this._props.arrowLinePattern = 'solid'; this._props.arrowheadLengthRatio = 7; // arrowheadLength / arrowLineWidth this._props.arrowheadWidthRatio = 0.3; // arrowheadWidth / arrowheadLength this._props.arrowheadOffsetRatio = 0.3; // arrowheadOffset / arrowheadLength this._props.circleArrowWrapOffsetRatio = 1.5; this._props.arrowOutOfPageRadiusPx = 5; this._props.textOffsetPx = 4; this._props.textFontSize = 14; this._props.pointRadiusPx = 2; this._props.shapeStrokeWidthPx = 2; this._props.shapeStrokePattern = 'solid'; this._props.shapeOutlineColor = 'rgb(0, 0, 0)'; this._props.shapeInsideColor = 'rgb(255, 255, 255)'; this._props.hiddenLineDraw = true; this._props.hiddenLineWidthPx = 2; this._props.hiddenLinePattern = 'dashed'; this._props.hiddenLineColor = 'rgb(0, 0, 0)'; this._props.centerOfMassStrokeWidthPx = 2; this._props.centerOfMassColor = 'rgb(180, 49, 4)'; this._props.centerOfMassRadiusPx = 5; this._props.rightAngleSizePx = 10; this._props.rightAngleStrokeWidthPx = 1; this._props.rightAngleColor = 'rgb(0, 0, 0)'; this._props.measurementStrokeWidthPx = 1; this._props.measurementStrokePattern = 'solid'; this._props.measurementEndLengthPx = 10; this._props.measurementOffsetPx = 3; this._props.measurementColor = 'rgb(0, 0, 0)'; this._props.groundDepthPx = 10; this._props.groundWidthPx = 10; this._props.groundSpacingPx = 10; this._props.groundOutlineColor = 'rgb(0, 0, 0)'; this._props.groundInsideColor = 'rgb(220, 220, 220)'; this._props.gridColor = 'rgb(200, 200, 200)'; this._props.positionColor = 'rgb(0, 0, 255)'; this._props.angleColor = 'rgb(0, 100, 180)'; this._props.velocityColor = 'rgb(0, 200, 0)'; this._props.angVelColor = 'rgb(100, 180, 0)'; this._props.accelerationColor = 'rgb(255, 0, 255)'; this._props.rotationColor = 'rgb(150, 0, 150)'; this._props.angAccColor = 'rgb(100, 0, 180)'; this._props.angMomColor = 'rgb(255, 0, 0)'; this._props.forceColor = 'rgb(210, 105, 30)'; this._props.momentColor = 'rgb(255, 102, 80)'; }; /*****************************************************************************/ /** The golden ratio. */ PrairieDraw.prototype.goldenRatio = (1 + Math.sqrt(5)) / 2; /** Get the canvas width. @return {number} The canvas width in Px. */ PrairieDraw.prototype.widthPx = function () { return this._width; }; /** Get the canvas height. @return {number} The canvas height in Px. */ PrairieDraw.prototype.heightPx = function () { return this._height; }; /*****************************************************************************/ /** Conversion constants. */ PrairieDraw.prototype.milesPerKilometer = 0.621371; /*****************************************************************************/ /** Scale the coordinate system. @param {Vector} factor Scale factors. */ PrairieDraw.prototype.scale = function (factor) { this._trans = PrairieGeom.scaleTransform(this._trans, factor); }; /** Translate the coordinate system. @param {Vector} offset Translation offset (drawing coords). */ PrairieDraw.prototype.translate = function (offset) { this._trans = PrairieGeom.translateTransform(this._trans, offset); }; /** Rotate the coordinate system. @param {number} angle Angle to rotate by (radians). */ PrairieDraw.prototype.rotate = function (angle) { this._trans = PrairieGeom.rotateTransform(this._trans, angle); }; /** Transform the coordinate system (scale, translate, rotate) to match old points to new. Drawing at the old locations will result in points at the new locations. @param {Vector} old1 The old location of point 1. @param {Vector} old2 The old location of point 2. @param {Vector} new1 The new location of point 1. @param {Vector} new2 The new location of point 2. */ PrairieDraw.prototype.transformByPoints = function (old1, old2, new1, new2) { this._trans = PrairieGeom.transformByPointsTransform(this._trans, old1, old2, new1, new2); }; /*****************************************************************************/ /** Transform a vector from drawing to pixel coords. @param {Vector} vDw Vector in drawing coords. @return {Vector} Vector in pixel coords. */ PrairieDraw.prototype.vec2Px = function (vDw) { return PrairieGeom.transformVec(this._trans, vDw); }; /** Transform a position from drawing to pixel coords. @param {Vector} pDw Position in drawing coords. @return {Vector} Position in pixel coords. */ PrairieDraw.prototype.pos2Px = function (pDw) { return PrairieGeom.transformPos(this._trans, pDw); }; /** Transform a vector from pixel to drawing coords. @param {Vector} vPx Vector in pixel coords. @return {Vector} Vector in drawing coords. */ PrairieDraw.prototype.vec2Dw = function (vPx) { return PrairieGeom.transformVec(this._trans.inverse(), vPx); }; /** Transform a position from pixel to drawing coords. @param {Vector} pPx Position in pixel coords. @return {Vector} Position in drawing coords. */ PrairieDraw.prototype.pos2Dw = function (pPx) { return PrairieGeom.transformPos(this._trans.inverse(), pPx); }; /** @private Returns true if the current transformation is a reflection. @return {bool} Whether the current transformation is a reflection. */ PrairieDraw.prototype._transIsReflection = function () { var det = this._trans.e(1, 1) * this._trans.e(2, 2) - this._trans.e(1, 2) * this._trans.e(2, 1); if (det < 0) { return true; } else { return false; } }; /** Transform a position from normalized viewport [0,1] to drawing coords. @param {Vector} pNm Position in normalized viewport coordinates. @return {Vector} Position in drawing coordinates. */ PrairieDraw.prototype.posNm2Dw = function (pNm) { var pPx = this.posNm2Px(pNm); return this.pos2Dw(pPx); }; /** Transform a position from normalized viewport [0,1] to pixel coords. @param {Vector} pNm Position in normalized viewport coords. @return {Vector} Position in pixel coords. */ PrairieDraw.prototype.posNm2Px = function (pNm) { return $V([pNm.e(1) * this._width, (1 - pNm.e(2)) * this._height]); }; /*****************************************************************************/ /** Set the 3D view to the given angles. @param {number} angleX The rotation angle about the X axis. @param {number} angleY The rotation angle about the Y axis. @param {number} angleZ The rotation angle about the Z axis. @param {bool} clip (Optional) Whether to clip to max/min range (default: true). @param {bool} redraw (Optional) Whether to redraw (default: true). */ PrairieDraw.prototype.setView3D = function (angleX, angleY, angleZ, clip, redraw) { clip = clip === undefined ? true : clip; redraw = redraw === undefined ? true : redraw; this._viewAngleX3D = angleX; this._viewAngleY3D = angleY; this._viewAngleZ3D = angleZ; if (clip) { this._viewAngleX3D = PrairieGeom.clip( this._viewAngleX3D, this._props.viewAngleXMin, this._props.viewAngleXMax ); this._viewAngleY3D = PrairieGeom.clip( this._viewAngleY3D, this._props.viewAngleYMin, this._props.viewAngleYMax ); this._viewAngleZ3D = PrairieGeom.clip( this._viewAngleZ3D, this._props.viewAngleZMin, this._props.viewAngleZMax ); } this._trans3D = PrairieGeom.rotateTransform3D( Matrix.I(4), this._viewAngleX3D, this._viewAngleY3D, this._viewAngleZ3D ); if (redraw) { this.redraw(); } }; /** Reset the 3D view to default. @param {bool} redraw (Optional) Whether to redraw (default: true). */ PrairieDraw.prototype.resetView3D = function (redraw) { this.setView3D( this._initViewAngleX3D, this._initViewAngleY3D, this._initViewAngleZ3D, undefined, redraw ); }; /** Increment the 3D view by the given angles. @param {number} deltaAngleX The incremental rotation angle about the X axis. @param {number} deltaAngleY The incremental rotation angle about the Y axis. @param {number} deltaAngleZ The incremental rotation angle about the Z axis. @param {bool} clip (Optional) Whether to clip to max/min range (default: true). */ PrairieDraw.prototype.incrementView3D = function (deltaAngleX, deltaAngleY, deltaAngleZ, clip) { this.setView3D( this._viewAngleX3D + deltaAngleX, this._viewAngleY3D + deltaAngleY, this._viewAngleZ3D + deltaAngleZ, clip ); }; /*****************************************************************************/ /** Scale the 3D coordinate system. @param {Vector} factor Scale factor. */ PrairieDraw.prototype.scale3D = function (factor) { this._trans3D = PrairieGeom.scaleTransform3D(this._trans3D, factor); }; /** Translate the 3D coordinate system. @param {Vector} offset Translation offset. */ PrairieDraw.prototype.translate3D = function (offset) { this._trans3D = PrairieGeom.translateTransform3D(this._trans3D, offset); }; /** Rotate the 3D coordinate system. @param {number} angleX Angle to rotate by around the X axis (radians). @param {number} angleY Angle to rotate by around the Y axis (radians). @param {number} angleZ Angle to rotate by around the Z axis (radians). */ PrairieDraw.prototype.rotate3D = function (angleX, angleY, angleZ) { this._trans3D = PrairieGeom.rotateTransform3D(this._trans3D, angleX, angleY, angleZ); }; /*****************************************************************************/ /** Transform a position to the view coordinates in 3D. @param {Vector} pDw Position in 3D drawing coords. @return {Vector} Position in 3D viewing coords. */ PrairieDraw.prototype.posDwToVw = function (pDw) { var pVw = PrairieGeom.transformPos3D(this._trans3D, pDw); return pVw; }; /** Transform a position from the view coordinates in 3D. @param {Vector} pVw Position in 3D viewing coords. @return {Vector} Position in 3D drawing coords. */ PrairieDraw.prototype.posVwToDw = function (pVw) { var pDw = PrairieGeom.transformPos3D(this._trans3D.inverse(), pVw); return pDw; }; /** Transform a vector to the view coordinates in 3D. @param {Vector} vDw Vector in 3D drawing coords. @return {Vector} Vector in 3D viewing coords. */ PrairieDraw.prototype.vecDwToVw = function (vDw) { var vVw = PrairieGeom.transformVec3D(this._trans3D, vDw); return vVw; }; /** Transform a vector from the view coordinates in 3D. @param {Vector} vVw Vector in 3D viewing coords. @return {Vector} Vector in 3D drawing coords. */ PrairieDraw.prototype.vecVwToDw = function (vVw) { var vDw = PrairieGeom.transformVec3D(this._trans3D.inverse(), vVw); return vDw; }; /** Transform a position from 3D to 2D drawing coords if necessary. @param {Vector} pDw Position in 2D or 3D drawing coords. @return {Vector} Position in 2D drawing coords. */ PrairieDraw.prototype.pos3To2 = function (pDw) { if (pDw.elements.length === 3) { return PrairieGeom.orthProjPos3D(this.posDwToVw(pDw)); } else { return pDw; } }; /** Transform a vector from 3D to 2D drawing coords if necessary. @param {Vector} vDw Vector in 2D or 3D drawing coords. @param {Vector} pDw Base point of vector (if in 3D). @return {Vector} Vector in 2D drawing coords. */ PrairieDraw.prototype.vec3To2 = function (vDw, pDw) { if (vDw.elements.length === 3) { var qDw = pDw.add(vDw); var p2Dw = this.pos3To2(pDw); var q2Dw = this.pos3To2(qDw); var v2Dw = q2Dw.subtract(p2Dw); return v2Dw; } else { return vDw; } }; /** Transform a position from 2D to 3D drawing coords if necessary (adding z = 0). @param {Vector} pDw Position in 2D or 3D drawing coords. @return {Vector} Position in 3D drawing coords. */ PrairieDraw.prototype.pos2To3 = function (pDw) { if (pDw.elements.length === 2) { return $V([pDw.e(1), pDw.e(2), 0]); } else { return pDw; } }; /** Transform a vector from 2D to 3D drawing coords if necessary (adding z = 0). @param {Vector} vDw Vector in 2D or 3D drawing coords. @return {Vector} Vector in 3D drawing coords. */ PrairieDraw.prototype.vec2To3 = function (vDw) { if (vDw.elements.length === 2) { return $V([vDw.e(1), vDw.e(2), 0]); } else { return vDw; } }; /*****************************************************************************/ /** Set a property. @param {string} name The name of the property. @param {number} value The value to set the property to. */ PrairieDraw.prototype.setProp = function (name, value) { if (!(name in this._props)) { throw new Error('PrairieDraw: unknown property name: ' + name); } this._props[name] = value; }; /** Get a property. @param {string} name The name of the property. @return {number} The current value of the property. */ PrairieDraw.prototype.getProp = function (name) { if (!(name in this._props)) { throw new Error('PrairieDraw: unknown property name: ' + name); } return this._props[name]; }; /** @private Colors. */ PrairieDraw._colors = { black: 'rgb(0, 0, 0)', white: 'rgb(255, 255, 255)', red: 'rgb(255, 0, 0)', green: 'rgb(0, 255, 0)', blue: 'rgb(0, 0, 255)', cyan: 'rgb(0, 255, 255)', magenta: 'rgb(255, 0, 255)', yellow: 'rgb(255, 255, 0)', }; /** @private Get a color property for a given type. @param {string} type Optional type to find the color for. */ PrairieDraw.prototype._getColorProp = function (type) { if (type === undefined) { return this._props.shapeOutlineColor; } var col = type + 'Color'; if (col in this._props) { var c = this._props[col]; if (c in PrairieDraw._colors) { return PrairieDraw._colors[c]; } else { return c; } } else if (type in PrairieDraw._colors) { return PrairieDraw._colors[type]; } else { return type; } }; /** @private Set shape drawing properties for drawing hidden lines. */ PrairieDraw.prototype.setShapeDrawHidden = function () { this._props.shapeStrokeWidthPx = this._props.hiddenLineWidthPx; this._props.shapeStrokePattern = this._props.hiddenLinePattern; this._props.shapeOutlineColor = this._props.hiddenLineColor; }; /*****************************************************************************/ /** Add an external option for this drawing. @param {string} name The option name. @param {object} value The default initial value. */ PrairieDraw.prototype.addOption = function (name, value, triggerRedraw) { if (!(name in this._options)) { this._options[name] = { value: value, resetValue: value, callbacks: {}, triggerRedraw: triggerRedraw === undefined ? true : triggerRedraw, }; } else if (!('value' in this._options[name])) { var option = this._options[name]; option.value = value; option.resetValue = value; for (var p in option.callbacks) { option.callbacks[p](option.value); } } }; /** Set an option to a given value. @param {string} name The option name. @param {object} value The new value for the option. @param {bool} redraw (Optional) Whether to trigger a redraw() (default: true). @param {Object} trigger (Optional) The object that triggered the change. @param {bool} setReset (Optional) Also set this value to be the new reset value (default: false). */ PrairieDraw.prototype.setOption = function (name, value, redraw, trigger, setReset) { redraw = redraw === undefined ? true : redraw; setReset = setReset === undefined ? false : setReset; if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } var option = this._options[name]; option.value = value; if (setReset) { option.resetValue = value; } for (var p in option.callbacks) { option.callbacks[p](option.value, trigger); } if (redraw) { this.redraw(); } }; /** Get the value of an option. @param {string} name The option name. @return {object} The current value for the option. */ PrairieDraw.prototype.getOption = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } if (!('value' in this._options[name])) { throw new Error('PrairieDraw: option has no value: ' + name); } return this._options[name].value; }; /** Set an option to the logical negation of its current value. @param {string} name The option name. */ PrairieDraw.prototype.toggleOption = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } if (!('value' in this._options[name])) { throw new Error('PrairieDraw: option has no value: ' + name); } var option = this._options[name]; option.value = !option.value; for (var p in option.callbacks) { option.callbacks[p](option.value); } this.redraw(); }; /** Register a callback on option changes. @param {string} name The option to register on. @param {Function} callback The callback(value) function. @param {string} callbackID (Optional) The ID of the callback. If omitted, a new unique ID will be generated. */ PrairieDraw.prototype.registerOptionCallback = function (name, callback, callbackID) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } var option = this._options[name]; var useID; if (callbackID === undefined) { var nextIDNumber = 0, curIDNumber; for (var p in option.callbacks) { curIDNumber = parseInt(p, 10); if (isFinite(curIDNumber)) { nextIDNumber = Math.max(nextIDNumber, curIDNumber + 1); } } useID = nextIDNumber.toString(); } else { useID = callbackID; } option.callbacks[useID] = callback.bind(this); option.callbacks[useID](option.value); }; /** Clear the value for the given option. @param {string} name The option to clear. */ PrairieDraw.prototype.clearOptionValue = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } if ('value' in this._options[name]) { delete this._options[name].value; } this.redraw(); }; /** Reset the value for the given option. @param {string} name The option to reset. */ PrairieDraw.prototype.resetOptionValue = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } var option = this._options[name]; if (!('resetValue' in option)) { throw new Error('PrairieDraw: option has no resetValue: ' + name); } option.value = option.resetValue; for (var p in option.callbacks) { option.callbacks[p](option.value); } }; /*****************************************************************************/ /** Save the graphics state (properties, options, and transformations). @see restore(). */ PrairieDraw.prototype.save = function () { this._ctx.save(); var oldProps = {}; for (var p in this._props) { oldProps[p] = this._props[p]; } this._propStack.push(oldProps); this._transStack.push(this._trans.dup()); this._trans3DStack.push(this._trans3D.dup()); }; /** Restore the graphics state (properties, options, and transformations). @see save(). */ PrairieDraw.prototype.restore = function () { this._ctx.restore(); if (this._propStack.length === 0) { throw new Error('PrairieDraw: tried to restore() without corresponding save()'); } if (this._propStack.length !== this._transStack.length) { throw new Error('PrairieDraw: incompatible save stack lengths'); } if (this._propStack.length !== this._trans3DStack.length) { throw new Error('PrairieDraw: incompatible save stack lengths'); } this._props = this._propStack.pop(); this._trans = this._transStack.pop(); this._trans3D = this._trans3DStack.pop(); }; /** Restore all outstanding saves. */ PrairieDraw.prototype.restoreAll = function () { while (this._propStack.length > 0) { this.restore(); } if (this._saveTrans !== undefined) { this._trans = this._saveTrans; } }; /*****************************************************************************/ /** Reset the canvas image and drawing context. */ PrairieDraw.prototype.clearDrawing = function () { this._ctx.clearRect(0, 0, this._width, this._height); }; /** Reset everything to the intial state. */ PrairieDraw.prototype.reset = function () { for (var optionName in this._options) { this.resetOptionValue(optionName); } this.resetView3D(false); this.redraw(); }; /** Stop all action and computation. */ PrairieDraw.prototype.stop = function () {}; /*****************************************************************************/ /** Set the visable coordinate sizes. @param {number} xSize The horizontal size of the drawing area in coordinate units. @param {number} ySize The vertical size of the drawing area in coordinate units. @param {number} canvasWidth (Optional) The width of the canvas in px. @param {bool} preserveCanvasSize (Optional) If true, do not resize the canvas to match the coordinate ratio. */ PrairieDraw.prototype.setUnits = function (xSize, ySize, canvasWidth, preserveCanvasSize) { this.clearDrawing(); this._trans = Matrix.I(3); if (canvasWidth !== undefined) { var canvasHeight = Math.floor((ySize / xSize) * canvasWidth); if (this._width !== canvasWidth || this._height !== canvasHeight) { this._canvas.width = canvasWidth; this._canvas.height = canvasHeight; this._width = canvasWidth; this._height = canvasHeight; } preserveCanvasSize = true; } var xScale = this._width / xSize; var yScale = this._height / ySize; if (xScale < yScale) { this._scale = xScale; if (!preserveCanvasSize && xScale !== yScale) { var newHeight = xScale * ySize; this._canvas.height = newHeight; this._height = newHeight; } this.translate($V([this._width / 2, this._height / 2])); this.scale($V([1, -1])); this.scale($V([xScale, xScale])); } else { this._scale = yScale; if (!preserveCanvasSize && xScale !== yScale) { var newWidth = yScale * xSize; this._canvas.width = newWidth; this._width = newWidth; } this.translate($V([this._width / 2, this._height / 2])); this.scale($V([1, -1])); this.scale($V([yScale, yScale])); } this._saveTrans = this._trans; }; /*****************************************************************************/ /** Draw a point. @param {Vector} posDw Position of the point (drawing coords). */ PrairieDraw.prototype.point = function (posDw) { posDw = this.pos3To2(posDw); var posPx = this.pos2Px(posDw); this._ctx.beginPath(); this._ctx.arc(posPx.e(1), posPx.e(2), this._props.pointRadiusPx, 0, 2 * Math.PI); this._ctx.fillStyle = this._props.shapeOutlineColor; this._ctx.fill(); }; /*****************************************************************************/ /** @private Set the stroke/fill styles for drawing lines. @param {string} type The type of line being drawn. */ PrairieDraw.prototype._setLineStyles = function (type) { var col = this._getColorProp(type); this._ctx.strokeStyle = col; this._ctx.fillStyle = col; }; /** Return the dash array for the given line pattern. @param {string} type The type of the dash pattern ('solid', 'dashed', 'dotted'). @return {Array} The numerical array of dash segment lengths. */ PrairieDraw.prototype._dashPattern = function (type) { if (type === 'solid') { return []; } else if (type === 'dashed') { return [6, 6]; } else if (type === 'dotted') { return [2, 2]; } else { throw new Error('PrairieDraw: unknown dash pattern: ' + type); } }; /** Draw a single line given start and end positions. @param {Vector} startDw Initial point of the line (drawing coords). @param {Vector} endDw Final point of the line (drawing coords). @param {string} type Optional type of line being drawn. */ PrairieDraw.prototype.line = function (startDw, endDw, type) { startDw = this.pos3To2(startDw); endDw = this.pos3To2(endDw); var startPx = this.pos2Px(startDw); var endPx = this.pos2Px(endDw); this._ctx.save(); this._setLineStyles(type); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.beginPath(); this._ctx.moveTo(startPx.e(1), startPx.e(2)); this._ctx.lineTo(endPx.e(1), endPx.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a cubic Bezier segment. @param {Vector} p0Dw The starting point. @param {Vector} p1Dw The first control point. @param {Vector} p2Dw The second control point. @param {Vector} p3Dw The ending point. @param {string} type (Optional) type of line being drawn. */ PrairieDraw.prototype.cubicBezier = function (p0Dw, p1Dw, p2Dw, p3Dw, type) { var p0Px = this.pos2Px(this.pos3To2(p0Dw)); var p1Px = this.pos2Px(this.pos3To2(p1Dw)); var p2Px = this.pos2Px(this.pos3To2(p2Dw)); var p3Px = this.pos2Px(this.pos3To2(p3Dw)); this._ctx.save(); this._setLineStyles(type); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.beginPath(); this._ctx.moveTo(p0Px.e(1), p0Px.e(2)); this._ctx.bezierCurveTo(p1Px.e(1), p1Px.e(2), p2Px.e(1), p2Px.e(2), p3Px.e(1), p3Px.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** @private Draw an arrowhead in pixel coords. @param {Vector} posPx Position of the tip. @param {Vector} dirPx Direction vector that the arrowhead points in. @param {number} lenPx Length of the arrowhead. */ PrairieDraw.prototype._arrowheadPx = function (posPx, dirPx, lenPx) { var dxPx = -(1 - this._props.arrowheadOffsetRatio) * lenPx; var dyPx = this._props.arrowheadWidthRatio * lenPx; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(dirPx)); this._ctx.beginPath(); this._ctx.moveTo(0, 0); this._ctx.lineTo(-lenPx, dyPx); this._ctx.lineTo(dxPx, 0); this._ctx.lineTo(-lenPx, -dyPx); this._ctx.closePath(); this._ctx.fill(); this._ctx.restore(); }; /** @private Draw an arrowhead. @param {Vector} posDw Position of the tip (drawing coords). @param {Vector} dirDw Direction vector that the arrowhead point in (drawing coords). @param {number} lenPx Length of the arrowhead (pixel coords). */ PrairieDraw.prototype._arrowhead = function (posDw, dirDw, lenPx) { var posPx = this.pos2Px(posDw); var dirPx = this.vec2Px(dirDw); this._arrowheadPx(posPx, dirPx, lenPx); }; /** Draw an arrow given start and end positions. @param {Vector} startDw Initial point of the arrow (drawing coords). @param {Vector} endDw Final point of the arrow (drawing coords). @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrow = function (startDw, endDw, type) { startDw = this.pos3To2(startDw); endDw = this.pos3To2(endDw); var offsetDw = endDw.subtract(startDw); var offsetPx = this.vec2Px(offsetDw); var arrowLengthPx = offsetPx.modulus(); var lineEndDw, drawArrowHead, arrowheadLengthPx; if (arrowLengthPx < 1) { // if too short, just draw a simple line lineEndDw = endDw; drawArrowHead = false; } else { var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; arrowheadLengthPx = Math.min(arrowheadMaxLengthPx, arrowLengthPx / 2); var arrowheadCenterLengthPx = (1 - this._props.arrowheadOffsetRatio) * arrowheadLengthPx; var lineLengthPx = arrowLengthPx - arrowheadCenterLengthPx; lineEndDw = startDw.add(offsetDw.x(lineLengthPx / arrowLengthPx)); drawArrowHead = true; } var startPx = this.pos2Px(startDw); var lineEndPx = this.pos2Px(lineEndDw); this.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern)); this._setLineStyles(type); this._ctx.beginPath(); this._ctx.moveTo(startPx.e(1), startPx.e(2)); this._ctx.lineTo(lineEndPx.e(1), lineEndPx.e(2)); this._ctx.stroke(); if (drawArrowHead) { this._arrowhead(endDw, offsetDw, arrowheadLengthPx); } this.restore(); }; /** Draw an arrow given the start position and offset. @param {Vector} startDw Initial point of the arrow (drawing coords). @param {Vector} offsetDw Offset vector of the arrow (drawing coords). @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowFrom = function (startDw, offsetDw, type) { var endDw = startDw.add(offsetDw); this.arrow(startDw, endDw, type); }; /** Draw an arrow given the end position and offset. @param {Vector} endDw Final point of the arrow (drawing coords). @param {Vector} offsetDw Offset vector of the arrow (drawing coords). @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowTo = function (endDw, offsetDw, type) { var startDw = endDw.subtract(offsetDw); this.arrow(startDw, endDw, type); }; /** Draw an arrow out of the page (circle with centered dot). @param {Vector} posDw The position of the arrow. @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowOutOfPage = function (posDw, type) { var posPx = this.pos2Px(posDw); var r = this._props.arrowOutOfPageRadiusPx; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.beginPath(); this._ctx.arc(0, 0, r, 0, 2 * Math.PI); this._ctx.fillStyle = 'rgb(255, 255, 255)'; this._ctx.fill(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._setLineStyles(type); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.arc(0, 0, this._props.arrowLineWidthPx * 0.7, 0, 2 * Math.PI); this._ctx.fill(); this._ctx.restore(); }; /** Draw an arrow into the page (circle with times). @param {Vector} posDw The position of the arrow. @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowIntoPage = function (posDw, type) { var posPx = this.pos2Px(posDw); var r = this._props.arrowOutOfPageRadiusPx; var rs = r / Math.sqrt(2); this._ctx.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._setLineStyles(type); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.beginPath(); this._ctx.arc(0, 0, r, 0, 2 * Math.PI); this._ctx.fillStyle = 'rgb(255, 255, 255)'; this._ctx.fill(); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(-rs, -rs); this._ctx.lineTo(rs, rs); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(rs, -rs); this._ctx.lineTo(-rs, rs); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a circle arrow by specifying the center and extent. @param {Vector} posDw The center of the circle arrow. @param {number} radDw The radius at the mid-angle. @param {number} centerAngleDw The center angle (counterclockwise from x axis, in radians). @param {number} extentAngleDw The extent of the arrow (counterclockwise, in radians). @param {string} type (Optional) The type of the arrow. @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). */ PrairieDraw.prototype.circleArrowCentered = function ( posDw, radDw, centerAngleDw, extentAngleDw, type, fixedRad ) { var startAngleDw = centerAngleDw - extentAngleDw / 2; var endAngleDw = centerAngleDw + extentAngleDw / 2; this.circleArrow(posDw, radDw, startAngleDw, endAngleDw, type, fixedRad); }; /** Draw a circle arrow. @param {Vector} posDw The center of the circle arrow. @param {number} radDw The radius at the mid-angle. @param {number} startAngleDw The starting angle (counterclockwise from x axis, in radians). @param {number} endAngleDw The ending angle (counterclockwise from x axis, in radians). @param {string} type (Optional) The type of the arrow. @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). @param {number} idealSegmentSize (Optional) The ideal linear segment size to use (radians). */ PrairieDraw.prototype.circleArrow = function ( posDw, radDw, startAngleDw, endAngleDw, type, fixedRad, idealSegmentSize ) { this.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern)); this._setLineStyles(type); // convert to Px coordinates var startOffsetDw = PrairieGeom.vector2DAtAngle(startAngleDw).x(radDw); var posPx = this.pos2Px(posDw); var startOffsetPx = this.vec2Px(startOffsetDw); var radiusPx = startOffsetPx.modulus(); var startAnglePx = PrairieGeom.angleOf(startOffsetPx); var deltaAngleDw = endAngleDw - startAngleDw; // assume a possibly reflected/rotated but equally scaled Dw/Px transformation var deltaAnglePx = this._transIsReflection() ? -deltaAngleDw : deltaAngleDw; var endAnglePx = startAnglePx + deltaAnglePx; // compute arrowhead properties var startRadiusPx = this._circleArrowRadius( radiusPx, startAnglePx, startAnglePx, endAnglePx, fixedRad ); var endRadiusPx = this._circleArrowRadius( radiusPx, endAnglePx, startAnglePx, endAnglePx, fixedRad ); var arrowLengthPx = radiusPx * Math.abs(endAnglePx - startAnglePx); var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; var arrowheadLengthPx = Math.min(arrowheadMaxLengthPx, arrowLengthPx / 2); var arrowheadCenterLengthPx = (1 - this._props.arrowheadOffsetRatio) * arrowheadLengthPx; var arrowheadExtraCenterLengthPx = (1 - this._props.arrowheadOffsetRatio / 3) * arrowheadLengthPx; var arrowheadAnglePx = arrowheadCenterLengthPx / endRadiusPx; var arrowheadExtraAnglePx = arrowheadExtraCenterLengthPx / endRadiusPx; var preEndAnglePx = endAnglePx - PrairieGeom.sign(endAnglePx - startAnglePx) * arrowheadAnglePx; var arrowBaseAnglePx = endAnglePx - PrairieGeom.sign(endAnglePx - startAnglePx) * arrowheadExtraAnglePx; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); idealSegmentSize = idealSegmentSize === undefined ? 0.2 : idealSegmentSize; // radians var numSegments = Math.ceil(Math.abs(preEndAnglePx - startAnglePx) / idealSegmentSize); var i, anglePx, rPx; var offsetPx = PrairieGeom.vector2DAtAngle(startAnglePx).x(startRadiusPx); this._ctx.beginPath(); this._ctx.moveTo(offsetPx.e(1), offsetPx.e(2)); for (i = 1; i <= numSegments; i++) { anglePx = PrairieGeom.linearInterp(startAnglePx, preEndAnglePx, i / numSegments); rPx = this._circleArrowRadius(radiusPx, anglePx, startAnglePx, endAnglePx, fixedRad); offsetPx = PrairieGeom.vector2DAtAngle(anglePx).x(rPx); this._ctx.lineTo(offsetPx.e(1), offsetPx.e(2)); } this._ctx.stroke(); this._ctx.restore(); var arrowBaseRadiusPx = this._circleArrowRadius( radiusPx, arrowBaseAnglePx, startAnglePx, endAnglePx, fixedRad ); var arrowPosPx = posPx.add(PrairieGeom.vector2DAtAngle(endAnglePx).x(endRadiusPx)); var arrowBasePosPx = posPx.add( PrairieGeom.vector2DAtAngle(arrowBaseAnglePx).x(arrowBaseRadiusPx) ); var arrowDirPx = arrowPosPx.subtract(arrowBasePosPx); var arrowPosDw = this.pos2Dw(arrowPosPx); var arrowDirDw = this.vec2Dw(arrowDirPx); this._arrowhead(arrowPosDw, arrowDirDw, arrowheadLengthPx); this.restore(); }; /** @private Compute the radius at a certain angle within a circle arrow. @param {number} midRadPx The radius at the midpoint of the circle arrow. @param {number} anglePx The angle at which to find the radius. @param {number} startAnglePx The starting angle (counterclockwise from x axis, in radians). @param {number} endAnglePx The ending angle (counterclockwise from x axis, in radians). @return {number} The radius at the given angle (pixel coords). @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). */ PrairieDraw.prototype._circleArrowRadius = function ( midRadPx, anglePx, startAnglePx, endAnglePx, fixedRad ) { if (fixedRad !== undefined && fixedRad === true) { return midRadPx; } if (Math.abs(endAnglePx - startAnglePx) < 1e-4) { return midRadPx; } var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; /* jshint laxbreak: true */ var spacingPx = arrowheadMaxLengthPx * this._props.arrowheadWidthRatio * this._props.circleArrowWrapOffsetRatio; var circleArrowWrapDensity = (midRadPx * Math.PI * 2) / spacingPx; var midAnglePx = (startAnglePx + endAnglePx) / 2; var offsetAnglePx = (anglePx - midAnglePx) * PrairieGeom.sign(endAnglePx - startAnglePx); if (offsetAnglePx > 0) { return midRadPx * (1 + offsetAnglePx / circleArrowWrapDensity); } else { return midRadPx * Math.exp(offsetAnglePx / circleArrowWrapDensity); } }; /*****************************************************************************/ /** Draw an arc in 3D. @param {Vector} posDw The center of the arc. @param {number} radDw The radius of the arc. @param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: an orthogonal vector to normDw). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). @param {string} type (Optional) The type of the line. @param {Object} options (Optional) Various options. */ PrairieDraw.prototype.arc3D = function ( posDw, radDw, normDw, refDw, startAngleDw, endAngleDw, options ) { posDw = this.pos2To3(posDw); normDw = normDw === undefined ? Vector.k : normDw; refDw = refDw === undefined ? PrairieGeom.chooseNormVec(normDw) : refDw; var fullCircle = startAngleDw === undefined && endAngleDw === undefined; startAngleDw = startAngleDw === undefined ? 0 : startAngleDw; endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw; options = options === undefined ? {} : options; var idealSegmentSize = options.idealSegmentSize === undefined ? (2 * Math.PI) / 40 : options.idealSegmentSize; var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector(); var vDw = normDw.toUnitVector().cross(uDw); var numSegments = Math.ceil(Math.abs(endAngleDw - startAngleDw) / idealSegmentSize); var points = []; var theta, p; for (var i = 0; i <= numSegments; i++) { theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, i / numSegments); p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta))); points.push(this.pos3To2(p)); } if (fullCircle) { points.pop(); this.polyLine(points, true, false); } else { this.polyLine(points); } }; /*****************************************************************************/ /** Draw a circle arrow in 3D. @param {Vector} posDw The center of the arc. @param {number} radDw The radius of the arc. @param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: x axis). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). @param {string} type (Optional) The type of the line. @param {Object} options (Optional) Various options. */ PrairieDraw.prototype.circleArrow3D = function ( posDw, radDw, normDw, refDw, startAngleDw, endAngleDw, type, options ) { posDw = this.pos2To3(posDw); normDw = normDw || Vector.k; refDw = refDw || Vector.i; startAngleDw = startAngleDw === undefined ? 0 : startAngleDw; endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw; options = options === undefined ? {} : options; var idealSegmentSize = options.idealSegmentSize === undefined ? (2 * Math.PI) / 40 : options.idealSegmentSize; var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector(); var vDw = normDw.toUnitVector().cross(uDw); var numSegments = Math.ceil(Math.abs(endAngleDw - startAngleDw) / idealSegmentSize); var points = []; var theta, p; for (var i = 0; i <= numSegments; i++) { theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, i / numSegments); p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta))); points.push(this.pos3To2(p)); } this.polyLineArrow(points, type); }; /** Label a circle line in 3D. @param {string} labelText The label text. @param {Vector} labelAnchor The label anchor (first coord -1 to 1 along the line, second -1 to 1 transverse). @param {Vector} posDw The center of the arc. @param {number} radDw The radius of the arc. @param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: x axis). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). */ PrairieDraw.prototype.labelCircleLine3D = function ( labelText, labelAnchor, posDw, radDw, normDw, refDw, startAngleDw, endAngleDw ) { if (labelText === undefined) { return; } posDw = this.pos2To3(posDw); normDw = normDw || Vector.k; refDw = refDw || Vector.i; startAngleDw = startAngleDw === undefined ? 0 : startAngleDw; endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw; var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector(); var vDw = normDw.toUnitVector().cross(uDw); var theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, (labelAnchor.e(1) + 1) / 2); var p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta))); var p2Dw = this.pos3To2(p); var t3Dw = uDw.x(-Math.sin(theta)).add(vDw.x(Math.cos(theta))); var n3Dw = uDw.x(Math.cos(theta)).add(vDw.x(Math.sin(theta))); var t2Px = this.vec2Px(this.vec3To2(t3Dw, p)); var n2Px = this.vec2Px(this.vec3To2(n3Dw, p)); n2Px = PrairieGeom.orthComp(n2Px, t2Px); t2Px = t2Px.toUnitVector(); n2Px = n2Px.toUnitVector(); var oPx = t2Px.x(labelAnchor.e(1)).add(n2Px.x(labelAnchor.e(2))); var oDw = this.vec2Dw(oPx); var aDw = oDw.x(-1).toUnitVector(); var anchor = aDw.x(1.0 / Math.abs(aDw.max())).x(Math.abs(labelAnchor.max())); this.text(p2Dw, anchor, labelText); }; /*****************************************************************************/ /** Draw a sphere. @param {Vector} posDw Position of the sphere center. @param {number} radDw Radius of the sphere. @param {bool} filled (Optional) Whether to fill the sphere (default: false). */ PrairieDraw.prototype.sphere = function (posDw, radDw, filled) { filled = filled === undefined ? false : filled; var posVw = this.posDwToVw(posDw); var edgeDw = posDw.add($V([radDw, 0, 0])); var edgeVw = this.posDwToVw(edgeDw); var radVw = edgeVw.subtract(posVw).modulus(); var posDw2 = PrairieGeom.orthProjPos3D(posVw); this.circle(posDw2, radVw, filled); }; /** Draw a circular slice on a sphere. @param {Vector} posDw Position of the sphere center. @param {number} radDw Radius of the sphere. @param {Vector} normDw Normal vector to the circle. @param {number} distDw Distance from sphere center to circle center along normDw. @param {string} drawBack (Optional) Whether to draw the back line (default: true). @param {string} drawFront (Optional) Whether to draw the front line (default: true). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: an orthogonal vector to normDw). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). */ PrairieDraw.prototype.sphereSlice = function ( posDw, radDw, normDw, distDw, drawBack, drawFront, refDw, startAngleDw, endAngleDw ) { var cRDwSq = radDw * radDw - distDw * distDw; if (cRDwSq <= 0) { return; } var cRDw = Math.sqrt(cRDwSq); var circlePosDw = posDw.add(normDw.toUnitVector().x(distDw)); drawBack = drawBack === undefined ? true : drawBack; drawFront = drawFront === undefined ? true : drawFront; var normVw = this.vecDwToVw(normDw); if (PrairieGeom.orthComp(Vector.k, normVw).modulus() < 1e-10) { // looking straight down on the circle if (distDw > 0) { // front side, completely visible this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); } else if (distDw < 0) { // back side, completely invisible this.save(); this.setShapeDrawHidden(); this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); this.restore(); } // if distDw == 0 then it's a great circle, don't draw it return; } var refVw; if (refDw === undefined) { refVw = PrairieGeom.orthComp(Vector.k, normVw); refDw = this.vecVwToDw(refVw); } refVw = this.vecDwToVw(refDw); var uVw = refVw.toUnitVector(); var vVw = normVw.toUnitVector().cross(uVw); var dVw = this.vecDwToVw(normDw.toUnitVector().x(distDw)); var cRVw = this.vecDwToVw(refDw.toUnitVector().x(cRDw)).modulus(); var A = -dVw.e(3); var B = uVw.e(3) * cRVw; var C = vVw.e(3) * cRVw; var BCMag = Math.sqrt(B * B + C * C); var AN = A / BCMag; var phi = Math.atan2(C, B); if (AN <= -1) { // only front if (drawFront) { this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); } } else if (AN >= 1) { // only back if (drawBack && this._props.hiddenLineDraw) { this.save(); this.setShapeDrawHidden(); this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); this.restore(); } } else { // front and back var acosAN = Math.acos(AN); var theta1 = phi + acosAN; var theta2 = phi + 2 * Math.PI - acosAN; var i, intersections, range; if (drawBack && this._props.hiddenLineDraw) { this.save(); this.setShapeDrawHidden(); if (theta2 > theta1) { if (startAngleDw === undefined || endAngleDw === undefined) { this.arc3D(circlePosDw, cRDw, normDw, refDw, theta1, theta2); } else { intersections = PrairieGeom.intersectAngleRanges( [theta1, theta2], [startAngleDw, endAngleDw] ); for (i = 0; i < intersections.length; i++) { range = intersections[i]; this.arc3D(circlePosDw, cRDw, normDw, refDw, range[0], range[1]); } } } this.restore(); } if (drawFront) { if (startAngleDw === undefined || endAngleDw === undefined) { this.arc3D(circlePosDw, cRDw, normDw, refDw, theta2, theta1 + 2 * Math.PI); } else { intersections = PrairieGeom.intersectAngleRanges( [theta2, theta1 + 2 * Math.PI], [startAngleDw, endAngleDw] ); for (i = 0; i < intersections.length; i++) { range = intersections[i]; this.arc3D(circlePosDw, cRDw, normDw, refDw, range[0], range[1]); } } } } }; /*****************************************************************************/ /** Label an angle with an inset label. @param {Vector} pos The corner position. @param {Vector} p1 Position of first other point. @param {Vector} p2 Position of second other point. @param {string} label The label text. */ PrairieDraw.prototype.labelAngle = function (pos, p1, p2, label) { pos = this.pos3To2(pos); p1 = this.pos3To2(p1); p2 = this.pos3To2(p2); var v1 = p1.subtract(pos); var v2 = p2.subtract(pos); var vMid = v1.add(v2).x(0.5); var anchor = vMid.x(-1.8 / PrairieGeom.supNorm(vMid)); this.text(pos, anchor, label); }; /*****************************************************************************/ /** Draw an arc. @param {Vector} centerDw The center of the circle. @param {Vector} radiusDw The radius of the circle (or major axis for ellipses). @param {number} startAngle (Optional) The start angle of the arc (radians, default: 0). @param {number} endAngle (Optional) The end angle of the arc (radians, default: 2 pi). @param {bool} filled (Optional) Whether to fill the arc (default: false). @param {Number} aspect (Optional) The aspect ratio (major / minor) (default: 1). */ PrairieDraw.prototype.arc = function (centerDw, radiusDw, startAngle, endAngle, filled, aspect) { startAngle = startAngle === undefined ? 0 : startAngle; endAngle = endAngle === undefined ? 2 * Math.PI : endAngle; filled = filled === undefined ? false : filled; aspect = aspect === undefined ? 1 : aspect; var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); var anglePx = PrairieGeom.angleOf(offsetPx); this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.save(); this._ctx.translate(centerPx.e(1), centerPx.e(2)); this._ctx.rotate(anglePx); this._ctx.scale(1, 1 / aspect); this._ctx.beginPath(); this._ctx.arc(0, 0, radiusPx, -endAngle, -startAngle); this._ctx.restore(); if (filled) { this._ctx.fill(); } this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a polyLine (closed or open). @param {Array} pointsDw A list of drawing coordinates that form the polyLine. @param {bool} closed (Optional) Whether the shape should be closed (default: false). @param {bool} filled (Optional) Whether the shape should be filled (default: true). */ PrairieDraw.prototype.polyLine = function (pointsDw, closed, filled) { if (pointsDw.length < 2) { return; } this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.beginPath(); var pDw = this.pos3To2(pointsDw[0]); var pPx = this.pos2Px(pDw); this._ctx.moveTo(pPx.e(1), pPx.e(2)); for (var i = 1; i < pointsDw.length; i++) { pDw = this.pos3To2(pointsDw[i]); pPx = this.pos2Px(pDw); this._ctx.lineTo(pPx.e(1), pPx.e(2)); } if (closed !== undefined && closed === true) { this._ctx.closePath(); if (filled === undefined || filled === true) { this._ctx.fill(); } } this._ctx.stroke(); this._ctx.restore(); }; /** Draw a polyLine arrow. @param {Array} pointsDw A list of drawing coordinates that form the polyLine. */ PrairieDraw.prototype.polyLineArrow = function (pointsDw, type) { if (pointsDw.length < 2) { return; } // convert the line to pixel coords and find its length var pointsPx = []; var i; var polyLineLengthPx = 0; for (i = 0; i < pointsDw.length; i++) { pointsPx.push(this.pos2Px(this.pos3To2(pointsDw[i]))); if (i > 0) { polyLineLengthPx += pointsPx[i].subtract(pointsPx[i - 1]).modulus(); } } // shorten the line to fit the arrowhead, dropping points and moving the last point var drawArrowHead, arrowheadEndPx, arrowheadOffsetPx, arrowheadLengthPx; if (polyLineLengthPx < 1) { // if too short, don't draw the arrowhead drawArrowHead = false; } else { drawArrowHead = true; var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; arrowheadLengthPx = Math.min(arrowheadMaxLengthPx, polyLineLengthPx / 2); var arrowheadCenterLengthPx = (1 - this._props.arrowheadOffsetRatio) * arrowheadLengthPx; var lengthToRemovePx = arrowheadCenterLengthPx; i = pointsPx.length - 1; arrowheadEndPx = pointsPx[i]; var segmentLengthPx; while (i > 0) { segmentLengthPx = pointsPx[i].subtract(pointsPx[i - 1]).modulus(); if (lengthToRemovePx > segmentLengthPx) { lengthToRemovePx -= segmentLengthPx; pointsPx.pop(); i--; } else { pointsPx[i] = PrairieGeom.linearInterpVector( pointsPx[i], pointsPx[i - 1], lengthToRemovePx / segmentLengthPx ); break; } } var arrowheadBasePx = pointsPx[i]; arrowheadOffsetPx = arrowheadEndPx.subtract(arrowheadBasePx); } // draw the line this._ctx.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern)); this._setLineStyles(type); this._ctx.beginPath(); var pPx = pointsPx[0]; this._ctx.moveTo(pPx.e(1), pPx.e(2)); for (i = 1; i < pointsPx.length; i++) { pPx = pointsPx[i]; this._ctx.lineTo(pPx.e(1), pPx.e(2)); } this._ctx.stroke(); // draw the arrowhead if (drawArrowHead) { i = pointsPx[i]; this._arrowheadPx(arrowheadEndPx, arrowheadOffsetPx, arrowheadLengthPx); } this._ctx.restore(); }; /*****************************************************************************/ /** Draw a circle. @param {Vector} centerDw The center in drawing coords. @param {number} radiusDw the radius in drawing coords. @param {bool} filled (Optional) Whether to fill the circle (default: true). */ PrairieDraw.prototype.circle = function (centerDw, radiusDw, filled) { filled = filled === undefined ? true : filled; var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, 0, 2 * Math.PI); if (filled) { this._ctx.fill(); } this._ctx.stroke(); this._ctx.restore(); }; /** Draw a filled circle. @param {Vector} centerDw The center in drawing coords. @param {number} radiusDw the radius in drawing coords. */ PrairieDraw.prototype.filledCircle = function (centerDw, radiusDw) { var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.fillStyle = this._props.shapeOutlineColor; this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, 0, 2 * Math.PI); this._ctx.fill(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a triagular distributed load @param {Vector} startDw The first point (in drawing coordinates) of the distributed load @param {Vector} endDw The end point (in drawing coordinates) of the distributed load @param {number} sizeStartDw length of the arrow at startDw @param {number} sizeEndDw length of the arrow at endDw @param {string} label the arrow size at startDw @param {string} label the arrow size at endDw @param {boolean} true if arrow heads are towards the line that connects points startDw and endDw, opposite direction if false @param {boolean} true if arrow points up (positive y-axis), false otherwise */ PrairieDraw.prototype.triangularDistributedLoad = function ( startDw, endDw, sizeStartDw, sizeEndDw, labelStart, labelEnd, arrowToLine, arrowDown ) { var LengthDw = endDw.subtract(startDw); var L = LengthDw.modulus(); if (arrowDown) { var sizeStartDwSign = sizeStartDw; var sizeEndDwSign = sizeEndDw; } else { var sizeStartDwSign = -sizeStartDw; var sizeEndDwSign = -sizeEndDw; } var nSpaces = Math.ceil((2 * L) / sizeStartDw); var spacing = L / nSpaces; var inc = 0; this.save(); this.setProp('shapeOutlineColor', 'rgb(255,0,0)'); this.setProp('arrowLineWidthPx', 1); this.setProp('arrowheadLengthRatio', 11); if (arrowToLine) { this.line(startDw.add($V([0, sizeStartDwSign])), endDw.add($V([0, sizeEndDwSign]))); var startArrow = startDw.add($V([0, sizeStartDwSign])); var endArrow = startDw; for (i = 0; i <= nSpaces; i++) { this.arrow( startArrow.add($V([inc, (inc * (sizeEndDwSign - sizeStartDwSign)) / L])), endArrow.add($V([inc, 0])) ); inc = inc + spacing; } this.text(startArrow, $V([2, 0]), labelStart); this.text( startArrow.add( $V([inc - spacing, ((inc - spacing) * (sizeEndDwSign - sizeStartDwSign)) / L]) ), $V([-2, 0]), labelEnd ); } else { this.line(startDw, endDw); var startArrow = startDw; var endArrow = startDw.subtract($V([0, sizeStartDwSign])); for (i = 0; i <= nSpaces; i++) { this.arrow( startArrow.add($V([inc, 0])), endArrow.add($V([inc, (-inc * (sizeEndDwSign - sizeStartDwSign)) / L]))<|fim▁hole|> } this.text(endArrow, $V([2, 0]), labelStart); this.text( endArrow.add( $V([inc - spacing, (-(inc - spacing) * (sizeEndDwSign - sizeStartDwSign)) / L]) ), $V([-2, 0]), labelEnd ); } this.restore(); }; /*****************************************************************************/ /** Draw a rod with hinge points at start and end and the given width. @param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates. @param {Vector} startDw The second hinge point (drawing coordinates). @param {number} widthDw The width of the rod (drawing coordinates). */ PrairieDraw.prototype.rod = function (startDw, endDw, widthDw) { var offsetLengthDw = endDw.subtract(startDw); var offsetWidthDw = offsetLengthDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var startPx = this.pos2Px(startDw); var offsetLengthPx = this.vec2Px(offsetLengthDw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var lengthPx = offsetLengthPx.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetLengthPx)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); this._ctx.arcTo(lengthPx + rPx, rPx, lengthPx + rPx, -rPx, rPx); this._ctx.arcTo(lengthPx + rPx, -rPx, 0, -rPx, rPx); this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx); this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx); if (this._props.shapeInsideColor !== 'none') { this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); } this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a L-shape rod with hinge points at start, center and end, and the given width. @param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates. @param {Vector} centerDw The second hinge point (drawing coordinates). @param {Vector} endDw The third hinge point (drawing coordinates). @param {number} widthDw The width of the rod (drawing coordinates). */ PrairieDraw.prototype.LshapeRod = function (startDw, centerDw, endDw, widthDw) { var offsetLength1Dw = centerDw.subtract(startDw); var offsetLength2Dw = endDw.subtract(centerDw); var offsetWidthDw = offsetLength1Dw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var startPx = this.pos2Px(startDw); var centerPx = this.pos2Px(centerDw); var endPx = this.pos2Px(endDw); var offsetLength1Px = this.vec2Px(offsetLength1Dw); var offsetLength2Px = this.vec2Px(offsetLength2Dw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var length1Px = offsetLength1Px.modulus(); var length2Px = offsetLength2Px.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetLength1Px)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); var beta = -PrairieGeom.angleFrom(offsetLength1Px, offsetLength2Px); var x1 = length1Px + rPx / Math.sin(beta) - rPx / Math.tan(beta); var y1 = rPx; var x2 = length1Px + length2Px * Math.cos(beta); var y2 = -length2Px * Math.sin(beta); var x3 = x2 + rPx * Math.sin(beta); var y3 = y2 + rPx * Math.cos(beta); var x4 = x3 + rPx * Math.cos(beta); var y4 = y3 - rPx * Math.sin(beta); var x5 = x2 + rPx * Math.cos(beta); var y5 = y2 - rPx * Math.sin(beta); var x6 = x5 - rPx * Math.sin(beta); var y6 = y5 - rPx * Math.cos(beta); var x7 = length1Px - rPx / Math.sin(beta) + rPx / Math.tan(beta); var y7 = -rPx; this._ctx.arcTo(x1, y1, x3, y3, rPx); this._ctx.arcTo(x4, y4, x5, y5, rPx); this._ctx.arcTo(x6, y6, x7, y7, rPx); this._ctx.arcTo(x7, y7, 0, -rPx, rPx); this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx); this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx); if (this._props.shapeInsideColor !== 'none') { this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); } this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a T-shape rod with hinge points at start, center, center-end and end, and the given width. @param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates. @param {Vector} centerDw The second hinge point (drawing coordinates). @param {Vector} endDw The third hinge point (drawing coordinates). @param {Vector} centerEndDw The fourth hinge point (drawing coordinates). @param {number} widthDw The width of the rod (drawing coordinates). */ PrairieDraw.prototype.TshapeRod = function (startDw, centerDw, endDw, centerEndDw, widthDw) { var offsetStartRodDw = centerDw.subtract(startDw); var offsetEndRodDw = endDw.subtract(centerDw); var offsetCenterRodDw = centerEndDw.subtract(centerDw); var offsetWidthDw = offsetStartRodDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var startPx = this.pos2Px(startDw); var centerPx = this.pos2Px(centerDw); var endPx = this.pos2Px(endDw); var offsetStartRodPx = this.vec2Px(offsetStartRodDw); var offsetEndRodPx = this.vec2Px(offsetEndRodDw); var offsetCenterRodPx = this.vec2Px(offsetCenterRodDw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var lengthStartRodPx = offsetStartRodPx.modulus(); var lengthEndRodPx = offsetEndRodPx.modulus(); var lengthCenterRodPx = offsetCenterRodPx.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetStartRodPx)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); var angleStartToEnd = PrairieGeom.angleFrom(offsetStartRodPx, offsetEndRodPx); var angleEndToCenter = PrairieGeom.angleFrom(offsetEndRodPx, offsetCenterRodPx); if (Math.abs(angleEndToCenter) < Math.PI) { var length1Px = lengthStartRodPx; var length2Px = lengthEndRodPx; var length3Px = lengthCenterRodPx; var beta = -angleStartToEnd; var alpha = -angleEndToCenter; } else { var length1Px = lengthStartRodPx; var length2Px = lengthCenterRodPx; var length3Px = lengthEndRodPx; var beta = -PrairieGeom.angleFrom(offsetStartRodPx, offsetCenterRodPx); var alpha = angleEndToCenter; } var x1 = length1Px + rPx / Math.sin(beta) - rPx / Math.tan(beta); var y1 = rPx; var x2 = length1Px + length2Px * Math.cos(beta); var y2 = -length2Px * Math.sin(beta); var x3 = x2 + rPx * Math.sin(beta); var y3 = y2 + rPx * Math.cos(beta); var x4 = x3 + rPx * Math.cos(beta); var y4 = y3 - rPx * Math.sin(beta); var x5 = x2 + rPx * Math.cos(beta); var y5 = y2 - rPx * Math.sin(beta); var x6 = x5 - rPx * Math.sin(beta); var y6 = y5 - rPx * Math.cos(beta); var x7 = length1Px + rPx * Math.cos(beta) * (1 / Math.sin(alpha) + 1 / Math.tan(alpha) - Math.tan(beta)); var y7 = -rPx / Math.cos(beta) - rPx * Math.sin(beta) * (1 / Math.sin(alpha) + 1 / Math.tan(alpha) - Math.tan(beta)); var x8 = length1Px + length3Px * Math.cos(beta + alpha); var y8 = -length3Px * Math.sin(beta + alpha); var x9 = x8 + rPx * Math.sin(beta + alpha); var y9 = y8 + rPx * Math.cos(beta + alpha); var x10 = x9 + rPx * Math.cos(beta + alpha); var y10 = y9 - rPx * Math.sin(beta + alpha); var x11 = x8 + rPx * Math.cos(beta + alpha); var y11 = y8 - rPx * Math.sin(beta + alpha); var x12 = x11 - rPx * Math.sin(beta + alpha); var y12 = y11 - rPx * Math.cos(beta + alpha); var x13 = length1Px - rPx / Math.sin(beta + alpha) + rPx / Math.tan(beta + alpha); var y13 = -rPx; this._ctx.arcTo(x1, y1, x3, y3, rPx); this._ctx.arcTo(x4, y4, x5, y5, rPx); this._ctx.arcTo(x6, y6, x7, y7, rPx); this._ctx.arcTo(x7, y7, x9, y9, rPx); this._ctx.arcTo(x10, y10, x11, y11, rPx); this._ctx.arcTo(x12, y12, x13, y13, rPx); this._ctx.arcTo(x13, y13, 0, -rPx, rPx); this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx); this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx); if (this._props.shapeInsideColor !== 'none') { this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); } this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a pivot. @param {Vector} baseDw The center of the base (drawing coordinates). @param {Vector} hingeDw The hinge point (center of circular end) in drawing coordinates. @param {number} widthDw The width of the pivot (drawing coordinates). */ PrairieDraw.prototype.pivot = function (baseDw, hingeDw, widthDw) { var offsetLengthDw = hingeDw.subtract(baseDw); var offsetWidthDw = offsetLengthDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var basePx = this.pos2Px(baseDw); var offsetLengthPx = this.vec2Px(offsetLengthDw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var lengthPx = offsetLengthPx.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(basePx.e(1), basePx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetLengthPx)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); this._ctx.arcTo(lengthPx + rPx, rPx, lengthPx + rPx, -rPx, rPx); this._ctx.arcTo(lengthPx + rPx, -rPx, 0, -rPx, rPx); this._ctx.lineTo(0, -rPx); this._ctx.closePath(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); this._ctx.stroke(); this._ctx.restore(); }; /** Draw a square with a given base point and center. @param {Vector} baseDw The mid-point of the base (drawing coordinates). @param {Vector} centerDw The center of the square (drawing coordinates). */ PrairieDraw.prototype.square = function (baseDw, centerDw) { var basePx = this.pos2Px(baseDw); var centerPx = this.pos2Px(centerDw); var offsetPx = centerPx.subtract(basePx); var rPx = offsetPx.modulus(); this._ctx.save(); this._ctx.translate(basePx.e(1), basePx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetPx)); this._ctx.beginPath(); this._ctx.rect(0, -rPx, 2 * rPx, 2 * rPx); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); this._ctx.stroke(); this._ctx.restore(); }; /** Draw an axis-aligned rectangle with a given width and height, centered at the origin. @param {number} widthDw The width of the rectangle. @param {number} heightDw The height of the rectangle. @param {number} centerDw Optional: The center of the rectangle (default: the origin). @param {number} angleDw Optional: The rotation angle of the rectangle (default: zero). @param {bool} filled Optional: Whether to fill the rectangle (default: true). */ PrairieDraw.prototype.rectangle = function (widthDw, heightDw, centerDw, angleDw, filled) { centerDw = centerDw === undefined ? $V([0, 0]) : centerDw; angleDw = angleDw === undefined ? 0 : angleDw; var pointsDw = [ $V([-widthDw / 2, -heightDw / 2]), $V([widthDw / 2, -heightDw / 2]), $V([widthDw / 2, heightDw / 2]), $V([-widthDw / 2, heightDw / 2]), ]; var closed = true; filled = filled === undefined ? true : filled; this.save(); this.translate(centerDw); this.rotate(angleDw); this.polyLine(pointsDw, closed, filled); this.restore(); }; /** Draw a rectangle with the given corners and height. @param {Vector} pos1Dw First corner of the rectangle. @param {Vector} pos2Dw Second corner of the rectangle. @param {number} heightDw The height of the rectangle. */ PrairieDraw.prototype.rectangleGeneric = function (pos1Dw, pos2Dw, heightDw) { var dDw = PrairieGeom.perp(pos2Dw.subtract(pos1Dw)).toUnitVector().x(heightDw); var pointsDw = [pos1Dw, pos2Dw, pos2Dw.add(dDw), pos1Dw.add(dDw)]; var closed = true; this.polyLine(pointsDw, closed); }; /** Draw a ground element. @param {Vector} posDw The position of the ground center (drawing coordinates). @param {Vector} normDw The outward normal (drawing coordinates). @param (number} lengthDw The total length of the ground segment. */ PrairieDraw.prototype.ground = function (posDw, normDw, lengthDw) { var tangentDw = normDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(lengthDw); var posPx = this.pos2Px(posDw); var normPx = this.vec2Px(normDw); var tangentPx = this.vec2Px(tangentDw); var lengthPx = tangentPx.modulus(); var groundDepthPx = Math.min(lengthPx, this._props.groundDepthPx); this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(normPx) - Math.PI / 2); this._ctx.beginPath(); this._ctx.rect(-lengthPx / 2, -groundDepthPx, lengthPx, groundDepthPx); this._ctx.fillStyle = this._props.groundInsideColor; this._ctx.fill(); this._ctx.beginPath(); this._ctx.moveTo(-lengthPx / 2, 0); this._ctx.lineTo(lengthPx / 2, 0); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.groundOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a ground element with hashed shading. @param {Vector} posDw The position of the ground center (drawing coords). @param {Vector} normDw The outward normal (drawing coords). @param (number} lengthDw The total length of the ground segment (drawing coords). @param {number} offsetDw (Optional) The offset of the shading (drawing coords). */ PrairieDraw.prototype.groundHashed = function (posDw, normDw, lengthDw, offsetDw) { offsetDw = offsetDw === undefined ? 0 : offsetDw; var tangentDw = normDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(lengthDw); var offsetVecDw = tangentDw.toUnitVector().x(offsetDw); var posPx = this.pos2Px(posDw); var normPx = this.vec2Px(normDw); var tangentPx = this.vec2Px(tangentDw); var lengthPx = tangentPx.modulus(); var offsetVecPx = this.vec2Px(offsetVecDw); var offsetPx = offsetVecPx.modulus() * PrairieGeom.sign(offsetDw); this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(normPx) + Math.PI / 2); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.groundOutlineColor; this._ctx.beginPath(); this._ctx.moveTo(-lengthPx / 2, 0); this._ctx.lineTo(lengthPx / 2, 0); this._ctx.stroke(); var startX = offsetPx % this._props.groundSpacingPx; var x = startX; while (x < lengthPx / 2) { this._ctx.beginPath(); this._ctx.moveTo(x, 0); this._ctx.lineTo(x - this._props.groundWidthPx, this._props.groundDepthPx); this._ctx.stroke(); x += this._props.groundSpacingPx; } x = startX - this._props.groundSpacingPx; while (x > -lengthPx / 2) { this._ctx.beginPath(); this._ctx.moveTo(x, 0); this._ctx.lineTo(x - this._props.groundWidthPx, this._props.groundDepthPx); this._ctx.stroke(); x -= this._props.groundSpacingPx; } this._ctx.restore(); }; /** Draw an arc ground element. @param {Vector} centerDw The center of the circle. @param {Vector} radiusDw The radius of the circle. @param {number} startAngle (Optional) The start angle of the arc (radians, default: 0). @param {number} endAngle (Optional) The end angle of the arc (radians, default: 2 pi). @param {bool} outside (Optional) Whether to draw the ground outside the curve (default: true). */ PrairieDraw.prototype.arcGround = function (centerDw, radiusDw, startAngle, endAngle, outside) { startAngle = startAngle === undefined ? 0 : startAngle; endAngle = endAngle === undefined ? 2 * Math.PI : endAngle; outside = outside === undefined ? true : outside; var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); var groundDepthPx = Math.min(radiusPx, this._props.groundDepthPx); var groundOffsetPx = outside ? groundDepthPx : -groundDepthPx; this._ctx.save(); // fill the shaded area this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, -endAngle, -startAngle, false); this._ctx.arc( centerPx.e(1), centerPx.e(2), radiusPx + groundOffsetPx, -startAngle, -endAngle, true ); this._ctx.fillStyle = this._props.groundInsideColor; this._ctx.fill(); // draw the ground surface this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, -endAngle, -startAngle); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.groundOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a center-of-mass object. @param {Vector} posDw The position of the center of mass. */ PrairieDraw.prototype.centerOfMass = function (posDw) { var posPx = this.pos2Px(posDw); var r = this._props.centerOfMassRadiusPx; this._ctx.save(); this._ctx.lineWidth = this._props.centerOfMassStrokeWidthPx; this._ctx.strokeStyle = this._props.centerOfMassColor; this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.beginPath(); this._ctx.moveTo(-r, 0); this._ctx.lineTo(r, 0); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(0, -r); this._ctx.lineTo(0, r); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.arc(0, 0, r, 0, 2 * Math.PI); this._ctx.stroke(); this._ctx.restore(); }; /** Draw a measurement line. @param {Vector} startDw The start position of the measurement. @param {Vector} endDw The end position of the measurement. @param {string} text The measurement label. */ PrairieDraw.prototype.measurement = function (startDw, endDw, text) { var startPx = this.pos2Px(startDw); var endPx = this.pos2Px(endDw); var offsetPx = endPx.subtract(startPx); var d = offsetPx.modulus(); var h = this._props.measurementEndLengthPx; var o = this._props.measurementOffsetPx; this._ctx.save(); this._ctx.lineWidth = this._props.measurementStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.measurementStrokePattern)); this._ctx.strokeStyle = this._props.measurementColor; this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetPx)); this._ctx.beginPath(); this._ctx.moveTo(0, o); this._ctx.lineTo(0, o + h); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(d, o); this._ctx.lineTo(d, o + h); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(0, o + h / 2); this._ctx.lineTo(d, o + h / 2); this._ctx.stroke(); this._ctx.restore(); var orthPx = offsetPx .rotate(-Math.PI / 2, $V([0, 0])) .toUnitVector() .x(-o - h / 2); var lineStartPx = startPx.add(orthPx); var lineEndPx = endPx.add(orthPx); var lineStartDw = this.pos2Dw(lineStartPx); var lineEndDw = this.pos2Dw(lineEndPx); this.labelLine(lineStartDw, lineEndDw, $V([0, -1]), text); }; /** Draw a right angle. @param {Vector} posDw The position angle point. @param {Vector} dirDw The baseline direction (angle is counter-clockwise from this direction in 2D). @param {Vector} normDw (Optional) The third direction (required for 3D). */ PrairieDraw.prototype.rightAngle = function (posDw, dirDw, normDw) { if (dirDw.modulus() < 1e-20) { return; } var posPx, dirPx, normPx; if (posDw.elements.length === 3) { posPx = this.pos2Px(this.pos3To2(posDw)); var d = this.vec2To3(this.vec2Dw($V([this._props.rightAngleSizePx, 0]))).modulus(); dirPx = this.vec2Px(this.vec3To2(dirDw.toUnitVector().x(d), posDw)); normPx = this.vec2Px(this.vec3To2(normDw.toUnitVector().x(d), posDw)); } else { posPx = this.pos2Px(posDw); dirPx = this.vec2Px(dirDw).toUnitVector().x(this._props.rightAngleSizePx); if (normDw !== undefined) { normPx = this.vec2Px(normDw).toUnitVector().x(this._props.rightAngleSizePx); } else { normPx = dirPx.rotate(-Math.PI / 2, $V([0, 0])); } } this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.lineWidth = this._props.rightAngleStrokeWidthPx; this._ctx.strokeStyle = this._props.rightAngleColor; this._ctx.beginPath(); this._ctx.moveTo(dirPx.e(1), dirPx.e(2)); this._ctx.lineTo(dirPx.e(1) + normPx.e(1), dirPx.e(2) + normPx.e(2)); this._ctx.lineTo(normPx.e(1), normPx.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /** Draw a right angle (improved version). @param {Vector} p0Dw The base point. @param {Vector} p1Dw The first other point. @param {Vector} p2Dw The second other point. */ PrairieDraw.prototype.rightAngleImproved = function (p0Dw, p1Dw, p2Dw) { var p0Px = this.pos2Px(this.pos3To2(p0Dw)); var p1Px = this.pos2Px(this.pos3To2(p1Dw)); var p2Px = this.pos2Px(this.pos3To2(p2Dw)); var d1Px = p1Px.subtract(p0Px); var d2Px = p2Px.subtract(p0Px); var minDLen = Math.min(d1Px.modulus(), d2Px.modulus()); if (minDLen < 1e-10) { return; } var rightAngleSizePx = Math.min(minDLen / 2, this._props.rightAngleSizePx); d1Px = d1Px.toUnitVector().x(rightAngleSizePx); d2Px = d2Px.toUnitVector().x(rightAngleSizePx); p1Px = p0Px.add(d1Px); p2Px = p0Px.add(d2Px); var p12Px = p1Px.add(d2Px); this._ctx.save(); this._ctx.lineWidth = this._props.rightAngleStrokeWidthPx; this._ctx.strokeStyle = this._props.rightAngleColor; this._ctx.beginPath(); this._ctx.moveTo(p1Px.e(1), p1Px.e(2)); this._ctx.lineTo(p12Px.e(1), p12Px.e(2)); this._ctx.lineTo(p2Px.e(1), p2Px.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw text. @param {Vector} posDw The position to draw at. @param {Vector} anchor The anchor on the text that will be located at pos (in -1 to 1 local coordinates). @param {string} text The text to draw. If text begins with "TEX:" then it is interpreted as LaTeX. @param {bool} boxed (Optional) Whether to draw a white box behind the text (default: false). @param {Number} angle (Optional) The rotation angle (radians, default: 0). */ PrairieDraw.prototype.text = function (posDw, anchor, text, boxed, angle) { if (text === undefined) { return; } boxed = boxed === undefined ? false : boxed; angle = angle === undefined ? 0 : angle; var posPx = this.pos2Px(this.pos3To2(posDw)); var offsetPx; if (text.length >= 4 && text.slice(0, 4) === 'TEX:') { var texText = text.slice(4); var hash = Sha1.hash(texText); this._texts = this._texts || {}; var img; if (hash in this._texts) { img = this._texts[hash]; var xPx = (-(anchor.e(1) + 1) / 2) * img.width; var yPx = ((anchor.e(2) - 1) / 2) * img.height; //var offsetPx = anchor.toUnitVector().x(Math.abs(anchor.max()) * this._props.textOffsetPx); offsetPx = anchor.x(this._props.textOffsetPx); var textBorderPx = 5; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(angle); if (boxed) { this._ctx.save(); this._ctx.fillStyle = 'white'; this._ctx.fillRect( xPx - offsetPx.e(1) - textBorderPx, yPx + offsetPx.e(2) - textBorderPx, img.width + 2 * textBorderPx, img.height + 2 * textBorderPx ); this._ctx.restore(); } this._ctx.drawImage(img, xPx - offsetPx.e(1), yPx + offsetPx.e(2)); this._ctx.restore(); } else { var imgSrc = 'text/' + hash + '.png'; img = new Image(); var that = this; img.onload = function () { that.redraw(); if (that.trigger) { that.trigger('imgLoad'); } }; img.src = imgSrc; this._texts[hash] = img; } } else { var align, baseline, bbRelOffset; /* jshint indent: false */ switch (PrairieGeom.sign(anchor.e(1))) { case -1: align = 'left'; bbRelOffset = 0; break; case 0: align = 'center'; bbRelOffset = 0.5; break; case 1: align = 'right'; bbRelOffset = 1; break; } switch (PrairieGeom.sign(anchor.e(2))) { case -1: baseline = 'bottom'; break; case 0: baseline = 'middle'; break; case 1: baseline = 'top'; break; } this.save(); this._ctx.textAlign = align; this._ctx.textBaseline = baseline; this._ctx.translate(posPx.e(1), posPx.e(2)); offsetPx = anchor.toUnitVector().x(Math.abs(anchor.max()) * this._props.textOffsetPx); var drawPx = $V([-offsetPx.e(1), offsetPx.e(2)]); var metrics = this._ctx.measureText(text); var d = this._props.textOffsetPx; //var bb0 = drawPx.add($V([-metrics.actualBoundingBoxLeft - d, -metrics.actualBoundingBoxAscent - d])); //var bb1 = drawPx.add($V([metrics.actualBoundingBoxRight + d, metrics.actualBoundingBoxDescent + d])); var textHeight = this._props.textFontSize; var bb0 = drawPx.add($V([-bbRelOffset * metrics.width - d, -d])); var bb1 = drawPx.add($V([(1 - bbRelOffset) * metrics.width + d, textHeight + d])); if (boxed) { this._ctx.save(); this._ctx.fillStyle = 'white'; this._ctx.fillRect(bb0.e(1), bb0.e(2), bb1.e(1) - bb0.e(1), bb1.e(2) - bb0.e(2)); this._ctx.restore(); } this._ctx.font = this._props.textFontSize.toString() + 'px serif'; this._ctx.fillText(text, drawPx.e(1), drawPx.e(2)); this.restore(); } }; /** Draw text to label a line. @param {Vector} startDw The start position of the line. @param {Vector} endDw The end position of the line. @param {Vector} pos The position relative to the line (-1 to 1 local coordinates, x along the line, y orthogonal). @param {string} text The text to draw. @param {Vector} anchor (Optional) The anchor position on the text. */ PrairieDraw.prototype.labelLine = function (startDw, endDw, pos, text, anchor) { if (text === undefined) { return; } startDw = this.pos3To2(startDw); endDw = this.pos3To2(endDw); var midpointDw = startDw.add(endDw).x(0.5); var offsetDw = endDw.subtract(startDw).x(0.5); var pDw = midpointDw.add(offsetDw.x(pos.e(1))); var u1Dw = offsetDw.toUnitVector(); var u2Dw = u1Dw.rotate(Math.PI / 2, $V([0, 0])); var oDw = u1Dw.x(pos.e(1)).add(u2Dw.x(pos.e(2))); var a = oDw.x(-1).toUnitVector().x(Math.abs(pos.max())); if (anchor !== undefined) { a = anchor; } this.text(pDw, a, text); }; /** Draw text to label a circle line. @param {Vector} posDw The center of the circle line. @param {number} radDw The radius at the mid-angle. @param {number} startAngleDw The starting angle (counterclockwise from x axis, in radians). @param {number} endAngleDw The ending angle (counterclockwise from x axis, in radians). @param {Vector} pos The position relative to the line (-1 to 1 local coordinates, x along the line, y orthogonal). @param {string} text The text to draw. @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). */ PrairieDraw.prototype.labelCircleLine = function ( posDw, radDw, startAngleDw, endAngleDw, pos, text, fixedRad ) { // convert to Px coordinates var startOffsetDw = PrairieGeom.vector2DAtAngle(startAngleDw).x(radDw); var posPx = this.pos2Px(posDw); var startOffsetPx = this.vec2Px(startOffsetDw); var radiusPx = startOffsetPx.modulus(); var startAnglePx = PrairieGeom.angleOf(startOffsetPx); var deltaAngleDw = endAngleDw - startAngleDw; // assume a possibly reflected/rotated but equally scaled Dw/Px transformation var deltaAnglePx = this._transIsReflection() ? -deltaAngleDw : deltaAngleDw; var endAnglePx = startAnglePx + deltaAnglePx; var textAnglePx = ((1.0 - pos.e(1)) / 2.0) * startAnglePx + ((1.0 + pos.e(1)) / 2.0) * endAnglePx; var u1Px = PrairieGeom.vector2DAtAngle(textAnglePx); var u2Px = u1Px.rotate(-Math.PI / 2, $V([0, 0])); var u1Dw = this.vec2Dw(u1Px).toUnitVector(); var u2Dw = this.vec2Dw(u2Px).toUnitVector(); var oDw = u1Dw.x(pos.e(2)).add(u2Dw.x(pos.e(1))); var aDw = oDw.x(-1).toUnitVector(); var a = aDw.x(1.0 / Math.abs(aDw.max())).x(Math.abs(pos.max())); var rPx = this._circleArrowRadius(radiusPx, textAnglePx, startAnglePx, endAnglePx, fixedRad); var pPx = u1Px.x(rPx).add(posPx); var pDw = this.pos2Dw(pPx); this.text(pDw, a, text); }; /** Find the anchor for the intersection of several lines. @param {Vector} labelPoint The point to be labeled. @param {Array} points The end of the lines that meet at labelPoint. @return {Vector} The anchor offset. */ PrairieDraw.prototype.findAnchorForIntersection = function (labelPointDw, pointsDw) { // find the angles on the unit circle for each of the lines var labelPointPx = this.pos2Px(this.pos3To2(labelPointDw)); var i, v; var angles = []; for (i = 0; i < pointsDw.length; i++) { v = this.pos2Px(this.pos3To2(pointsDw[i])).subtract(labelPointPx); v = $V([v.e(1), -v.e(2)]); if (v.modulus() > 1e-6) { angles.push(PrairieGeom.angleOf(v)); } } if (angles.length === 0) { return $V([1, 0]); } // save the first angle to tie-break later var tieBreakAngle = angles[0]; // find the biggest gap between angles (might be multiple) angles.sort(function (a, b) { return a - b; }); var maxAngleDiff = angles[0] - angles[angles.length - 1] + 2 * Math.PI; var maxIs = [0]; var angleDiff; for (i = 1; i < angles.length; i++) { angleDiff = angles[i] - angles[i - 1]; if (angleDiff > maxAngleDiff - 1e-6) { if (angleDiff > maxAngleDiff + 1e-6) { // we are clearly greater maxAngleDiff = angleDiff; maxIs = [i]; } else { // we are basically equal maxIs.push(i); } } } // tie-break by choosing the first angle CCW from the tieBreakAngle var minCCWDiff = 2 * Math.PI; var angle, bestAngle; for (i = 0; i < maxIs.length; i++) { angle = angles[maxIs[i]] - maxAngleDiff / 2; angleDiff = angle - tieBreakAngle; if (angleDiff < 0) { angleDiff += 2 * Math.PI; } if (angleDiff < minCCWDiff) { minCCWDiff = angleDiff; bestAngle = angle; } } // find anchor from bestAngle var dir = PrairieGeom.vector2DAtAngle(bestAngle); dir = dir.x(1 / PrairieGeom.supNorm(dir)); return dir.x(-1); }; /** Label the intersection of several lines. @param {Vector} labelPoint The point to be labeled. @param {Array} points The end of the lines that meet at labelPoint. @param {String} label The label text. @param {Number} scaleOffset (Optional) Scale factor for the offset (default: 1). */ PrairieDraw.prototype.labelIntersection = function (labelPoint, points, label, scaleOffset) { scaleOffset = scaleOffset === undefined ? 1 : scaleOffset; var anchor = this.findAnchorForIntersection(labelPoint, points); this.text(labelPoint, anchor.x(scaleOffset), label); }; /*****************************************************************************/ PrairieDraw.prototype.clearHistory = function (name) { if (name in this._history) { delete this._history[name]; } else { console.log('WARNING: history not found: ' + name); } }; PrairieDraw.prototype.clearAllHistory = function () { this._history = {}; }; /** Save the history of a data value. @param {string} name The history variable name. @param {number} dt The time resolution to save at. @param {number} maxTime The maximum age of history to save. @param {number} curTime The current time. @param {object} curValue The current data value. @return {Array} A history array of vectors of the form [time, value]. */ PrairieDraw.prototype.history = function (name, dt, maxTime, curTime, curValue) { if (!(name in this._history)) { this._history[name] = [[curTime, curValue]]; } else { var h = this._history[name]; if (h.length < 2) { h.push([curTime, curValue]); } else { var prevPrevTime = h[h.length - 2][0]; if (curTime - prevPrevTime < dt) { // new time jump will still be short, replace the last record h[h.length - 1] = [curTime, curValue]; } else { // new time jump would be too long, just add the new record h.push([curTime, curValue]); } } // discard old values as necessary var i = 0; while (curTime - h[i][0] > maxTime && i < h.length - 1) { i++; } if (i > 0) { this._history[name] = h.slice(i); } } return this._history[name]; }; PrairieDraw.prototype.pairsToVectors = function (pairArray) { var vectorArray = []; for (var i = 0; i < pairArray.length; i++) { vectorArray.push($V(pairArray[i])); } return vectorArray; }; PrairieDraw.prototype.historyToTrace = function (data) { var trace = []; for (var i = 0; i < data.length; i++) { trace.push(data[i][1]); } return trace; }; /** Plot a history sequence. @param {Vector} originDw The lower-left position of the axes. @param {Vector} sizeDw The size of the axes (vector from lower-left to upper-right). @param {Vector} sizeData The size of the axes in data coordinates. @param {number} timeOffset The horizontal position for the current time. @param {string} yLabel The vertical axis label. @param {Array} data An array of [time, value] arrays to plot. @param {string} type (Optional) The type of line being drawn. */ PrairieDraw.prototype.plotHistory = function ( originDw, sizeDw, sizeData, timeOffset, yLabel, data, type ) { var scale = $V([sizeDw.e(1) / sizeData.e(1), sizeDw.e(2) / sizeData.e(2)]); var lastTime = data[data.length - 1][0]; var offset = $V([timeOffset - lastTime, 0]); var plotData = PrairieGeom.scalePoints( PrairieGeom.translatePoints(this.pairsToVectors(data), offset), scale ); this.save(); this.translate(originDw); this.save(); this.setProp('arrowLineWidthPx', 1); this.setProp('arrowheadLengthRatio', 11); this.arrow($V([0, 0]), $V([sizeDw.e(1), 0])); this.arrow($V([0, 0]), $V([0, sizeDw.e(2)])); this.text($V([sizeDw.e(1), 0]), $V([1, 1.5]), 'TEX:$t$'); this.text($V([0, sizeDw.e(2)]), $V([1.5, 1]), yLabel); this.restore(); var col = this._getColorProp(type); this.setProp('shapeOutlineColor', col); this.setProp('pointRadiusPx', '4'); this.save(); this._ctx.beginPath(); var bottomLeftPx = this.pos2Px($V([0, 0])); var topRightPx = this.pos2Px(sizeDw); var offsetPx = topRightPx.subtract(bottomLeftPx); this._ctx.rect(bottomLeftPx.e(1), 0, offsetPx.e(1), this._height); this._ctx.clip(); this.polyLine(plotData, false); this.restore(); this.point(plotData[plotData.length - 1]); this.restore(); }; /** Draw a history of positions as a faded line. @param {Array} history History data, array of [time, position] pairs, where position is a vector. @param {number} t Current time. @param {number} maxT Maximum history time. @param {Array} currentRGB RGB triple for current time color. @param {Array} oldRGB RGB triple for old time color. */ PrairieDraw.prototype.fadeHistoryLine = function (history, t, maxT, currentRGB, oldRGB) { if (history.length < 2) { return; } for (var i = history.length - 2; i >= 0; i--) { // draw line backwards so newer segments are on top var pT = history[i][0]; var pDw1 = history[i][1]; var pDw2 = history[i + 1][1]; var alpha = (t - pT) / maxT; var rgb = PrairieGeom.linearInterpArray(currentRGB, oldRGB, alpha); var color = 'rgb(' + rgb[0].toFixed(0) + ', ' + rgb[1].toFixed(0) + ', ' + rgb[2].toFixed(0) + ')'; this.line(pDw1, pDw2, color); } }; /*****************************************************************************/ PrairieDraw.prototype.mouseDown3D = function (event) { event.preventDefault(); this._mouseDown3D = true; this._lastMouseX3D = event.clientX; this._lastMouseY3D = event.clientY; }; PrairieDraw.prototype.mouseUp3D = function () { this._mouseDown3D = false; }; PrairieDraw.prototype.mouseMove3D = function (event) { if (!this._mouseDown3D) { return; } var deltaX = event.clientX - this._lastMouseX3D; var deltaY = event.clientY - this._lastMouseY3D; this._lastMouseX3D = event.clientX; this._lastMouseY3D = event.clientY; this.incrementView3D(deltaY * 0.01, 0, deltaX * 0.01); }; PrairieDraw.prototype.activate3DControl = function () { /* Listen just on the canvas for mousedown, but on whole window * for move/up. This allows mouseup while off-canvas (and even * off-window) to be captured. Ideally we should also listen for * mousedown on the whole window and use mouseEventOnCanvas(), but * this is broken on Canary for some reason (some areas off-canvas * don't work). The advantage of listening for mousedown on the * whole window is that we can get the event during the "capture" * phase rather than the later "bubble" phase, allowing us to * preventDefault() before things like select-drag starts. */ this._canvas.addEventListener('mousedown', this.mouseDown3D.bind(this), true); window.addEventListener('mouseup', this.mouseUp3D.bind(this), true); window.addEventListener('mousemove', this.mouseMove3D.bind(this), true); }; /*****************************************************************************/ PrairieDraw.prototype.mouseDownTracking = function (event) { event.preventDefault(); this._mouseDownTracking = true; this._lastMouseXTracking = event.pageX; this._lastMouseYTracking = event.pageY; }; PrairieDraw.prototype.mouseUpTracking = function () { this._mouseDownTracking = false; }; PrairieDraw.prototype.mouseMoveTracking = function (event) { if (!this._mouseDownTracking) { return; } this._lastMouseXTracking = event.pageX; this._lastMouseYTracking = event.pageY; }; PrairieDraw.prototype.activateMouseTracking = function () { this._canvas.addEventListener('mousedown', this.mouseDownTracking.bind(this), true); window.addEventListener('mouseup', this.mouseUpTracking.bind(this), true); window.addEventListener('mousemove', this.mouseMoveTracking.bind(this), true); }; PrairieDraw.prototype.mouseDown = function () { if (this._mouseDownTracking !== undefined) { return this._mouseDownTracking; } else { return false; } }; PrairieDraw.prototype.mousePositionDw = function () { var xPx = this._lastMouseXTracking - this._canvas.offsetLeft; var yPx = this._lastMouseYTracking - this._canvas.offsetTop; var posPx = $V([xPx, yPx]); var posDw = this.pos2Dw(posPx); return posDw; }; /*****************************************************************************/ /** Creates a PrairieDrawAnim object. @constructor @this {PrairieDraw} @param {HTMLCanvasElement or string} canvas The canvas element to draw on or the ID of the canvas elemnt. @param {Function} drawfcn An optional function that draws on the canvas at time t. */ function PrairieDrawAnim(canvas, drawFcn) { PrairieDraw.call(this, canvas, null); this._drawTime = 0; this._deltaTime = 0; this._running = false; this._sequences = {}; this._animStateCallbacks = []; this._animStepCallbacks = []; if (drawFcn) { this.draw = drawFcn.bind(this); } this.save(); this.draw(0); this.restoreAll(); } PrairieDrawAnim.prototype = new PrairieDraw(); /** @private Store the appropriate version of requestAnimationFrame. Use this like: prairieDraw.requestAnimationFrame.call(window, this.callback.bind(this)); We can't do prairieDraw.requestAnimationFrame(callback), because that would run requestAnimationFrame in the context of prairieDraw ("this" would be prairieDraw), and requestAnimationFrame needs "this" to be "window". We need to pass this.callback.bind(this) as the callback function rather than just this.callback as otherwise the callback functions is called from "window" context, and we want it to be called from the context of our own object. */ /* jshint laxbreak: true */ if (typeof window !== 'undefined') { PrairieDrawAnim.prototype._requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; } /** Prototype function to draw on the canvas, should be implemented by children. @param {number} t Current animation time in seconds. */ PrairieDrawAnim.prototype.draw = function (t) { /* jshint unused: false */ }; /** Start the animation. */ PrairieDrawAnim.prototype.startAnim = function () { if (!this._running) { this._running = true; this._startFrame = true; this._requestAnimationFrame.call(window, this._callback.bind(this)); for (var i = 0; i < this._animStateCallbacks.length; i++) { this._animStateCallbacks[i](true); } } }; /** Stop the animation. */ PrairieDrawAnim.prototype.stopAnim = function () { this._running = false; for (var i = 0; i < this._animStateCallbacks.length; i++) { this._animStateCallbacks[i](false); } }; /** Toggle the animation. */ PrairieDrawAnim.prototype.toggleAnim = function () { if (this._running) { this.stopAnim(); } else { this.startAnim(); } }; /** Register a callback on animation state changes. @param {Function} callback The callback(animated) function. */ PrairieDrawAnim.prototype.registerAnimCallback = function (callback) { this._animStateCallbacks.push(callback.bind(this)); callback.apply(this, [this._running]); }; /** Register a callback on animation steps. @param {Function} callback The callback(t) function. */ PrairieDrawAnim.prototype.registerAnimStepCallback = function (callback) { this._animStepCallbacks.push(callback.bind(this)); }; /** @private Callback function to handle the animationFrame events. */ PrairieDrawAnim.prototype._callback = function (tMS) { if (this._startFrame) { this._startFrame = false; this._timeOffset = tMS - this._drawTime; } var animTime = tMS - this._timeOffset; this._deltaTime = (animTime - this._drawTime) / 1000; this._drawTime = animTime; var t = animTime / 1000; for (var i = 0; i < this._animStepCallbacks.length; i++) { this._animStepCallbacks[i](t); } this.save(); this.draw(t); this._deltaTime = 0; this.restoreAll(); if (this._running) { this._requestAnimationFrame.call(window, this._callback.bind(this)); } }; /** Get the elapsed time since the last redraw. return {number} Elapsed time in seconds. */ PrairieDrawAnim.prototype.deltaTime = function () { return this._deltaTime; }; /** Redraw the drawing at the current time. */ PrairieDrawAnim.prototype.redraw = function () { if (!this._running) { this.save(); this.draw(this._drawTime / 1000); this.restoreAll(); } }; /** Reset the animation time to zero. @param {bool} redraw (Optional) Whether to redraw (default: true). */ PrairieDrawAnim.prototype.resetTime = function (redraw) { this._drawTime = 0; for (var i = 0; i < this._animStepCallbacks.length; i++) { this._animStepCallbacks[i](0); } this._startFrame = true; if (redraw === undefined || redraw === true) { this.redraw(); } }; /** Reset everything to the intial state. */ PrairieDrawAnim.prototype.reset = function () { for (var optionName in this._options) { this.resetOptionValue(optionName); } this.resetAllSequences(); this.clearAllHistory(); this.stopAnim(); this.resetView3D(false); this.resetTime(false); this.redraw(); }; /** Stop all action and computation. */ PrairieDrawAnim.prototype.stop = function () { this.stopAnim(); }; PrairieDrawAnim.prototype.lastDrawTime = function () { return this._drawTime / 1000; }; /*****************************************************************************/ PrairieDrawAnim.prototype.mouseDownAnimOnClick = function (event) { event.preventDefault(); this.startAnim(); }; PrairieDrawAnim.prototype.activateAnimOnClick = function () { this._canvas.addEventListener('mousedown', this.mouseDownAnimOnClick.bind(this), true); }; /*****************************************************************************/ /** Interpolate between different states in a sequence. @param {Array} states An array of objects, each specifying scalar or vector state values. @param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1]. @param {Array} holdTimes Hold times for the corresponding state. @param {Array} t Current time. @return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding). */ PrairieDrawAnim.prototype.sequence = function (states, transTimes, holdTimes, t) { var totalTime = 0; var i; for (i = 0; i < states.length; i++) { totalTime += transTimes[i]; totalTime += holdTimes[i]; } var ts = t % totalTime; totalTime = 0; var state = {}; var e, ip; var lastTotalTime = 0; for (i = 0; i < states.length; i++) { ip = i === states.length - 1 ? 0 : i + 1; totalTime += transTimes[i]; if (totalTime > ts) { // in transition from i to i+1 state.t = ts - lastTotalTime; state.index = i; state.alpha = state.t / (totalTime - lastTotalTime); for (e in states[i]) { state[e] = PrairieGeom.linearInterp(states[i][e], states[ip][e], state.alpha); } return state; } lastTotalTime = totalTime; totalTime += holdTimes[i]; if (totalTime > ts) { // holding at i+1 state.t = 0; state.index = ip; state.alpha = 0; for (e in states[i]) { state[e] = states[ip][e]; } return state; } lastTotalTime = totalTime; } }; /*****************************************************************************/ /** Interpolate between different states in a sequence under external prompting. @param {string} name Name of this transition sequence. @param {Array} states An array of objects, each specifying scalar or vector state values. @param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1]. @param {Array} t Current animation time. @return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding). */ PrairieDrawAnim.prototype.controlSequence = function (name, states, transTimes, t) { if (!(name in this._sequences)) { this._sequences[name] = { index: 0, inTransition: false, startTransition: false, indefiniteHold: true, callbacks: [], }; } var seq = this._sequences[name]; var state; var transTime = 0; if (seq.startTransition) { seq.startTransition = false; seq.inTransition = true; seq.indefiniteHold = false; seq.startTime = t; } if (seq.inTransition) { transTime = t - seq.startTime; } if (seq.inTransition && transTime >= transTimes[seq.index]) { seq.inTransition = false; seq.indefiniteHold = true; seq.index = (seq.index + 1) % states.length; delete seq.startTime; } if (!seq.inTransition) { state = PrairieGeom.dupState(states[seq.index]); state.index = seq.index; state.t = 0; state.alpha = 0; state.inTransition = false; return state; } var alpha = transTime / transTimes[seq.index]; var nextIndex = (seq.index + 1) % states.length; state = PrairieGeom.linearInterpState(states[seq.index], states[nextIndex], alpha); state.t = transTime; state.index = seq.index; state.alpha = alpha; state.inTransition = true; return state; }; /** Start the next transition for the given sequence. @param {string} name Name of the sequence to transition. @param {string} stateName (Optional) Only transition if we are currently in stateName. */ PrairieDrawAnim.prototype.stepSequence = function (name, stateName) { if (!(name in this._sequences)) { throw new Error('PrairieDraw: unknown sequence: ' + name); } var seq = this._sequences[name]; if (!seq.lastState.indefiniteHold) { return; } if (stateName !== undefined) { if (seq.lastState.name !== stateName) { return; } } seq.startTransition = true; this.startAnim(); }; /*****************************************************************************/ /** Interpolate between different states (new version). @param {string} name Name of this transition sequence. @param {Array} states An array of objects, each specifying scalar or vector state values. @param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1]. @param {Array} holdtimes Hold times for each state. A negative value means to hold until externally triggered. @param {Array} t Current animation time. @return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding). */ PrairieDrawAnim.prototype.newSequence = function ( name, states, transTimes, holdTimes, interps, names, t ) { var seq = this._sequences[name]; if (seq === undefined) { this._sequences[name] = { startTransition: false, lastState: {}, callbacks: [], initialized: false, }; seq = this._sequences[name]; } var i; if (!seq.initialized) { seq.initialized = true; for (var e in states[0]) { if (typeof states[0][e] === 'number') { seq.lastState[e] = states[0][e]; } else if (typeof states[0][e] === 'function') { seq.lastState[e] = states[0][e](null, 0); } } seq.lastState.inTransition = false; seq.lastState.indefiniteHold = false; seq.lastState.index = 0; seq.lastState.name = names[seq.lastState.index]; seq.lastState.t = 0; seq.lastState.realT = t; if (holdTimes[0] < 0) { seq.lastState.indefiniteHold = true; } for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('enter', seq.lastState.index, seq.lastState.name); } } if (seq.startTransition) { seq.startTransition = false; seq.lastState.inTransition = true; seq.lastState.indefiniteHold = false; seq.lastState.t = 0; seq.lastState.realT = t; for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('exit', seq.lastState.index, seq.lastState.name); } } var endTime, nextIndex; while (true) { nextIndex = (seq.lastState.index + 1) % states.length; if (seq.lastState.inTransition) { endTime = seq.lastState.realT + transTimes[seq.lastState.index]; if (t >= endTime) { seq.lastState = this._interpState( seq.lastState, states[nextIndex], interps, endTime, endTime ); seq.lastState.inTransition = false; seq.lastState.index = nextIndex; seq.lastState.name = names[seq.lastState.index]; if (holdTimes[nextIndex] < 0) { seq.lastState.indefiniteHold = true; } else { seq.lastState.indefiniteHold = false; } for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('enter', seq.lastState.index, seq.lastState.name); } } else { return this._interpState(seq.lastState, states[nextIndex], interps, t, endTime); } } else { endTime = seq.lastState.realT + holdTimes[seq.lastState.index]; if (holdTimes[seq.lastState.index] >= 0 && t > endTime) { seq.lastState = this._extrapState(seq.lastState, states[seq.lastState.index], endTime); seq.lastState.inTransition = true; seq.lastState.indefiniteHold = false; for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('exit', seq.lastState.index, seq.lastState.name); } } else { return this._extrapState(seq.lastState, states[seq.lastState.index], t); } } } }; PrairieDrawAnim.prototype._interpState = function (lastState, nextState, interps, t, tFinal) { var s1 = PrairieGeom.dupState(nextState); s1.realT = tFinal; s1.t = tFinal - lastState.realT; var s = {}; var alpha = (t - lastState.realT) / (tFinal - lastState.realT); for (var e in nextState) { if (e in interps) { s[e] = interps[e](lastState, s1, t - lastState.realT); } else { s[e] = PrairieGeom.linearInterp(lastState[e], s1[e], alpha); } } s.realT = t; s.t = Math.min(t - lastState.realT, s1.t); s.index = lastState.index; s.inTransition = lastState.inTransition; s.indefiniteHold = lastState.indefiniteHold; return s; }; PrairieDrawAnim.prototype._extrapState = function (lastState, lastStateData, t) { var s = {}; for (var e in lastStateData) { if (typeof lastStateData[e] === 'number') { s[e] = lastStateData[e]; } else if (typeof lastStateData[e] === 'function') { s[e] = lastStateData[e](lastState, t - lastState.realT); } } s.realT = t; s.t = t - lastState.realT; s.index = lastState.index; s.inTransition = lastState.inTransition; s.indefiniteHold = lastState.indefiniteHold; return s; }; /** Register a callback on animation sequence events. @param {string} seqName The sequence to register on. @param {Function} callback The callback(event, index, stateName) function. */ PrairieDrawAnim.prototype.registerSeqCallback = function (seqName, callback) { if (!(seqName in this._sequences)) { throw new Error('PrairieDraw: unknown sequence: ' + seqName); } var seq = this._sequences[seqName]; seq.callbacks.push(callback.bind(this)); if (seq.inTransition) { callback.apply(this, ['exit', seq.lastState.index, seq.lastState.name]); } else { callback.apply(this, ['enter', seq.lastState.index, seq.lastState.name]); } }; /** Make a two-state sequence transitioning to and from 0 and 1. @param {string} name The name of the sequence; @param {number} transTime The transition time between the two states. @return {number} The current state (0 to 1). */ PrairieDrawAnim.prototype.activationSequence = function (name, transTime, t) { var stateZero = { trans: 0 }; var stateOne = { trans: 1 }; var states = [stateZero, stateOne]; var transTimes = [transTime, transTime]; var holdTimes = [-1, -1]; var interps = {}; var names = ['zero', 'one']; var state = this.newSequence(name, states, transTimes, holdTimes, interps, names, t); return state.trans; }; PrairieDrawAnim.prototype.resetSequence = function (name) { var seq = this._sequences[name]; if (seq !== undefined) { seq.initialized = false; } }; PrairieDrawAnim.prototype.resetAllSequences = function () { for (var name in this._sequences) { this.resetSequence(name); } }; /*****************************************************************************/ PrairieDraw.prototype.drawImage = function (imgSrc, posDw, anchor, widthDw) { var img; if (imgSrc in this._images) { // FIXME: should check that the image is really loaded, in case we are fired beforehand (also for text images). img = this._images[imgSrc]; var posPx = this.pos2Px(posDw); var scale; if (widthDw === undefined) { scale = 1; } else { var offsetDw = $V([widthDw, 0]); var offsetPx = this.vec2Px(offsetDw); var widthPx = offsetPx.modulus(); scale = widthPx / img.width; } var xPx = (-(anchor.e(1) + 1) / 2) * img.width; var yPx = ((anchor.e(2) - 1) / 2) * img.height; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.scale(scale, scale); this._ctx.translate(xPx, yPx); this._ctx.drawImage(img, 0, 0); this._ctx.restore(); } else { img = new Image(); var that = this; img.onload = function () { that.redraw(); if (that.trigger) { that.trigger('imgLoad'); } }; img.src = imgSrc; this._images[imgSrc] = img; } }; /*****************************************************************************/ PrairieDraw.prototype.mouseEventPx = function (event) { var element = this._canvas; var xPx = event.pageX; var yPx = event.pageY; do { xPx -= element.offsetLeft; yPx -= element.offsetTop; /* jshint boss: true */ // suppress warning for assignment on next line } while ((element = element.offsetParent)); xPx *= this._canvas.width / this._canvas.scrollWidth; yPx *= this._canvas.height / this._canvas.scrollHeight; var posPx = $V([xPx, yPx]); return posPx; }; PrairieDraw.prototype.mouseEventDw = function (event) { var posPx = this.mouseEventPx(event); var posDw = this.pos2Dw(posPx); return posDw; }; PrairieDraw.prototype.mouseEventOnCanvas = function (event) { var posPx = this.mouseEventPx(event); console.log(posPx.e(1), posPx.e(2), this._width, this._height); /* jshint laxbreak: true */ if ( posPx.e(1) >= 0 && posPx.e(1) <= this._width && posPx.e(2) >= 0 && posPx.e(2) <= this._height ) { console.log(true); return true; } console.log(false); return false; }; PrairieDraw.prototype.reportMouseSample = function (event) { var posDw = this.mouseEventDw(event); var numDecPlaces = 2; /* jshint laxbreak: true */ console.log( '$V([' + posDw.e(1).toFixed(numDecPlaces) + ', ' + posDw.e(2).toFixed(numDecPlaces) + ']),' ); }; PrairieDraw.prototype.activateMouseSampling = function () { this._canvas.addEventListener('click', this.reportMouseSample.bind(this)); }; /*****************************************************************************/ PrairieDraw.prototype.activateMouseLineDraw = function () { if (this._mouseLineDrawActive === true) { return; } this._mouseLineDrawActive = true; this.mouseLineDraw = false; this.mouseLineDrawing = false; if (this._mouseLineDrawInitialized !== true) { this._mouseLineDrawInitialized = true; if (this._mouseDrawCallbacks === undefined) { this._mouseDrawCallbacks = []; } this._canvas.addEventListener('mousedown', this.mouseLineDrawMousedown.bind(this), true); window.addEventListener('mouseup', this.mouseLineDrawMouseup.bind(this), true); window.addEventListener('mousemove', this.mouseLineDrawMousemove.bind(this), true); } /* for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); */ }; PrairieDraw.prototype.deactivateMouseLineDraw = function () { this._mouseLineDrawActive = false; this.mouseLineDraw = false; this.mouseLineDrawing = false; this.redraw(); }; PrairieDraw.prototype.mouseLineDrawMousedown = function (event) { if (!this._mouseLineDrawActive) { return; } event.preventDefault(); var posDw = this.mouseEventDw(event); this.mouseLineDrawStart = posDw; this.mouseLineDrawEnd = posDw; this.mouseLineDrawing = true; this.mouseLineDraw = true; for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); }; PrairieDraw.prototype.mouseLineDrawMousemove = function (event) { if (!this._mouseLineDrawActive) { return; } if (!this.mouseLineDrawing) { return; } this.mouseLineDrawEnd = this.mouseEventDw(event); for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); // FIXME: add rate-limiting }; PrairieDraw.prototype.mouseLineDrawMouseup = function () { if (!this._mouseLineDrawActive) { return; } if (!this.mouseLineDrawing) { return; } this.mouseLineDrawing = false; for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); }; PrairieDraw.prototype.mouseLineDrawMouseout = function (event) { if (!this._mouseLineDrawActive) { return; } if (!this.mouseLineDrawing) { return; } this.mouseLineDrawEnd = this.mouseEventDw(event); this.mouseLineDrawing = false; for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); }; PrairieDraw.prototype.registerMouseLineDrawCallback = function (callback) { if (this._mouseDrawCallbacks === undefined) { this._mouseDrawCallbacks = []; } this._mouseDrawCallbacks.push(callback.bind(this)); }; /*****************************************************************************/ /** Plot a line graph. @param {Array} data Array of vectors to plot. @param {Vector} originDw The lower-left position of the axes. @param {Vector} sizeDw The size of the axes (vector from lower-left to upper-right). @param {Vector} originData The lower-left position of the axes in data coordinates. @param {Vector} sizeData The size of the axes in data coordinates. @param {string} xLabel The vertical axis label. @param {string} yLabel The vertical axis label. @param {string} type (Optional) The type of line being drawn. @param {string} drawAxes (Optional) Whether to draw the axes (default: true). @param {string} drawPoint (Optional) Whether to draw the last point (default: true). @param {string} pointLabel (Optional) Label for the last point (default: undefined). @param {string} pointAnchor (Optional) Anchor for the last point label (default: $V([0, -1])). @param {Object} options (Optional) Plotting options: horizAxisPos: "bottom", "top", or a numerical value in data coordinates (default: "bottom") vertAxisPos: "left", "right", or a numerical value in data coordinates (default: "left") */ PrairieDraw.prototype.plot = function ( data, originDw, sizeDw, originData, sizeData, xLabel, yLabel, type, drawAxes, drawPoint, pointLabel, pointAnchor, options ) { drawAxes = drawAxes === undefined ? true : drawAxes; drawPoint = drawPoint === undefined ? true : drawPoint; options = options === undefined ? {} : options; var horizAxisPos = options.horizAxisPos === undefined ? 'bottom' : options.horizAxisPos; var vertAxisPos = options.vertAxisPos === undefined ? 'left' : options.vertAxisPos; var drawXGrid = options.drawXGrid === undefined ? false : options.drawXGrid; var drawYGrid = options.drawYGrid === undefined ? false : options.drawYGrid; var dXGrid = options.dXGrid === undefined ? 1 : options.dXGrid; var dYGrid = options.dYGrid === undefined ? 1 : options.dYGrid; var drawXTickLabels = options.drawXTickLabels === undefined ? false : options.drawXTickLabels; var drawYTickLabels = options.drawYTickLabels === undefined ? false : options.drawYTickLabels; var xLabelPos = options.xLabelPos === undefined ? 1 : options.xLabelPos; var yLabelPos = options.yLabelPos === undefined ? 1 : options.yLabelPos; var xLabelAnchor = options.xLabelAnchor === undefined ? $V([1, 1.5]) : options.xLabelAnchor; var yLabelAnchor = options.yLabelAnchor === undefined ? $V([1.5, 1]) : options.yLabelAnchor; var yLabelRotate = options.yLabelRotate === undefined ? false : options.yLabelRotate; this.save(); this.translate(originDw); // grid var ix0 = Math.ceil(originData.e(1) / dXGrid); var ix1 = Math.floor((originData.e(1) + sizeData.e(1)) / dXGrid); var x0 = 0; var x1 = sizeDw.e(1); var iy0 = Math.ceil(originData.e(2) / dYGrid); var iy1 = Math.floor((originData.e(2) + sizeData.e(2)) / dYGrid); var y0 = 0; var y1 = sizeDw.e(2); var i, x, y; if (drawXGrid) { for (i = ix0; i <= ix1; i++) { x = PrairieGeom.linearMap( originData.e(1), originData.e(1) + sizeData.e(1), 0, sizeDw.e(1), i * dXGrid ); this.line($V([x, y0]), $V([x, y1]), 'grid'); } } if (drawYGrid) { for (i = iy0; i <= iy1; i++) { y = PrairieGeom.linearMap( originData.e(2), originData.e(2) + sizeData.e(2), 0, sizeDw.e(2), i * dYGrid ); this.line($V([x0, y]), $V([x1, y]), 'grid'); } } var label; if (drawXTickLabels) { for (i = ix0; i <= ix1; i++) { x = PrairieGeom.linearMap( originData.e(1), originData.e(1) + sizeData.e(1), 0, sizeDw.e(1), i * dXGrid ); label = String(i * dXGrid); this.text($V([x, y0]), $V([0, 1]), label); } } if (drawYTickLabels) { for (i = iy0; i <= iy1; i++) { y = PrairieGeom.linearMap( originData.e(2), originData.e(2) + sizeData.e(2), 0, sizeDw.e(2), i * dYGrid ); label = String(i * dYGrid); this.text($V([x0, y]), $V([1, 0]), label); } } // axes var axisX, axisY; if (vertAxisPos === 'left') { axisX = 0; } else if (vertAxisPos === 'right') { axisX = sizeDw.e(1); } else { axisX = PrairieGeom.linearMap( originData.e(1), originData.e(1) + sizeData.e(1), 0, sizeDw.e(1), vertAxisPos ); } if (horizAxisPos === 'bottom') { axisY = 0; } else if (horizAxisPos === 'top') { axisY = sizeDw.e(2); } else { axisY = PrairieGeom.linearMap( originData.e(2), originData.e(2) + sizeData.e(2), 0, sizeDw.e(2), horizAxisPos ); } if (drawAxes) { this.save(); this.setProp('arrowLineWidthPx', 1); this.setProp('arrowheadLengthRatio', 11); this.arrow($V([0, axisY]), $V([sizeDw.e(1), axisY])); this.arrow($V([axisX, 0]), $V([axisX, sizeDw.e(2)])); x = xLabelPos * sizeDw.e(1); y = yLabelPos * sizeDw.e(2); this.text($V([x, axisY]), xLabelAnchor, xLabel); var angle = yLabelRotate ? -Math.PI / 2 : 0; this.text($V([axisX, y]), yLabelAnchor, yLabel, undefined, angle); this.restore(); } var col = this._getColorProp(type); this.setProp('shapeOutlineColor', col); this.setProp('pointRadiusPx', '4'); var bottomLeftPx = this.pos2Px($V([0, 0])); var topRightPx = this.pos2Px(sizeDw); var offsetPx = topRightPx.subtract(bottomLeftPx); this.save(); this.scale(sizeDw); this.scale($V([1 / sizeData.e(1), 1 / sizeData.e(2)])); this.translate(originData.x(-1)); this.save(); this._ctx.beginPath(); this._ctx.rect(bottomLeftPx.e(1), 0, offsetPx.e(1), this._height); this._ctx.clip(); this.polyLine(data, false); this.restore(); if (drawPoint) { this.point(data[data.length - 1]); if (pointLabel !== undefined) { if (pointAnchor === undefined) { pointAnchor = $V([0, -1]); } this.text(data[data.length - 1], pointAnchor, pointLabel); } } this.restore(); this.restore(); }; /*****************************************************************************/ return { PrairieDraw: PrairieDraw, PrairieDrawAnim: PrairieDrawAnim, }; });<|fim▁end|>
); inc = inc + spacing;