code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* Software Name : AsmDex * Version : 1.0 * * Copyright © 2012 France Télécom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the 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. */ package org.ow2.asmdex.instruction; import org.ow2.asmdex.structureCommon.Label; /** * Interface for Debug Instructions that store a Label to which they are connected. * * @author Julien Névo */ public interface IDebugLocalVariableInstruction { /** * Returns the label linked to this instruction. It can be a start, end or restart. * @return the label linked to this instruction. It can be a start, end or restart. */ Label getLabel(); }
NativeScript/android-runtime
test-app/runtime-binding-generator/src/main/java/org/ow2/asmdex/instruction/IDebugLocalVariableInstruction.java
Java
apache-2.0
2,093
"use strict"; let active_overlay; let close_handler; let open_overlay_name; function reset_state() { active_overlay = undefined; close_handler = undefined; open_overlay_name = undefined; } exports.is_active = function () { return !!open_overlay_name; }; exports.is_modal_open = function () { return $(".modal").hasClass("in"); }; exports.info_overlay_open = function () { return open_overlay_name === "informationalOverlays"; }; exports.settings_open = function () { return open_overlay_name === "settings"; }; exports.streams_open = function () { return open_overlay_name === "subscriptions"; }; exports.lightbox_open = function () { return open_overlay_name === "lightbox"; }; exports.drafts_open = function () { return open_overlay_name === "drafts"; }; exports.recent_topics_open = function () { return open_overlay_name === "recent_topics"; }; // To address bugs where mouse might apply to the streams/settings // overlays underneath an open modal within those settings UI, we add // this inline style to '.overlay.show', overriding the // "pointer-events: all" style in app_components.scss. // // This is kinda hacky; it only works for modals within overlays, and // we need to make sure it gets re-enabled when the modal closes. exports.disable_background_mouse_events = function () { $(".overlay.show").attr("style", "pointer-events: none"); }; // This removes only the inline-style of the element that // was added in disable_background_mouse_events and // enables the background mouse events. exports.enable_background_mouse_events = function () { $(".overlay.show").attr("style", null); }; exports.active_modal = function () { if (!exports.is_modal_open()) { blueslip.error("Programming error — Called active_modal when there is no modal open"); return; } return "#" + $(".modal.in").attr("id"); }; exports.open_overlay = function (opts) { popovers.hide_all(); if (!opts.name || !opts.overlay || !opts.on_close) { blueslip.error("Programming error in open_overlay"); return; } if (active_overlay || open_overlay_name || close_handler) { blueslip.error( "Programming error — trying to open " + opts.name + " before closing " + open_overlay_name, ); return; } blueslip.debug("open overlay: " + opts.name); // Our overlays are kind of crufty...we have an HTML id // attribute for them and then a data-overlay attribute for // them. Make sure they match. if (opts.overlay.attr("data-overlay") !== opts.name) { blueslip.error("Bad overlay setup for " + opts.name); return; } open_overlay_name = opts.name; active_overlay = opts.overlay; opts.overlay.addClass("show"); opts.overlay.attr("aria-hidden", "false"); $(".app").attr("aria-hidden", "true"); $(".fixed-app").attr("aria-hidden", "true"); $(".header").attr("aria-hidden", "true"); close_handler = function () { opts.on_close(); reset_state(); }; }; exports.open_modal = function (selector) { if (selector === undefined) { blueslip.error("Undefined selector was passed into open_modal"); return; } if (selector[0] !== "#") { blueslip.error("Non-id-based selector passed in to open_modal: " + selector); return; } if (exports.is_modal_open()) { blueslip.error( "open_modal() was called while " + exports.active_modal() + " modal was open.", ); return; } blueslip.debug("open modal: " + selector); const elem = $(selector).expectOne(); elem.modal("show").attr("aria-hidden", false); // Disable background mouse events when modal is active exports.disable_background_mouse_events(); // Remove previous alert messages from modal, if exists. elem.find(".alert").hide(); elem.find(".alert-notification").html(""); }; exports.close_overlay = function (name) { popovers.hide_all(); if (name !== open_overlay_name) { blueslip.error("Trying to close " + name + " when " + open_overlay_name + " is open."); return; } if (name === undefined) { blueslip.error("Undefined name was passed into close_overlay"); return; } blueslip.debug("close overlay: " + name); active_overlay.removeClass("show"); active_overlay.attr("aria-hidden", "true"); $(".app").attr("aria-hidden", "false"); $(".fixed-app").attr("aria-hidden", "false"); $(".header").attr("aria-hidden", "false"); if (!close_handler) { blueslip.error("Overlay close handler for " + name + " not properly setup."); return; } close_handler(); }; exports.close_active = function () { if (!open_overlay_name) { blueslip.warn("close_active() called without checking is_active()"); return; } exports.close_overlay(open_overlay_name); }; exports.close_modal = function (selector) { if (selector === undefined) { blueslip.error("Undefined selector was passed into close_modal"); return; } if (!exports.is_modal_open()) { blueslip.warn("close_active_modal() called without checking is_modal_open()"); return; } if (exports.active_modal() !== selector) { blueslip.error( "Trying to close " + selector + " modal when " + exports.active_modal() + " is open.", ); return; } blueslip.debug("close modal: " + selector); const elem = $(selector).expectOne(); elem.modal("hide").attr("aria-hidden", true); // Enable mouse events for the background as the modal closes. exports.enable_background_mouse_events(); }; exports.close_active_modal = function () { if (!exports.is_modal_open()) { blueslip.warn("close_active_modal() called without checking is_modal_open()"); return; } $(".modal.in").modal("hide").attr("aria-hidden", true); }; exports.close_for_hash_change = function () { $(".overlay.show").removeClass("show"); reset_state(); }; exports.open_settings = function () { exports.open_overlay({ name: "settings", overlay: $("#settings_overlay_container"), on_close() { hashchange.exit_overlay(); }, }); }; exports.initialize = function () { $("body").on("click", ".overlay, .overlay .exit", (e) => { let $target = $(e.target); // if the target is not the .overlay element, search up the node tree // until it is found. if ($target.is(".exit, .exit-sign, .overlay-content, .exit span")) { $target = $target.closest("[data-overlay]"); } else if (!$target.is(".overlay")) { // not a valid click target then. return; } const target_name = $target.attr("data-overlay"); exports.close_overlay(target_name); e.preventDefault(); e.stopPropagation(); }); }; window.overlays = exports;
brainwane/zulip
static/js/overlays.js
JavaScript
apache-2.0
7,098
package cat.urv.crises.distcom; import java.math.BigInteger; import thep.paillier.EncryptedInteger; import thep.paillier.exceptions.BigIntegerClassNotValid; import thep.paillier.exceptions.PublicKeysNotEqualException; import cat.urv.crises.distcom.model.KeyPair; import cat.urv.crises.distcom.model.PrivateSet; public class Test { final static BigInteger crs = BigInteger.valueOf(1010101010); public static void main(String[] args) throws BigIntegerClassNotValid, PublicKeysNotEqualException { BigInteger[] setA = {a(1), a(2), a(3), a(4), a(5), a(6)}; BigInteger[] setB = {a(2), a(4), a(6), a(8)}; KeyPair kpA = new KeyPair(1024); PrivateSet privateSetA = new PrivateSet(setA, kpA.getPublicKey()); EncryptedInteger[] test1 = privateSetA.cardinalityIntersection(setB, crs); EncryptedInteger[] test2 = privateSetA.intersection(setB); int card = 0; for (EncryptedInteger i: test1) { if (i.decrypt(kpA.getPrivateKey()).equals(crs)) { card++; } } System.out.println("Card: "+ card); System.out.print("Intersection: "); for (EncryptedInteger i: test2) { BigInteger j = i.decrypt(kpA.getPrivateKey()); if (in(j,setA)) { System.out.println(i.decrypt(kpA.getPrivateKey())); } } } public static BigInteger a(long b) { return BigInteger.valueOf(b); } public static boolean in(BigInteger a, BigInteger[] set) { for (BigInteger i: set) { if (i.equals(a)) return true; } return false; } }
ablancoj/psi
src/main/java/cat/urv/crises/distcom/Test.java
Java
apache-2.0
1,472
'use strict'; /* eslint-disable no-unused-expressions */ const map = require('../../../lib/middleware/inflight/map'); describe('map tests', () => { const testKey = 'test-key'; let testMap; beforeEach(() => { testMap = map(); }); context('when adding new entry', () => { beforeEach(() => { testMap.increment(testKey); }); it('entry is added successfully', () => { expect(testMap.get(testKey)).to.equal(1); expect(testMap.size()).to.equal(1); }); }); context('incrementing existing entry', () => { beforeEach(() => { testMap.increment(testKey); testMap.increment(testKey); }); it('entry is updated successfully', () => { expect(testMap.get(testKey)).to.equal(2); }); }); context('decrementing existing entry with value larger than 1', () => { beforeEach(() => { testMap.increment(testKey); testMap.increment(testKey); testMap.decrement(testKey); }); it('entry is updated successfully', () => { expect(testMap.get(testKey)).to.equal(1); expect(testMap.size()).to.equal(1); }); }); context('decrementing existing entry with value 1', () => { beforeEach(() => { testMap.increment(testKey); testMap.decrement(testKey); }); it('entry is updated successfully', () => { expect(testMap.get(testKey)).to.be.undefined; expect(testMap.size()).to.equal(0); }); }); });
cloudfoundry-incubator/cf-abacus
lib/utils/express/src/test/middleware/inflight/map.test.js
JavaScript
apache-2.0
1,453
package cmd import ( cmdconf "github.com/cloudfoundry/bosh-init/cmd/config" boshui "github.com/cloudfoundry/bosh-init/ui" boshtbl "github.com/cloudfoundry/bosh-init/ui/table" ) type EnvironmentsCmd struct { config cmdconf.Config ui boshui.UI } func NewEnvironmentsCmd(config cmdconf.Config, ui boshui.UI) EnvironmentsCmd { return EnvironmentsCmd{config: config, ui: ui} } func (c EnvironmentsCmd) Run() error { environments := c.config.Environments() table := boshtbl.Table{ Content: "environments", Header: []string{"URL", "Alias"}, SortBy: []boshtbl.ColumnSort{{Column: 0, Asc: true}}, } for _, t := range environments { table.Rows = append(table.Rows, []boshtbl.Value{ boshtbl.NewValueString(t.URL), boshtbl.NewValueString(t.Alias), }) } c.ui.PrintTable(table) return nil }
forrestsill/bosh-init
cmd/environments.go
GO
apache-2.0
820
package net.bull.javamelody.swing; /* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. 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 Oracle or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.plaf.basic.BasicButtonUI; /** * Component to be used as tabComponent. * Contains a JLabel to show the text and * a JButton to close the tab it belongs to */ public class MButtonTabComponent extends JPanel { @SuppressWarnings("all") static final ButtonMouseListener BUTTON_MOUSE_LISTENER = new ButtonMouseListener(); private static final long serialVersionUID = 1L; private final JTabbedPane pane; static class ButtonMouseListener extends MouseAdapter { @Override public void mouseEntered(MouseEvent e) { final Component component = e.getComponent(); if (component instanceof JButton) { final JButton button = (JButton) component; button.setBorderPainted(true); } } @Override public void mouseExited(MouseEvent e) { final Component component = e.getComponent(); if (component instanceof JButton) { final JButton button = (JButton) component; button.setBorderPainted(false); } } } /** * Constructor. * @param pane JTabbedPane */ public MButtonTabComponent(final JTabbedPane pane) { //unset default FlowLayout' gaps super(new FlowLayout(FlowLayout.LEFT, 0, 0)); if (pane == null) { throw new IllegalArgumentException("TabbedPane is null"); } this.pane = pane; setOpaque(false); //make JLabel read titles from JTabbedPane final JLabel label = new JLabel() { private static final long serialVersionUID = 1L; @Override public String getText() { final int i = pane.indexOfTabComponent(MButtonTabComponent.this); if (i != -1) { return pane.getTitleAt(i); } return null; } }; add(label); //add more space between the label and the button label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); //tab button final JButton button = new TabButton(); add(button); //add more space to the top of the component setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); } private class TabButton extends JButton implements ActionListener { private static final long serialVersionUID = 1L; /** * Constructor. */ TabButton() { super(); final int size = 17; setPreferredSize(new Dimension(size, size)); // setToolTipText("close this tab"); //Make the button looks the same for all Laf's setUI(new BasicButtonUI()); //Make it transparent setContentAreaFilled(false); //No need to be focusable setFocusable(false); setBorder(BorderFactory.createEtchedBorder()); setBorderPainted(false); //Making nice rollover effect //we use the same listener for all buttons addMouseListener(BUTTON_MOUSE_LISTENER); setRolloverEnabled(true); //Close the proper tab by clicking the button addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { final int i = getTabbedPane().indexOfTabComponent(MButtonTabComponent.this); if (i != -1) { getTabbedPane().remove(i); } } //we don't want to update UI for this button @Override public void updateUI() { // RAS } //paint the cross @Override protected void paintComponent(Graphics g) { super.paintComponent(g); final Graphics2D g2 = (Graphics2D) g.create(); //shift the image for pressed buttons if (getModel().isPressed()) { g2.translate(1, 1); } g2.setStroke(new BasicStroke(2)); g2.setColor(Color.BLACK); if (getModel().isRollover()) { g2.setColor(Color.MAGENTA); } final int delta = 6; g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1); g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1); g2.dispose(); } } JTabbedPane getTabbedPane() { return pane; } }
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/MButtonTabComponent.java
Java
apache-2.0
5,978
<?php /** * Copyright 2016, Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @package GoogleApiAdsDfp * @subpackage Util * @category WebServices * @copyright 2016, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 */ error_reporting(E_STRICT | E_ALL); require_once 'Google/Api/Ads/Dfp/Util/v201608/DateTimeUtils.php'; require_once 'Google/Api/Ads/Dfp/v201608/PublisherQueryLanguageService.php'; /** * Unit tests for {@link DateTimeUtils}. * @group small */ class DateTimeUtilsTest extends PHPUnit_Framework_TestCase { const TIME_ZONE_ID1 = 'America/New_York'; const TIME_ZONE_ID2 = 'PST8PDT'; const TIME_ZONE_ID3 = 'Europe/Moscow'; private $dfpDate1; private $dfpDate2; private $dfpDate3; private $dateTime1; private $dateTime2; private $dateTime3; private $dfpDateTime1; private $dfpDateTime2; private $dfpDateTime3; private $stringDate1; private $stringDate2; private $stringDate3; private $stringDateTime1; private $stringDateTime2; private $stringDateTime3; private $stringDateTimeWithTimeZone1; private $stringDateTimeWithTimeZone2; private $stringDateTimeWithTimeZone3; protected function setUp() { $this->stringDate1 = '1983-06-02'; $this->stringDate2 = '2014-12-31'; $this->stringDate3 = '1999-09-23'; $this->stringDateTime1 = '1983-06-02T08:30:15'; $this->stringDateTime2 = '1983-06-02T00:00:00'; $this->stringDateTime3 = '1983-06-02T08:30:15'; $this->stringDateTimeWithTimeZone1 = '1983-06-02T08:30:15-04:00'; $this->stringDateTimeWithTimeZone2 = '1983-06-02T00:00:00-07:00'; $this->stringDateTimeWithTimeZone3 = '1983-06-02T08:30:15+04:00'; $this->dfpDate1 = new Date(1983, 6, 2); $this->dfpDate2 = new Date(2014, 12, 31); $this->dfpDate3 = new Date(1999, 9, 23); $this->dateTime1 = new DateTime($this->stringDateTime1, new DateTimeZone(self::TIME_ZONE_ID1)); $this->dateTime2 = new DateTime($this->stringDateTime2, new DateTimeZone(self::TIME_ZONE_ID2)); $this->dateTime3 = new DateTime($this->stringDateTime3, new DateTimeZone(self::TIME_ZONE_ID3)); $this->dfpDateTime1 = new DfpDateTime(new Date(1983, 6, 2), 8, 30, 15, self::TIME_ZONE_ID1); $this->dfpDateTime2 = new DfpDateTime(new Date(1983, 6, 2), 0, 0, 0, self::TIME_ZONE_ID2); $this->dfpDateTime3 = new DfpDateTime(new Date(1983, 6, 2), 8, 30, 15, self::TIME_ZONE_ID3); } /** * @covers DateTimeUtils::ToDfpDateTime */ public function testToDfpDateTime() { $this->assertEquals($this->dfpDateTime1, DateTimeUtils::ToDfpDateTime($this->dateTime1)); $this->assertEquals($this->dfpDateTime2, DateTimeUtils::ToDfpDateTime($this->dateTime2)); $this->assertEquals($this->dfpDateTime3, DateTimeUtils::ToDfpDateTime($this->dateTime3)); } /** * @covers DateTimeUtils::ToDfpDateTimeFromString */ public function _testToDfpDateTimeFromString() { $actualDfpDateTime1 = DateTimeUtils::ToDfpDateTimeFromString( $this->stringDateTimeWithTimeZone1); self::assertEquals($this->dfpDateTime1, $actualDfpDateTime1); $this->assertEquals('-04:00', $actualDfpDateTime1->timeZone); $actualDfpDateTime2 = DateTimeUtils::ToDfpDateTimeFromString( $this->stringDateTimeWithTimeZone2); self::assertEquals($this->dfpDateTime2, $actualDfpDateTime2); $this->assertEquals('-07:00', $actualDfpDateTime2->timeZone); $actualDfpDateTime3 = DateTimeUtils::ToDfpDateTimeFromString( $this->stringDateTimeWithTimeZone3); self::assertEquals($this->dfpDateTime2, $actualDfpDateTime3); $this->assertEquals('+04:00', $actualDfpDateTime3->timeZone); } /** * @covers DateTimeUtils::ToDfpDateTimeFromStringWithTimeZone */ public function _testToDfpDateTimeFromStringWithTimeZone() { $self->assertTrue(self::isEqual($this->dfpDateTime1, DateTimeUtils::ToDfpDateTimeFromStringWithTimeZone( $this->stringDateTimeWithTimeZone1, self::TIME_ZONE_ID1))); $self->assertTrue(self::assertEquals($this->dfpDateTime2->getTimestamp(), DateTimeUtils::ToDfpDateTimeFromStringWithTimeZone( $this->stringDateTimeWithTimeZone2, self::TIME_ZONE_ID2))); $self->assertTrue(self::assertEquals($this->dfpDateTime3->getTimestamp(), DateTimeUtils::ToDfpDateTimeFromStringWithTimeZone( $this->stringDateTimeWithTimeZone3, self::TIME_ZONE_ID3))); } /** * @covers DateTimeUtils::FromDfpDateTime */ public function testFromDfpDateTime() { $this->assertEquals($this->dateTime1, DateTimeUtils::FromDfpDateTime($this->dfpDateTime1)); $this->assertEquals($this->dateTime2, DateTimeUtils::FromDfpDateTime($this->dfpDateTime2)); $this->assertEquals($this->dateTime3, DateTimeUtils::FromDfpDateTime($this->dfpDateTime3)); } /** * @covers DateTimeUtils::ToString */ public function testToString() { $this->assertEquals($this->stringDate1, DateTimeUtils::ToString($this->dfpDate1)); $this->assertEquals($this->stringDate2, DateTimeUtils::ToString($this->dfpDate2)); $this->assertEquals($this->stringDate3, DateTimeUtils::ToString($this->dfpDate3)); } /** * @covers DateTimeUtils::ToStringWithTimeZone */ public function testToStringWithTimeZone() { $this->assertEquals($this->stringDateTimeWithTimeZone1, DateTimeUtils::ToStringWithTimeZone($this->dfpDateTime1)); $this->assertEquals($this->stringDateTimeWithTimeZone2, DateTimeUtils::ToStringWithTimeZone($this->dfpDateTime2)); $this->assertEquals($this->stringDateTimeWithTimeZone3, DateTimeUtils::ToStringWithTimeZone($this->dfpDateTime3)); } /** * @covers DateTimeUtils::ToStringForTimeZone */ public function testToStringForTimeZone() { $this->assertEquals($this->stringDateTime1, DateTimeUtils::ToStringForTimeZone($this->dfpDateTime1, self::TIME_ZONE_ID1)); $this->assertEquals($this->stringDateTime2, DateTimeUtils::ToStringForTimeZone($this->dfpDateTime2, self::TIME_ZONE_ID2)); $this->assertEquals($this->stringDateTime3, DateTimeUtils::ToStringForTimeZone($this->dfpDateTime3, self::TIME_ZONE_ID3)); $this->assertEquals($this->stringDateTime1, DateTimeUtils::ToStringForTimeZone(DateTimeUtils::ToDfpDateTime( $this->dateTime1->setTimeZone( new DateTimeZone(self::TIME_ZONE_ID2))), self::TIME_ZONE_ID1)); $this->assertEquals($this->stringDateTime2, DateTimeUtils::ToStringForTimeZone(DateTimeUtils::ToDfpDateTime( $this->dateTime2->setTimeZone( new DateTimeZone(self::TIME_ZONE_ID1))), self::TIME_ZONE_ID2)); $this->assertEquals($this->stringDateTime3, DateTimeUtils::ToStringForTimeZone(DateTimeUtils::ToDfpDateTime( $this->dateTime3->setTimeZone( new DateTimeZone(self::TIME_ZONE_ID1))), self::TIME_ZONE_ID3)); } public static function isEqual(DfpDateTime $expected, DfpDateTime $actual) { return $expected == $actual || ($expected->date->year == $actual->date->year && $expected->date->month == $actual->date->month && $expected->date->day == $actual->date->day && $expected->hour == $actual->hour && $expected->minute == $actual->minute && $expected->second == $actual->second); // TODO(vtsao): Figure out how to compare IANA versus offset time zones. } } date_default_timezone_set(DateTimeUtilsTest::TIME_ZONE_ID1);
gamejolt/googleads-php-lib
tests/Google/Api/Ads/Dfp/Util/v201608/DateTimeUtilsTest.php
PHP
apache-2.0
8,201
package nl.uva.larissa.repository; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.validation.ValidationException; import javax.ws.rs.core.MultivaluedMap; import nl.uva.larissa.UUIDUtil; import nl.uva.larissa.json.ISO8601VerboseDateFormat; import nl.uva.larissa.json.ParseException; import nl.uva.larissa.json.StatementParser; import nl.uva.larissa.json.StatementParserImpl; import nl.uva.larissa.json.StatementPrinter; import nl.uva.larissa.json.StatementPrinterImpl; import nl.uva.larissa.json.model.Agent; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; public class StatementFilterUtil { static enum Parameter { VERB("verb") { @Override public void setValue(StatementFilter result, String value) { try { result.setVerb(new IRI(value)); } catch (IRISyntaxException e) { throw new IllegalArgumentException(String.format( "'%s' is not a valid IRI", value), e); } } @Override public String getValueAsString(StatementFilter filter) { IRI iri = filter.getVerb(); return iri == null ? null : iri.toString(); } }, ACTIVITY("activity") { @Override public void setValue(StatementFilter result, String value) { try { result.setActivity(new IRI(value)); } catch (IRISyntaxException e) { throw new IllegalArgumentException(String.format( "'%s' is not a valid IRI", value), e); } } @Override public String getValueAsString(StatementFilter filter) { IRI iri = filter.getActivity(); return iri == null ? null : iri.toString(); } }, AGENT("agent") { @Override public void setValue(StatementFilter result, String value) { try { result.setAgent(getParser().parse(Agent.class, value)); } catch (ParseException e) { throw new IllegalArgumentException(e); } } @Override public String getValueAsString(StatementFilter filter) { Agent agent = filter.getAgent(); try { return agent == null ? null : getPrinter().printCompact( agent); } catch (IOException e) { throw new RuntimeException(e); } } }, SINCE("since") { @Override public void setValue(StatementFilter result, String value) { try { result.setSince(new ISO8601VerboseDateFormat().parse(value)); } catch (java.text.ParseException e) { throw new IllegalArgumentException(e); } } @Override public String getValueAsString(StatementFilter filter) { Date since = filter.getSince(); return since == null ? null : new ISO8601VerboseDateFormat() .format(since); } }, UNTIL("until") { @Override public void setValue(StatementFilter result, String value) { try { result.setUntil(new ISO8601VerboseDateFormat().parse(value)); } catch (java.text.ParseException e) { throw new IllegalArgumentException(e); } } @Override public String getValueAsString(StatementFilter filter) { Date until = filter.getUntil(); return until == null ? null : new ISO8601VerboseDateFormat() .format(until); } }, LIMIT("limit") { @Override public void setValue(StatementFilter result, String value) { result.setLimit(Integer.parseInt(value)); } @Override public String getValueAsString(StatementFilter filter) { Integer limit = filter.getLimit(); return limit == null ? null : limit.toString(); } }, FORMAT("format") { @Override public void setValue(StatementFilter result, String value) { result.setFormat(value); } @Override public String getValueAsString(StatementFilter filter) { return filter.getFormat(); } }, REGISTRATION("registration") { @Override public void setValue(StatementFilter result, String value) { if (value != null && !UUIDUtil.isUUID(value)) { throw new IllegalArgumentException("'" + value + "' is not a valid UUID"); } result.setRegistration(value); } @Override public String getValueAsString(StatementFilter filter) { return filter.getRegistration(); } }, RELATED_ACTIVITIES("related_activities") { @Override public void setValue(StatementFilter result, String value) { result.setRelatedActivities(Boolean.valueOf(value)); } @Override public String getValueAsString(StatementFilter filter) { Boolean result = filter.getRelatedActivities(); return result == null ? null : Boolean.toString(result); } }, RELATED_AGENTS("related_agents") { @Override public void setValue(StatementFilter result, String value) { result.setRelatedAgents(Boolean.valueOf(value)); } @Override public String getValueAsString(StatementFilter filter) { Boolean result = filter.getRelatedAgents(); return result == null ? null : Boolean.toString(result); } }, ASCENDING("ascending") { @Override public void setValue(StatementFilter result, String value) { result.setAscending(Boolean.valueOf(value)); } @Override public String getValueAsString(StatementFilter filter) { Boolean result = filter.getAscending(); return result == null ? null : Boolean.toString(result); } }, STARTID("startId") { // FIXME validate @Override public void setValue(StatementFilter result, String value) { result.setStartId(value); } @Override public String getValueAsString(StatementFilter filter) { return filter.getStartId(); } }; private final String name; // FIXME should be injected but can't with non-injected constructor private StatementParser parser = new StatementParserImpl(); private StatementPrinter printer = new StatementPrinterImpl(); @Inject private Parameter(String name) { this.name = name; } public abstract void setValue(StatementFilter result, String value); public String getName() { return name; } public abstract String getValueAsString(StatementFilter filter); public StatementParser getParser() { return parser; } public StatementPrinter getPrinter() { return printer; } } private static Map<String, Parameter> PARAMETERS; static { PARAMETERS = new HashMap<>(Parameter.values().length); for (Parameter arg : Parameter.values()) { PARAMETERS.put(arg.getName(), arg); } } public static StatementFilter fromParameters( MultivaluedMap<String, String> map) throws ValidationException { StatementFilter result = new StatementFilter(); for (Entry<String, List<String>> entry : map.entrySet()) { List<String> entryValues = entry.getValue(); String entryKey = entry.getKey(); if (entryValues.size() != 1) { throw new ValidationException( String.format( "Parameter '%s' must have exactly 1 value, but has %s values.", entryKey, entryValues.size())); } String entryValue = entryValues.get(0); Parameter parameter = PARAMETERS.get(entryKey); if (parameter == null) { throw new ValidationException(String.format( "Unsupported parameter '%s'; must be one of %s.", entryKey, PARAMETERS.keySet())); } parameter.setValue(result, entryValue); } return result; } public static StatementFilter fromMoreUrl(String more) throws IllegalArgumentException { try { more = URLDecoder.decode(more, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } Pattern patt = Pattern.compile("(?:([a-zA-Z_]+)=([^&]+))+"); Matcher matcher = patt.matcher(more); StatementFilter result = new StatementFilter(); while (matcher.find()) { String key = matcher.group(1); String value = matcher.group(2); Parameter arg = PARAMETERS.get(key); if (arg == null) { throw new IllegalArgumentException("unknown parameter: " + key); } arg.setValue(result, value); } return result; } public static String toMoreUrl(StatementFilter filter) { // FIXME hardcoded path StringBuilder result = new StringBuilder("/larissa/xAPI/statements?"); for (Parameter arg : Parameter.values()) { String value = arg.getValueAsString(filter); if (value != null) { try { result.append(arg.getName()).append('=') .append(URLEncoder.encode(value, "UTF-8")) .append('&'); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } int lastIndex = result.length() - 1; if (result.charAt(lastIndex) == '&') { result.deleteCharAt(lastIndex); } return result.toString(); } }
Apereo-Learning-Analytics-Initiative/Larissa
src/main/java/nl/uva/larissa/repository/StatementFilterUtil.java
Java
apache-2.0
8,770
# Copyright 2021, OpenCensus Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from azure.identity import ClientSecretCredential from opencensus.ext.azure.trace_exporter import AzureExporter from opencensus.trace.samplers import ProbabilitySampler from opencensus.trace.tracer import Tracer tenant_id = "<tenant-id>" client_id = "<client-id>" client_secret = "<client-secret>" credential = ClientSecretCredential( tenant_id=tenant_id, client_id=client_id, client_secret=client_secret ) tracer = Tracer( exporter=AzureExporter( credential=credential, connection_string="<your-connection-string>"), sampler=ProbabilitySampler(1.0) ) with tracer.span(name='foo'): print('Hello, World!')
census-instrumentation/opencensus-python
contrib/opencensus-ext-azure/examples/traces/credential.py
Python
apache-2.0
1,225
--- layout: base title: 'Statistics of PronType in UD_Old_East_Slavic-RNC' udver: '2' --- ## Treebank Statistics: UD_Old_East_Slavic-RNC: Features: `PronType` This feature is universal but the values `Emp`, `Exc` are language-specific. It occurs with 9 different values: `Dem`, `Emp`, `Exc`, `Ind`, `Int`, `Neg`, `Prs`, `Rel`, `Tot`. 3644 tokens (10%) have a non-empty value of `PronType`. 578 types (6%) occur at least once with a non-empty value of `PronType`. 87 lemmas (2%) occur at least once with a non-empty value of `PronType`. The feature is used with 4 part-of-speech tags: <tt><a href="orv_rnc-pos-DET.html">DET</a></tt> (1844; 5% instances), <tt><a href="orv_rnc-pos-PRON.html">PRON</a></tt> (1798; 5% instances), <tt><a href="orv_rnc-pos-ADV.html">ADV</a></tt> (1; 0% instances), <tt><a href="orv_rnc-pos-SCONJ.html">SCONJ</a></tt> (1; 0% instances). ### `DET` 1844 <tt><a href="orv_rnc-pos-DET.html">DET</a></tt> tokens (100% of all `DET` tokens) have a non-empty value of `PronType`. The most frequent other feature values with which `DET` and `PronType` co-occurred: <tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=EMPTY</tt> (1657; 90%), <tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=EMPTY</tt> (1221; 66%), <tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt> (1215; 66%). `DET` tokens may have the following values of `PronType`: * `Dem` (686; 37% of non-empty `PronType`): <em>сей, то, тѣхъ, тѣ, того, т., те, тот, сего, сіе</em> * `Emp` (19; 1% of non-empty `PronType`): <em>самаго, само(м), самой, самомꙋ, самы(м), са(м), самое, самъ, самы, самы(х)</em> * `Exc` (2; 0% of non-empty `PronType`): <em>каковое, коликое</em> * `Ind` (9; 0% of non-empty `PronType`): <em>однимъ, которомъ, нѣкое, нѣкоего, нѣкоторо(м), нѣкую, нѣкіихъ, однем</em> * `Int` (15; 1% of non-empty `PronType`): <em>чей, Кіими, какимъ, каковаго, каковы, какомъ, какіе, кое, кои, коих</em> * `Neg` (15; 1% of non-empty `PronType`): <em>никоторою, никакихъ, никоторыми, ниедино, никакими, никакова, никакои, никакой, никакою</em> * `Prs` (677; 37% of non-empty `PronType`): <em>твой, мои, твоему, своего, твои, твоего, моему, свое, нашему, своими</em> * `Rel` (62; 3% of non-empty `PronType`): <em>которые, какова, которое, какую, какая, какие, каково, какову, каковы, какое</em> * `Tot` (359; 19% of non-empty `PronType`): <em>всѣхъ, всꙗ, вся, всеа, всякіе, все, всем, всех, всю, вси</em> * `EMPTY` (2): <em>еди(н), единою</em> <table> <tr><th>Paradigm <i>свой</i></th><th><tt>Prs</tt></th><th><tt>Dem</tt></th><th><tt>Tot</tt></th></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Abbr.html">Abbr</a></tt><tt>=Yes</tt></tt></td><td></td><td><em>с.</em></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Animacy.html">Animacy</a></tt><tt>=Anim</tt>|<tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своего, своег[о]</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Animacy.html">Animacy</a></tt><tt>=Anim</tt>|<tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt></tt></td><td><em>своих</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Animacy.html">Animacy</a></tt><tt>=Anim</tt>|<tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своих, своихъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Animacy.html">Animacy</a></tt><tt>=Anim</tt>|<tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своих</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt></tt></td><td><em>свой</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>свой, свои</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своя, свое, свои</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td><em>свою</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>свою</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своꙗ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>свое</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своему, своемꙋ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своим, своимъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своей</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своимъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своему, своемꙋ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своимъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своего, своево</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своихъ, своих</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своей, своеи, своее, своея, своеꙗ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своихъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своего</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td><em>своим</em></td><td></td><td><em>своимъ</em></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своимъ, своімъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt></tt></td><td><em>своими</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своими</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своею, сво[е]ю</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Dual</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своею</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своими</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своим, своимъ, свои(м)</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своімъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Loc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своем, своемъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Loc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своихъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Loc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своей, своеи</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Loc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своихъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Loc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своемъ, свое(м), своем</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Loc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своих, своіхъ</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>своя</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="orv_rnc-feat-Poss.html">Poss</a></tt><tt>=Yes</tt>|<tt><a href="orv_rnc-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt></tt></td><td><em>свое</em></td><td></td><td></td></tr> </table> ### `PRON` 1798 <tt><a href="orv_rnc-pos-PRON.html">PRON</a></tt> tokens (100% of all `PRON` tokens) have a non-empty value of `PronType`. The most frequent other feature values with which `PRON` and `PronType` co-occurred: <tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt> (1237; 69%). `PRON` tokens may have the following values of `PronType`: * `Dem` (100; 6% of non-empty `PronType`): <em>томъ, того, то, том, тово, тому, сего, семъ, т., те</em> * `Ind` (9; 1% of non-empty `PronType`): <em>которомъ, что, которыхъ, кто, нечто, нѣкто, нѣчто</em> * `Int` (65; 4% of non-empty `PronType`): <em>что, кто, кѣм, ког[о], комꙋ, што, кимъ, ково, кого, кому</em> * `Neg` (27; 2% of non-empty `PronType`): <em>никому, никто, нихто, ничего, ничтоже, что, кем, кого, нечем, нечим</em> * `Prs` (1376; 77% of non-empty `PronType`): <em>тебѣ, его, ты, ево, я, ему, имъ, они, ихъ, тебе</em> * `Rel` (202; 11% of non-empty `PronType`): <em>что, которые, кто, иже, ꙗже, хто, кого, егоже, кому, чем</em> * `Tot` (19; 1% of non-empty `PronType`): <em>всем, всемъ, все, всех, вся, весь, вси</em> * `EMPTY` (8): <em>сѧ, ся</em> <table> <tr><th>Paradigm <i>что</i></th><th><tt>Int</tt></th><th><tt>Rel</tt></th><th><tt>Neg</tt></th><th><tt>Ind</tt></th></tr> <tr><td><tt>_</tt></td><td></td><td><em>что</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td></td><td><em>Что</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td><em>что</em></td><td><em>что</em></td><td><em>что</em></td><td><em>что</em></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td></td><td><em>чему, чому</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td><em>чего</em></td><td><em>чево, чего</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Ins</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td></td><td><em>чимъ</em></td><td><em>чѣмъ</em></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Loc</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td><em>чемъ</em></td><td><em>чем, чемъ</em></td><td><em>чем, чемъ</em></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td></td><td><em>что</em></td><td></td><td></td></tr> <tr><td><tt><tt><a href="orv_rnc-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="orv_rnc-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="orv_rnc-feat-Number.html">Number</a></tt><tt>=Sing</tt></tt></td><td><em>что, што, чьто</em></td><td><em>что</em></td><td></td><td><em>что</em></td></tr> </table> `PronType` seems to be **lexical feature** of `PRON`. 90% lemmas (47) occur only with one value of `PronType`. ### `ADV` 1 <tt><a href="orv_rnc-pos-ADV.html">ADV</a></tt> tokens (0% of all `ADV` tokens) have a non-empty value of `PronType`. The most frequent other feature values with which `ADV` and `PronType` co-occurred: <tt><a href="orv_rnc-feat-Degree.html">Degree</a></tt><tt>=EMPTY</tt> (1; 100%). `ADV` tokens may have the following values of `PronType`: * `Int` (1; 100% of non-empty `PronType`): <em>что</em> * `EMPTY` (688): <em>тако, как, гдѣ, нн҃ѣ, какъ, тогда, здѣ, нынѣ, всегда, ныне</em> ### `SCONJ` 1 <tt><a href="orv_rnc-pos-SCONJ.html">SCONJ</a></tt> tokens (0% of all `SCONJ` tokens) have a non-empty value of `PronType`. `SCONJ` tokens may have the following values of `PronType`: * `Rel` (1; 100% of non-empty `PronType`): <em>иже</em> * `EMPTY` (384): <em>что, ꙗко, чтобъ, яко, егда, аще, ино, как, буде, чтоб</em> ## Relations with Agreement in `PronType` The 10 most frequent relations where parent and child node agree in `PronType`: <tt>PRON --[<tt><a href="orv_rnc-dep-nmod.html">nmod</a></tt>]--> PRON</tt> (9; 82%), <tt>PRON --[<tt><a href="orv_rnc-dep-conj.html">conj</a></tt>]--> PRON</tt> (3; 100%), <tt>PRON --[<tt><a href="orv_rnc-dep-dislocated.html">dislocated</a></tt>]--> PRON</tt> (3; 100%), <tt>DET --[<tt><a href="orv_rnc-dep-conj.html">conj</a></tt>]--> DET</tt> (1; 100%), <tt>DET --[<tt><a href="orv_rnc-dep-nmod.html">nmod</a></tt>]--> PRON</tt> (1; 100%).
UniversalDependencies/docs
treebanks/orv_rnc/orv_rnc-feat-PronType.md
Markdown
apache-2.0
24,781
module.exports.inputs = [{ "data": { "1": {"id": 1}, "2": {"id": 2}, "3": {"id": 3}, "4": {"id": 4}, "5": {"id": 5}, "6": {"id": 6} }, "keys": ["","1","2","3","4","5","6"], "grid": [ " ", " ", " ", " ", " !#$ ", " %&' ", " ", " " ] },{ "data": { "1": {"id": 7}, "2": {"id": 8}, "3": {"id": 9}, "4": {"id": 10}, "5": {"id": 11}, "6": {"id": 12} }, "keys": ["","1","2","3","4","5","6"], "grid": [ " ", " ", " ", " ", " ", " !#$ ", " %&' ", " " ] }]; module.exports.result = { "data": { "1": {"id": 1}, "2": {"id": 2}, "3": {"id": 3}, "4": {"id": 7}, "5": {"id": 8}, "6": {"id": 9}, "7": {"id": 10}, "8": {"id": 11}, "9": {"id": 12}, }, "keys": ["","1","2","3","4","5","6","7","8","9"], "grid": [ " ", " ", " ", " ", " !#$ ", " %&' ", " ()* ", " " ] };
naturalatlas/tilestrata-utfmerge
test/fixtures/a.js
JavaScript
apache-2.0
994
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.artifacts.ivyservice.ivyresolve; import org.gradle.StartParameter; import org.gradle.api.artifacts.component.ModuleComponentIdentifier; import org.gradle.api.artifacts.result.ResolvedArtifactResult; import org.gradle.api.artifacts.verification.DependencyVerificationMode; import org.gradle.api.internal.DocumentationRegistry; import org.gradle.api.internal.artifacts.configurations.ResolutionStrategyInternal; import org.gradle.api.internal.artifacts.configurations.dynamicversion.CachePolicy; import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.verification.ChecksumAndSignatureVerificationOverride; import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.verification.DependencyVerificationOverride; import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.verification.writer.WriteDependencyVerificationFile; import org.gradle.api.internal.artifacts.ivyservice.resolutionstrategy.ExternalResourceCachePolicy; import org.gradle.api.internal.artifacts.repositories.resolver.MetadataFetchingCost; import org.gradle.api.internal.artifacts.verification.DependencyVerificationException; import org.gradle.api.internal.artifacts.verification.signatures.BuildTreeDefinedKeys; import org.gradle.api.internal.artifacts.verification.signatures.SignatureVerificationServiceFactory; import org.gradle.api.internal.component.ArtifactType; import org.gradle.api.internal.properties.GradleProperties; import org.gradle.api.invocation.Gradle; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.api.resources.ResourceException; import org.gradle.internal.Factory; import org.gradle.internal.component.external.model.ModuleDependencyMetadata; import org.gradle.internal.component.model.ComponentArtifactMetadata; import org.gradle.internal.component.model.ComponentOverrideMetadata; import org.gradle.internal.component.model.ComponentResolveMetadata; import org.gradle.internal.component.model.ConfigurationMetadata; import org.gradle.internal.component.model.ModuleSources; import org.gradle.internal.concurrent.CompositeStoppable; import org.gradle.internal.concurrent.Stoppable; import org.gradle.internal.hash.ChecksumService; import org.gradle.internal.lazy.Lazy; import org.gradle.internal.operations.BuildOperationExecutor; import org.gradle.internal.resolve.ArtifactResolveException; import org.gradle.internal.resolve.ModuleVersionResolveException; import org.gradle.internal.resolve.result.BuildableArtifactResolveResult; import org.gradle.internal.resolve.result.BuildableArtifactSetResolveResult; import org.gradle.internal.resolve.result.BuildableComponentArtifactsResolveResult; import org.gradle.internal.resolve.result.BuildableModuleComponentMetaDataResolveResult; import org.gradle.internal.resolve.result.BuildableModuleVersionListingResolveResult; import org.gradle.internal.resource.ExternalResource; import org.gradle.internal.resource.ExternalResourceName; import org.gradle.internal.resource.ReadableContent; import org.gradle.internal.resource.metadata.ExternalResourceMetaData; import org.gradle.internal.resource.transfer.ExternalResourceConnector; import org.gradle.internal.service.scopes.Scopes; import org.gradle.internal.service.scopes.ServiceScope; import org.gradle.util.internal.BuildCommencedTimeProvider; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.List; @ServiceScope(Scopes.BuildTree.class) public class StartParameterResolutionOverride { private final StartParameter startParameter; private final File gradleDir; private final Lazy<BuildTreeDefinedKeys> keyRing; public StartParameterResolutionOverride(StartParameter startParameter, File gradleDir) { this.startParameter = startParameter; this.gradleDir = gradleDir; this.keyRing = Lazy.locking().of(() -> { File keyringsFile = DependencyVerificationOverride.keyringsFile(gradleDir); return new BuildTreeDefinedKeys(keyringsFile); }); } public void applyToCachePolicy(CachePolicy cachePolicy) { if (startParameter.isOffline()) { cachePolicy.setOffline(); } else if (startParameter.isRefreshDependencies()) { cachePolicy.setRefreshDependencies(); } } public ModuleComponentRepository overrideModuleVersionRepository(ModuleComponentRepository original) { if (startParameter.isOffline()) { return new OfflineModuleComponentRepository(original); } return original; } public DependencyVerificationOverride dependencyVerificationOverride(BuildOperationExecutor buildOperationExecutor, ChecksumService checksumService, SignatureVerificationServiceFactory signatureVerificationServiceFactory, DocumentationRegistry documentationRegistry, BuildCommencedTimeProvider timeProvider, Factory<GradleProperties> gradlePropertiesFactory) { List<String> checksums = startParameter.getWriteDependencyVerifications(); if (!checksums.isEmpty()) { File verificationsFile = DependencyVerificationOverride.dependencyVerificationsFile(gradleDir); return DisablingVerificationOverride.of( new WriteDependencyVerificationFile(verificationsFile, keyRing.get(), buildOperationExecutor, checksums, checksumService, signatureVerificationServiceFactory, startParameter.isDryRun(), startParameter.isExportKeys()) ); } else { File verificationsFile = DependencyVerificationOverride.dependencyVerificationsFile(gradleDir); if (verificationsFile.exists()) { if (startParameter.getDependencyVerificationMode() == DependencyVerificationMode.OFF) { return DependencyVerificationOverride.NO_VERIFICATION; } try { File sessionReportDir = computeReportDirectory(timeProvider); return DisablingVerificationOverride.of( new ChecksumAndSignatureVerificationOverride(buildOperationExecutor, startParameter.getGradleUserHomeDir(), verificationsFile, keyRing.get(), checksumService, signatureVerificationServiceFactory, startParameter.getDependencyVerificationMode(), documentationRegistry, sessionReportDir, gradlePropertiesFactory) ); } catch (Exception e) { return new FailureVerificationOverride(e); } } } return DependencyVerificationOverride.NO_VERIFICATION; } private File computeReportDirectory(BuildCommencedTimeProvider timeProvider) { // TODO: This is not quite correct: we're using the "root project" build directory // but technically speaking, this can be changed _after_ this service is created. // There's currently no good way to figure that out. File buildDir = new File(gradleDir.getParentFile(), "build"); File reportsDirectory = new File(buildDir, "reports"); File verifReportsDirectory = new File(reportsDirectory, "dependency-verification"); return new File(verifReportsDirectory, "at-" + timeProvider.getCurrentTime()); } private static class OfflineModuleComponentRepository extends BaseModuleComponentRepository { private final FailedRemoteAccess failedRemoteAccess = new FailedRemoteAccess(); public OfflineModuleComponentRepository(ModuleComponentRepository original) { super(original); } @Override public ModuleComponentRepositoryAccess getRemoteAccess() { return failedRemoteAccess; } } private static class FailedRemoteAccess implements ModuleComponentRepositoryAccess { @Override public String toString() { return "offline remote"; } @Override public void listModuleVersions(ModuleDependencyMetadata dependency, BuildableModuleVersionListingResolveResult result) { result.failed(new ModuleVersionResolveException(dependency.getSelector(), () -> String.format("No cached version listing for %s available for offline mode.", dependency.getSelector()))); } @Override public void resolveComponentMetaData(ModuleComponentIdentifier moduleComponentIdentifier, ComponentOverrideMetadata requestMetaData, BuildableModuleComponentMetaDataResolveResult result) { result.failed(new ModuleVersionResolveException(moduleComponentIdentifier, () -> String.format("No cached version of %s available for offline mode.", moduleComponentIdentifier.getDisplayName()))); } @Override public void resolveArtifactsWithType(ComponentResolveMetadata component, ArtifactType artifactType, BuildableArtifactSetResolveResult result) { result.failed(new ArtifactResolveException(component.getId(), "No cached version available for offline mode")); } @Override public void resolveArtifacts(ComponentResolveMetadata component, ConfigurationMetadata variant, BuildableComponentArtifactsResolveResult result) { result.failed(new ArtifactResolveException(component.getId(), "No cached version available for offline mode")); } @Override public void resolveArtifact(ComponentArtifactMetadata artifact, ModuleSources moduleSources, BuildableArtifactResolveResult result) { result.failed(new ArtifactResolveException(artifact.getId(), "No cached version available for offline mode")); } @Override public MetadataFetchingCost estimateMetadataFetchingCost(ModuleComponentIdentifier moduleComponentIdentifier) { return MetadataFetchingCost.CHEAP; } } public ExternalResourceCachePolicy overrideExternalResourceCachePolicy(ExternalResourceCachePolicy original) { if (startParameter.isOffline()) { return ageMillis -> false; } return original; } public ExternalResourceConnector overrideExternalResourceConnector(ExternalResourceConnector original) { if (startParameter.isOffline()) { return new OfflineExternalResourceConnector(); } return original; } private static class OfflineExternalResourceConnector implements ExternalResourceConnector { @Nullable @Override public <T> T withContent(ExternalResourceName location, boolean revalidate, ExternalResource.ContentAndMetadataAction<T> action) throws ResourceException { throw offlineResource(location); } @Nullable @Override public ExternalResourceMetaData getMetaData(ExternalResourceName location, boolean revalidate) throws ResourceException { throw offlineResource(location); } @Nullable @Override public List<String> list(ExternalResourceName parent) throws ResourceException { throw offlineResource(parent); } @Override public void upload(ReadableContent resource, ExternalResourceName destination) throws IOException { throw new ResourceException(destination.getUri(), String.format("Cannot upload to '%s' in offline mode.", destination.getUri())); } private ResourceException offlineResource(ExternalResourceName source) { return new ResourceException(source.getUri(), String.format("No cached resource '%s' available for offline mode.", source.getUri())); } } private static class FailureVerificationOverride implements DependencyVerificationOverride { private final Exception error; private FailureVerificationOverride(Exception error) { this.error = error; } @Override public ModuleComponentRepository overrideDependencyVerification(ModuleComponentRepository original, String resolveContextName, ResolutionStrategyInternal resolutionStrategy) { throw new DependencyVerificationException("Dependency verification cannot be performed", error); } } public static class DisablingVerificationOverride implements DependencyVerificationOverride, Stoppable { private final static Logger LOGGER = Logging.getLogger(DependencyVerificationOverride.class); private final DependencyVerificationOverride delegate; public static DisablingVerificationOverride of(DependencyVerificationOverride delegate) { return new DisablingVerificationOverride(delegate); } private DisablingVerificationOverride(DependencyVerificationOverride delegate) { this.delegate = delegate; } @Override public ModuleComponentRepository overrideDependencyVerification(ModuleComponentRepository original, String resolveContextName, ResolutionStrategyInternal resolutionStrategy) { if (resolutionStrategy.isDependencyVerificationEnabled()) { return delegate.overrideDependencyVerification(original, resolveContextName, resolutionStrategy); } else { LOGGER.warn("Dependency verification has been disabled for configuration " + resolveContextName); return original; } } @Override public void buildFinished(Gradle gradle) { delegate.buildFinished(gradle); } @Override public void artifactsAccessed(String displayName) { delegate.artifactsAccessed(displayName); } @Override public ResolvedArtifactResult verifiedArtifact(ResolvedArtifactResult artifact) { return delegate.verifiedArtifact(artifact); } @Override public void stop() { CompositeStoppable.stoppable(delegate).stop(); } } }
blindpirate/gradle
subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/ivyservice/ivyresolve/StartParameterResolutionOverride.java
Java
apache-2.0
14,818
# AUTOGENERATED FILE FROM balenalib/coral-dev-alpine:3.10-run # Default to UTF-8 file.encoding ENV LANG C.UTF-8 # add a simple script that can auto-detect the appropriate JAVA_HOME value # based on whether the JDK or only the JRE is installed RUN { \ echo '#!/bin/sh'; \ echo 'set -e'; \ echo; \ echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \ } > /usr/local/bin/docker-java-home \ && chmod +x /usr/local/bin/docker-java-home ENV JAVA_HOME /usr/lib/jvm/java-1.8-openjdk ENV PATH $PATH:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin RUN set -x \ && apk add --no-cache \ openjdk8 \ && [ "$JAVA_HOME" = "$(docker-java-home)" ] CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Alpine Linux 3.10 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v8-jdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && ln -f /bin/sh /bin/sh.real \ && ln -f /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/openjdk/coral-dev/alpine/3.10/8-jdk/run/Dockerfile
Dockerfile
apache-2.0
1,754
<?php namespace Base; use \SizesQuery as ChildSizesQuery; use \Exception; use \PDO; use Map\SizesTableMap; use Propel\Runtime\Propel; use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\ActiveQuery\ModelCriteria; use Propel\Runtime\ActiveRecord\ActiveRecordInterface; use Propel\Runtime\Collection\Collection; use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Exception\BadMethodCallException; use Propel\Runtime\Exception\LogicException; use Propel\Runtime\Exception\PropelException; use Propel\Runtime\Map\TableMap; use Propel\Runtime\Parser\AbstractParser; /** * Base class that represents a row from the 'sizes' table. * * * * @package propel.generator..Base */ abstract class Sizes implements ActiveRecordInterface { /** * TableMap class name */ const TABLE_MAP = '\\Map\\SizesTableMap'; /** * attribute to determine if this object has previously been saved. * @var boolean */ protected $new = true; /** * attribute to determine whether this object has been deleted. * @var boolean */ protected $deleted = false; /** * The columns that have been modified in current object. * Tracking modified columns allows us to only update modified columns. * @var array */ protected $modifiedColumns = array(); /** * The (virtual) columns that are added at runtime * The formatters can add supplementary columns based on a resultset * @var array */ protected $virtualColumns = array(); /** * The value for the size field. * * @var int */ protected $size; /** * The value for the description field. * * @var string */ protected $description; /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. * * @var boolean */ protected $alreadyInSave = false; /** * Initializes internal state of Base\Sizes object. */ public function __construct() { } /** * Returns whether the object has been modified. * * @return boolean True if the object has been modified. */ public function isModified() { return !!$this->modifiedColumns; } /** * Has specified column been modified? * * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID * @return boolean True if $col has been modified. */ public function isColumnModified($col) { return $this->modifiedColumns && isset($this->modifiedColumns[$col]); } /** * Get the columns that have been modified in this object. * @return array A unique list of the modified column names for this object. */ public function getModifiedColumns() { return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; } /** * Returns whether the object has ever been saved. This will * be false, if the object was retrieved from storage or was created * and then saved. * * @return boolean true, if the object has never been persisted. */ public function isNew() { return $this->new; } /** * Setter for the isNew attribute. This method will be called * by Propel-generated children and objects. * * @param boolean $b the state of the object. */ public function setNew($b) { $this->new = (boolean) $b; } /** * Whether this object has been deleted. * @return boolean The deleted state of this object. */ public function isDeleted() { return $this->deleted; } /** * Specify whether this object has been deleted. * @param boolean $b The deleted state of this object. * @return void */ public function setDeleted($b) { $this->deleted = (boolean) $b; } /** * Sets the modified state for the object to be false. * @param string $col If supplied, only the specified column is reset. * @return void */ public function resetModified($col = null) { if (null !== $col) { if (isset($this->modifiedColumns[$col])) { unset($this->modifiedColumns[$col]); } } else { $this->modifiedColumns = array(); } } /** * Compares this with another <code>Sizes</code> instance. If * <code>obj</code> is an instance of <code>Sizes</code>, delegates to * <code>equals(Sizes)</code>. Otherwise, returns <code>false</code>. * * @param mixed $obj The object to compare to. * @return boolean Whether equal to the object specified. */ public function equals($obj) { if (!$obj instanceof static) { return false; } if ($this === $obj) { return true; } if (null === $this->getPrimaryKey() || null === $obj->getPrimaryKey()) { return false; } return $this->getPrimaryKey() === $obj->getPrimaryKey(); } /** * Get the associative array of the virtual columns in this object * * @return array */ public function getVirtualColumns() { return $this->virtualColumns; } /** * Checks the existence of a virtual column in this object * * @param string $name The virtual column name * @return boolean */ public function hasVirtualColumn($name) { return array_key_exists($name, $this->virtualColumns); } /** * Get the value of a virtual column in this object * * @param string $name The virtual column name * @return mixed * * @throws PropelException */ public function getVirtualColumn($name) { if (!$this->hasVirtualColumn($name)) { throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); } return $this->virtualColumns[$name]; } /** * Set the value of a virtual column in this object * * @param string $name The virtual column name * @param mixed $value The value to give to the virtual column * * @return $this|Sizes The current object, for fluid interface */ public function setVirtualColumn($name, $value) { $this->virtualColumns[$name] = $value; return $this; } /** * Logs a message using Propel::log(). * * @param string $msg * @param int $priority One of the Propel::LOG_* logging levels * @return boolean */ protected function log($msg, $priority = Propel::LOG_INFO) { return Propel::log(get_class($this) . ': ' . $msg, $priority); } /** * Export the current object properties to a string, using a given parser format * <code> * $book = BookQuery::create()->findPk(9012); * echo $book->exportTo('JSON'); * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); * </code> * * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. * @return string The exported data */ public function exportTo($parser, $includeLazyLoadColumns = true) { if (!$parser instanceof AbstractParser) { $parser = AbstractParser::getParser($parser); } return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); } /** * Clean up internal collections prior to serializing * Avoids recursive loops that turn into segmentation faults when serializing */ public function __sleep() { $this->clearAllReferences(); $cls = new \ReflectionClass($this); $propertyNames = []; $serializableProperties = array_diff($cls->getProperties(), $cls->getProperties(\ReflectionProperty::IS_STATIC)); foreach($serializableProperties as $property) { $propertyNames[] = $property->getName(); } return $propertyNames; } /** * Get the [size] column value. * * @return int */ public function getSize() { return $this->size; } /** * Get the [description] column value. * * @return string */ public function getDescription() { return $this->description; } /** * Set the value of [size] column. * * @param int $v new value * @return $this|\Sizes The current object (for fluent API support) */ public function setSize($v) { if ($v !== null) { $v = (int) $v; } if ($this->size !== $v) { $this->size = $v; $this->modifiedColumns[SizesTableMap::COL_SIZE] = true; } return $this; } // setSize() /** * Set the value of [description] column. * * @param string $v new value * @return $this|\Sizes The current object (for fluent API support) */ public function setDescription($v) { if ($v !== null) { $v = (string) $v; } if ($this->description !== $v) { $this->description = $v; $this->modifiedColumns[SizesTableMap::COL_DESCRIPTION] = true; } return $this; } // setDescription() /** * Indicates whether the columns in this object are only set to default values. * * This method can be used in conjunction with isModified() to indicate whether an object is both * modified _and_ has some values set which are non-default. * * @return boolean Whether the columns in this object are only been set with default values. */ public function hasOnlyDefaultValues() { // otherwise, everything was equal, so return TRUE return true; } // hasOnlyDefaultValues() /** * Hydrates (populates) the object variables with values from the database resultset. * * An offset (0-based "start column") is specified so that objects can be hydrated * with a subset of the columns in the resultset rows. This is needed, for example, * for results of JOIN queries where the resultset row includes columns from two or * more tables. * * @param array $row The row returned by DataFetcher->fetch(). * @param int $startcol 0-based offset column which indicates which restultset column to start with. * @param boolean $rehydrate Whether this object is being re-hydrated from the database. * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. * * @return int next starting column * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. */ public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) { try { $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : SizesTableMap::translateFieldName('Size', TableMap::TYPE_PHPNAME, $indexType)]; $this->size = (null !== $col) ? (int) $col : null; $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : SizesTableMap::translateFieldName('Description', TableMap::TYPE_PHPNAME, $indexType)]; $this->description = (null !== $col) ? (string) $col : null; $this->resetModified(); $this->setNew(false); if ($rehydrate) { $this->ensureConsistency(); } return $startcol + 2; // 2 = SizesTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException(sprintf('Error populating %s object', '\\Sizes'), 0, $e); } } /** * Checks and repairs the internal consistency of the object. * * This method is executed after an already-instantiated object is re-hydrated * from the database. It exists to check any foreign keys to make sure that * the objects related to the current object are correct based on foreign key. * * You can override this method in the stub class, but you should always invoke * the base method from the overridden method (i.e. parent::ensureConsistency()), * in case your model changes. * * @throws PropelException */ public function ensureConsistency() { } // ensureConsistency /** * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. * * This will only work if the object has been saved and has a valid primary key set. * * @param boolean $deep (optional) Whether to also de-associated any related objects. * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. * @return void * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db */ public function reload($deep = false, ConnectionInterface $con = null) { if ($this->isDeleted()) { throw new PropelException("Cannot reload a deleted object."); } if ($this->isNew()) { throw new PropelException("Cannot reload an unsaved object."); } if ($con === null) { $con = Propel::getServiceContainer()->getReadConnection(SizesTableMap::DATABASE_NAME); } // We don't need to alter the object instance pool; we're just modifying this instance // already in the pool. $dataFetcher = ChildSizesQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); $row = $dataFetcher->fetch(); $dataFetcher->close(); if (!$row) { throw new PropelException('Cannot find matching row in the database to reload object values.'); } $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate if ($deep) { // also de-associate any related objects? } // if (deep) } /** * Removes this object from datastore and sets delete attribute. * * @param ConnectionInterface $con * @return void * @throws PropelException * @see Sizes::setDeleted() * @see Sizes::isDeleted() */ public function delete(ConnectionInterface $con = null) { if ($this->isDeleted()) { throw new PropelException("This object has already been deleted."); } if ($con === null) { $con = Propel::getServiceContainer()->getWriteConnection(SizesTableMap::DATABASE_NAME); } $con->transaction(function () use ($con) { $deleteQuery = ChildSizesQuery::create() ->filterByPrimaryKey($this->getPrimaryKey()); $ret = $this->preDelete($con); if ($ret) { $deleteQuery->delete($con); $this->postDelete($con); $this->setDeleted(true); } }); } /** * Persists this object to the database. * * If the object is new, it inserts it; otherwise an update is performed. * All modified related objects will also be persisted in the doSave() * method. This method wraps all precipitate database operations in a * single transaction. * * @param ConnectionInterface $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see doSave() */ public function save(ConnectionInterface $con = null) { if ($this->isDeleted()) { throw new PropelException("You cannot save an object that has been deleted."); } if ($con === null) { $con = Propel::getServiceContainer()->getWriteConnection(SizesTableMap::DATABASE_NAME); } return $con->transaction(function () use ($con) { $isInsert = $this->isNew(); $ret = $this->preSave($con); if ($isInsert) { $ret = $ret && $this->preInsert($con); } else { $ret = $ret && $this->preUpdate($con); } if ($ret) { $affectedRows = $this->doSave($con); if ($isInsert) { $this->postInsert($con); } else { $this->postUpdate($con); } $this->postSave($con); SizesTableMap::addInstanceToPool($this); } else { $affectedRows = 0; } return $affectedRows; }); } /** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param ConnectionInterface $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(ConnectionInterface $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; if ($this->isNew() || $this->isModified()) { // persist changes if ($this->isNew()) { $this->doInsert($con); $affectedRows += 1; } else { $affectedRows += $this->doUpdate($con); } $this->resetModified(); } $this->alreadyInSave = false; } return $affectedRows; } // doSave() /** * Insert the row in the database. * * @param ConnectionInterface $con * * @throws PropelException * @see doSave() */ protected function doInsert(ConnectionInterface $con) { $modifiedColumns = array(); $index = 0; $this->modifiedColumns[SizesTableMap::COL_SIZE] = true; if (null !== $this->size) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . SizesTableMap::COL_SIZE . ')'); } // check the columns in natural order for more readable SQL queries if ($this->isColumnModified(SizesTableMap::COL_SIZE)) { $modifiedColumns[':p' . $index++] = 'size'; } if ($this->isColumnModified(SizesTableMap::COL_DESCRIPTION)) { $modifiedColumns[':p' . $index++] = 'description'; } $sql = sprintf( 'INSERT INTO sizes (%s) VALUES (%s)', implode(', ', $modifiedColumns), implode(', ', array_keys($modifiedColumns)) ); try { $stmt = $con->prepare($sql); foreach ($modifiedColumns as $identifier => $columnName) { switch ($columnName) { case 'size': $stmt->bindValue($identifier, $this->size, PDO::PARAM_INT); break; case 'description': $stmt->bindValue($identifier, $this->description, PDO::PARAM_STR); break; } } $stmt->execute(); } catch (Exception $e) { Propel::log($e->getMessage(), Propel::LOG_ERR); throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); } try { $pk = $con->lastInsertId(); } catch (Exception $e) { throw new PropelException('Unable to get autoincrement id.', 0, $e); } $this->setSize($pk); $this->setNew(false); } /** * Update the row in the database. * * @param ConnectionInterface $con * * @return Integer Number of updated rows * @see doSave() */ protected function doUpdate(ConnectionInterface $con) { $selectCriteria = $this->buildPkeyCriteria(); $valuesCriteria = $this->buildCriteria(); return $selectCriteria->doUpdate($valuesCriteria, $con); } /** * Retrieves a field from the object by name passed in as a string. * * @param string $name name * @param string $type The type of fieldname the $name is of: * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. * Defaults to TableMap::TYPE_PHPNAME. * @return mixed Value of field. */ public function getByName($name, $type = TableMap::TYPE_PHPNAME) { $pos = SizesTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } /** * Retrieves a field from the object by Position as specified in the xml schema. * Zero-based. * * @param int $pos position in xml schema * @return mixed Value of field at $pos */ public function getByPosition($pos) { switch ($pos) { case 0: return $this->getSize(); break; case 1: return $this->getDescription(); break; default: return null; break; } // switch() } /** * Exports the object as an array. * * You can specify the key type of the array by passing one of the class * type constants. * * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME, * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. * Defaults to TableMap::TYPE_PHPNAME. * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion * * @return array an associative array containing the field names (as keys) and field values */ public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array()) { if (isset($alreadyDumpedObjects['Sizes'][$this->hashCode()])) { return '*RECURSION*'; } $alreadyDumpedObjects['Sizes'][$this->hashCode()] = true; $keys = SizesTableMap::getFieldNames($keyType); $result = array( $keys[0] => $this->getSize(), $keys[1] => $this->getDescription(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { $result[$key] = $virtualColumn; } return $result; } /** * Sets a field from the object by name passed in as a string. * * @param string $name * @param mixed $value field value * @param string $type The type of fieldname the $name is of: * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. * Defaults to TableMap::TYPE_PHPNAME. * @return $this|\Sizes */ public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) { $pos = SizesTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); return $this->setByPosition($pos, $value); } /** * Sets a field from the object by Position as specified in the xml schema. * Zero-based. * * @param int $pos position in xml schema * @param mixed $value field value * @return $this|\Sizes */ public function setByPosition($pos, $value) { switch ($pos) { case 0: $this->setSize($value); break; case 1: $this->setDescription($value); break; } // switch() return $this; } /** * Populates the object using an array. * * This is particularly useful when populating an object from one of the * request arrays (e.g. $_POST). This method goes through the column * names, checking to see whether a matching key exists in populated * array. If so the setByName() method is called for that column. * * You can specify the key type of the array by additionally passing one * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME, * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. * The default key type is the column's TableMap::TYPE_PHPNAME. * * @param array $arr An array to populate the object from. * @param string $keyType The type of keys the array uses. * @return void */ public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) { $keys = SizesTableMap::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) { $this->setSize($arr[$keys[0]]); } if (array_key_exists($keys[1], $arr)) { $this->setDescription($arr[$keys[1]]); } } /** * Populate the current object from a string, using a given parser format * <code> * $book = new Book(); * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); * </code> * * You can specify the key type of the array by additionally passing one * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME, * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. * The default key type is the column's TableMap::TYPE_PHPNAME. * * @param mixed $parser A AbstractParser instance, * or a format name ('XML', 'YAML', 'JSON', 'CSV') * @param string $data The source data to import from * @param string $keyType The type of keys the array uses. * * @return $this|\Sizes The current object, for fluid interface */ public function importFrom($parser, $data, $keyType = TableMap::TYPE_PHPNAME) { if (!$parser instanceof AbstractParser) { $parser = AbstractParser::getParser($parser); } $this->fromArray($parser->toArray($data), $keyType); return $this; } /** * Build a Criteria object containing the values of all modified columns in this object. * * @return Criteria The Criteria object containing all modified values. */ public function buildCriteria() { $criteria = new Criteria(SizesTableMap::DATABASE_NAME); if ($this->isColumnModified(SizesTableMap::COL_SIZE)) { $criteria->add(SizesTableMap::COL_SIZE, $this->size); } if ($this->isColumnModified(SizesTableMap::COL_DESCRIPTION)) { $criteria->add(SizesTableMap::COL_DESCRIPTION, $this->description); } return $criteria; } /** * Builds a Criteria object containing the primary key for this object. * * Unlike buildCriteria() this method includes the primary key values regardless * of whether or not they have been modified. * * @throws LogicException if no primary key is defined * * @return Criteria The Criteria object containing value(s) for primary key(s). */ public function buildPkeyCriteria() { $criteria = ChildSizesQuery::create(); $criteria->add(SizesTableMap::COL_SIZE, $this->size); return $criteria; } /** * If the primary key is not null, return the hashcode of the * primary key. Otherwise, return the hash code of the object. * * @return int Hashcode */ public function hashCode() { $validPk = null !== $this->getSize(); $validPrimaryKeyFKs = 0; $primaryKeyFKs = []; if ($validPk) { return crc32(json_encode($this->getPrimaryKey(), JSON_UNESCAPED_UNICODE)); } elseif ($validPrimaryKeyFKs) { return crc32(json_encode($primaryKeyFKs, JSON_UNESCAPED_UNICODE)); } return spl_object_hash($this); } /** * Returns the primary key for this object (row). * @return int */ public function getPrimaryKey() { return $this->getSize(); } /** * Generic method to set the primary key (size column). * * @param int $key Primary key. * @return void */ public function setPrimaryKey($key) { $this->setSize($key); } /** * Returns true if the primary key for this object is null. * @return boolean */ public function isPrimaryKeyNull() { return null === $this->getSize(); } /** * Sets contents of passed object to values from current object. * * If desired, this method can also make copies of all associated (fkey referrers) * objects. * * @param object $copyObj An object of \Sizes (or compatible) type. * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. * @throws PropelException */ public function copyInto($copyObj, $deepCopy = false, $makeNew = true) { $copyObj->setDescription($this->getDescription()); if ($makeNew) { $copyObj->setNew(true); $copyObj->setSize(NULL); // this is a auto-increment column, so set to default value } } /** * Makes a copy of this object that will be inserted as a new row in table when saved. * It creates a new object filling in the simple attributes, but skipping any primary * keys that are defined for the table. * * If desired, this method can also make copies of all associated (fkey referrers) * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. * @return \Sizes Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) { // we use get_class(), because this might be a subclass $clazz = get_class($this); $copyObj = new $clazz(); $this->copyInto($copyObj, $deepCopy); return $copyObj; } /** * Clears the current object, sets all attributes to their default values and removes * outgoing references as well as back-references (from other objects to this one. Results probably in a database * change of those foreign objects when you call `save` there). */ public function clear() { $this->size = null; $this->description = null; $this->alreadyInSave = false; $this->clearAllReferences(); $this->resetModified(); $this->setNew(true); $this->setDeleted(false); } /** * Resets all references and back-references to other model objects or collections of model objects. * * This method is used to reset all php object references (not the actual reference in the database). * Necessary for object serialisation. * * @param boolean $deep Whether to also clear the references on all referrer objects. */ public function clearAllReferences($deep = false) { if ($deep) { } // if ($deep) } /** * Return the string representation of this object * * @return string */ public function __toString() { return (string) $this->exportTo(SizesTableMap::DEFAULT_STRING_FORMAT); } /** * Code to be run before persisting the object * @param ConnectionInterface $con * @return boolean */ public function preSave(ConnectionInterface $con = null) { return true; } /** * Code to be run after persisting the object * @param ConnectionInterface $con */ public function postSave(ConnectionInterface $con = null) { } /** * Code to be run before inserting to database * @param ConnectionInterface $con * @return boolean */ public function preInsert(ConnectionInterface $con = null) { return true; } /** * Code to be run after inserting to database * @param ConnectionInterface $con */ public function postInsert(ConnectionInterface $con = null) { } /** * Code to be run before updating the object in database * @param ConnectionInterface $con * @return boolean */ public function preUpdate(ConnectionInterface $con = null) { return true; } /** * Code to be run after updating the object in database * @param ConnectionInterface $con */ public function postUpdate(ConnectionInterface $con = null) { } /** * Code to be run before deleting the object in database * @param ConnectionInterface $con * @return boolean */ public function preDelete(ConnectionInterface $con = null) { return true; } /** * Code to be run after deleting the object in database * @param ConnectionInterface $con */ public function postDelete(ConnectionInterface $con = null) { } /** * Derived method to catches calls to undefined methods. * * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). * Allows to define default __call() behavior if you overwrite __call() * * @param string $name * @param mixed $params * * @return array|string */ public function __call($name, $params) { if (0 === strpos($name, 'get')) { $virtualColumn = substr($name, 3); if ($this->hasVirtualColumn($virtualColumn)) { return $this->getVirtualColumn($virtualColumn); } $virtualColumn = lcfirst($virtualColumn); if ($this->hasVirtualColumn($virtualColumn)) { return $this->getVirtualColumn($virtualColumn); } } if (0 === strpos($name, 'from')) { $format = substr($name, 4); return $this->importFrom($format, reset($params)); } if (0 === strpos($name, 'to')) { $format = substr($name, 2); $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; return $this->exportTo($format, $includeLazyLoadColumns); } throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); } }
Sleepwalker2014/ums
db/Base/Sizes.php
PHP
apache-2.0
35,743
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_162) on Sat Feb 02 18:57:41 CET 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>com.communote.plugins.mq.message.core.data.topic (Communote 3.5 API)</title> <meta name="date" content="2019-02-02"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.communote.plugins.mq.message.core.data.topic (Communote 3.5 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../../com/communote/plugins/mq/message/core/data/tag/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../../../com/communote/plugins/mq/message/core/data/user/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/communote/plugins/mq/message/core/data/topic/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;com.communote.plugins.mq.message.core.data.topic</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../../com/communote/plugins/mq/message/core/data/topic/BaseTopic.html" title="class in com.communote.plugins.mq.message.core.data.topic">BaseTopic</a></td> <td class="colLast"> <div class="block">The Class BaseTopic.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../../com/communote/plugins/mq/message/core/data/topic/ExternalObject.html" title="class in com.communote.plugins.mq.message.core.data.topic">ExternalObject</a></td> <td class="colLast"> <div class="block">External object of a topic</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../../com/communote/plugins/mq/message/core/data/topic/Topic.html" title="class in com.communote.plugins.mq.message.core.data.topic">Topic</a></td> <td class="colLast"> <div class="block">The Class Topic.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../../com/communote/plugins/mq/message/core/data/topic/TopicProperty.html" title="class in com.communote.plugins.mq.message.core.data.topic">TopicProperty</a></td> <td class="colLast"> <div class="block">Property of a topic</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../../com/communote/plugins/mq/message/core/data/topic/TopicRights.html" title="class in com.communote.plugins.mq.message.core.data.topic">TopicRights</a></td> <td class="colLast"> <div class="block">Topic access rights</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../../com/communote/plugins/mq/message/core/data/tag/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../../../com/communote/plugins/mq/message/core/data/user/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/communote/plugins/mq/message/core/data/topic/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2019 <a href="https://communote.github.io/">Communote team</a>. All rights reserved.</small></p> </body> </html>
Communote/communote.github.io
generated/javadoc/com/communote/plugins/mq/message/core/data/topic/package-summary.html
HTML
apache-2.0
6,867
<div style="height:100%"> <p>{{message}}</p> <div class="row show-grid" style="height:100%"> <div class="col-md-2" style="padding-left:2%"> <h3>Order By:</h3> <div class="form-group"> <select class="form-control" ng-model="selectedOrder" ng-change="reCalculateDisplayedMasteries()" ng-options="x for x in orders"></select> </div> <hr /> <h3>Filters:</h3> <div class="checkbox" ng-repeat="filter in filterValues"> <label> <input type="checkbox" ng-change="reCalculateDisplayedMasteries()" ng-model="filters[filter.name]"> {{filter.name}} </label> </div> </div> <div class="col-md-8" style="height:100%; overflow-y: auto"> <div ng-repeat="cm in championMasteries" class="row show-grid"> <div class="col-md-1" style="padding-top:1%"> <img ng-src="http://ddragon.leagueoflegends.com/cdn/6.8.1/img/champion/{{cm.Champion.key}}.png" alt="..." class="img-thumbnail"> </div> <div class="col-md-11"> <div class="row show-grid"> <div class="col-md-10"> <h2 class="champName">{{cm.Champion.name}}</h2> <h4 class="champTitle">{{cm.Champion.title}}</h4> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="{{cm.Mastery.championPointsSinceLastLevel}}" aria-valuemin="0" aria-valuemax="{{cm.Mastery.championPointsSinceLastLevel + cm.Mastery.championPointsUntilNextLevel}}" style="width: {{(cm.Mastery.championPointsSinceLastLevel / (cm.Mastery.championPointsSinceLastLevel + cm.Mastery.championPointsUntilNextLevel)) * 100}}%;"> {{cm.Mastery.championPointsSinceLastLevel}}/{{cm.Mastery.championPointsSinceLastLevel + cm.Mastery.championPointsUntilNextLevel}} </div> </div> </div> <div class="col-md-1"> <h4 style="text-align: center">Level</h4> <h2 style="text-align: center; margin-top:0">{{cm.Mastery.championLevel}}</h2> </div> </div> </div> <hr /> </div> </div> <div class="col-md-2" style="padding-left:2%"> <h3>Summoner:</h3> <div ng-show="summonerData != null" class="row show-grid"> <div class="col-md-2" style="padding: 0 0 0 0;"> <img ng-src="http://ddragon.leagueoflegends.com/cdn/6.8.1/img/profileicon/{{summonerData.profileIconId}}.png" alt="..." class="img-thumbnail"> </div> <div class="col-md-10"> <p>Name: {{summonerData.name}}</p> <p>Level: {{summonerData.summonerLevel}}</p> </div> </div> <h3>Stats:</h3> <div ng-show="summonerData != null" class="row show-grid" ng-controller="summonerController"> <div class="col-md-12"> <p>{{$scope.formSummonerName}}</p> <p>Total Wins: {{summonerStats.totalWins}}</p> <p>Total Champions killed: {{summonerStats.totalChampionKills}}</p> <p>Total Assists:{{summonerStats.totalAssists}}</p> <p>Total Turrents killed: {{summonerStats.totalTurretsKilled}}</p> <p>Total Minions killed: {{summonerStats.totalMinionKills}}</p> <p>Total Neutral Minion killed: {{summonerStats.totalNeutralMinionsKilled}}</p> </div> </div> </div> </div> </div>
wmolyneux/MasteryMaster
wwwroot/champMasteries.html
HTML
apache-2.0
4,100
"use strict"; var _ = require("lodash"); var overrides = { username: "u", accessKey: "k", verboseDebugging: "verbose", port: "P", vv: "-vv" }; var booleans = { verboseDebugging: true, doctor: true }; module.exports = function processOptions(options) { options.username = options.username || process.env.SAUCE_USERNAME; options.accessKey = options.accessKey || process.env.SAUCE_ACCESS_KEY; return _.reduce( _.omit(options, [ "readyFileId", "verbose", "logger", "log", "connectRetries", "connectRetryTimeout", "downloadRetries", "downloadRetryTimeout", "detached", "connectVersion" ]), function (argList, value, key) { if (typeof value === "undefined" || value === null) { return argList; } var argName = overrides[key] || _.kebabCase(key); if (argName.length === 1) { argName = "-" + argName; } else if(argName[0] !== "-") { argName = "--" + argName; } if (Array.isArray(value)) { value = value.join(","); } if (booleans[key] || value === true) { argList.push(argName); } else { argList.push(argName, value); } return argList; }, []); };
jzthree/GraphBoard
node_modules/sauce-connect-launcher/lib/process_options.js
JavaScript
apache-2.0
1,262
// import SearchModule from './search' // import SearchController from './search.controller'; // import SearchComponent from './search.component'; // import SearchTemplate from './search.html'; // // describe('Search', () => { // let $rootScope, makeController; // // beforeEach(window.module(SearchModule)); // beforeEach(inject((_$rootScope_) => { // $rootScope = _$rootScope_; // makeController = () => { // return new SearchController(); // }; // })); // // describe('Module', () => { // // top-level specs: i.e., routes, injection, naming // }); // // describe('Controller', () => { // // controller specs // // }); // // describe('Template', () => { // // template specs // // tip: use regex to ensure correct bindings are used e.g., {{ }} // // }); // // describe('Component', () => { // // component/directive specs // let component = SearchComponent; // // it('includes the intended template',() => { // expect(component.template).to.equal(SearchTemplate); // }); // // it('invokes the right controller', () => { // expect(component.controller).to.equal(SearchController); // }); // }); // });
mazurevich/test
client/app/components/home/search/search.spec.js
JavaScript
apache-2.0
1,214
Vagrant LEMP ============= Ubuntu + Nginx + MongoDB and PHP ###Requirements * VirtualBox or VMware * Vagrant ###Installation In command line: git clone https://github.com/buonzz-systems/vagrant-lemp.git cd vagrant-lemp vagrant up Wait until the installation is finish. Then login to the box by vagrant ssh
buonzz-systems/vagrant-lemp
README.md
Markdown
apache-2.0
343
package org.kuali.rice.kew.api.peopleflow; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.kuali.rice.core.api.CoreConstants; import org.kuali.rice.core.api.mo.AbstractDataTransferObject; import org.kuali.rice.core.api.mo.ModelBuilder; import org.kuali.rice.core.api.mo.ModelObjectUtils; import org.kuali.rice.kew.api.action.ActionRequestPolicy; import org.kuali.rice.kew.api.action.DelegationType; import org.w3c.dom.Element; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; @XmlRootElement(name = PeopleFlowMember.Constants.ROOT_ELEMENT_NAME) @XmlAccessorType(XmlAccessType.NONE) @XmlType(name = PeopleFlowMember.Constants.TYPE_NAME, propOrder = { PeopleFlowMember.Elements.MEMBER_ID, PeopleFlowMember.Elements.MEMBER_TYPE, PeopleFlowMember.Elements.ACTION_REQUEST_POLICY, PeopleFlowMember.Elements.RESPONSIBILITY_ID, PeopleFlowMember.Elements.PRIORITY, PeopleFlowMember.Elements.DELEGATES, CoreConstants.CommonElements.FUTURE_ELEMENTS }) public final class PeopleFlowMember extends AbstractDataTransferObject implements PeopleFlowMemberContract { private static final int STARTING_PRIORITY = 1; @XmlElement(name = Elements.MEMBER_ID, required = true) private final String memberId; @XmlElement(name = Elements.MEMBER_TYPE, required = true) private final MemberType memberType; @XmlElement(name = Elements.ACTION_REQUEST_POLICY, required = false) private final ActionRequestPolicy actionRequestPolicy; @XmlElement(name = Elements.RESPONSIBILITY_ID, required = false) private final String responsibilityId; @XmlElement(name = Elements.PRIORITY, required = true) private final int priority; @XmlElementWrapper(name = Elements.DELEGATES, required = false) @XmlElement(name = Elements.DELEGATE, required = false) private final List<PeopleFlowDelegate> delegates; @SuppressWarnings("unused") @XmlAnyElement private final Collection<Element> _futureElements = null; /** * Private constructor used only by JAXB. */ private PeopleFlowMember() { this.memberId = null; this.memberType = null; this.actionRequestPolicy = null; this.responsibilityId = null; this.priority = STARTING_PRIORITY; this.delegates = null; } private PeopleFlowMember(Builder builder) { this.memberId = builder.getMemberId(); this.memberType = builder.getMemberType(); this.actionRequestPolicy = builder.getActionRequestPolicy(); this.responsibilityId = builder.getResponsibilityId(); this.priority = builder.getPriority(); this.delegates = ModelObjectUtils.buildImmutableCopy(builder.getDelegates()); } @Override public String getMemberId() { return this.memberId; } @Override public MemberType getMemberType() { return this.memberType; } @Override public ActionRequestPolicy getActionRequestPolicy() { return this.actionRequestPolicy; } @Override public String getResponsibilityId() { return this.responsibilityId; } @Override public int getPriority() { return this.priority; } @Override public List<PeopleFlowDelegate> getDelegates() { return this.delegates; } /** * A builder which can be used to construct {@link PeopleFlowMember} instances. Enforces the constraints of the * {@link PeopleFlowMemberContract}. */ public final static class Builder implements Serializable, ModelBuilder, PeopleFlowMemberContract { private String memberId; private MemberType memberType; private ActionRequestPolicy actionRequestPolicy; private String responsibilityId; private int priority; private List<PeopleFlowDelegate.Builder> delegates; private Builder(String memberId, MemberType memberType) { setMemberId(memberId); setMemberType(memberType); setPriority(STARTING_PRIORITY); setDelegates(new ArrayList<PeopleFlowDelegate.Builder>()); } public static Builder create(String memberId, MemberType memberType) { return new Builder(memberId, memberType); } public static Builder create(PeopleFlowMemberContract contract) { if (contract == null) { throw new IllegalArgumentException("contract was null"); } Builder builder = create(contract.getMemberId(), contract.getMemberType()); builder.setActionRequestPolicy(contract.getActionRequestPolicy()); builder.setResponsibilityId(contract.getResponsibilityId()); builder.setPriority(contract.getPriority()); if (CollectionUtils.isNotEmpty(contract.getDelegates())) { for (PeopleFlowDelegateContract delegate : contract.getDelegates()) { builder.getDelegates().add(PeopleFlowDelegate.Builder.create(delegate)); } } return builder; } public PeopleFlowMember build() { return new PeopleFlowMember(this); } @Override public String getMemberId() { return this.memberId; } @Override public MemberType getMemberType() { return this.memberType; } @Override public ActionRequestPolicy getActionRequestPolicy() { return this.actionRequestPolicy; } @Override public String getResponsibilityId() { return this.responsibilityId; } @Override public int getPriority() { return this.priority; } @Override public List<PeopleFlowDelegate.Builder> getDelegates() { return delegates; } public void setMemberId(String memberId) { if (StringUtils.isBlank(memberId)) { throw new IllegalArgumentException("memberId was null or blank"); } this.memberId = memberId; } public void setMemberType(MemberType memberType) { if (memberType == null) { throw new IllegalArgumentException("memberType was null"); } this.memberType = memberType; } public void setActionRequestPolicy(ActionRequestPolicy actionRequestPolicy) { this.actionRequestPolicy = actionRequestPolicy; } public void setResponsibilityId(String responsibilityId) { this.responsibilityId = responsibilityId; } public void setPriority(int priority) { if (priority < STARTING_PRIORITY) { throw new IllegalArgumentException("Given priority was smaller than the minimum prior value of " + STARTING_PRIORITY); } this.priority = priority; } public void setDelegates(List<PeopleFlowDelegate.Builder> delegates) { this.delegates = delegates; } } /** * Defines some internal constants used on this class. */ static class Constants { final static String ROOT_ELEMENT_NAME = "peopleFlowMember"; final static String TYPE_NAME = "PeopleFlowMemberType"; } /** * A private class which exposes constants which define the XML element names to use when this object is marshalled to XML. */ static class Elements { final static String MEMBER_ID = "memberId"; final static String MEMBER_TYPE = "memberType"; final static String ACTION_REQUEST_POLICY = "actionRequestPolicy"; final static String RESPONSIBILITY_ID = "responsibilityId"; final static String PRIORITY = "priority"; final static String DELEGATES = "delegates"; final static String DELEGATE = "delegate"; } }
sbower/kuali-rice-1
kew/api/src/main/java/org/kuali/rice/kew/api/peopleflow/PeopleFlowMember.java
Java
apache-2.0
8,357
package mqfiletransferagent.actors import akka.actor.ActorSystem import akka.actor.Actor import akka.actor.Props import akka.testkit.TestKit import org.scalatest.WordSpecLike import org.scalatest.Matchers import org.scalatest.BeforeAndAfterAll import akka.testkit.ImplicitSender import scala.concurrent.duration._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner import akka.testkit.TestProbe import akka.camel.CamelMessage class CoordinatorQueueProducerSpec extends TestKit(ActorSystem("CoordinatorQueueProducerSpec")) with ImplicitSender with WordSpecLike with BeforeAndAfterAll { override def afterAll { TestKit.shutdownActorSystem(system) } //akka-camel is keeping the actor from receiving messages in tests }
antongerbracht/MQFileTransfer
MQFileTransferAgent/src/test/scala/mqfiletransferagent/actors/CoordinatorQueueProducerSpec.scala
Scala
apache-2.0
745
# Copyright 2018 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file in README.md and # CONTRIBUTING.md located at the root of this package. # # ---------------------------------------------------------------------------- module Google module Compute module Data # Base class for ResourceRefs # Imports self_link from disk class DiskSelfLinkRef include Comparable def ==(other) return false unless other.is_a? DiskSelfLinkRef return false if resource != other.resource true end def <=>(other) resource <=> other.resource end # Overriding inspect method ensures that Chef logs only the # fetched value to the console def inspect "'#{resource}'" end end # A class to fetch the resource value from a referenced block # Will return the value exported from a different Chef resource class DiskSelfLinkRefCatalog < DiskSelfLinkRef def initialize(title, parent_resource) @title = title @parent_resource = parent_resource end # Chef requires the title for autorequiring def autorequires [@title] end def to_s resource.to_s end def to_json(_arg = nil) return if resource.nil? resource.to_json end def resource Chef.run_context.resource_collection.each do |entry| return entry.exports[:self_link] if entry.name == @title end raise ArgumentError, "gcompute_disk[#{@title}] required" end end # A class to manage a JSON blob from GCP API # Will immediately return value from JSON blob without changes class DiskSelfLinkRefApi < DiskSelfLinkRef attr_reader :resource def initialize(resource) @resource = resource end def to_s @resource.to_s end def to_json(_arg = nil) @resource.to_json end end end module Property # A class to manage fetching self_link from a disk class DiskSelfLinkRef def self.coerce ->(parent_resource, value) { ::Google::Compute::Property::DiskSelfLinkRef.catalog_parse(value, parent_resource) } end def catalog_parse(value, parent_resource = nil) return if value.nil? self.class.catalog_parse(value, parent_resource) end def self.catalog_parse(value, parent_resource = nil) return if value.nil? return value if value.is_a? Data::DiskSelfLinkRef Data::DiskSelfLinkRefCatalog.new(value, parent_resource) end # Used for fetched JSON values def self.api_parse(value) return if value.nil? return value if value.is_a? Data::DiskSelfLinkRef Data::DiskSelfLinkRefApi.new(value) end end end end end
GoogleCloudPlatform/chef-google-compute
libraries/google/compute/property/disk_selflink.rb
Ruby
apache-2.0
3,921
div.exampleboxshadowa{ box-shadow: -5px -5px 0 grey; } div.exampleboxshadowb{ box-shadow: -5px -5px 5px grey; } div.exampleboxshadowc{ box-shadow: -5px -5px 0 5px grey; } div.exampleboxshadowd{ box-shadow: -5px -5px 5px 5px grey; } div.exampleboxshadowe{ box-shadow: 0 0 5px .5px grey; } div.exampleboxshadowf{ box-shadow: 0 0 10px 2px grey; } div.exampleboxshadowg{ box-shadow:inset -5px -5px 0 grey; } div.exampleboxshadowh{ box-shadow:inset -5px -5px 5px grey; } div.exampleboxshadowi{ box-shadow:inset -5px -5px 0 5px grey; } div.exampleboxshadowj{ box-shadow:inset -5px -5px 5px 5px grey; } div.exampleboxshadowk{ box-shadow:inset 0 0 5px .5px; } div.exampleboxshadowl{ box-shadow:inset 0 0 10px 2px; }
ikerlorente11/Egibide
DAW/2-Desarrollo-de-aplicaciones-web/DIW/Ejercicios/Tema3/Sombras/ejercicio2_sombras.css
CSS
apache-2.0
816
$def with (ratings) $:{RENDER("common/stage_title.html", ["Character Profile", "Submit", "/submit"])} <div id="submit-character-content" class="content"> <form id="submit-form" name="submitcharacter" class="form clear" action="/submit/character" method="post" enctype="multipart/form-data"> $:{CSRF()} <div class="column files"> <h3>Files</h3> <label>Picture</label> <input type="file" name="submitfile" id="submitfile" class="styled-input" accept="image/*" /> <p class="color-lighter" style="padding-top: 0.5em;"><i>Limit (JPG): 10 MB</i></p> <p class="color-lighter" style="padding-top: 0.5em;"><i>Limit (PNG): 10 MB</i></p> <p class="color-lighter" style="padding-top: 0.5em;"><i>Limit (GIF): 10 MB</i></p> <label>Thumbnail</label> <input type="file" name="thumbfile" id="thumbfile" class="styled-input" accept="image/*" /> </div><!-- /tiles --> <div class="column info"> <h3>Character Bio</h3> <label for="charactertitle">Name</label> <input type="text" class="input" name="title" id="charactertitle" maxlength="100" /> <label for="characterage">Age</label> <input type="text" class="input" name="age" id="characterage" maxlength="100" /> <label for="charactergender">Gender</label> <input type="text" class="input" name="gender" id="charactergender" maxlength="100" /> <label for="characterheight">Height</label> <input type="text" class="input" name="height" id="characterheight" maxlength="100" /> <label for="characterweight">Weight</label> <input type="text" class="input" name="weight" id="characterweight" maxlength="100" /> <label for="characterspecies">Species</label> <input type="text" class="input" name="species" id="characterspecies" maxlength="100" /> <label for="characterrating">Rating</label> <select name="rating" class="input" id="characterrating"> <option value="" selected="selected">&nbsp;</option> $for rating in ratings: <option value="${rating.code}">${rating.name_with_age}</option> </select> <p class="color-lighter tags-help"><i>Please apply a rating to this character according to our <a href="/help/ratings" target="_blank">ratings guidelines</a>.</i></p> </div><!-- /info --> <div class="column description"> <h3>Description</h3> <label for="characterdesc">Description</label> <textarea name="content" class="markdown input expanding" rows="9" id="characterdesc"></textarea> </div><!-- /descrition --> <div class="column tagging"> <h3>Tags</h3> <textarea name="tags" class="input" rows="3" id="tags-textarea"></textarea> <p class="color-lighter tags-help"><i>When tagging, make sure to describe your character thoroughly (anthro, human, robot, and so on). Separate tags with a space. Use an underscore for multiple words in a tag, ex. red_fox</i></p> </div><!-- /tagging --> <div class="column options"> <h3>Additional Options</h3> <label for="submit-friends" class="input-checkbox last-input"> <input type="checkbox" name="friends" id="submit-friends" /> Make this submission visible only to my friends </label> </div><!-- /options --> <div class="buttons clear"> <button type="submit" class="button positive" style="float: right;">Continue</button> <a class="button" href="/index">Return Home</a> </div><!-- /buttons --> </form> </div><!-- /content -->
dzamie/weasyl
templates/submit/character.html
HTML
apache-2.0
3,595
/** * Copyright 2016 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.github.ambry.router; import com.github.ambry.clustermap.ClusterMap; import com.github.ambry.clustermap.ReplicaId; import com.github.ambry.commons.BlobId; import com.github.ambry.commons.ResponseHandler; import com.github.ambry.commons.ServerErrorCode; import com.github.ambry.config.RouterConfig; import com.github.ambry.network.Port; import com.github.ambry.network.ResponseInfo; import com.github.ambry.protocol.DeleteRequest; import com.github.ambry.protocol.DeleteResponse; import com.github.ambry.utils.Time; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class manages the internal state of a {@code DeleteOperation} during its life cycle. A {@code DeleteOperation} * can be issued to two types of blobs. * Simple blob: A single blob that is under the max put chunk size. The {@code DeleteOperation} will be issued to the * actual blob. * Composite blob: A blob consists of a number of data blobs and a metadata blob that manages the medadata of all the * data blobs. The {@code DeleteOperation} is issued only to delete the metadata blob. */ class DeleteOperation { //Operation arguments private final RouterConfig routerConfig; private final ResponseHandler responseHandler; private final BlobId blobId; private final String serviceId; private final FutureResult<Void> futureResult; private final Callback<Void> callback; private final Time time; private final NonBlockingRouterMetrics routerMetrics; private final long submissionTimeMs; private final long deletionTimeMs; // Parameters associated with the state. // The operation tracker that tracks the state of this operation. private final OperationTracker operationTracker; // A map used to find inflight requests using a correlation id. private final HashMap<Integer, DeleteRequestInfo> deleteRequestInfos; // The result of this operation to be set into FutureResult. private final Void operationResult = null; // the cause for failure of this operation. This will be set if and when the operation encounters an irrecoverable // failure. private final AtomicReference<Exception> operationException = new AtomicReference<Exception>(); // RouterErrorCode that is resolved from all the received ServerErrorCode for this operation. private RouterErrorCode resolvedRouterErrorCode; // Denotes whether the operation is complete. private boolean operationCompleted = false; private static final Logger logger = LoggerFactory.getLogger(DeleteOperation.class); /** * Instantiates a {@link DeleteOperation}. * @param routerConfig The {@link RouterConfig} that contains router-level configurations. * @param routerMetrics The {@link NonBlockingRouterMetrics} to record all router-related metrics. * @param responsehandler The {@link ResponseHandler} used to notify failures for failure detection. * @param blobId The {@link BlobId} that is to be deleted by this {@code DeleteOperation}. * @param serviceId The service ID of the service deleting the blob. This can be null if unknown. * @param callback The {@link Callback} that is supplied by the caller. * @param time A {@link Time} reference. * @param futureResult The {@link FutureResult} that is returned to the caller. */ DeleteOperation(ClusterMap clusterMap, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, ResponseHandler responsehandler, BlobId blobId, String serviceId, Callback<Void> callback, Time time, FutureResult<Void> futureResult) { this.submissionTimeMs = time.milliseconds(); this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.responseHandler = responsehandler; this.blobId = blobId; this.serviceId = serviceId; this.futureResult = futureResult; this.callback = callback; this.time = time; this.deletionTimeMs = time.milliseconds(); this.deleteRequestInfos = new HashMap<Integer, DeleteRequestInfo>(); byte blobDcId = blobId.getDatacenterId(); String originatingDcName = clusterMap.getDatacenterName(blobDcId); this.operationTracker = new SimpleOperationTracker(routerConfig, RouterOperation.DeleteOperation, blobId.getPartition(), originatingDcName, false); } /** * Gets a list of {@link DeleteRequest} for sending to replicas. * @param requestRegistrationCallback the {@link RequestRegistrationCallback} to call for every request * that gets created as part of this poll operation. */ void poll(RequestRegistrationCallback<DeleteOperation> requestRegistrationCallback) { cleanupExpiredInflightRequests(); checkAndMaybeComplete(); if (!isOperationComplete()) { fetchRequests(requestRegistrationCallback); } } /** * Fetch {@link DeleteRequest}s to send for the operation. */ private void fetchRequests(RequestRegistrationCallback<DeleteOperation> requestRegistrationCallback) { Iterator<ReplicaId> replicaIterator = operationTracker.getReplicaIterator(); while (replicaIterator.hasNext()) { ReplicaId replica = replicaIterator.next(); String hostname = replica.getDataNodeId().getHostname(); Port port = replica.getDataNodeId().getPortToConnectTo(); DeleteRequest deleteRequest = createDeleteRequest(); deleteRequestInfos.put(deleteRequest.getCorrelationId(), new DeleteRequestInfo(time.milliseconds(), replica)); RouterRequestInfo requestInfo = new RouterRequestInfo(hostname, port, deleteRequest, replica); requestRegistrationCallback.registerRequestToSend(this, requestInfo); replicaIterator.remove(); if (RouterUtils.isRemoteReplica(routerConfig, replica)) { logger.trace("Making request with correlationId {} to a remote replica {} in {} ", deleteRequest.getCorrelationId(), replica.getDataNodeId(), replica.getDataNodeId().getDatacenterName()); routerMetrics.crossColoRequestCount.inc(); } else { logger.trace("Making request with correlationId {} to a local replica {} ", deleteRequest.getCorrelationId(), replica.getDataNodeId()); } routerMetrics.getDataNodeBasedMetrics(replica.getDataNodeId()).deleteRequestRate.mark(); } } /** * Create a {@link DeleteRequest} for sending to a replica. * @return The DeleteRequest. */ private DeleteRequest createDeleteRequest() { return new DeleteRequest(NonBlockingRouter.correlationIdGenerator.incrementAndGet(), routerConfig.routerHostname, blobId, deletionTimeMs); } /** * Handles a response for a delete operation. It determines whether the request was successful, * updates operation tracker, and notifies the response handler for failure detection. * can be different cases during handling a response. For the same delete operation, it is possible * that different {@link ServerErrorCode} are received from different replicas. These error codes * are eventually resolved to a single {@link RouterErrorCode}. * @param responseInfo The {@link ResponseInfo} to be handled. * @param deleteResponse The {@link DeleteResponse} associated with this response. */ void handleResponse(ResponseInfo responseInfo, DeleteResponse deleteResponse) { DeleteRequest deleteRequest = (DeleteRequest) responseInfo.getRequestInfo().getRequest(); DeleteRequestInfo deleteRequestInfo = deleteRequestInfos.remove(deleteRequest.getCorrelationId()); // deleteRequestInfo can be null if this request was timed out before this response is received. No // metric is updated here, as corresponding metrics have been updated when the request was timed out. if (deleteRequestInfo == null) { return; } ReplicaId replica = deleteRequestInfo.replica; long requestLatencyMs = time.milliseconds() - deleteRequestInfo.startTimeMs; routerMetrics.routerRequestLatencyMs.update(requestLatencyMs); routerMetrics.getDataNodeBasedMetrics(replica.getDataNodeId()).deleteRequestLatencyMs.update(requestLatencyMs); // Check the error code from NetworkClient. if (responseInfo.getError() != null) { logger.trace("DeleteRequest with response correlationId {} timed out for replica {} ", deleteRequest.getCorrelationId(), replica.getDataNodeId()); updateOperationState(replica, RouterErrorCode.OperationTimedOut); } else { if (deleteResponse == null) { logger.trace( "DeleteRequest with response correlationId {} received UnexpectedInternalError on response deserialization for replica {} ", deleteRequest.getCorrelationId(), replica.getDataNodeId()); updateOperationState(replica, RouterErrorCode.UnexpectedInternalError); } else { // The true case below should not really happen. This means a response has been received // not for its original request. We will immediately fail this operation. if (deleteResponse.getCorrelationId() != deleteRequest.getCorrelationId()) { logger.error("The correlation id in the DeleteResponse " + deleteResponse.getCorrelationId() + " is not the same as the correlation id in the associated DeleteRequest: " + deleteRequest.getCorrelationId()); routerMetrics.unknownReplicaResponseError.inc(); setOperationException( new RouterException("Received wrong response that is not for the corresponding request.", RouterErrorCode.UnexpectedInternalError)); updateOperationState(replica, RouterErrorCode.UnexpectedInternalError); } else { // The status of operation tracker will be updated within the processServerError method. processServerError(replica, deleteResponse.getError(), deleteResponse.getCorrelationId()); if (deleteResponse.getError() == ServerErrorCode.Blob_Authorization_Failure) { operationCompleted = true; } } } } checkAndMaybeComplete(); } /** * A wrapper class that is used to check if a request has been expired. */ private class DeleteRequestInfo { final long startTimeMs; final ReplicaId replica; DeleteRequestInfo(long submissionTime, ReplicaId replica) { this.startTimeMs = submissionTime; this.replica = replica; } } /** * Goes through the inflight request list of this {@code DeleteOperation} and remove those that * have been timed out. */ private void cleanupExpiredInflightRequests() { Iterator<Map.Entry<Integer, DeleteRequestInfo>> itr = deleteRequestInfos.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<Integer, DeleteRequestInfo> deleteRequestInfoEntry = itr.next(); DeleteRequestInfo deleteRequestInfo = deleteRequestInfoEntry.getValue(); if (time.milliseconds() - deleteRequestInfo.startTimeMs > routerConfig.routerRequestTimeoutMs) { itr.remove(); logger.trace("Delete Request with correlationid {} in flight has expired for replica {} ", deleteRequestInfoEntry.getKey(), deleteRequestInfo.replica.getDataNodeId()); // Do not notify this as a failure to the response handler, as this timeout could simply be due to // connection unavailability. If there is indeed a network error, the NetworkClient will provide an error // response and the response handler will be notified accordingly. updateOperationState(deleteRequestInfo.replica, RouterErrorCode.OperationTimedOut); } } } /** * Processes {@link ServerErrorCode} received from {@code replica}. This method maps a {@link ServerErrorCode} * to a {@link RouterErrorCode}, and then makes corresponding state update. * @param replica The replica for which the ServerErrorCode was generated. * @param serverErrorCode The ServerErrorCode received from the replica. * @param correlationId the correlationId of the request */ private void processServerError(ReplicaId replica, ServerErrorCode serverErrorCode, int correlationId) { switch (serverErrorCode) { case No_Error: case Blob_Deleted: operationTracker.onResponse(replica, true); if (RouterUtils.isRemoteReplica(routerConfig, replica)) { logger.trace("Cross colo request successful for remote replica {} in {} ", replica.getDataNodeId(), replica.getDataNodeId().getDatacenterName()); routerMetrics.crossColoSuccessCount.inc(); } break; case Blob_Authorization_Failure: updateOperationState(replica, RouterErrorCode.BlobAuthorizationFailure); break; case Blob_Expired: updateOperationState(replica, RouterErrorCode.BlobExpired); break; case Blob_Not_Found: updateOperationState(replica, RouterErrorCode.BlobDoesNotExist); break; case Partition_Unknown: updateOperationState(replica, RouterErrorCode.UnexpectedInternalError); break; case Disk_Unavailable: case Replica_Unavailable: updateOperationState(replica, RouterErrorCode.AmbryUnavailable); break; default: updateOperationState(replica, RouterErrorCode.UnexpectedInternalError); break; } if (serverErrorCode != ServerErrorCode.No_Error) { logger.trace("Replica {} returned an error {} for a delete request with response correlationId : {} ", replica.getDataNodeId(), serverErrorCode, correlationId); } } /** * Updates the state of the {@code DeleteOperation}. This includes two parts: 1) resolves the * {@link RouterErrorCode} depending on the precedence level of the new router error code from * {@code replica} and the current {@code resolvedRouterErrorCode}. An error code with a smaller * precedence level overrides an error code with a larger precedence level. 2) updates the * {@code DeleteOperation} based on the {@link RouterErrorCode}, and the source {@link ReplicaId} * for which the {@link RouterErrorCode} is generated. * @param replica The replica for which the RouterErrorCode was generated. * @param error {@link RouterErrorCode} that indicates the error for the replica. */ private void updateOperationState(ReplicaId replica, RouterErrorCode error) { if (resolvedRouterErrorCode == null) { resolvedRouterErrorCode = error; } else { if (getPrecedenceLevel(error) < getPrecedenceLevel(resolvedRouterErrorCode)) { resolvedRouterErrorCode = error; } } operationTracker.onResponse(replica, false); if (error != RouterErrorCode.BlobDeleted && error != RouterErrorCode.BlobExpired) { routerMetrics.routerRequestErrorCount.inc(); } routerMetrics.getDataNodeBasedMetrics(replica.getDataNodeId()).deleteRequestErrorCount.inc(); } /** * Completes the {@code DeleteOperation} if it is done. */ private void checkAndMaybeComplete() { // operationCompleted is true if Blob_Authorization_Failure was received. if (operationTracker.isDone() || operationCompleted == true) { if (!operationTracker.hasSucceeded()) { setOperationException( new RouterException("The DeleteOperation could not be completed.", resolvedRouterErrorCode)); } operationCompleted = true; } } /** * Gets the precedence level for a {@link RouterErrorCode}. A precedence level is a relative priority assigned * to a {@link RouterErrorCode}. If a {@link RouterErrorCode} has not been assigned a precedence level, a * {@code Integer.MIN_VALUE} will be returned. * @param routerErrorCode The {@link RouterErrorCode} for which to get its precedence level. * @return The precedence level of the {@link RouterErrorCode}. */ private Integer getPrecedenceLevel(RouterErrorCode routerErrorCode) { switch (routerErrorCode) { case BlobAuthorizationFailure: return 1; case BlobExpired: return 2; case AmbryUnavailable: return 3; case UnexpectedInternalError: return 4; case OperationTimedOut: return 5; case BlobDoesNotExist: return 6; default: return Integer.MIN_VALUE; } } /** * Returns whether the operation has completed. * @return whether the operation has completed. */ boolean isOperationComplete() { return operationCompleted; } /** * Gets {@link BlobId} of this {@code DeleteOperation}. * @return The {@link BlobId}. */ BlobId getBlobId() { return blobId; } /** * @return the service ID for the service requesting this delete operation. */ String getServiceId() { return serviceId; } /** * Get the {@link FutureResult} for this {@code DeleteOperation}. * @return The {@link FutureResult}. */ FutureResult<Void> getFutureResult() { return futureResult; } /** * Gets the {@link Callback} for this {@code DeleteOperation}. * @return The {@link Callback}. */ Callback<Void> getCallback() { return callback; } /** * Gets the exception associated with this operation if it failed; null otherwise. * @return exception associated with this operation if it failed; null otherwise. */ Exception getOperationException() { return operationException.get(); } /** * Gets the result for this {@code DeleteOperation}. In a {@link DeleteOperation}, nothing is returned * to the caller as a result of this operation. Including this {@link Void} result is for consistency * with other operations. * @return Void. */ Void getOperationResult() { return operationResult; } /** * Sets the exception associated with this operation. When this is called, the operation has failed. * @param exception the irrecoverable exception associated with this operation. */ void setOperationException(Exception exception) { operationException.set(exception); } long getSubmissionTimeMs() { return submissionTimeMs; } }
pnarayanan/ambry
ambry-router/src/main/java/com.github.ambry.router/DeleteOperation.java
Java
apache-2.0
18,606
# encoding: utf-8 require 'spec_helper' require 'yaml' require_relative '../../lib/cve-history' describe CVEHistory do let(:buildpack_cve) { { 'title' => 'some-title', 'description' => 'some-description', 'raw_description' => '' } } let(:cves_dir) { Dir.mktmpdir } let(:yaml_path) { 'ruby.yml' } before do allow(GitClient).to receive(:add_everything) allow(GitClient).to receive(:safe_commit) end describe '#read_yaml_cves' do subject { described_class } context 'CVE list exists' do context 'and is empty' do before do File.write(File.join(cves_dir, yaml_path), '') allow(YAML).to receive(:load_file).and_call_original end it 'loads the file and prints an empty array' do old_cves = subject.read_yaml_cves(cves_dir, yaml_path) expect(YAML).to have_received(:load_file) expect(old_cves).to eq [] end end context 'and is not empty' do let(:cve_list) { [buildpack_cve] } before do File.write(File.join(cves_dir, yaml_path), cve_list.to_yaml) allow(YAML).to receive(:load_file).and_call_original end it 'retrieves the contents of the file as a array' do old_cves = subject.read_yaml_cves(cves_dir, yaml_path) expect(YAML).to have_received(:load_file) expect(old_cves).to eq [buildpack_cve] end end end context 'CVE list does not exist' do it 'creates an empty YAML file' do old_cves = subject.read_yaml_cves(cves_dir, yaml_path) expect(File.exist? File.join(cves_dir, yaml_path)).to eq true expect(old_cves).to eq [] end end end describe '#write_yaml_cves' do let(:cve_list) { [buildpack_cve, 'quack'] } subject { described_class } context 'when the CVE list is an array' do before do File.write(File.join(cves_dir, yaml_path), cve_list.to_yaml) end it 'writes the contents to the correct YAML file' do subject.write_yaml_cves(cve_list, cves_dir, yaml_path) expect(YAML.load_file(File.join(cves_dir, yaml_path))).to eq cve_list end end context 'when cve_list is not an array' do it 'raises an error without attempting to write to the file' do expect { subject.write_yaml_cves('sandwich', cves_dir, yaml_path) }.to raise_error(RuntimeError) expect_any_instance_of(File).not_to receive(:write) end end context 'when the YAML file is not found' do it 'raises an error without attempting to write to the file' do expect { subject.write_yaml_cves([], cves_dir, yaml_path) }.to raise_error(RuntimeError) expect_any_instance_of(File).not_to receive(:write) end end end end
cloudfoundry/buildpacks-ci
spec/lib/cve-history_spec.rb
Ruby
apache-2.0
2,804
<?php namespace App\Http\Controllers; use App\Models\VrMenuTranslations; use Illuminate\Routing\Controller; class VrMenuTranslationsController extends Controller { /** * Display a listing of the resource. * GET /vrmenutranslations * * @return Response */ public function index() { // } /** * Show the form for creating a new resource. * GET /vrmenutranslations/create * * @return Response */ public function create() { // } /** * Store a newly created resource in storage. * POST /vrmenutranslations * * @return Response */ public function storeFromVrMenuController($data, $record) { } /** * Display the specified resource. * GET /vrmenutranslations/{id} * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * GET /vrmenutranslations/{id}/edit * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * PUT /vrmenutranslations/{id} * * @param int $id * @return Response */ public function updateFromVrMenuController($data, $id) { } /** * Remove the specified resource from storage. * DELETE /vrmenutranslations/{id} * * @param int $id * @return Response */ public function destroy($id) { // } }
makalaite/personal_vr.dev
app/Http/Controllers/VrMenuTranslationsController.php
PHP
apache-2.0
1,372
// Copyright 2020 The Oppia 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. /** * @fileoverview Backend api service for stats reporting. */ import { downgradeInjectable } from '@angular/upgrade/static'; import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { ContextService } from 'services/context.service'; import { ExplorationPlayerConstants } from 'pages/exploration-player-page/exploration-player-page.constants'; import { UrlInterpolationService } from 'domain/utilities/url-interpolation.service'; interface SessionStateStats { 'total_answers_count': number; 'useful_feedback_count': number; 'total_hit_count': number; 'first_hit_count': number; 'num_times_solution_viewed': number; 'num_completions': number; } export interface AggregatedStats { 'num_starts': number; 'num_completions': number; 'num_actual_starts': number; 'state_stats_mapping': { [stateName: string]: SessionStateStats }; } @Injectable({ providedIn: 'root' }) export class StatsReportingBackendApiService { constructor( private contextService: ContextService, private http: HttpClient, private urlInterpolationService: UrlInterpolationService) {} private getFullStatsUrl( urlIdentifier: string, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): string { try { return this.urlInterpolationService.interpolateUrl( ExplorationPlayerConstants.STATS_REPORTING_URLS[urlIdentifier], { exploration_id: explorationId }); } catch (e) { let additionalInfo = ( '\nUndefined exploration id error debug logs:' + '\nThe event being recorded: ' + urlIdentifier + '\nExploration ID: ' + this.contextService.getExplorationId() ); if (currentStateName) { additionalInfo += ( '\nCurrent State name: ' + currentStateName); } if (nextExpId) { additionalInfo += ( '\nRefresher exp id: ' + nextExpId); } if ( previousStateName && nextStateName) { additionalInfo += ( '\nOld State name: ' + previousStateName + '\nNew State name: ' + nextStateName); } e.message += additionalInfo; throw e; } } postsStats( aggregatedStats: AggregatedStats, expVersion: number, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'STATS_EVENTS', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { aggregated_stats: aggregatedStats, exp_version: expVersion }).toPromise(); } recordExpStarted( params: Object, sessionId: string, stateName: string, expVersion: number, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'EXPLORATION_STARTED', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { params: params, session_id: sessionId, state_name: stateName, version: expVersion }).toPromise(); } recordStateHit( clientTimeSpentInSecs: number, expVersion: number, newStateName: string, oldParams: Object, sessionId: string, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'STATE_HIT', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { client_time_spent_in_secs: clientTimeSpentInSecs, exploration_version: expVersion, new_state_name: newStateName, old_params: oldParams, session_id: sessionId, }).toPromise(); } recordExplorationActuallyStarted( expVersion: number, stateName: string, sessionId: string, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'EXPLORATION_ACTUALLY_STARTED', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { exploration_version: expVersion, state_name: stateName, session_id: sessionId }).toPromise(); } recordSolutionHit( timeSpentInStateSecs: number, expVersion: number, stateName: string, sessionId: string, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'SOLUTION_HIT', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { exploration_version: expVersion, state_name: stateName, session_id: sessionId, time_spent_in_state_secs: timeSpentInStateSecs }).toPromise(); } recordLeaveForRefresherExp( expVersion: number, refresherExpId: string, stateName: string, sessionId: string, timeSpentInStateSecs: number, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'LEAVE_FOR_REFRESHER_EXP', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { exploration_version: expVersion, refresher_exp_id: refresherExpId, state_name: stateName, session_id: sessionId, time_spent_in_state_secs: timeSpentInStateSecs }).toPromise(); } recordStateCompleted( expVersion: number, sessionId: string, stateName: string, timeSpentInStateSecs: number, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'STATE_COMPLETED', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { exp_version: expVersion, state_name: stateName, session_id: sessionId, time_spent_in_state_secs: timeSpentInStateSecs }).toPromise(); } recordExplorationCompleted( clientTimeSpentInSecs: number, collectionId: string, params: Object, sessionId: string, stateName: string, version: number, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'EXPLORATION_COMPLETED', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { client_time_spent_in_secs: clientTimeSpentInSecs, collection_id: collectionId, params: params, session_id: sessionId, state_name: stateName, version: version }).toPromise(); } recordAnswerSubmitted( answer: string, params: Object, version: number, sessionId: string, clientTimeSpentInSecs: number, oldStateName: string, answerGroupIndex: number, ruleSpecIndex: number, classificationCategorization: string, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'ANSWER_SUBMITTED', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { answer: answer, params: params, version: version, session_id: sessionId, client_time_spent_in_secs: clientTimeSpentInSecs, old_state_name: oldStateName, answer_group_index: answerGroupIndex, rule_spec_index: ruleSpecIndex, classification_categorization: classificationCategorization }).toPromise(); } recordMaybeLeaveEvent( clientTimeSpentInSecs: number, collectionId: string, params: Object, sessionId: string, stateName: string, version: number, explorationId: string, currentStateName: string, nextExpId: string, previousStateName: string, nextStateName: string): Promise<Object> { return this.http.post(this.getFullStatsUrl( 'EXPLORATION_MAYBE_LEFT', explorationId, currentStateName, nextExpId, previousStateName, nextStateName), { client_time_spent_in_secs: clientTimeSpentInSecs, collection_id: collectionId, params: params, session_id: sessionId, state_name: stateName, version: version }).toPromise(); } } angular.module('oppia').factory( 'StatsReportingBackendApiService', downgradeInjectable(StatsReportingBackendApiService));
prasanna08/oppia
core/templates/domain/exploration/stats-reporting-backend-api.service.ts
TypeScript
apache-2.0
9,465
/* * 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. */ package com.facebook.presto.operator; import com.facebook.airlift.stats.CounterStat; import com.facebook.presto.Session; import com.facebook.presto.memory.QueryContextVisitor; import com.facebook.presto.memory.context.AggregatedMemoryContext; import com.facebook.presto.memory.context.LocalMemoryContext; import com.facebook.presto.memory.context.MemoryTrackingContext; import com.facebook.presto.operator.OperationTimer.OperationTiming; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.plan.PlanNodeId; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import java.util.Optional; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import static com.facebook.presto.operator.BlockedReason.WAITING_FOR_MEMORY; import static com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static io.airlift.units.DataSize.succinctBytes; import static io.airlift.units.Duration.succinctNanos; import static java.lang.Math.max; import static java.lang.String.format; import static java.util.Objects.requireNonNull; /** * Only {@link #getOperatorStats()} and revocable-memory-related operations are ThreadSafe */ public class OperatorContext { private final int operatorId; private final PlanNodeId planNodeId; private final String operatorType; private final DriverContext driverContext; private final Executor executor; private final CounterStat rawInputDataSize = new CounterStat(); private final CounterStat rawInputPositions = new CounterStat(); private final OperationTiming addInputTiming = new OperationTiming(); private final CounterStat inputDataSize = new CounterStat(); private final CounterStat inputPositions = new CounterStat(); private final OperationTiming getOutputTiming = new OperationTiming(); private final CounterStat outputDataSize = new CounterStat(); private final CounterStat outputPositions = new CounterStat(); private final AtomicLong physicalWrittenDataSize = new AtomicLong(); private final AtomicReference<SettableFuture<?>> memoryFuture; private final AtomicReference<SettableFuture<?>> revocableMemoryFuture; private final AtomicReference<BlockedMonitor> blockedMonitor = new AtomicReference<>(); private final AtomicLong blockedWallNanos = new AtomicLong(); private final OperationTiming finishTiming = new OperationTiming(); private final OperatorSpillContext spillContext; private final AtomicReference<Supplier<OperatorInfo>> infoSupplier = new AtomicReference<>(); private final AtomicLong peakUserMemoryReservation = new AtomicLong(); private final AtomicLong peakSystemMemoryReservation = new AtomicLong(); private final AtomicLong peakTotalMemoryReservation = new AtomicLong(); @GuardedBy("this") private boolean memoryRevokingRequested; @Nullable @GuardedBy("this") private Runnable memoryRevocationRequestListener; private final MemoryTrackingContext operatorMemoryContext; public OperatorContext( int operatorId, PlanNodeId planNodeId, String operatorType, DriverContext driverContext, Executor executor, MemoryTrackingContext operatorMemoryContext) { checkArgument(operatorId >= 0, "operatorId is negative"); this.operatorId = operatorId; this.planNodeId = requireNonNull(planNodeId, "planNodeId is null"); this.operatorType = requireNonNull(operatorType, "operatorType is null"); this.driverContext = requireNonNull(driverContext, "driverContext is null"); this.spillContext = new OperatorSpillContext(this.driverContext); this.executor = requireNonNull(executor, "executor is null"); this.memoryFuture = new AtomicReference<>(SettableFuture.create()); this.memoryFuture.get().set(null); this.revocableMemoryFuture = new AtomicReference<>(SettableFuture.create()); this.revocableMemoryFuture.get().set(null); this.operatorMemoryContext = requireNonNull(operatorMemoryContext, "operatorMemoryContext is null"); operatorMemoryContext.initializeLocalMemoryContexts(operatorType); } public int getOperatorId() { return operatorId; } public String getOperatorType() { return operatorType; } public DriverContext getDriverContext() { return driverContext; } public Session getSession() { return driverContext.getSession(); } public boolean isDone() { return driverContext.isDone(); } void recordAddInput(OperationTimer operationTimer, Page page) { operationTimer.recordOperationComplete(addInputTiming); if (page != null) { inputDataSize.update(page.getSizeInBytes()); inputPositions.update(page.getPositionCount()); } } /** * Record the number of rows and amount of physical bytes that were read by an operator. * This metric is valid only for source operators. */ public void recordRawInput(long sizeInBytes, long positionCount) { rawInputDataSize.update(sizeInBytes); rawInputPositions.update(positionCount); } /** * Record the number of rows and amount of physical bytes that were read by an operator and * the time it took to read the data. This metric is valid only for source operators. */ public void recordRawInputWithTiming(long sizeInBytes, long positionCount, long readNanos) { rawInputDataSize.update(sizeInBytes); rawInputPositions.update(positionCount); addInputTiming.record(readNanos, 0, 0); } /** * Record the size in bytes of input blocks that were processed by an operator. * This metric is valid only for source operators. */ public void recordProcessedInput(long sizeInBytes, long positions) { inputDataSize.update(sizeInBytes); inputPositions.update(positions); } void recordGetOutput(OperationTimer operationTimer, Page page) { operationTimer.recordOperationComplete(getOutputTiming); if (page != null) { outputDataSize.update(page.getSizeInBytes()); outputPositions.update(page.getPositionCount()); } } public void recordOutput(long sizeInBytes, long positions) { outputDataSize.update(sizeInBytes); outputPositions.update(positions); } public void recordPhysicalWrittenData(long sizeInBytes) { physicalWrittenDataSize.getAndAdd(sizeInBytes); } public void recordBlocked(ListenableFuture<?> blocked) { requireNonNull(blocked, "blocked is null"); BlockedMonitor monitor = new BlockedMonitor(); BlockedMonitor oldMonitor = blockedMonitor.getAndSet(monitor); if (oldMonitor != null) { oldMonitor.run(); } blocked.addListener(monitor, executor); // Do not register blocked with driver context. The driver handles this directly. } void recordFinish(OperationTimer operationTimer) { operationTimer.recordOperationComplete(finishTiming); } public ListenableFuture<?> isWaitingForMemory() { return memoryFuture.get(); } public ListenableFuture<?> isWaitingForRevocableMemory() { return revocableMemoryFuture.get(); } // caller should close this context as it's a new context public LocalMemoryContext newLocalSystemMemoryContext(String allocationTag) { return new InternalLocalMemoryContext(operatorMemoryContext.newSystemMemoryContext(allocationTag), memoryFuture, this::updatePeakMemoryReservations, true); } // caller shouldn't close this context as it's managed by the OperatorContext public LocalMemoryContext localUserMemoryContext() { return new InternalLocalMemoryContext(operatorMemoryContext.localUserMemoryContext(), memoryFuture, this::updatePeakMemoryReservations, false); } // caller shouldn't close this context as it's managed by the OperatorContext public LocalMemoryContext localSystemMemoryContext() { return new InternalLocalMemoryContext(operatorMemoryContext.localSystemMemoryContext(), memoryFuture, this::updatePeakMemoryReservations, false); } // caller shouldn't close this context as it's managed by the OperatorContext public LocalMemoryContext localRevocableMemoryContext() { return new InternalLocalMemoryContext(operatorMemoryContext.localRevocableMemoryContext(), revocableMemoryFuture, () -> {}, false); } // caller shouldn't close this context as it's managed by the OperatorContext public AggregatedMemoryContext aggregateUserMemoryContext() { return new InternalAggregatedMemoryContext(operatorMemoryContext.aggregateUserMemoryContext(), memoryFuture, this::updatePeakMemoryReservations, false); } // caller should close this context as it's a new context public AggregatedMemoryContext newAggregateSystemMemoryContext() { return new InternalAggregatedMemoryContext(operatorMemoryContext.newAggregateSystemMemoryContext(), memoryFuture, this::updatePeakMemoryReservations, true); } // listen to all memory allocations and update the peak memory reservations accordingly private void updatePeakMemoryReservations() { long userMemory = operatorMemoryContext.getUserMemory(); long systemMemory = operatorMemoryContext.getSystemMemory(); long totalMemory = userMemory + systemMemory; peakUserMemoryReservation.accumulateAndGet(userMemory, Math::max); peakSystemMemoryReservation.accumulateAndGet(systemMemory, Math::max); peakTotalMemoryReservation.accumulateAndGet(totalMemory, Math::max); } public long getReservedRevocableBytes() { return operatorMemoryContext.getRevocableMemory(); } private static void updateMemoryFuture(ListenableFuture<?> memoryPoolFuture, AtomicReference<SettableFuture<?>> targetFutureReference) { if (!memoryPoolFuture.isDone()) { SettableFuture<?> currentMemoryFuture = targetFutureReference.get(); while (currentMemoryFuture.isDone()) { SettableFuture<?> settableFuture = SettableFuture.create(); // We can't replace one that's not done, because the task may be blocked on that future if (targetFutureReference.compareAndSet(currentMemoryFuture, settableFuture)) { currentMemoryFuture = settableFuture; } else { currentMemoryFuture = targetFutureReference.get(); } } SettableFuture<?> finalMemoryFuture = currentMemoryFuture; // Create a new future, so that this operator can un-block before the pool does, if it's moved to a new pool memoryPoolFuture.addListener(() -> finalMemoryFuture.set(null), directExecutor()); } } public void destroy() { // reset memory revocation listener so that OperatorContext doesn't hold any references to Driver instance synchronized (this) { memoryRevocationRequestListener = null; } operatorMemoryContext.close(); if (operatorMemoryContext.getSystemMemory() != 0) { throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Operator %s has non-zero system memory (%d bytes) after destroy()", this, operatorMemoryContext.getSystemMemory())); } if (operatorMemoryContext.getUserMemory() != 0) { throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Operator %s has non-zero user memory (%d bytes) after destroy()", this, operatorMemoryContext.getUserMemory())); } if (operatorMemoryContext.getRevocableMemory() != 0) { throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Operator %s has non-zero revocable memory (%d bytes) after destroy()", this, operatorMemoryContext.getRevocableMemory())); } } public SpillContext getSpillContext() { return spillContext; } public void moreMemoryAvailable() { memoryFuture.get().set(null); } public synchronized boolean isMemoryRevokingRequested() { return memoryRevokingRequested; } /** * Returns how much revocable memory will be revoked by the operator */ public long requestMemoryRevoking() { long revokedMemory = 0L; Runnable listener = null; synchronized (this) { if (!isMemoryRevokingRequested() && operatorMemoryContext.getRevocableMemory() > 0) { memoryRevokingRequested = true; revokedMemory = operatorMemoryContext.getRevocableMemory(); listener = memoryRevocationRequestListener; } } if (listener != null) { runListener(listener); } return revokedMemory; } public synchronized void resetMemoryRevokingRequested() { memoryRevokingRequested = false; } public void setMemoryRevocationRequestListener(Runnable listener) { requireNonNull(listener, "listener is null"); boolean shouldNotify; synchronized (this) { checkState(memoryRevocationRequestListener == null, "listener already set"); memoryRevocationRequestListener = listener; shouldNotify = memoryRevokingRequested; } // if memory revoking is requested immediately run the listener if (shouldNotify) { runListener(listener); } } private static void runListener(Runnable listener) { requireNonNull(listener, "listener is null"); try { listener.run(); } catch (RuntimeException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Exception while running the listener", e); } } public void setInfoSupplier(Supplier<OperatorInfo> infoSupplier) { requireNonNull(infoSupplier, "infoProvider is null"); this.infoSupplier.set(infoSupplier); } public CounterStat getInputDataSize() { return inputDataSize; } public CounterStat getInputPositions() { return inputPositions; } public CounterStat getOutputDataSize() { return outputDataSize; } public CounterStat getOutputPositions() { return outputPositions; } public long getPhysicalWrittenDataSize() { return physicalWrittenDataSize.get(); } @Override public String toString() { return format("%s-%s", operatorType, planNodeId); } public OperatorStats getOperatorStats() { Supplier<OperatorInfo> infoSupplier = this.infoSupplier.get(); OperatorInfo info = Optional.ofNullable(infoSupplier).map(Supplier::get).orElse(null); long inputPositionsCount = inputPositions.getTotalCount(); return new OperatorStats( driverContext.getTaskId().getStageExecutionId().getStageId().getId(), driverContext.getTaskId().getStageExecutionId().getId(), driverContext.getPipelineContext().getPipelineId(), operatorId, planNodeId, operatorType, 1, addInputTiming.getCalls(), succinctNanos(addInputTiming.getWallNanos()), succinctNanos(addInputTiming.getCpuNanos()), succinctBytes(addInputTiming.getAllocationBytes()), succinctBytes(rawInputDataSize.getTotalCount()), rawInputPositions.getTotalCount(), succinctBytes(inputDataSize.getTotalCount()), inputPositionsCount, (double) inputPositionsCount * inputPositionsCount, getOutputTiming.getCalls(), succinctNanos(getOutputTiming.getWallNanos()), succinctNanos(getOutputTiming.getCpuNanos()), succinctBytes(getOutputTiming.getAllocationBytes()), succinctBytes(outputDataSize.getTotalCount()), outputPositions.getTotalCount(), succinctBytes(physicalWrittenDataSize.get()), succinctNanos(blockedWallNanos.get()), finishTiming.getCalls(), succinctNanos(finishTiming.getWallNanos()), succinctNanos(finishTiming.getCpuNanos()), succinctBytes(finishTiming.getAllocationBytes()), succinctBytes(operatorMemoryContext.getUserMemory()), succinctBytes(getReservedRevocableBytes()), succinctBytes(operatorMemoryContext.getSystemMemory()), succinctBytes(peakUserMemoryReservation.get()), succinctBytes(peakSystemMemoryReservation.get()), succinctBytes(peakTotalMemoryReservation.get()), succinctBytes(spillContext.getSpilledBytes()), memoryFuture.get().isDone() ? Optional.empty() : Optional.of(WAITING_FOR_MEMORY), info); } public <C, R> R accept(QueryContextVisitor<C, R> visitor, C context) { return visitor.visitOperatorContext(this, context); } private static long nanosBetween(long start, long end) { return max(0, end - start); } private class BlockedMonitor implements Runnable { private final long start = System.nanoTime(); private boolean finished; @Override public synchronized void run() { if (finished) { return; } finished = true; blockedMonitor.compareAndSet(this, null); blockedWallNanos.getAndAdd(getBlockedTime()); } public long getBlockedTime() { return nanosBetween(start, System.nanoTime()); } } @ThreadSafe private static class OperatorSpillContext implements SpillContext { private final DriverContext driverContext; private final AtomicLong reservedBytes = new AtomicLong(); private final AtomicLong spilledBytes = new AtomicLong(); public OperatorSpillContext(DriverContext driverContext) { this.driverContext = driverContext; } @Override public void updateBytes(long bytes) { if (bytes >= 0) { reservedBytes.addAndGet(bytes); driverContext.reserveSpill(bytes); spilledBytes.addAndGet(bytes); } else { reservedBytes.accumulateAndGet(-bytes, this::decrementSpilledReservation); driverContext.freeSpill(-bytes); } } public long getSpilledBytes() { return spilledBytes.longValue(); } private long decrementSpilledReservation(long reservedBytes, long bytesBeingFreed) { checkArgument(bytesBeingFreed >= 0); checkArgument(bytesBeingFreed <= reservedBytes, "tried to free %s spilled bytes from %s bytes reserved", bytesBeingFreed, reservedBytes); return reservedBytes - bytesBeingFreed; } @Override public void close() { // Only products of SpillContext.newLocalSpillContext() should be closed. throw new UnsupportedOperationException(format("%s should not be closed directly", getClass())); } @Override public String toString() { return toStringHelper(this) .add("usedBytes", reservedBytes.get()) .toString(); } } private static class InternalLocalMemoryContext implements LocalMemoryContext { private final LocalMemoryContext delegate; private final AtomicReference<SettableFuture<?>> memoryFuture; private final Runnable allocationListener; private final boolean closeable; InternalLocalMemoryContext(LocalMemoryContext delegate, AtomicReference<SettableFuture<?>> memoryFuture, Runnable allocationListener, boolean closeable) { this.delegate = requireNonNull(delegate, "delegate is null"); this.memoryFuture = requireNonNull(memoryFuture, "memoryFuture is null"); this.allocationListener = requireNonNull(allocationListener, "allocationListener is null"); this.closeable = closeable; } @Override public long getBytes() { return delegate.getBytes(); } @Override public ListenableFuture<?> setBytes(long bytes) { ListenableFuture<?> blocked = delegate.setBytes(bytes); updateMemoryFuture(blocked, memoryFuture); allocationListener.run(); return blocked; } @Override public boolean trySetBytes(long bytes) { if (delegate.trySetBytes(bytes)) { allocationListener.run(); return true; } return false; } @Override public void close() { if (!closeable) { throw new UnsupportedOperationException("Called close on unclosable local memory context"); } delegate.close(); } } private static class InternalAggregatedMemoryContext implements AggregatedMemoryContext { private final AggregatedMemoryContext delegate; private final AtomicReference<SettableFuture<?>> memoryFuture; private final Runnable allocationListener; private final boolean closeable; InternalAggregatedMemoryContext(AggregatedMemoryContext delegate, AtomicReference<SettableFuture<?>> memoryFuture, Runnable allocationListener, boolean closeable) { this.delegate = requireNonNull(delegate, "delegate is null"); this.memoryFuture = requireNonNull(memoryFuture, "memoryFuture is null"); this.allocationListener = requireNonNull(allocationListener, "allocationListener is null"); this.closeable = closeable; } @Override public AggregatedMemoryContext newAggregatedMemoryContext() { return delegate.newAggregatedMemoryContext(); } @Override public LocalMemoryContext newLocalMemoryContext(String allocationTag) { return new InternalLocalMemoryContext(delegate.newLocalMemoryContext(allocationTag), memoryFuture, allocationListener, true); } @Override public long getBytes() { return delegate.getBytes(); } @Override public void close() { if (!closeable) { throw new UnsupportedOperationException("Called close on unclosable aggregated memory context"); } delegate.close(); allocationListener.run(); } } @VisibleForTesting public MemoryTrackingContext getOperatorMemoryContext() { return operatorMemoryContext; } }
ptkool/presto
presto-main/src/main/java/com/facebook/presto/operator/OperatorContext.java
Java
apache-2.0
24,618
package main // Config reflects configuration options for metis-cli type Config struct { ActiveCluster string // Name of the current active Metis Cluster, if any Clusters map[string]string // Set to string (cluster name) and value being cluster address Key string } // PuppetAPIRequest reflects the puppeteering APIRequest type PuppetAPIRequest struct { Key string Action string Content string } // PuppetCacheResponse reflects what would be provided when returning the NodeList during caching type PuppetCacheResponse struct { Content map[string]interface{} } // PuppetStatusResponse reflects what would be provided when returning the status of the Cluster type PuppetStatusResponse struct { Content string }
StroblIndustries/metis-cli
src/go/structs.go
GO
apache-2.0
753
import { UNDEFINED } from "../types/primitive-type"; export default function* ExpressionStatement (node, context, next) { let executionResult = yield next(node.expression, context); let executionValue = executionResult && executionResult.result && executionResult.result.getValue(); return context.result(executionValue || UNDEFINED); }
jrsearles/SandBoxr
src/visitors/expression-statement.js
JavaScript
apache-2.0
344
/** * Copyright 2011-2021 Asakusa Framework Team. * * 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. */ package com.asakusafw.runtime.util; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.junit.Test; /** * Test for {@link BasicByteArrayComparator}. */ public class BasicByteArrayComparatorTest { private static final ByteArrayComparator CMP = new BasicByteArrayComparator(); /** * eq - simple case. */ @Test public void eq() { assertThat(CMP.equals(array(1), 0, 1, array(1), 0, 1), is(true)); assertThat(CMP.equals(array(1), 0, 1, array(2), 0, 1), is(false)); assertThat(CMP.equals(array(1, 2), 0, 1, array(1, 3), 0, 1), is(true)); assertThat(CMP.equals(array(1, 2), 1, 1, array(1, 3), 1, 1), is(false)); assertThat(CMP.equals(array(1, 2), 0, 1, array(1, 2), 0, 2), is(false)); } /** * eq - word. */ @Test public void eq_word() { assertThat(CMP.equals( array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8, array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8), is(true)); assertThat(CMP.equals( array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8, array(0, 1, 2, 3, 4, 5, 6, 7, 8, 0), 1, 8), is(true)); assertThat(CMP.equals( array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8, array(1, 2, 3, 4, 5, 6, 7, 0), 0, 8), is(false)); } /** * eq - double words. */ @Test public void eq_double_word() { assertThat(CMP.equals( array(1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1), 0, 16, array(1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1), 0, 16), is(true)); assertThat(CMP.equals( array(1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1), 0, 16, array(1, 2, 3, 4, 5, 6, 7, 8, 9, 7, 6, 5, 4, 3, 2, 1), 0, 16), is(false)); } /** * eq - word + bytes. */ @Test public void eq_word_rest() { assertThat(CMP.equals( array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0), 0, 10, array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0), 0, 10), is(true)); assertThat(CMP.equals( array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0), 0, 10, array(1, 2, 3, 4, 5, 6, 7, 8, 9, 1), 0, 10), is(false)); } /** * cmp - simple case. */ @Test public void cmp() { assertThat(CMP.compare(array(1), 0, 1, array(1), 0, 1), is(equalTo(0))); assertThat(CMP.compare(array(1), 0, 1, array(2), 0, 1), is(lessThan(0))); assertThat(CMP.compare(array(1), 0, 1, array(0), 0, 1), is(greaterThan(0))); assertThat(CMP.compare(array(1), 0, 1, array(0xff), 0, 1), is(lessThan(0))); assertThat(CMP.compare(array(1, 2), 0, 1, array(1, 3), 0, 1), is(equalTo(0))); assertThat(CMP.compare(array(1, 2), 1, 1, array(1, 3), 1, 1), is(lessThan(0))); assertThat(CMP.compare(array(1, 2), 1, 1, array(1, 1), 1, 1), is(greaterThan(0))); assertThat(CMP.compare(array(1, 2), 0, 2, array(1, 2, 0), 0, 3), is(lessThan(0))); assertThat(CMP.compare(array(1, 2, 0), 0, 3, array(1, 2), 0, 2), is(greaterThan(0))); } /** * cmp - word. */ @Test public void cmp_word() { assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8, array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8), is(equalTo(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8, array(0, 1, 2, 3, 4, 5, 6, 7, 8, 0), 1, 8), is(equalTo(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8, array(1, 2, 3, 4, 5, 6, 7, 0), 0, 8), is(greaterThan(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 0), 0, 8, array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8), is(lessThan(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8, array(1, 2, 3, 4, 5, 6, 7, 0xff), 0, 8), is(lessThan(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 0xff), 0, 8, array(1, 2, 3, 4, 5, 6, 7, 8), 0, 8), is(greaterThan(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 0), 0, 8, array(0, 2, 3, 4, 5, 6, 7, 8), 0, 8), is(greaterThan(0))); assertThat(CMP.compare( array(0, 2, 3, 4, 5, 6, 7, 8), 0, 8, array(1, 2, 3, 4, 5, 6, 7, 0), 0, 8), is(lessThan(0))); } /** * cmp - word rest. */ @Test public void cmp_rest() { assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8, 0, 1), 0, 10, array(1, 2, 3, 4, 5, 6, 7, 8, 0, 1), 0, 10), is(equalTo(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8, 0, 1), 0, 10, array(0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 0), 1, 10), is(equalTo(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8, 0, 1), 0, 10, array(1, 2, 3, 4, 5, 6, 7, 8, 0, 2), 0, 10), is(lessThan(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8, 0, 2), 0, 10, array(1, 2, 3, 4, 5, 6, 7, 8, 0, 1), 0, 10), is(greaterThan(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8, 0, 1), 0, 10, array(1, 2, 3, 4, 5, 6, 7, 8, 0, 0xff), 0, 10), is(lessThan(0))); assertThat(CMP.compare( array(1, 2, 3, 4, 5, 6, 7, 8, 0, 0xff), 0, 10, array(1, 2, 3, 4, 5, 6, 7, 8, 0, 1), 0, 10), is(greaterThan(0))); } private byte[] array(int... bytes) { byte[] results = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { results[i] = (byte) bytes[i]; } return results; } }
asakusafw/asakusafw
core-project/asakusa-runtime/src/test/java/com/asakusafw/runtime/util/BasicByteArrayComparatorTest.java
Java
apache-2.0
6,429
<!-- Copyright © 2015 Cask Data, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <div class="side-panel top text-center"> <div class="row nomargin"> <div class="col-xs-12 col-sm-6 text-left nopadding"> <div class="hydrator-metadata" ng-class="{'expanded': TopPanelController.metadataExpanded}"> <div ng-click="TopPanelController.openMetadata()" class="clearfix"> <div class="pipeline-type"> <span ng-if="TopPanelController.state.artifact.name === TopPanelController.GLOBALS.etlBatch" uib-tooltip="Type: Batch" tooltip-placement="right" tooltip-class="toppanel-tooltip icon-tooltip" class="icon-ETLBatch"></span> <span ng-if="TopPanelController.state.artifact.name === TopPanelController.GLOBALS.etlRealtime" uib-tooltip="Type: Realtime" tooltip-placement="right" tooltip-class="toppanel-tooltip icon-tooltip" class="icon-ETLRealtime"></span> </div> <div class="pipeline-name pull-left"> <div ng-class="{'placeholder': !TopPanelController.state.metadata.name.length}" ng-if="!TopPanelController.metadataExpanded" ng-bind="TopPanelController.state.metadata['name'] | myEllipsis: 28" uib-tooltip="{{ TopPanelController.state.metadata.name }}" tooltip-placement="right" tooltip-enable="TopPanelController.state.metadata.name.length > 27" tooltip-class="toppanel-tooltip"></div> <input type="text" ng-if="TopPanelController.metadataExpanded" ng-model="TopPanelController.state.metadata['name']" my-maxlength="64" placeholder="Name your pipeline" ng-keyup="TopPanelController.onEnterOnMetadata($event)" /> <div ng-class="{'placeholder': !TopPanelController.state.metadata['description'].length}" ng-if="!TopPanelController.metadataExpanded" ng-bind="TopPanelController.parsedDescription | myEllipsis: 65" uib-tooltip-html="TopPanelController.tooltipDescription" tooltip-placement="right" tooltip-enable="TopPanelController.tooltipDescription.length > 64" tooltip-class="toppanel-tooltip" ng-if="!TopPanelController.metadataExpanded" tooltip-append-to-body="true"></div> <textarea ng-model="TopPanelController.state.metadata['description']" placeholder="Enter a description for your pipeline." ng-if="TopPanelController.metadataExpanded"></textarea> </div> </div> <div class="btn-group pull-right"> <button type="button" class="btn btn-default" ng-click="TopPanelController.resetMetadata()">Cancel</button> <button type="button" class="btn btn-success" ng-click="TopPanelController.saveMetadata()">Save</button> </div> </div> </div> <div class="col-sm-3 col-sm-offset-3 text-right nopadding"> <div class="btn-group action-buttons"> <div class="btn" ng-repeat="action in TopPanelController.canvasOperations" ng-click="action.fn()" uib-tooltip="{{action.name}}" tooltip-placement="bottom" tooltip-append-to-body="true" tooltip-class="toppanel-tooltip"> <span class="fa {{action.icon}}"></span> </div> </div> </div> </div> </div>
chtyim/cdap
cdap-ui/app/features/hydrator/templates/create/toppanel.html
HTML
apache-2.0
4,159
# Cleistothelebolus Malloch & Cain GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Can. J. Bot. 49(6): 851 (1971) #### Original name Cleistothelebolus Malloch & Cain ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Cleistothelebolus/README.md
Markdown
apache-2.0
242
package com.example.android.sunshine.app.wear; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.example.android.sunshine.app.sync.SunshineSyncAdapter; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataItem; import com.google.android.gms.wearable.Wearable; import com.google.android.gms.wearable.WearableListenerService; /* Listens for weather data request from wear device. Has sync adapter send data if received. */ public class WeatherListenerService extends WearableListenerService implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks { private static final String TAG = WeatherListenerService.class.getSimpleName(); private GoogleApiClient mGoogleApiClient; @Override public void onCreate() { super.onCreate(); if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Wearable.API) .build(); } mGoogleApiClient.connect(); } @Override public void onDataChanged(DataEventBuffer dataEvents) { for (DataEvent dataEvent : dataEvents) { if (dataEvent.getType() != DataEvent.TYPE_CHANGED) { continue; } DataItem dataItem = dataEvent.getDataItem(); if (dataItem.getUri().getPath().equals(WeatherConstants.PATH_WEATHER_DATA_REQUEST)) { SunshineSyncAdapter.syncImmediately(getApplicationContext()); } } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.d(TAG, "onConnectionFailed"); } @Override public void onConnected(@Nullable Bundle bundle) { Log.d(TAG, "onConnected"); } @Override public void onConnectionSuspended(int i) { Log.d(TAG, "onConnectionSuspended"); } }
debun8/SunshineWear
app/src/main/java/com/example/android/sunshine/app/wear/WeatherListenerService.java
Java
apache-2.0
2,316
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import sdsnansumpw = require( './index' ); // TESTS // // The function returns a number... { const x = new Float32Array( 10 ); sdsnansumpw( x.length, x, 1 ); // $ExpectType number } // The compiler throws an error if the function is provided a first argument which is not a number... { const x = new Float32Array( 10 ); sdsnansumpw( '10', x, 1 ); // $ExpectError sdsnansumpw( true, x, 1 ); // $ExpectError sdsnansumpw( false, x, 1 ); // $ExpectError sdsnansumpw( null, x, 1 ); // $ExpectError sdsnansumpw( undefined, x, 1 ); // $ExpectError sdsnansumpw( [], x, 1 ); // $ExpectError sdsnansumpw( {}, x, 1 ); // $ExpectError sdsnansumpw( ( x: number ): number => x, x, 1 ); // $ExpectError } // The compiler throws an error if the function is provided a second argument which is not a Float32Array... { const x = new Float32Array( 10 ); sdsnansumpw( x.length, 10, 1 ); // $ExpectError sdsnansumpw( x.length, '10', 1 ); // $ExpectError sdsnansumpw( x.length, true, 1 ); // $ExpectError sdsnansumpw( x.length, false, 1 ); // $ExpectError sdsnansumpw( x.length, null, 1 ); // $ExpectError sdsnansumpw( x.length, undefined, 1 ); // $ExpectError sdsnansumpw( x.length, [], 1 ); // $ExpectError sdsnansumpw( x.length, {}, 1 ); // $ExpectError sdsnansumpw( x.length, ( x: number ): number => x, 1 ); // $ExpectError } // The compiler throws an error if the function is provided a third argument which is not a number... { const x = new Float32Array( 10 ); sdsnansumpw( x.length, x, '10' ); // $ExpectError sdsnansumpw( x.length, x, true ); // $ExpectError sdsnansumpw( x.length, x, false ); // $ExpectError sdsnansumpw( x.length, x, null ); // $ExpectError sdsnansumpw( x.length, x, undefined ); // $ExpectError sdsnansumpw( x.length, x, [] ); // $ExpectError sdsnansumpw( x.length, x, {} ); // $ExpectError sdsnansumpw( x.length, x, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an unsupported number of arguments... { const x = new Float32Array( 10 ); sdsnansumpw(); // $ExpectError sdsnansumpw( x.length ); // $ExpectError sdsnansumpw( x.length, x ); // $ExpectError sdsnansumpw( x.length, x, 1, 10 ); // $ExpectError } // Attached to main export is an `ndarray` method which returns a number... { const x = new Float32Array( 10 ); sdsnansumpw.ndarray( x.length, x, 1, 0 ); // $ExpectType number } // The compiler throws an error if the `ndarray` method is provided a first argument which is not a number... { const x = new Float32Array( 10 ); sdsnansumpw.ndarray( '10', x, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( true, x, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( false, x, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( null, x, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( undefined, x, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( [], x, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( {}, x, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( ( x: number ): number => x, x, 1, 0 ); // $ExpectError } // The compiler throws an error if the `ndarray` method is provided a second argument which is not a Float32Array... { const x = new Float32Array( 10 ); sdsnansumpw.ndarray( x.length, 10, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, '10', 1, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, true, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, false, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, null, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, undefined, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, [], 1, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, {}, 1, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, ( x: number ): number => x, 1, 0 ); // $ExpectError } // The compiler throws an error if the `ndarray` method is provided a third argument which is not a number... { const x = new Float32Array( 10 ); sdsnansumpw.ndarray( x.length, x, '10', 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, x, true, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, x, false, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, x, null, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, x, undefined, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, x, [], 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, x, {}, 0 ); // $ExpectError sdsnansumpw.ndarray( x.length, x, ( x: number ): number => x, 0 ); // $ExpectError } // The compiler throws an error if the `ndarray` method is provided a fourth argument which is not a number... { const x = new Float32Array( 10 ); sdsnansumpw.ndarray( x.length, x, 1, '10' ); // $ExpectError sdsnansumpw.ndarray( x.length, x, 1, true ); // $ExpectError sdsnansumpw.ndarray( x.length, x, 1, false ); // $ExpectError sdsnansumpw.ndarray( x.length, x, 1, null ); // $ExpectError sdsnansumpw.ndarray( x.length, x, 1, undefined ); // $ExpectError sdsnansumpw.ndarray( x.length, x, 1, [] ); // $ExpectError sdsnansumpw.ndarray( x.length, x, 1, {} ); // $ExpectError sdsnansumpw.ndarray( x.length, x, 1, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the `ndarray` method is provided an unsupported number of arguments... { const x = new Float32Array( 10 ); sdsnansumpw.ndarray(); // $ExpectError sdsnansumpw.ndarray( x.length ); // $ExpectError sdsnansumpw.ndarray( x.length, x ); // $ExpectError sdsnansumpw.ndarray( x.length, x, 1 ); // $ExpectError sdsnansumpw.ndarray( x.length, x, 1, 0, 10 ); // $ExpectError }
stdlib-js/stdlib
lib/node_modules/@stdlib/blas/ext/base/sdsnansumpw/docs/types/test.ts
TypeScript
apache-2.0
6,127
/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * 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. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import static java.lang.String.valueOf; import static org.mvel2.util.ParseTools.subset; public class EvalNode extends Node { public EvalNode() { } public EvalNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); } public EvalNode(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { appender.append(String.valueOf(TemplateRuntime.eval(valueOf(MVEL.eval(contents, ctx, factory)), ctx, factory))); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } public String toString() { return "EvalNode:" + name + "{" + (contents == null ? "" : new String(contents)) + "} (start=" + begin + ";end=" + end + ")"; } }
codehaus/mvel
src/main/java/org/mvel2/templates/res/EvalNode.java
Java
apache-2.0
2,181
delete from ps_VCHR_PYMT_STG where BUSINESS_UNIT='FED01' and VCHR_BLD_KEY_C1 in (select VCHR_BLD_KEY_C1 from ps_VCHR_HDR_STG where VCHR_SRC='XLS'); delete from ps_VCHR_DIST_STG where BUSINESS_UNIT='FED01' and VCHR_BLD_KEY_C1 in (select VCHR_BLD_KEY_C1 from ps_VCHR_HDR_STG where VCHR_SRC='XLS'); delete from ps_VCHR_LINE_STG where BUSINESS_UNIT='FED01' and VCHR_BLD_KEY_C1 in (select VCHR_BLD_KEY_C1 from ps_VCHR_HDR_STG where VCHR_SRC='XLS'); delete from ps_VCHR_HDR_STG where BUSINESS_UNIT='FED01' and VCHR_SRC='XLS'; INSERT INTO PS_VCHR_HDR_STG ( BUSINESS_UNIT, VCHR_BLD_KEY_C1, VCHR_BLD_KEY_C2, VCHR_BLD_KEY_N1, VCHR_BLD_KEY_N2, VOUCHER_ID, LEASE_PYMNT_DT, VOUCHER_STYLE, INVOICE_ID, INVOICE_DT, VENDOR_SETID, VENDOR_ID, VNDR_LOC, ADDRESS_SEQ_NUM, GRP_AP_ID, ORIGIN, OPRID, ACCOUNTING_DT, POST_VOUCHER, DST_CNTRL_ID, VOUCHER_ID_RELATED, GROSS_AMT, DSCNT_AMT, TAX_EXEMPT, SALETX_AMT, FREIGHT_AMT, MISC_AMT, PYMNT_TERMS_CD, ENTERED_DT, TXN_CURRENCY_CD, RT_TYPE, RATE_MULT, RATE_DIV, VAT_ENTRD_AMT, MATCH_ACTION, CUR_RT_SOURCE, DSCNT_AMT_FLG, DUE_DT_FLG, VCHR_APPRVL_FLG, BUSPROCNAME, APPR_RULE_SET, VAT_DCLRTN_POINT, VAT_CALC_TYPE, VAT_CALC_GROSS_NET, VAT_RECALC_FLG, VAT_CALC_FRGHT_FLG, VAT_TREATMENT_GRP, COUNTRY_SHIP_FROM, STATE_SHIP_FROM, COUNTRY_SHIP_TO, STATE_SHIP_TO, COUNTRY_VAT_BILLFR, COUNTRY_VAT_BILLTO, VAT_EXCPTN_CERTIF, VAT_ROUND_RULE, COUNTRY_LOC_SELLER, STATE_LOC_SELLER, COUNTRY_LOC_BUYER, STATE_LOC_BUYER, COUNTRY_VAT_SUPPLY, STATE_VAT_SUPPLY, COUNTRY_VAT_PERFRM, STATE_VAT_PERFRM, STATE_VAT_DEFAULT, PREPAID_REF, PREPAID_AUTO_APPLY, DESCR254_MIXED, EIN_FEDERAL, EIN_STATE_LOCAL, PROCESS_INSTANCE, IN_PROCESS_FLG, BUSINESS_UNIT_PO, PO_ID, PACKSLIP_NO, PAY_TRM_BSE_DT_OPT, VAT_CALC_MISC_FLG, IMAGE_REF_ID, IMAGE_DATE, PAY_SCHEDULE_TYPE, TAX_GRP, TAX_PYMNT_TYPE, INSPECT_DT, INV_RECPT_DT, RECEIPT_DT, BILL_OF_LADING, CARRIER_ID, DOC_TYPE, DSCNT_DUE_DT, DSCNT_PRORATE_FLG, DUE_DT, ECQUEUEINSTANCE, ECTRANSID, FRGHT_CHARGE_CODE, LC_ID, MISC_CHARGE_CODE, REMIT_ADDR_SEQ_NUM, SALETX_CHARGE_CODE, VCHR_BLD_CODE, BUSINESS_UNIT_AR, CUST_ID, ITEM, ITEM_LINE, ERS_INV_SEQ, LS_KEY, VCHR_SRC, VAT_EXCPTN_TYPE, TERMS_BASIS_DT, BUSINESS_UNIT_AM, ASSET_ID, LEASE_ID, CLAIM_NO, POLICY_NUM, ENDORSER_PARTY, BUSINESS_UNIT_BI, BI_INVOICE, USER_VCHR_CHAR1, USER_VCHR_CHAR2, USER_VCHR_DEC, USER_VCHR_DATE, USER_VCHR_NUM1, USER_HDR_CHAR1, CUSTOM_C100_A1, CUSTOM_C100_A2, CUSTOM_C100_A3, CUSTOM_C100_A4, CUSTOM_DATE_A, CUSTOM_C1_A, VAT_NRCVR_CHRG_CD, VAT_CF_ANLSYS_TYPE) VALUES ( 'FED01', '%vchrBldKeyC1%', ' ', 0, 0, 'NEXT', null, 'REG', '%invoiceNumber%', to_date('%T%', '%dateFormat%'), ' ', 'USA0000002', ' ', 0, ' ', ' ', ' ', null, ' ', ' ', ' ', 1000, 0, ' ', 0, 0, 0, ' ', null, ' ', ' ', 0, 0, 0, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '123456789A', ' ', ' ', 0, ' ', ' ', ' ', ' ', ' ', ' ', ' ', null, ' ', ' ', ' ', null, null, null, ' ', ' ', ' ', null, ' ', null, 0, ' ', ' ', ' ', ' ', 0, ' ', ' ', ' ', ' ', ' ', 0, 0, 0, 'XLS', ' ', null, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 0, null, 0, ' ', ' ', ' ', ' ', ' ', null, ' ', ' ', ' '); INSERT INTO PS_VCHR_LINE_STG ( BUSINESS_UNIT, VCHR_BLD_KEY_C1, VCHR_BLD_KEY_C2, VCHR_BLD_KEY_N1, VCHR_BLD_KEY_N2, VOUCHER_ID, LEASE_PYMNT_DT, VOUCHER_LINE_NUM, BUSINESS_UNIT_PO, PO_ID, LINE_NBR, SCHED_NBR, DESCR, MERCHANDISE_AMT, ITM_SETID, INV_ITEM_ID, QTY_VCHR, STATISTIC_AMOUNT, UNIT_OF_MEASURE, UNIT_PRICE, DSCNT_APPL_FLG, TAX_CD_VAT, BUSINESS_UNIT_RECV, RECEIVER_ID, RECV_LN_NBR, RECV_SHIP_SEQ_NBR, MATCH_LINE_OPT, DISTRIB_MTHD_FLG, SHIPTO_ID, SUT_BASE_ID, TAX_CD_SUT, ULTIMATE_USE_CD, SUT_EXCPTN_TYPE, SUT_EXCPTN_CERTIF, SUT_APPLICABILITY, VAT_APPLICABILITY, VAT_TXN_TYPE_CD, VAT_USE_ID, ADDR_SEQ_NUM_SHIP, BUS_UNIT_RELATED, VOUCHER_ID_RELATED, VENDOR_ID, VNDR_LOC, DESCR254_MIXED, SPEEDCHART_KEY, BUSINESS_UNIT_GL, ACCOUNT, ALTACCT, OPERATING_UNIT, PRODUCT, FUND_CODE, CLASS_FLD, PROGRAM_CODE, BUDGET_REF, AFFILIATE, AFFILIATE_INTRA1, AFFILIATE_INTRA2, CHARTFIELD1, CHARTFIELD2, CHARTFIELD3, DEPTID, PROJECT_ID, BUSINESS_UNIT_PC, ACTIVITY_ID, ANALYSIS_TYPE, RESOURCE_TYPE, RESOURCE_CATEGORY, RESOURCE_SUB_CAT, ECQUEUEINSTANCE, ECTRANSID, TAX_DSCNT_FLG, TAX_FRGHT_FLG, TAX_MISC_FLG, TAX_VAT_FLG, PHYSICAL_NATURE, VAT_RCRD_INPT_FLG, VAT_RCRD_OUTPT_FLG, VAT_TREATMENT, VAT_SVC_SUPPLY_FLG, VAT_SERVICE_TYPE, COUNTRY_LOC_BUYER, STATE_LOC_BUYER, COUNTRY_LOC_SELLER, STATE_LOC_SELLER, COUNTRY_VAT_SUPPLY, STATE_VAT_SUPPLY, COUNTRY_VAT_PERFRM, STATE_VAT_PERFRM, STATE_SHIP_FROM, STATE_VAT_DEFAULT, REQUESTOR_ID, VAT_ENTRD_AMT, VAT_RECEIPT, VAT_RGSTRN_SELLER, IST_TXN_FLG, TRANS_DT, WTHD_SW, WTHD_CD, MFG_ID, USER_VCHR_CHAR1, USER_VCHR_CHAR2, USER_VCHR_DEC, USER_VCHR_DATE, USER_VCHR_NUM1, USER_LINE_CHAR1, CUSTOM_C100_B1, CUSTOM_C100_B2, CUSTOM_C100_B3, CUSTOM_C100_B4, CUSTOM_DATE_B, CUSTOM_C1_B, USER_SCHED_CHAR1, CUSTOM_C100_C1, CUSTOM_C100_C2, CUSTOM_C100_C3, CUSTOM_DATE_C1, CUSTOM_DATE_C2, CUSTOM_C1_C, VAT_RVRSE_CHG_GDS, PACKSLIP_NO, BUSINESS_UNIT_BI, BI_INVOICE, LINE_SEQ_NUM, CATEGORY_ID) VALUES ( 'FED01', '%vchrBldKeyC1%', ' ', 0, 0, 'NEXT', null, 1, ' ', ' ', 0, 0, ' ', 1000, ' ', ' ', 0, 0, ' ', 0, ' ', ' ', ' ', ' ', 0, 0, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'N', ' ', ' ', 0, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 0, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 0, ' ', ' ', ' ', null, ' ', ' ', ' ', ' ', ' ', 0, null, 0, ' ', ' ', ' ', ' ', ' ', null, ' ', ' ', ' ', '00007', ' ', null, null, ' ', ' ', ' ', ' ', ' ', 0, ' '); INSERT INTO PS_VCHR_DIST_STG ( BUSINESS_UNIT, VCHR_BLD_KEY_C1, VCHR_BLD_KEY_C2, VCHR_BLD_KEY_N1, VCHR_BLD_KEY_N2, VOUCHER_ID, LEASE_PYMNT_DT, VOUCHER_LINE_NUM, DISTRIB_LINE_NUM, BUSINESS_UNIT_GL, ACCOUNT, ALTACCT, DEPTID, STATISTICS_CODE, STATISTIC_AMOUNT, QTY_VCHR, DESCR, MERCHANDISE_AMT, BUSINESS_UNIT_PO, PO_ID, LINE_NBR, SCHED_NBR, PO_DIST_LINE_NUM, BUSINESS_UNIT_PC, ACTIVITY_ID, ANALYSIS_TYPE, RESOURCE_TYPE, RESOURCE_CATEGORY, RESOURCE_SUB_CAT, ASSET_FLG, BUSINESS_UNIT_AM, ASSET_ID, PROFILE_ID, COST_TYPE, VAT_TXN_TYPE_CD, BUSINESS_UNIT_RECV, RECEIVER_ID, RECV_LN_NBR, RECV_SHIP_SEQ_NBR, RECV_DIST_LINE_NUM, OPERATING_UNIT, PRODUCT, FUND_CODE, CLASS_FLD, PROGRAM_CODE, BUDGET_REF, AFFILIATE, AFFILIATE_INTRA1, AFFILIATE_INTRA2, CHARTFIELD1, CHARTFIELD2, CHARTFIELD3, PROJECT_ID, BUDGET_DT, ENTRY_EVENT, ECQUEUEINSTANCE, ECTRANSID, JRNL_LN_REF, VAT_APORT_CNTRL, USER_VCHR_CHAR1, USER_VCHR_CHAR2, USER_VCHR_DEC, USER_VCHR_DATE, USER_VCHR_NUM1, USER_DIST_CHAR1, CUSTOM_C100_D1, CUSTOM_C100_D2, CUSTOM_C100_D3, CUSTOM_C100_D4, CUSTOM_DATE_D, CUSTOM_C1_D, OPEN_ITEM_KEY, VAT_RECOVERY_PCT, VAT_REBATE_PCT, VAT_CALC_AMT, VAT_BASIS_AMT, VAT_RCVRY_AMT, VAT_NRCVR_AMT, VAT_REBATE_AMT, VAT_TRANS_AMT, TAX_CD_VAT_PCT, VAT_INV_AMT, VAT_NONINV_AMT, BUSINESS_UNIT_WO, WO_ID, WO_TASK_ID, RSRC_TYPE, RES_LN_NBR) VALUES ( 'FED01', '%vchrBldKeyC1%', ' ', 0, 0, 'NEXT', null, 1, 1, 'FED01', '1000', ' ', ' ', ' ', 0, 0, ' ', 1000, ' ', ' ', 0, 0, 0, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 0, 0, 0, ' ', ' ', 'G999', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', null, ' ', 0, ' ', ' ', ' ', ' ', ' ', 0, null, 0, ' ', ' ', ' ', ' ', ' ', null, ' ', ' ', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ' ', ' ', 0, ' ', 0); INSERT INTO PS_VCHR_PYMT_STG ( BUSINESS_UNIT, VCHR_BLD_KEY_C1, VCHR_BLD_KEY_C2, VCHR_BLD_KEY_N1, VCHR_BLD_KEY_N2, VOUCHER_ID, LEASE_PYMNT_DT, PYMNT_CNT, BANK_CD, BANK_ACCT_KEY, PYMNT_METHOD, PYMNT_MESSAGE, PYMNT_VCHR_PCT, PYMNT_HANDLING_CD, PYMNT_HOLD, PYMNT_HOLD_REASON, MESSAGE_CD, PYMNT_GROSS_AMT, PYMNT_SEPARATE, SCHEDULED_PAY_DT, PYMNT_ACTION, PYMNT_ID_REF, PYMNT_GROUP_CD, EFT_LAYOUT_CD) VALUES ( 'FED01', '%vchrBldKeyC1%', ' ', 0, 0, 'NEXT', null, 1, 'FDBNK', 'EMPL', 'EFT', 'EXCELPAYMENTwl', 0, 'RE', ' ', ' ', ' ', 1000, ' ', to_date('%T%', '%dateFormat%'), ' ', ' ', ' ', 'SPSCHK');
siwenyan/ro2
ro/ROScripts/921/pir/04_7250_612_611.sql
SQL
apache-2.0
8,038
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Entidades; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author André Amaro */ @Entity @Table(name = "projeto") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Projeto.findAll", query = "SELECT p FROM Projeto p") , @NamedQuery(name = "Projeto.findByIdProjeto", query = "SELECT p FROM Projeto p WHERE p.idProjeto = :idProjeto") , @NamedQuery(name = "Projeto.findByNome", query = "SELECT p FROM Projeto p WHERE p.nome = :nome") , @NamedQuery(name = "Projeto.findByDescricao", query = "SELECT p FROM Projeto p WHERE p.descricao = :descricao")}) public class Projeto implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "id_projeto") private Integer idProjeto; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "nome") private String nome; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "descricao") private String descricao; public Projeto() { } public Projeto(Integer idProjeto) { this.idProjeto = idProjeto; } public Projeto(Integer idProjeto, String nome, String descricao) { this.idProjeto = idProjeto; this.nome = nome; this.descricao = descricao; } public Integer getIdProjeto() { return idProjeto; } public void setIdProjeto(Integer idProjeto) { this.idProjeto = idProjeto; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } @Override public int hashCode() { int hash = 0; hash += (idProjeto != null ? idProjeto.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Projeto)) { return false; } Projeto other = (Projeto) object; if ((this.idProjeto == null && other.idProjeto != null) || (this.idProjeto != null && !this.idProjeto.equals(other.idProjeto))) { return false; } return true; } @Override public String toString() { return "Entidades.Projeto[ idProjeto=" + idProjeto + " ]"; } }
Andre-Amaro-Mamedio-dos-Santos/Projeto_DW
src/main/java/Entidades/Projeto.java
Java
apache-2.0
3,200
# Latte Online Expense Manager Online Expense Manager
dianw/latte
README.md
Markdown
apache-2.0
54
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/hlo_sharding.h" #include <algorithm> #include <numeric> #include <string> #include <utility> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/types/span.h" #include "tensorflow/compiler/xla/overflow_util.h" #include "tensorflow/compiler/xla/service/hlo_op_metadata.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/errors.h" namespace xla { using absl::StrCat; using absl::StrJoin; HloSharding HloSharding::AssignDevice(int64_t device_id, absl::Span<const OpMetadata> metadata) { return HloSharding(device_id, metadata); } HloSharding HloSharding::Tile1D(const Shape& input_shape, int64_t num_tiles, absl::Span<const OpMetadata> metadata) { CHECK_EQ(1, input_shape.rank()); CHECK_GT(num_tiles, 1); std::vector<int64_t> dimensions(1, num_tiles); Array<int64_t> assignment(dimensions); std::iota(assignment.begin(), assignment.end(), 0); return HloSharding(assignment, /*replicate_on_last_tile_dim=*/false, metadata); } HloSharding HloSharding::PartialTile( const Array<int64_t>& group_tile_assignment, absl::Span<const absl::Span<const int64_t>> replication_groups, absl::Span<const OpMetadata> metadata) { CHECK_EQ(group_tile_assignment.num_elements(), replication_groups.size()); if (replication_groups.size() == 1) { return Replicate(metadata); } auto new_tile_dims = group_tile_assignment.dimensions(); new_tile_dims.push_back(replication_groups[0].size()); auto new_tile_assignment = Array<int64_t>(new_tile_dims); new_tile_assignment.Each( [&](absl::Span<const int64_t> indices, int64_t* device) { std::vector<int64_t> group_index(indices.begin(), indices.end()); group_index.pop_back(); int64_t group = group_tile_assignment(group_index); *device = replication_groups[group][indices.back()]; }); return PartialTile(new_tile_assignment, metadata); } HloSharding HloSharding::PartialTile( const Array<int64_t>& tile_assignment_last_dim_replicate, absl::Span<const OpMetadata> metadata) { if (tile_assignment_last_dim_replicate.num_dimensions() == 1 || tile_assignment_last_dim_replicate.dimensions().back() == tile_assignment_last_dim_replicate.num_elements()) { return Replicate(metadata); } if (tile_assignment_last_dim_replicate.dimensions().back() == 1) { auto new_tile_dims = tile_assignment_last_dim_replicate.dimensions(); new_tile_dims.pop_back(); auto fully_tiled = tile_assignment_last_dim_replicate; fully_tiled.Reshape(new_tile_dims); return HloSharding(fully_tiled, /*replicate_on_last_tile_dim=*/false, metadata); } std::vector<std::set<int64_t>> sorted_groups( tile_assignment_last_dim_replicate.num_elements() / tile_assignment_last_dim_replicate.dimensions().back()); auto get_group_id = [&](absl::Span<const int64_t> indices) { int64_t group_id = 0; for (int64_t i = 0; i < indices.size() - 1; ++i) { group_id *= tile_assignment_last_dim_replicate.dim(i); group_id += indices[i]; } return group_id; }; tile_assignment_last_dim_replicate.Each( [&](absl::Span<const int64_t> indices, const int64_t device) { sorted_groups[get_group_id(indices)].insert(device); }); Array<int64_t> sorted_tile(tile_assignment_last_dim_replicate.dimensions()); sorted_tile.Each([&](absl::Span<const int64_t> indices, int64_t* device) { const int64_t group_id = get_group_id(indices); auto begin = sorted_groups[group_id].begin(); *device = *begin; sorted_groups[group_id].erase(begin); }); return HloSharding(sorted_tile, /*replicate_on_last_tile_dim=*/true, metadata); } HloSharding HloSharding::Subgroup( const Array<int64_t>& tile_assignment, absl::Span<const OpSharding::Type> subgroup_types, absl::Span<const OpMetadata> metadata) { if (subgroup_types.empty()) { return HloSharding(tile_assignment, /*replicate_on_last_tile_dim=*/false, metadata); } // If there is only one type of subgrouping and there is no tiling on data // dimensions, it can be canonicalized to a simple manual/replicated sharding. if (absl::c_all_of( subgroup_types, [&](const OpSharding::Type t) { return t == subgroup_types[0]; }) && Product(absl::Span<const int64_t>(tile_assignment.dimensions()) .subspan(0, tile_assignment.num_dimensions() - subgroup_types.size())) == 1) { if (subgroup_types[0] == OpSharding::MANUAL) { return Manual(metadata); } if (subgroup_types[0] == OpSharding::REPLICATED) { return Replicate(metadata); } } // Normalize the subgroups to simplify two cases: // - Remove trivial dims of size 1. // - Merge dims of the same type. // - Sort types. int64_t data_dims = tile_assignment.num_dimensions() - subgroup_types.size(); std::vector<int64_t> perm(data_dims); std::iota(perm.begin(), perm.end(), 0); // Make sure the replicate dims are at the end so that we can leverage // PartialTile() to sort the elements. struct CmpTypeRepliateLast { bool operator()(OpSharding::Type a, OpSharding::Type b) const { if (a == b) { return false; } if (a == OpSharding::REPLICATED) { return false; } if (b == OpSharding::REPLICATED) { return true; } return a < b; } }; std::map<OpSharding::Type, std::vector<int64_t>, CmpTypeRepliateLast> type_to_dims; bool needs_merging = false; for (int64_t i = 0; i < subgroup_types.size(); ++i) { if (tile_assignment.dim(i + data_dims) == 1) { needs_merging = true; continue; } auto& dims = type_to_dims[subgroup_types[i]]; needs_merging |= !dims.empty(); dims.push_back(i + data_dims); } needs_merging |= type_to_dims.size() > 1; auto create_sharding = [](const Array<int64_t> tiles, absl::Span<const OpSharding::Type> types, absl::Span<const OpMetadata> metadata) { if (types.size() == 1 && types.back() == OpSharding::REPLICATED) { // Normalize to partial tile. return PartialTile(tiles, metadata); } if (!types.empty() && types.back() == OpSharding::REPLICATED) { // If the last type is REPLICATED, we first create a partially replicated // sharding without other subgroups so that the elements are sorted. Then // we fix the subgroup types. HloSharding sharding = PartialTile(tiles, metadata); sharding.replicate_on_last_tile_dim_ = false; for (const OpSharding::Type type : types) { sharding.subgroup_types_.push_back(type); } return sharding; } return HloSharding(tiles, types, metadata); }; if (needs_merging) { auto data_tile_shape = absl::Span<const int64_t>(tile_assignment.dimensions()) .subspan(0, data_dims); std::vector<int64_t> merged_shape(data_tile_shape.begin(), data_tile_shape.end()); std::vector<int64_t> transposed_shape = merged_shape; std::vector<OpSharding::Type> merged_types; for (const auto& type_dims : type_to_dims) { int64_t dim_size = 1; for (int64_t dim : type_dims.second) { perm.push_back(dim); dim_size *= tile_assignment.dim(dim); transposed_shape.push_back(tile_assignment.dim(dim)); } merged_shape.push_back(dim_size); merged_types.push_back(type_dims.first); } Array<int64_t> new_tiles(transposed_shape); new_tiles.Each([&](absl::Span<const int64_t> indices, int64_t* value) { std::vector<int64_t> src_indices(tile_assignment.num_dimensions(), 0); for (int64_t i = 0; i < indices.size(); ++i) { src_indices[perm[i]] = indices[i]; } *value = tile_assignment(src_indices); }); new_tiles.Reshape(merged_shape); return create_sharding(new_tiles, merged_types, metadata); } return create_sharding(tile_assignment, subgroup_types, metadata); } HloSharding HloSharding::Tuple(const ShapeTree<HloSharding>& sub_shardings) { std::vector<HloSharding> flattened_list; flattened_list.reserve(sub_shardings.leaf_count()); for (const auto& index_to_sharding : sub_shardings.leaves()) { flattened_list.push_back(index_to_sharding.second); } if (flattened_list.empty()) { // Empty tuple sharding ends up having no leaves, but we want to allow // empty tuple HLO instruction results to have sharding, so we fetch the // root ({}) sharding value from the ShapeTree. // A ShapeTree created with ShapeTree<HloSharding>(shape, init) will have // init as value at its root. flattened_list.push_back(sub_shardings.element(ShapeIndex({}))); } return HloSharding(flattened_list); } HloSharding HloSharding::Tuple(const Shape& tuple_shape, absl::Span<const HloSharding> shardings) { CHECK(tuple_shape.IsTuple()) << ShapeUtil::HumanString(tuple_shape); for (auto& sharding : shardings) { CHECK(!sharding.IsTuple()) << sharding.ToString() << ShapeUtil::HumanString(tuple_shape); } std::vector<HloSharding> flattened_list(shardings.begin(), shardings.end()); CHECK_EQ(flattened_list.size(), RequiredLeaves(tuple_shape)) << "Flat list has " << flattened_list.size() << ", required " << RequiredLeaves(tuple_shape); return HloSharding(flattened_list); } HloSharding HloSharding::SingleTuple(const Shape& tuple_shape, const HloSharding& sharding) { CHECK(tuple_shape.IsTuple()) << ShapeUtil::HumanString(tuple_shape); CHECK(!sharding.IsTuple()) << sharding.ToString(); int64_t leaf_count = RequiredLeaves(tuple_shape); std::vector<HloSharding> flattened_list; flattened_list.resize(leaf_count, sharding); return HloSharding(flattened_list); } HloSharding HloSharding::Single(const Shape& shape, const HloSharding& sharding) { return shape.IsTuple() ? SingleTuple(shape, sharding) : sharding; } std::string HloSharding::ToString(bool include_metadata) const { if (IsTuple()) { CHECK(metadata_.empty()); std::string result = "{"; for (int i = 0; i < tuple_elements_.size(); ++i) { const HloSharding& element = tuple_elements_[i]; if (i != 0) { absl::StrAppend(&result, ", "); if (i % 5 == 0) { absl::StrAppend(&result, "/*index=", i, "*/"); } } absl::StrAppend(&result, element.ToString(include_metadata)); } absl::StrAppend(&result, "}"); return result; } std::string metadata; if (include_metadata) { if (metadata_.size() == 1) { metadata = StrCat(" metadata={", OpMetadataToString(metadata_.front()), "}"); } else if (metadata_.size() > 1) { std::vector<std::string> metadata_strings; metadata_strings.reserve(metadata_.size()); for (const auto& single_metadata : metadata_) { metadata_strings.push_back( StrCat("{", OpMetadataToString(single_metadata), "}")); } metadata = StrCat(" metadata={", StrJoin(metadata_strings, ", "), "}"); } } std::string last_tile_dims; if (!subgroup_types_.empty()) { auto op_sharding_type_to_string = [](OpSharding::Type type) { switch (type) { case OpSharding::MANUAL: return "manual"; case OpSharding::MAXIMAL: return "maximul"; case OpSharding::REPLICATED: return "replicated"; default: return "error_type."; } }; std::vector<std::string> sharding_type_strings; sharding_type_strings.reserve(subgroup_types_.size()); for (const auto& single_sharding_type : subgroup_types_) { sharding_type_strings.push_back( op_sharding_type_to_string(single_sharding_type)); } last_tile_dims = StrCat(" last_tile_dims={", StrJoin(sharding_type_strings, ", "), "}"); } if (replicated_) { return StrCat("{replicated", metadata, "}"); } if (manual_) { return StrCat("{manual", metadata, "}"); } if (maximal_) { return StrCat( "{maximal device=", static_cast<int64_t>(*tile_assignment_.begin()), metadata, "}"); } return StrCat("{devices=[", StrJoin(tile_assignment_.dimensions(), ","), "]", StrJoin(tile_assignment_, ","), replicate_on_last_tile_dim_ ? " last_tile_dim_replicate" : "", last_tile_dims, metadata, "}"); } bool HloSharding::UsesDevice(int64_t device) const { if (IsTuple()) { return absl::c_any_of(tuple_elements_, [&](const HloSharding& s) { return s.UsesDevice(device); }); } const auto& devices = tile_assignment_; return replicated_ || manual_ || absl::c_linear_search(devices, device); } std::map<int64_t, int64_t> HloSharding::UsedDevices(int64_t* count) const { int64_t element_count = 1; std::map<int64_t, int64_t> device_map; if (IsTuple()) { for (auto& tuple_element_sharding : tuple_elements()) { auto unique_device = tuple_element_sharding.UniqueDevice(); if (unique_device) { device_map[*unique_device] += 1; } } element_count = tuple_elements().size(); } else { auto unique_device = UniqueDevice(); if (unique_device) { device_map[*unique_device] += 1; } } if (count != nullptr) { *count = element_count; } return device_map; } std::vector<int64_t> HloSharding::TileIndexForDevice(int64_t device) const { CHECK(!maximal_); CHECK(!manual_); CHECK(!IsTuple()); std::vector<int64_t> ret_index; tile_assignment_.Each([&](absl::Span<const int64_t> index, int64_t d) { if (d == device) { ret_index = {index.begin(), index.end()}; } }); CHECK(!ret_index.empty()); ret_index.resize(TiledDataRank()); return ret_index; } int64_t HloSharding::DeviceForTileIndex(absl::Span<const int64_t> index) const { CHECK(!replicated_); CHECK(!manual_); CHECK(!IsTuple()); if (maximal_) { return *tile_assignment_.begin(); } if (index.size() == TiledDataRank() && index.size() < tile_assignment_.num_dimensions()) { std::vector<int64_t> first_subgroup_index(index.begin(), index.end()); for (int64_t i = 0; i < tile_assignment_.num_dimensions() - index.size(); ++i) { first_subgroup_index.push_back(0); } return tile_assignment_(first_subgroup_index); } return tile_assignment_(index); } std::vector<int64_t> HloSharding::TileOffsetForDevice(const Shape& shape, int64_t device) const { CHECK(!IsTuple()); CHECK(!manual_); if (maximal_) { return std::vector<int64_t>(shape.dimensions_size(), 0); } CHECK_EQ(shape.dimensions_size(), TiledDataRank()); std::vector<int64_t> index = TileIndexForDevice(device); for (int64_t i = 0; i < index.size(); ++i) { const int64_t shape_dim = shape.dimensions(i); index[i] = std::min( index[i] * CeilOfRatio(shape_dim, tile_assignment_.dim(i)), shape_dim); } return index; } std::vector<int64_t> HloSharding::TileLimitForDevice(const Shape& shape, int64_t device) const { CHECK(!IsTuple()); CHECK(!manual_); if (maximal_) { return std::vector<int64_t>(shape.dimensions().begin(), shape.dimensions().end()); } CHECK_EQ(shape.dimensions_size(), TiledDataRank()); std::vector<int64_t> index = TileIndexForDevice(device); for (int64_t i = 0; i < index.size(); ++i) { const int64_t shape_dim = shape.dimensions(i); index[i] = std::min( (index[i] + 1) * CeilOfRatio(shape_dim, tile_assignment_.dim(i)), shape_dim); } return index; } int64_t HloSharding::RequiredLeaves(const Shape& shape) { // Empty tuples (with arbitrary nesting) have no leaf nodes as far as // ShapeUtil and ShapeTree are concerned, but they do have a single // tuple_elements_ entry since we want to allow empty tuple results to // have sharding. const int64_t leaf_count = ShapeUtil::GetLeafCount(shape); return (leaf_count == 0) ? 1 : leaf_count; } Status HloSharding::CheckLeafCount(const Shape& shape) const { int64_t leaf_count = ShapeUtil::GetLeafCount(shape); if (leaf_count == 0 && tuple_elements_.size() == 1) { // Allow (but don't require) empty tuples to have a single sharding return Status::OK(); } TF_RET_CHECK(leaf_count == tuple_elements_.size()) << "Shape " << ShapeUtil::HumanString(shape) << " has " << leaf_count << " leaf nodes while this sharding has " << tuple_elements_.size(); return Status::OK(); } StatusOr<ShapeTree<HloSharding>> HloSharding::AsShapeTree( const Shape& shape) const { if (IsTuple()) { ShapeTree<HloSharding> result(shape, HloSharding::Replicate()); TF_RETURN_IF_ERROR(CheckLeafCount(shape)); auto it = tuple_elements_.begin(); for (auto& index_to_sharding : result.leaves()) { index_to_sharding.second = *it++; } if (ShapeUtil::IsEmptyTuple(shape)) { // Empty tuples have no leaves, but we want to assign them a sharding // anyway, so we use the root element sharding. *result.mutable_element(ShapeIndex({})) = *it; } return std::move(result); } else { return ShapeTree<HloSharding>(shape, *this); } } StatusOr<HloSharding> HloSharding::GetTupleSharding(const Shape& shape) const { if (IsTuple()) { TF_RETURN_IF_ERROR(CheckLeafCount(shape)); return *this; } return Tuple(ShapeTree<HloSharding>(shape, *this)); } absl::optional<int64_t> HloSharding::UniqueDevice() const { if (IsTuple()) { if (tuple_elements_.empty()) { return absl::nullopt; } absl::optional<int64_t> unique_device; for (auto& tuple_sharding : tuple_elements_) { auto device = tuple_sharding.UniqueDevice(); if (!device || (unique_device && *device != *unique_device)) { return absl::nullopt; } unique_device = device; } return unique_device; } if (!replicated_ && maximal_) { return static_cast<int64_t>(*tile_assignment_.begin()); } return absl::nullopt; } int64_t HloSharding::GetUniqueDevice() const { auto device = UniqueDevice(); CHECK(device) << "Sharding does not have a unique device: " << *this; return *device; } Status HloSharding::ValidateTuple(const Shape& shape, int64_t num_devices) const { if (!shape.IsTuple()) { return tensorflow::errors::InvalidArgument( StrCat("Sharding is tuple-shaped but validation shape is not.")); } TF_RETURN_IF_ERROR(CheckLeafCount(shape)); if (ShapeUtil::GetLeafCount(shape) == 0 && tuple_elements_.empty()) { // Empty tuples are allowed to not have sharding return Status::OK(); } // Now we've validated the number of tuple elements, it's safe to request a // shape tree. ShapeTree<HloSharding> shape_tree = GetAsShapeTree(shape); for (const auto& index_to_sharding : shape_tree.leaves()) { Status status = index_to_sharding.second.ValidateNonTuple( ShapeUtil::GetSubshape(shape, index_to_sharding.first), num_devices); if (!status.ok()) { tensorflow::errors::AppendToMessage( &status, StrCat("Note: While validating sharding tuple element ", index_to_sharding.first.ToString(), " which is ", index_to_sharding.second.ToString())); return status; } } return Status::OK(); } Status HloSharding::Validate(const Shape& shape, int64_t num_devices) const { if (shape.IsToken()) { return Status::OK(); } Status status = IsTuple() ? ValidateTuple(shape, num_devices) : ValidateNonTuple(shape, num_devices); if (!status.ok()) { tensorflow::errors::AppendToMessage( &status, StrCat("Note: While validating sharding ", ToString(), " against shape ", ShapeUtil::HumanString(shape))); } return status; } Status HloSharding::ValidateNonTuple(const Shape& shape, int64_t num_devices) const { if (shape.IsTuple()) { return tensorflow::errors::InvalidArgument( StrCat("Validation shape is a tuple but sharding is not.")); } if (replicated_) { return Status::OK(); } // All tile assignments must be less than the number of available cores and // unique. Status status = Status::OK(); absl::flat_hash_set<int64_t> seen_cores; tile_assignment_.Each([&](absl::Span<const int64_t> indices, int32_t core) { // Don't overwrite a bad status, so we report the first error. if (status.ok()) { if (core >= num_devices) { status = tensorflow::errors::InvalidArgument( StrCat("core ", core, " > ", num_devices, " in tile assignment")); } else if (seen_cores.contains(core)) { status = tensorflow::errors::InvalidArgument( StrCat("core ", core, " is not unique in tile assignment")); } seen_cores.insert(core); } }); if (!status.ok()) { return status; } if (IsTileMaximal() || IsManual()) { return Status::OK(); } // The tile assignment tensor must have the same rank as the input, or input // rank + 1 for replicate_on_last_tile_dim_. if (shape.rank() + (replicate_on_last_tile_dim_ ? 1 : 0) + subgroup_types_.size() != tile_assignment_.num_dimensions()) { return tensorflow::errors::InvalidArgument( "Number of tile assignment dimensions is different to the input rank. " "sharding=", ToString(), ", input_shape=", ShapeUtil::HumanString(shape)); } // The correct constructor has to be used to create tile maximal shardings. if (tile_assignment_.num_elements() == 1) { return tensorflow::errors::InvalidArgument( "Tile assignment only contains a single device. If a replicated " "sharding was intended, use HloSharding::Replicated(). If a device " "placement was intended, use HloSharding::AssignDevice()"); } return Status::OK(); } /*static*/ StatusOr<HloSharding> HloSharding::FromProto( const OpSharding& proto) { std::vector<OpMetadata> metadata(proto.metadata().begin(), proto.metadata().end()); std::vector<int> subgroup_types_int(proto.last_tile_dims().begin(), proto.last_tile_dims().end()); std::vector<OpSharding::Type> subgroup_types; absl::c_transform( subgroup_types_int, std::back_inserter(subgroup_types), [](const int type) { return static_cast<OpSharding::Type>(type); }); if (proto.type() == OpSharding::TUPLE) { TF_RET_CHECK(metadata.empty()) << "Tuple sharding is expected to have no metadata."; std::vector<HloSharding> tuple_shardings; tuple_shardings.reserve(proto.tuple_shardings().size()); for (const OpSharding& tuple_sharding_proto : proto.tuple_shardings()) { TF_ASSIGN_OR_RETURN(HloSharding sharding, HloSharding::FromProto(tuple_sharding_proto)); tuple_shardings.push_back(sharding); } return HloSharding(tuple_shardings); } else if (proto.type() == OpSharding::REPLICATED) { return Replicate(metadata); } else if (proto.type() == OpSharding::MANUAL) { return Manual(metadata); } else if (proto.tile_assignment_devices().size() == 1) { return HloSharding(proto.tile_assignment_devices(0), metadata); } TF_RET_CHECK(proto.type() != OpSharding::MAXIMAL) << "Maximal sharding is expected to have single device assignment, but " << proto.tile_assignment_devices().size() << " has provided."; TF_RET_CHECK(proto.tile_assignment_devices().size() > 1); TF_RET_CHECK(!proto.tile_assignment_dimensions().empty()); // RE: the product of tile assignment tensor dimensions must be // equal to tile_assignment_devices.size(). int64_t product_of_dimensions = 1; for (auto dimension : proto.tile_assignment_dimensions()) { TF_RET_CHECK(dimension > 0); product_of_dimensions = MultiplyWithoutOverflow(product_of_dimensions, dimension); TF_RET_CHECK(product_of_dimensions > 0); } TF_RET_CHECK(product_of_dimensions == proto.tile_assignment_devices().size()); // Some versions of gcc cannot infer the TileAssignment constructor from a // braced initializer-list, so create one manually. std::vector<int64_t> devices(proto.tile_assignment_devices().begin(), proto.tile_assignment_devices().end()); Array<int64_t> tile_assignment( std::vector<int64_t>(proto.tile_assignment_dimensions().begin(), proto.tile_assignment_dimensions().end())); std::copy(proto.tile_assignment_devices().begin(), proto.tile_assignment_devices().end(), tile_assignment.begin()); if (!subgroup_types.empty()) { TF_RET_CHECK(!proto.replicate_on_last_tile_dim()); return Subgroup(tile_assignment, subgroup_types, metadata); } return proto.replicate_on_last_tile_dim() ? PartialTile(tile_assignment, metadata) : HloSharding(tile_assignment, /*replicate_on_last_tile_dim=*/false, metadata); } OpSharding HloSharding::ToProto() const { OpSharding result; if (IsTuple()) { CHECK(metadata_.empty()); for (const HloSharding& element : tuple_elements_) { *result.add_tuple_shardings() = element.ToProto(); } result.set_type(OpSharding::TUPLE); return result; } result.mutable_metadata()->Reserve(metadata_.size()); for (const auto& metadata : metadata_) { *result.add_metadata() = metadata; } for (int64_t dim : tile_assignment_.dimensions()) { result.add_tile_assignment_dimensions(dim); } for (auto device : tile_assignment_) { result.add_tile_assignment_devices(device); } if (IsReplicated()) { result.set_type(OpSharding::REPLICATED); result.clear_tile_assignment_dimensions(); } else if (IsTileMaximal()) { result.set_type(OpSharding::MAXIMAL); } else if (IsManual()) { result.set_type(OpSharding::MANUAL); result.clear_tile_assignment_dimensions(); } else { result.set_type(OpSharding::OTHER); result.set_replicate_on_last_tile_dim(ReplicateOnLastTileDim()); for (auto type : subgroup_types_) { result.add_last_tile_dims(type); } } return result; } Shape HloSharding::TileShape(const Shape& shape) const { if (IsTileMaximal() || IsManual()) { return shape; } Shape result_shape = shape; for (int64_t i = 0; i < TiledDataRank(); ++i) { result_shape.set_dimensions( i, CeilOfRatio<int64_t>(shape.dimensions(i), tile_assignment_.dim(i))); } return result_shape; } Shape HloSharding::TileShape(const Shape& shape, int64_t device) const { if (IsTileMaximal() || IsManual()) { return shape; } std::vector<int64_t> index = TileIndexForDevice(device); Shape result_shape = shape; for (int64_t i = 0; i < index.size(); ++i) { const int64_t shape_dim = shape.dimensions(i); int64_t offset = std::min( index[i] * CeilOfRatio(shape_dim, tile_assignment_.dim(i)), shape_dim); int64_t limit = std::min( (index[i] + 1) * CeilOfRatio(shape_dim, tile_assignment_.dim(i)), shape_dim); result_shape.set_dimensions(i, limit - offset); } return result_shape; } int64_t HloSharding::NumTiles() const { if (IsTileMaximal()) { return 1; } CHECK(!IsManual()); return Product(absl::Span<const int64_t>(tile_assignment_.dimensions()) .subspan(0, TiledDataRank())); } int64_t HloSharding::NumTiles(absl::Span<const int64_t> dims) const { if (IsTileMaximal()) { return 1; } CHECK(!IsManual()); CHECK(!ReplicateOnLastTileDim() || !absl::c_linear_search(dims, tile_assignment().num_dimensions() - 1)); int64_t num_tiles = 1; for (auto d : dims) { CHECK(d < tile_assignment().num_dimensions()); num_tiles *= tile_assignment().dim(d); } return num_tiles; } HloSharding HloSharding::GetSubSharding(const Shape& shape, const ShapeIndex& index) const { CHECK(IsTuple()); int64_t sharding_index = 0; const Shape* sub_shape = &shape; for (int64_t idx : index) { for (int64_t i = 0; i < idx; ++i) { sharding_index += ShapeUtil::GetLeafCount(ShapeUtil::GetSubshape(*sub_shape, {i})); } sub_shape = &ShapeUtil::GetSubshape(*sub_shape, {idx}); } if (sub_shape->IsTuple()) { auto begin_it = tuple_elements_.begin() + sharding_index; std::vector<HloSharding> sub_shardings( begin_it, begin_it + ShapeUtil::GetLeafCount(*sub_shape)); return HloSharding::Tuple(*sub_shape, sub_shardings); } else { return tuple_elements_[sharding_index]; } } absl::optional<HloSharding> HloSharding::ExtractSingleSharding() const { if (!IsTuple()) { return *this; } if (tuple_elements_.empty()) { return absl::nullopt; } for (int64_t i = 1; i < tuple_elements_.size(); ++i) { if (tuple_elements_[0] != tuple_elements_[i]) { return absl::nullopt; } } return tuple_elements_.front(); } HloSharding HloSharding::WithMetadata(absl::Span<const OpMetadata> metadata, bool overwrite) const { auto assign_metadata = [&](HloSharding& sharding) { if (sharding.metadata_.empty() || overwrite) { sharding.metadata_.assign(metadata.begin(), metadata.end()); } }; HloSharding sharding = *this; if (sharding.IsTuple()) { for (HloSharding& sub_sharding : sharding.tuple_elements()) { assign_metadata(sub_sharding); } } else { assign_metadata(sharding); } return sharding; } HloSharding HloSharding::WithoutMetadata() const { HloSharding sharding = *this; sharding.metadata_.clear(); for (HloSharding& sub_sharding : sharding.tuple_elements()) { sub_sharding.metadata_.clear(); } return sharding; } std::ostream& operator<<(std::ostream& out, const HloSharding& sharding) { out << sharding.ToString(); return out; } } // namespace xla
Intel-Corporation/tensorflow
tensorflow/compiler/xla/service/hlo_sharding.cc
C++
apache-2.0
31,191
using System; namespace MyWebApi.Areas.HelpPage { /// <summary> /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. /// </summary> public class TextSample { public TextSample(string text) { if (text == null) { throw new ArgumentNullException("text"); } Text = text; } public string Text { get; private set; } public override bool Equals(object obj) { TextSample other = obj as TextSample; return other != null && Text == other.Text; } public override int GetHashCode() { return Text.GetHashCode(); } public override string ToString() { return Text; } } }
tracehub/MyTraceHub
MyWebApi/Areas/HelpPage/SampleGeneration/TextSample.cs
C#
apache-2.0
920
package net.remisan.security.manager; import net.remisan.base.manager.Manager; import net.remisan.security.model.SecurityRole; public interface SecurityRoleManager extends Manager<SecurityRole> { SecurityRole getByName(String name); }
remi-san/security-model
src/main/java/net/remisan/security/manager/SecurityRoleManager.java
Java
apache-2.0
241
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.primitives.resources.impl; import io.atomix.catalyst.serializer.SerializableTypeResolver; import io.atomix.copycat.client.CopycatClient; import io.atomix.resource.ResourceFactory; import io.atomix.resource.ResourceStateMachine; import java.util.Properties; /** * Atomic counter map factory. */ public class AtomixAtomicCounterMapFactory implements ResourceFactory<AtomixAtomicCounterMap> { @Override public SerializableTypeResolver createSerializableTypeResolver() { return new AtomixAtomicCounterMapCommands.TypeResolver(); } @Override public ResourceStateMachine createStateMachine(Properties config) { return new AtomixAtomicCounterMapState(config); } @Override public AtomixAtomicCounterMap createInstance(CopycatClient client, Properties options) { return new AtomixAtomicCounterMap(client, options); } }
sdnwiselab/onos
core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixAtomicCounterMapFactory.java
Java
apache-2.0
1,526
package VMOMI::DistributedVirtualSwitchHostInfrastructureTrafficClass; use parent 'VMOMI::SimpleType'; use strict; use warnings; 1;
stumpr/p5-vmomi
lib/VMOMI/DistributedVirtualSwitchHostInfrastructureTrafficClass.pm
Perl
apache-2.0
134
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.sys.entity.dy; import org.hibernate.validator.constraints.Length; import com.thinkgem.jeesite.common.persistence.DataEntity; import com.thinkgem.jeesite.modules.sys.entity.User; /** * 会员信息管理Entity * @author shenzb.fnst * @version 2015-10-12 */ public class DyClient extends DataEntity<DyClient> { private static final long serialVersionUID = 1L; private String dyid; // 米友号 private String openid; // 微信标识 private String name; // 姓名 private String nickname; // 微信昵称 private String email; // 邮箱 private String payPassword; //支付密码 private String mobile; // 手机 private String qq; // QQ号 private String wx; // 微信号 private String photo; // 微信头像 private String vip; // 会员等级 private String avoidDeposit = "0"; // 是否免除保证金(1:是,0:否) private String idcardNumber; //身份证号码 private String sealFlag; // 封号标记 private String emailFlag; //邮箱人认证 private String brokerId; // 所属经纪人id private String authenticationMark; // 身份认证 private String defaultIncomeExpense; // 默认收支方式 private String authenticationPositiveImageUrl; // 身份证正面照片 private String authenticationNegativeImageUrl; // 身份证反面照片 /** * 开户银行支行 */ private String bankName; /** * 银行所在省市 */ private String bankLocation; private String newPayPassword; // 新密码 private User broker; private DyFinance dyFinance; public DyClient() { super(); } public DyClient(String id){ super(id); } /** * dyid的取得 * @return dyid */ @Length(min=1, max=200, message="米友号长度必须介于 1 和 200 之间") public String getDyid() { return dyid; } /** * dyid的设定 * @param dyid dyid */ public void setDyid(String dyid) { this.dyid = dyid; } /** * openid的取得 * @return openid */ @Length(min=1, max=200, message="微信标识长度必须介于 1 和 200 之间") public String getOpenid() { return openid; } /** * openid的设定 * @param openid openid */ public void setOpenid(String openid) { this.openid = openid; } /** * name的取得 * @return name */ @Length(min=0, max=100, message="姓名长度必须介于 0 和 100 之间") public String getName() { return name; } /** * name的设定 * @param name name */ public void setName(String name) { this.name = name; } /** * nickname的取得 * @return nickname */ @Length(min=1, max=100, message="微信昵称长度必须介于 1 和 100 之间") public String getNickname() { return nickname; } /** * nickname的设定 * @param nickname nickname */ public void setNickname(String nickname) { this.nickname = nickname; } /** * email的取得 * @return email */ @Length(min=0, max=200, message="邮箱长度必须介于 0 和 200 之间") public String getEmail() { return email; } /** * email的设定 * @param email email */ public void setEmail(String email) { this.email = email; } /** * payPassword的取得 * @return payPassword */ @Length(min=0, max=100, message="支付密码长度必须介于 0 和 100 之间") public String getPayPassword() { return payPassword; } /** * payPassword的设定 * @param payPassword payPassword */ public void setPayPassword(String payPassword) { this.payPassword = payPassword; } /** * mobile的取得 * @return mobile */ @Length(min=0, max=200, message="手机长度必须介于 0 和 200 之间") public String getMobile() { return mobile; } /** * mobile的设定 * @param mobile mobile */ public void setMobile(String mobile) { this.mobile = mobile; } /** * qq的取得 * @return qq */ @Length(min=0, max=200, message="QQ号长度必须介于 0 和 200 之间") public String getQq() { return qq; } /** * qq的设定 * @param qq qq */ public void setQq(String qq) { this.qq = qq; } /** * wx的取得 * @return wx */ @Length(min=0, max=200, message="微信号长度必须介于 0 和 200 之间") public String getWx() { return wx; } /** * wx的设定 * @param wx wx */ public void setWx(String wx) { this.wx = wx; } /** * photo的取得 * @return photo */ @Length(min=1, max=1000, message="微信头像长度必须介于 1 和 1000 之间") public String getPhoto() { return photo; } /** * photo的设定 * @param photo photo */ public void setPhoto(String photo) { this.photo = photo; } /** * vip的取得 * @return vip */ @Length(min=1, max=11, message="会员等级长度必须介于 1 和 11 之间") public String getVip() { return vip; } /** * vip的设定 * @param vip vip */ public void setVip(String vip) { this.vip = vip; } /** * 是否免除保证金(1:是,0:否) * @return avoidDeposit */ public String getAvoidDeposit() { return avoidDeposit; } /** * 是否免除保证金(1:是,0:否) * @param avoidDeposit avoidDeposit */ public void setAvoidDeposit(String avoidDeposit) { this.avoidDeposit = avoidDeposit; } /** * sealFlag的取得 * @return sealFlag */ @Length(min=1, max=1, message="封号标记长度必须介于 1 和 1 之间") public String getSealFlag() { return sealFlag; } /** * sealFlag的设定 * @param sealFlag sealFlag */ public void setSealFlag(String sealFlag) { this.sealFlag = sealFlag; } /** * emailFlag的取得 * @return emailFlag */ @Length(min=1, max=1, message="邮箱认证长度必须介于 1 和 1 之间") public String getEmailFlag() { return emailFlag; } /** * emailFlag的设定 * @param emailFlag emailFlag */ public void setEmailFlag(String emailFlag) { this.emailFlag = emailFlag; } /** * brokerId的取得 * @return brokerId */ @Length(min=1, max=64, message="所属经纪人id长度必须介于 1 和 64 之间") public String getBrokerId() { return brokerId; } /** * brokerId的设定 * @param brokerId brokerId */ public void setBrokerId(String brokerId) { this.brokerId = brokerId; } @Length(max=18, message="身份证号码必须为18位") public String getIDcardNumber() { return idcardNumber; } public void setIDcardNumber(String iDcardNumber) { idcardNumber = iDcardNumber; } /** * authenticationMark的取得 * @return authenticationMark */ @Length(min=0, max=11, message="身份认证长度必须介于 0 和 11 之间") public String getAuthenticationMark() { return authenticationMark; } /** * authenticationMark的设定 * @param authenticationMark authenticationMark */ public void setAuthenticationMark(String authenticationMark) { this.authenticationMark = authenticationMark; } /** * defaultIncomeExpense的取得 * @return defaultIncomeExpense */ @Length(min=0, max=100, message="默认收支方式长度必须介于 0 和 100 之间") public String getDefaultIncomeExpense() { return defaultIncomeExpense; } /** * defaultIncomeExpense的设定 * @param defaultIncomeExpense defaultIncomeExpense */ public void setDefaultIncomeExpense(String defaultIncomeExpense) { this.defaultIncomeExpense = defaultIncomeExpense; } /** * authenticationPositiveImageUrl的取得 * @return authenticationPositiveImageUrl */ @Length(min=0, max=500, message="身份证正面照片长度必须介于 0 和 500 之间") public String getAuthenticationPositiveImageUrl() { return authenticationPositiveImageUrl; } /** * authenticationPositiveImageUrl的设定 * @param authenticationPositiveImageUrl authenticationPositiveImageUrl */ public void setAuthenticationPositiveImageUrl(String authenticationPositiveImageUrl) { this.authenticationPositiveImageUrl = authenticationPositiveImageUrl; } /** * authenticationNegativeImageUrl的取得 * @return authenticationNegativeImageUrl */ @Length(min=0, max=500, message="身份证反面照片长度必须介于 0 和 500 之间") public String getAuthenticationNegativeImageUrl() { return authenticationNegativeImageUrl; } /** * authenticationNegativeImageUrl的设定 * @param authenticationNegativeImageUrl authenticationNegativeImageUrl */ public void setAuthenticationNegativeImageUrl(String authenticationNegativeImageUrl) { this.authenticationNegativeImageUrl = authenticationNegativeImageUrl; } /** * broker的取得 * @return broker */ public User getBroker() { return broker; } /** * broker的设定 * @param broker broker */ public void setBroker(User broker) { this.broker = broker; } /** * dyFinance的取得 * @return dyFinance */ public DyFinance getDyFinance() { return dyFinance; } /** * dyFinance的设定 * @param dyFinance dyFinance */ public void setDyFinance(DyFinance dyFinance) { this.dyFinance = dyFinance; } /** * 开户银行支行的取得 * @return 开户银行支行 */ @Length(min=0, max=100, message="开户银行支行长度必须介于 0 和 100 之间") public String getBankName() { return bankName; } /** * 开户银行支行的设定 * @param bankName 开户银行支行 */ public void setBankName(String bankName) { this.bankName = bankName; } /** * 银行所在省市的取得 * @return 银行所在省市 */ @Length(min=0, max=200, message="银行所在省市长度必须介于 0 和 200 之间") public String getBankLocation() { return bankLocation; } /** * 银行所在省市的设定 * @param bankLocation 银行所在省市 */ public void setBankLocation(String bankLocation) { this.bankLocation = bankLocation; } /** * newPayPassword的取得 * @return newPayPassword */ public String getNewPayPassword() { return newPayPassword; } /** * newPayPassword的设定 * @param newPayPassword newPayPassword */ public void setNewPayPassword(String newPayPassword) { this.newPayPassword = newPayPassword; } }
GSSBuse/GSSB
src/main/java/com/thinkgem/jeesite/modules/sys/entity/dy/DyClient.java
Java
apache-2.0
10,149
<?php // GENERATED CODE -- DO NOT EDIT! // Original file comments: // Copyright 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. // namespace Google\Cloud\Eventarc\V1; /** * Eventarc allows users to subscribe to various events that are provided by * Google Cloud services and forward them to supported destinations. */ class EventarcGrpcClient extends \Grpc\BaseStub { /** * @param string $hostname hostname * @param array $opts channel options * @param \Grpc\Channel $channel (optional) re-use channel object */ public function __construct($hostname, $opts, $channel = null) { parent::__construct($hostname, $opts, $channel); } /** * Get a single trigger. * @param \Google\Cloud\Eventarc\V1\GetTriggerRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function GetTrigger(\Google\Cloud\Eventarc\V1\GetTriggerRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/GetTrigger', $argument, ['\Google\Cloud\Eventarc\V1\Trigger', 'decode'], $metadata, $options); } /** * List triggers. * @param \Google\Cloud\Eventarc\V1\ListTriggersRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function ListTriggers(\Google\Cloud\Eventarc\V1\ListTriggersRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/ListTriggers', $argument, ['\Google\Cloud\Eventarc\V1\ListTriggersResponse', 'decode'], $metadata, $options); } /** * Create a new trigger in a particular project and location. * @param \Google\Cloud\Eventarc\V1\CreateTriggerRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function CreateTrigger(\Google\Cloud\Eventarc\V1\CreateTriggerRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/CreateTrigger', $argument, ['\Google\LongRunning\Operation', 'decode'], $metadata, $options); } /** * Update a single trigger. * @param \Google\Cloud\Eventarc\V1\UpdateTriggerRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function UpdateTrigger(\Google\Cloud\Eventarc\V1\UpdateTriggerRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/UpdateTrigger', $argument, ['\Google\LongRunning\Operation', 'decode'], $metadata, $options); } /** * Delete a single trigger. * @param \Google\Cloud\Eventarc\V1\DeleteTriggerRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function DeleteTrigger(\Google\Cloud\Eventarc\V1\DeleteTriggerRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/DeleteTrigger', $argument, ['\Google\LongRunning\Operation', 'decode'], $metadata, $options); } /** * Get a single Channel. * @param \Google\Cloud\Eventarc\V1\GetChannelRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function GetChannel(\Google\Cloud\Eventarc\V1\GetChannelRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/GetChannel', $argument, ['\Google\Cloud\Eventarc\V1\Channel', 'decode'], $metadata, $options); } /** * List channels. * @param \Google\Cloud\Eventarc\V1\ListChannelsRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function ListChannels(\Google\Cloud\Eventarc\V1\ListChannelsRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/ListChannels', $argument, ['\Google\Cloud\Eventarc\V1\ListChannelsResponse', 'decode'], $metadata, $options); } /** * Create a new channel in a particular project and location. * @param \Google\Cloud\Eventarc\V1\CreateChannelRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function CreateChannel(\Google\Cloud\Eventarc\V1\CreateChannelRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/CreateChannel', $argument, ['\Google\LongRunning\Operation', 'decode'], $metadata, $options); } /** * Update a single channel. * @param \Google\Cloud\Eventarc\V1\UpdateChannelRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function UpdateChannel(\Google\Cloud\Eventarc\V1\UpdateChannelRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/UpdateChannel', $argument, ['\Google\LongRunning\Operation', 'decode'], $metadata, $options); } /** * Delete a single channel. * @param \Google\Cloud\Eventarc\V1\DeleteChannelRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function DeleteChannel(\Google\Cloud\Eventarc\V1\DeleteChannelRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/DeleteChannel', $argument, ['\Google\LongRunning\Operation', 'decode'], $metadata, $options); } /** * Get a single ChannelConnection. * @param \Google\Cloud\Eventarc\V1\GetChannelConnectionRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function GetChannelConnection(\Google\Cloud\Eventarc\V1\GetChannelConnectionRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/GetChannelConnection', $argument, ['\Google\Cloud\Eventarc\V1\ChannelConnection', 'decode'], $metadata, $options); } /** * List channel connections. * @param \Google\Cloud\Eventarc\V1\ListChannelConnectionsRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function ListChannelConnections(\Google\Cloud\Eventarc\V1\ListChannelConnectionsRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/ListChannelConnections', $argument, ['\Google\Cloud\Eventarc\V1\ListChannelConnectionsResponse', 'decode'], $metadata, $options); } /** * Create a new ChannelConnection in a particular project and location. * @param \Google\Cloud\Eventarc\V1\CreateChannelConnectionRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function CreateChannelConnection(\Google\Cloud\Eventarc\V1\CreateChannelConnectionRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/CreateChannelConnection', $argument, ['\Google\LongRunning\Operation', 'decode'], $metadata, $options); } /** * Delete a single ChannelConnection. * @param \Google\Cloud\Eventarc\V1\DeleteChannelConnectionRequest $argument input argument * @param array $metadata metadata * @param array $options call options * @return \Grpc\UnaryCall */ public function DeleteChannelConnection(\Google\Cloud\Eventarc\V1\DeleteChannelConnectionRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection', $argument, ['\Google\LongRunning\Operation', 'decode'], $metadata, $options); } }
googleapis/google-cloud-php
Eventarc/src/V1/EventarcGrpcClient.php
PHP
apache-2.0
9,552
IIS Manager Extension ================ IIS Manager is applicationHost.config file editor. It automatically generate XML Document Transform file (a.k.a applicationHost.xdt) ![IIS Manager](http://f.st-hatena.com/images/fotolife/s/shiba-yan/20151222/20151222011844_original.png) ## Gettting Started 1. Install from Site Extension Gallery (Azure Portal or Kudu) 2. Click the "Save XDT" button after you edit the applicationHost.config. And click the "Restart Site" button, shutdown IIS worker process. ## License [Apache License 2.0](https://github.com/shibayan/IISManager/blob/master/LICENSE)
shibayan/IISManager
README.md
Markdown
apache-2.0
596
--- title: Release 0.47 short-description: Release notes for 0.47 ... # New features ## Allow early return from a script Added the function `subdir_done()`. Its invocation exits the current script at the point of invocation. All previously invoked build targets and commands are build/executed. All following ones are ignored. If the current script was invoked via `subdir()` the parent script continues normally. ## Concatenate string literals returned from `get_define()` After obtaining the value of a preprocessor symbol consecutive string literals are merged into a single string literal. For example a preprocessor symbol's value `"ab" "cd"` is returned as `"abcd"`. ## ARM compiler(version 6) for C and CPP Cross-compilation is now supported for ARM targets using ARM compiler version 6 - ARMCLANG. The required ARMCLANG compiler options for building a shareable library are not included in the current Meson implementation for ARMCLANG support, so it can not build shareable libraries. This current Meson implementation for ARMCLANG support can not build assembly files with arm syntax (we need to use armasm instead of ARMCLANG for the `.s` files with this syntax) and only supports GNU syntax. The default extension of the executable output is `.axf`. The environment path should be set properly for the ARM compiler executables. The `--target`, `-mcpu` options with the appropriate values should be mentioned in the cross file as shown in the snippet below. ```ini [properties] c_args = ['--target=arm-arm-none-eabi', '-mcpu=cortex-m0plus'] cpp_args = ['--target=arm-arm-none-eabi', '-mcpu=cortex-m0plus'] ``` Note: - The current changes are tested on Windows only. - PIC support is not enabled by default for ARM, if users want to use it, they need to add the required arguments explicitly from cross-file(`c_args`/`cpp_args`) or some other way. ## New base build option for LLVM (Apple) bitcode support When building with clang on macOS, you can now build your static and shared binaries with embedded bitcode by enabling the `b_bitcode` [base option](Builtin-options.md#Base_options) by passing `-Db_bitcode=true` to Meson. This is better than passing the options manually in the environment since Meson will automatically disable conflicting options such as `b_asneeded`, and will disable bitcode support on targets that don't support it such as `shared_module()`. Since this requires support in the linker, it is currently only enabled when using Apple ld. In the future it can be extended to clang on other platforms too. ## New compiler check: `check_header()` The existing compiler check `has_header()` only checks if the header exists, either with the `__has_include` C++11 builtin, or by running the pre-processor. However, sometimes the header you are looking for is unusable on some platforms or with some compilers in a way that is only detectable at compile-time. For such cases, you should use `check_header()` which will include the header and run a full compile. Note that `has_header()` is much faster than `check_header()`, so it should be used whenever possible. ## New action `copy:` for `configure_file()` In addition to the existing actions `configuration:` and `command:`, [`configure_file()`](#Reference-manual.md#configure_file) now accepts a keyword argument `copy:` which specifies a new action to copy the file specified with the `input:` keyword argument to a file in the build directory with the name specified with the `output:` keyword argument. These three keyword arguments are, as before, mutually exclusive. You can only do one action at a time. ## New keyword argument `encoding:` for `configure_file()` Add a new keyword to [`configure_file()`](#Reference-manual.md#configure_file) that allows the developer to specify the input and output file encoding. The default value is the same as before: UTF-8. In the past, Meson would not handle non-UTF-8/ASCII files correctly, and in the worst case would try to coerce it to UTF-8 and mangle the data. UTF-8 is the standard encoding now, but sometimes it is necessary to process files that use a different encoding. For additional details see [#3135](https://github.com/mesonbuild/meson/pull/3135). ## New keyword argument `output_format:` for `configure_file()` When called without an input file, `configure_file` generates a C header file by default. A keyword argument was added to allow specifying the output format, for example for use with nasm or yasm: ```meson conf = configuration_data() conf.set('FOO', 1) configure_file('config.asm', configuration: conf, output_format: 'nasm') ``` ## Substitutions in `custom_target(depfile:)` The `depfile` keyword argument to `custom_target` now accepts the `@BASENAME@` and `@PLAINNAME@` substitutions. ## Deprecated `build_always:` for custom targets Setting `build_always` to `true` for a custom target not only marks the target to be always considered out of date, but also adds it to the set of default targets. This option is therefore deprecated and the new option `build_always_stale` is introduced. `build_always_stale` *only* marks the target to be always considered out of date, but does not add it to the set of default targets. The old behaviour can be achieved by combining `build_always_stale` with `build_by_default`. The documentation has been updated accordingly. ## New built-in object type: dictionary Meson dictionaries use a syntax similar to python's dictionaries, but have a narrower scope: they are immutable, keys can only be string literals, and initializing a dictionary with duplicate keys causes a fatal error. Example usage: ```meson d = {'foo': 42, 'bar': 'baz'} foo = d.get('foo') foobar = d.get('foobar', 'fallback-value') foreach key, value : d Do something with key and value endforeach ``` ## Array options treat `-Dopt=` and `-Dopt=[]` as equivalent Prior to this change passing -Dopt= to an array opt would be interpreted as `['']` (an array with an empty string), now `-Dopt=` is the same as `-Dopt=[]`, an empty list. ## Feature detection based on `meson_version:` in `project()` Meson will now print a `WARNING:` message during configuration if you use a function or a keyword argument that was added in a meson version that's newer than the version specified inside `project()`. For example: ```meson project('featurenew', meson_version: '>=0.43') cdata = configuration_data() cdata.set('FOO', 'bar') message(cdata.get_unquoted('FOO')) ``` This will output: ``` The Meson build system Version: 0.47.0.dev1 Source dir: C:\path\to\srctree Build dir: C:\path\to\buildtree Build type: native build Project name: featurenew Project version: undefined Build machine cpu family: x86_64 Build machine cpu: x86_64 WARNING: Project targetting '>=0.43' but tried to use feature introduced in '0.44.0': configuration_data.get_unquoted() Message: bar Build targets in project: 0 WARNING: Project specifies a minimum meson_version '>=0.43' which conflicts with: * 0.44.0: {'configuration_data.get_unquoted()'} ``` ## New type of build option for features A new type of [option called `feature`](Build-options.md#features) can be defined in `meson_options.txt` for the traditional `enabled / disabled / auto` tristate. The value of this option can be passed to the `required` keyword argument of functions `dependency()`, `find_library()`, `find_program()` and `add_languages()`. A new global option `auto_features` has been added to override the value of all `auto` features. It is intended to be used by packagers to have full control on which feature must be enabled or disabled. ## New options to `gnome.gdbus_codegen()` You can now pass additional arguments to gdbus-codegen using the `extra_args` keyword. This is the same for the other gnome function calls. Meson now automatically adds autocleanup support to the generated code. This can be modified by setting the autocleanup keyword. For example: ```meson sources += gnome.gdbus_codegen('com.mesonbuild.Test', 'com.mesonbuild.Test.xml', autocleanup : 'none', extra_args : ['--pragma-once']) ``` ## Made 'install' a top level Meson command You can now run `meson install` in your build directory and it will do the install. It has several command line options you can toggle the behaviour that is not in the default `ninja install` invocation. This is similar to how `meson test` already works. For example, to install only the files that have changed, you can do: ```console $ meson install --only-changed ``` ## `install_mode:` keyword argument extended to all installable targets It is now possible to pass an `install_mode` argument to all installable targets, such as `executable()`, libraries, headers, man pages and custom/generated targets. The `install_mode` argument can be used to specify the file mode in symbolic format and optionally the owner/uid and group/gid for the installed files. ## New built-in option `install_umask` with a default value 022 This umask is used to define the default permissions of files and directories created in the install tree. Files will preserve their executable mode, but the exact permissions will obey the `install_umask`. The `install_umask` can be overridden in the meson command-line: ```console $ meson --install-umask=027 builddir/ ``` A project can also override the default in the `project()` call: ```meson project('myproject', 'c', default_options : ['install_umask=027']) ``` To disable the `install_umask`, set it to `preserve`, in which case permissions are copied from the files in their origin. ## Octal and binary string literals Octal and binary integer literals can now be used in build and option files. ```meson int_493 = 0o755 int_1365 = 0b10101010101 ``` ## New keyword arguments: 'check' and 'capture' for `run_command()` If `check:` is `true`, then the configuration will fail if the command returns a non-zero exit status. The default value is `false` for compatibility reasons. `run_command()` used to always capture the output and stored it for use in build files. However, sometimes the stdout is in a binary format which is meant to be discarded. For that case, you can now set the `capture:` keyword argument to `false`. ## Windows resource files dependencies The `compile_resources()` function of the `windows` module now takes the `depend_files:` and `depends:` keywords. When using binutils's `windres`, dependencies on files `#include`'d by the preprocessor are now automatically tracked. ## Polkit support for privileged installation When running `install`, if installation fails with a permission error and `pkexec` is available, Meson will attempt to use it to spawn a permission dialog for privileged installation and retry the installation. If `pkexec` is not available, the old behaviour is retained and you will need to explicitly run the install step with `sudo`.
MathieuDuponchelle/meson
docs/markdown/Release-notes-for-0.47.0.md
Markdown
apache-2.0
10,895
/* Copyright 2015 Esri 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.​ */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace ConfigureSummaryReport.Model { [DataContract] public class Operators { ObservableCollection<string> _operatorStrings; private ObservableCollection<string> _appendedOperators; public Operators() { ////TODO make sure this doesn't overwrite if OR is saved currentAppendedOperator = "AND"; } [DataMember] public ObservableCollection<string> operatorStrings { get { if (_operatorStrings == null) { _operatorStrings = new ObservableCollection<string>(){ "Equal To", "Not Equal To", "Less Than", "Greator Than" }; } return _operatorStrings; } set { //TODO is this necessary _operatorStrings = value; } } [DataMember] public ObservableCollection<string> appendedOperators { get { if (_appendedOperators == null) { _appendedOperators = new ObservableCollection<string>() { "AND", "OR" }; } return _appendedOperators; } set { //TODO is this necessary _appendedOperators = value; } } //[System.ComponentModel.DefaultValue("AND")] [DataMember] public string currentAppendedOperator { get; set; } } }
Esri/damage-assessment-summary
source/DamageAssessmentSummary/Model/Operators.cs
C#
apache-2.0
2,584
/* * Copyright 2020 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. */ #ifndef ECCLESIA_MAGENT_SYSMODEL_X86_FRU_H_ #define ECCLESIA_MAGENT_SYSMODEL_X86_FRU_H_ #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "ecclesia/magent/lib/eeprom/smbus_eeprom.h" #include "ecclesia/magent/lib/ipmi/ipmi.h" namespace ecclesia { struct FruInfo { std::string product_name; std::string manufacturer; std::string serial_number; std::string part_number; }; class SysmodelFru { public: SysmodelFru(FruInfo fru_info); // Allow the object to be copyable // Make sure that copy construction is relatively light weight. // In cases where it is not feasible to copy construct data members,it may // make sense to wrap the data member in a shared_ptr. SysmodelFru(const SysmodelFru &sysmodel_fru) = default; SysmodelFru &operator=(const SysmodelFru &sysmodel_fru) = default; absl::string_view GetManufacturer() const; absl::string_view GetSerialNumber() const; absl::string_view GetPartNumber() const; private: FruInfo fru_info_; }; // An interface class for reading System Model FRUs. class SysmodelFruReaderIntf { public: virtual ~SysmodelFruReaderIntf() {} // Returns a SysmodelFru instance if available. virtual std::optional<SysmodelFru> Read() = 0; }; // FileSysmodelFruReader provides a caching interface for reading FRUs from a // file. If it is successful in reading the FRU, it will return a copy of that // successful read for the rest of its lifetime. class FileSysmodelFruReader : public SysmodelFruReaderIntf { public: FileSysmodelFruReader(std::string filepath) : filepath_(std::move(filepath)) {} std::optional<SysmodelFru> Read() override; private: std::string filepath_; // Stores the cached FRU that was read. std::optional<SysmodelFru> cached_fru_; }; // This class provides a caching interface for reading a FRU via the IPMI // interface. class IpmiSysmodelFruReader : public SysmodelFruReaderIntf { public: // An IPMI FRU can be uniquely identified by its fru_id and read from the IPMI // interface. explicit IpmiSysmodelFruReader(IpmiInterface *ipmi_intf, uint16_t fru_id) : ipmi_intf_(ipmi_intf), fru_id_(fru_id) {} std::optional<SysmodelFru> Read() override; private: IpmiInterface *const ipmi_intf_; const uint16_t fru_id_; // Stores the cached FRU that was read. std::optional<SysmodelFru> cached_fru_; }; // SmbusEepromFruReader provides a caching interface for reading FRUs from a // SMBUS eeprom. If it is successful in reading the FRU, it will return a copy // of that successful read for the rest of its lifetime. class SmbusEepromFruReader : public SysmodelFruReaderIntf { public: SmbusEepromFruReader(std::unique_ptr<SmbusEeprom> eeprom) : eeprom_(std::move(eeprom)) {} // If the FRU contents are cached, the cached content is returned. Otherwise // performs the low level FRU read, and if successful, populates the cache // and returns the read. std::optional<SysmodelFru> Read() override; private: std::unique_ptr<SmbusEeprom> eeprom_; // Stores the cached FRU that was read. std::optional<SysmodelFru> cached_fru_; }; // SysmodelFruReaderFactory wraps a lambda for constructing a SysmodelFruReader // instance. class SysmodelFruReaderFactory { public: using FactoryFunction = std::function<std::unique_ptr<SysmodelFruReaderIntf>()>; SysmodelFruReaderFactory(std::string name, FactoryFunction factory) : name_(std::move(name)), factory_(std::move(factory)) {} // Returns the name of the associated SysmodelFruReaderIntf. absl::string_view Name() const { return name_; } // Invokes the FactoryFunction to construct a SysmodelFruReaderIntf instance. std::unique_ptr<SysmodelFruReaderIntf> Construct() const { return factory_(); } private: std::string name_; FactoryFunction factory_; }; // This method generates a map of FruReader names to FruReader instances. The // FruReader name is the same as that of the FruReader factory. Thus the factory // names must be unique. absl::flat_hash_map<std::string, std::unique_ptr<SysmodelFruReaderIntf>> CreateFruReaders(absl::Span<const SysmodelFruReaderFactory> fru_factories); } // namespace ecclesia #endif // ECCLESIA_MAGENT_SYSMODEL_X86_FRU_H_
google/ecclesia-machine-management
ecclesia/magent/sysmodel/x86/fru.h
C
apache-2.0
4,978
package com.apwglobal.nice.conv; import com.apwglobal.nice.domain.IncomingPayment; import pl.allegro.webapi.UserIncomingPaymentStruct; public class IncomingPaymentConv { public static IncomingPayment convert(long sellerId, UserIncomingPaymentStruct s) { return new IncomingPayment.Builder() .amount(s.getPayTransAmount()) .buyerId(s.getPayTransBuyerId()) .sellerId(sellerId) .incomplete(s.getPayTransIncomplete()) .itemsCounter(s.getPayTransCount()) .status(s.getPayTransStatus()) .mainTransactionId(s.getPayTransMainId()) .postageAmount(s.getPayTransPostageAmount()) .price(s.getPayTransPrice()) .receiveDate(s.getPayTransRecvDate()) .transactionId(s.getPayTransId()) .build(); } }
awronski/allegro-nice-api
allegro-nice-api/src/main/java/com/apwglobal/nice/conv/IncomingPaymentConv.java
Java
apache-2.0
895
package com.github.pires.obd.commands.mikolaj.WRLambdaEquivalenceRatio; import com.github.pires.obd.enums.AvailableCommandNames; /** * Created by Mikolaj on 2015-08-01. */ public class S2WRLambdaEquivalenceRatioObdCommand extends WRLambdaEquivalenceRatioObdCommand { public S2WRLambdaEquivalenceRatioObdCommand() { super("01 25"); } /** * @param other a {@link S2WRLambdaEquivalenceRatioObdCommand} object. */ public S2WRLambdaEquivalenceRatioObdCommand(S2WRLambdaEquivalenceRatioObdCommand other) { super(other); } @Override public String getName() { return AvailableCommandNames.S2_WR_LAMBDA_ER.getValue(); } }
mikes01/obd-java-api
src/main/java/com/github/pires/obd/commands/mikolaj/WRLambdaEquivalenceRatio/S2WRLambdaEquivalenceRatioObdCommand.java
Java
apache-2.0
686
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <div> <textarea name="" id="txt_value" cols="30" rows="10"></textarea> </div> <button id="btn_set">存储</button> <button id="btn_get">读取</button> <script> if(!window.localStorage) { alert('不支持LocalStorage'); } else { var btnSet = document.querySelector('#btn_set'); var btnGet = document.querySelector('#btn_get'); var txtValue =document.querySelector('#txt_value'); btn_set.addEventListener('click', function() { // localStorage.setItem('key1', txt_value.value); localStorage['key1'] = txt_value.value; // if (window.sessionStorage) { // sessionStorage['key2'] = txt_value.value; // } }); btn_get.addEventListener('click', function() { // txt_value.value = localStorage['key1']; // 不存在 undefined txt_value.value = localStorage.getItem('key1'); // 不存在为空 // if (window.sessionStorage) { // txt_value.value = sessionStorage.getItem('key2'); // } }); } </script> </body> </html>
puyanLiu/LPYFramework
前端练习/06H5/02/06web-storage.html
HTML
apache-2.0
1,277
namespace SE.DSP.Pop.Web.WebHost.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
YangEricLiu/Pop
src/Web/WebHost/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
C#
apache-2.0
156
<!DOCTYPE html> <html lang="en"> <head> <!-- <base href="/sam-angel-make-up/"> --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Sam Angel Make Up : Maquillage Epillation Onglerie à Sénas</title> <link rel="shortcut icon" href="/favicon.ico"> <?php include __DIR__ . '/header-scripts.php'; ?> </head> <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> <?php include __DIR__ . '/menu.php'; ?> <!-- About Section --> <section id="about" class="container content-section"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <h2 class="text-center">Ma Formation Maquillage</h2> <p class="text-justify">Ayant suivi la formation Sophie Lecomte à Aix en Provence, la plus prestigieuse école de maquillage artistique de la région. Aujourd'hui la seule école nationale pouvant délivrer un diplôme d'état. J'ai appris dans cette école : la conception de postiches, péruques, le coiffage, la maquillage studio, théatre, plateau TV, cinéma, ainsi que les effets spéciaux (viellissement, brûlures, cicatrices ...) Lors de cette formation, nous sommes allés maquiller les enfants malades de la Timone (Marseille) lors de l'arbre de Noël. Un investissement humain essentiel mais très destabilisant car à l'époque je n'étais âgé que de 18 ans (évênement profondément marquant). J'ai participé à titre bénévole à de nombreuses organisations ce qui m'a valu de passer dans le journal "Le Provencal" aujourd'hui nommé "La Provence".</p> <p>Exemples de maquillage artisitique :</p> <ul> <li>défillés de mode</li> <li>pièces de théatre</li> <li>reconstitutions historiques</li> </ul> </div> </div> </section> <!-- About Section --> <section id="about" class="container content-section text-justify"> <div class="row"> <div class="col-sm-12"> <ul class="nav nav-tabs nav-justified" role="tablist"> <li role="presentation" class="active"> <a href="#home" aria-controls="home" role="tab" data-toggle="tab"> Raphaël </a> </li> <li role="presentation"> <a href="#profile" aria-controls="profile" role="tab" data-toggle="tab"> Halloween </a> </li> <li role="presentation"> <a href="#messages" aria-controls="messages" role="tab" data-toggle="tab"> Effets </a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="home"> <div id="carousel-maquillage-1" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-maquillage-1" data-slide-to="0" class="active"></li> <li data-target="#carousel-maquillage-1" data-slide-to="1"></li> <li data-target="#carousel-maquillage-1" data-slide-to="2"></li> <li data-target="#carousel-maquillage-1" data-slide-to="3"></li> <li data-target="#carousel-maquillage-1" data-slide-to="4"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="img/photos/maquillage/diaporama-1/maquillage-raphael-11.jpg" alt="Maquillage Rapahael étape 5"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-1/maquillage-raphael-1.jpg" alt="Maquillage Rapahael étape 1"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-1/maquillage-raphael-2.jpg" alt="Maquillage Rapahael étape 2"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-1/maquillage-raphael-3.jpg" alt="Maquillage Rapahael étape 3"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-1/maquillage-raphael-9.jpg" alt="Maquillage Rapahael étape 4"> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-maquillage-1" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Suivant</span> </a> <a class="right carousel-control" href="#carousel-maquillage-1" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Précédent</span> </a> </div> </div> <div role="tabpanel" class="tab-pane" id="profile"> <div id="carousel-maquillage-2" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-maquillage-2" data-slide-to="0" class="active"></li> <li data-target="#carousel-maquillage-2" data-slide-to="1"></li> <li data-target="#carousel-maquillage-2" data-slide-to="2"></li> <li data-target="#carousel-maquillage-1" data-slide-to="3"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="img/photos/maquillage/diaporama-2/maquillage-samantha.jpg" alt="maquillage Samantha"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-2/maquillage-axel.jpg" alt="maquillage Axel"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-2/maquillage-raphael-enzo.jpg" alt="maquillage Raphael Enzo"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-2/maquillage-enzo.jpg" alt="Maquillage Enzo"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-2/maquillage-famille.jpg" alt="Maquillage Famille Vampires"> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-maquillage-2" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Suivant</span> </a> <a class="right carousel-control" href="#carousel-maquillage-2" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Précédent</span> </a> </div> </div> <div role="tabpanel" class="tab-pane" id="messages"> <div id="carousel-maquillage-3" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-maquillage-3" data-slide-to="0" class="active"></li> <li data-target="#carousel-maquillage-3" data-slide-to="1"></li> <li data-target="#carousel-maquillage-3" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="img/photos/maquillage/diaporama-3/maquillage-brulure.jpg" alt="maquillage brulure"> </div> <!-- <div class="item"> <img src="img/photos/maquillage/diaporama-3/maquillage-oeil-au-beurre-noir.jpg" alt="Maquillage oeil au beurre noir"> </div> --> <div class="item"> <img src="img/photos/maquillage/diaporama-3/maquillage-star-wars.jpg" alt="Maquillage star wars"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-3/maquillage-vieillissement.jpg" alt="maquillage vieillissement"> </div> <div class="item"> <img src="img/photos/maquillage/diaporama-3/maquillage-postiche.jpg" alt="maquillage postiche moustache"> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-maquillage-3" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Suivant</span> </a> <a class="right carousel-control" href="#carousel-maquillage-3" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Précédent</span> </a> </div> </div> </div> </div> </div> </section> <!-- About Section --> <section id="about" class="container content-section"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <h2 class="text-center">Maquillage Mariage</h2> <p class="text-justify">Ce jour est unique, c'est le plus beau jour de sa vie ! Je saurais être à votre écoute sur chacun des détails que vous souhaitez pour que ce moment reste inoubliable.</p> </div> </div> </section> <!-- About Section --> <section id="about" class="container content-section text-justify"> <div class="row"> <div class="col-sm-12"> <!-- Nav tabs --> <ul class="nav nav-tabs nav-justified" role="tablist"> <li role="presentation" class="active"> <a href="#home2" aria-controls="home2" role="tab" data-toggle="tab"> Josiane </a> </li> <li role="presentation"> <a href="#profile2" aria-controls="profile2" role="tab" data-toggle="tab"> Cindy </a> </li> <li role="presentation"> <a href="#messages2" aria-controls="messages2" role="tab" data-toggle="tab"> Sam </a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="home2"> <div id="carousel-maquillage-4" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-maquillage-4" data-slide-to="0" class="active"></li> <li data-target="#carousel-maquillage-4" data-slide-to="1"></li> <li data-target="#carousel-maquillage-4" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <!-- <div class="item active"> <img src="img/photos/maquillage-soiree-mariage/diaporama-1/4.jpg"> </div> --> <div class="item active"> <img src="img/photos/maquillage-soiree-mariage/diaporama-1/5.jpg" alt="Maquillage Mariage Géraldine devant l'église'"> </div> <div class="item"> <img src="img/photos/maquillage-soiree-mariage/diaporama-1/6.jpg" alt="Maquillage Mariage Géraldine devant l'olivier'"> </div> <div class="item"> <img src="img/photos/maquillage-soiree-mariage/diaporama-1/7.jpg" alt="Maquillage Mariage Géraldine gros plan"> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-maquillage-4" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Suivant</span> </a> <a class="right carousel-control" href="#carousel-maquillage-4" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Précédent</span> </a> </div> </div> <div role="tabpanel" class="tab-pane" id="profile2"> <div id="carousel-maquillage-5" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-maquillage-5" data-slide-to="0" class="active"></li> <li data-target="#carousel-maquillage-5" data-slide-to="1"></li> <li data-target="#carousel-maquillage-5" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="img/photos/maquillage-soiree-mariage/diaporama-2/1.jpg" alt="Mariage Josianne blonde"> </div> <div class="item"> <img src="img/photos/maquillage-soiree-mariage/diaporama-2/2.jpg" alt="Mariage Josianne rouge à lèvre"> </div> <div class="item"> <img src="img/photos/maquillage-soiree-mariage/diaporama-2/3.jpg" alt="Mariage Josianne brune"> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-maquillage-5" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Suivant</span> </a> <a class="right carousel-control" href="#carousel-maquillage-5" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Précédent</span> </a> </div> </div> <div role="tabpanel" class="tab-pane" id="messages2"> <div id="carousel-maquillage-6" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-maquillage-6" data-slide-to="0" class="active"></li> <li data-target="#carousel-maquillage-6" data-slide-to="1"></li> <li data-target="#carousel-maquillage-6" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="img/photos/maquillage-soiree-mariage/diaporama-3/8.jpg" alt="Mariage Samantha à la mairie"> </div> <div class="item"> <img src="img/photos/maquillage-soiree-mariage/diaporama-3/9.jpg" alt="Mariage Samantha bouquet de fleur"> </div> <div class="item"> <img src="img/photos/maquillage-soiree-mariage/diaporama-3/10.jpg" alt="Mariage Samantha fard à paupière"> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-maquillage-6" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Suivant</span> </a> <a class="right carousel-control" href="#carousel-maquillage-6" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Précédent</span> </a> </div> </div> </div> </div> </div> </section> <section id="about" class="container content-section text-justify"> <div class="row"> <div class="col-sm-12 margin-bottom-lg"> <?php include __DIR__ . '/facebook.php'; ?> </div> </div> <div class="row margin-top-lg"> <h2 class="text-center">Tarifs Maquillage</h2> <div class="col-sm-6 col-sm-offset-3 col-lg-6 col-lg-offset-3"> <table class="table"> <tr> <td>Jour</td> <td class="price-table">20 €</td> </tr> <tr> <td>Nuit</td> <td class="price-table">25 €</td> </tr> </table> <h2 class="text-center">Mariage : <strong>Essais offerts</strong></h2> <p>Plusieurs forfaits mariés sont disponibles :<br> Exemple : pose gel sur ongle naturel + maquillage = 70 €<br> Nous vous comblerons pour le plus beau jour de votre vie : téléphonez moi pour avoir tous nos tarifs et forfaits.</p> </div> </div> </section> <?php include __DIR__ . '/contact.php'; ?> <?php include __DIR__ . '/footer.php'; ?> </body> </html>
hugsbrugs/sam-angel-make-up
src/html/maquillage.php
PHP
apache-2.0
21,660
/* * 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. */ package de.knightsoftnet.mtwidgets.client.ui.widget; import de.knightsoftnet.mtwidgets.client.ui.widget.features.HasAutofocus; import de.knightsoftnet.mtwidgets.client.ui.widget.features.HasValidationMessageElement; import de.knightsoftnet.mtwidgets.client.ui.widget.helper.ErrorMessageFormater; import de.knightsoftnet.mtwidgets.client.ui.widget.helper.FeatureCheck; import de.knightsoftnet.mtwidgets.client.ui.widget.helper.IdAndNameBean; import de.knightsoftnet.mtwidgets.client.ui.widget.helper.IdAndNameIdComperator; import de.knightsoftnet.mtwidgets.client.ui.widget.helper.IdAndNameNameComperator; import de.knightsoftnet.mtwidgets.client.ui.widget.helper.ListSortEnum; import de.knightsoftnet.mtwidgets.client.ui.widget.helper.MessagesForValues; import de.knightsoftnet.validators.client.decorators.ExtendedValueBoxEditor; import com.google.gwt.editor.client.EditorError; import com.google.gwt.editor.client.HasEditorErrors; import com.google.gwt.editor.client.IsEditor; import com.google.gwt.editor.ui.client.adapters.ValueBoxEditor; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Focusable; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.HasEnabled; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.impl.FocusImpl; import elemental.dom.NodeList; import elemental.html.InputElement; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; /** * a radio box with id and name which is sortable and returns id. * * @author Manfred Tremmel * * @param <T> type of the id */ public class SortableIdAndNameRadioButton<T extends Comparable<T>> extends Composite implements HasValue<T>, HasEditorErrors<T>, IsEditor<ValueBoxEditor<T>>, Focusable, HasValidationMessageElement, HasAutofocus, HasEnabled { private boolean valueChangeHandlerInitialized; private final String widgetId; private final ListSortEnum sortOrder; private final MessagesForValues<T> messages; private final List<IdAndNameBean<T>> entries; private final FlowPanel flowPanel; private final Map<T, RadioButton> idToButtonMap; private final ValueBoxEditor<T> editor; private static final FocusImpl IMPL = FocusImpl.getFocusImplForWidget(); private HTMLPanel validationMessageElement; private boolean enabled; /** * widget ui constructor. * * @param pwidgetId widget id which is the same for all created radio buttons * @param psort the sort order of the countries * @param pmessages message resolver * @param pids ids to add to listBox */ @SafeVarargs public SortableIdAndNameRadioButton(final String pwidgetId, final ListSortEnum psort, final MessagesForValues<T> pmessages, final T... pids) { this(pwidgetId, psort, pmessages, Arrays.asList(pids)); } /** * widget ui constructor. * * @param pwidgetId widget id which is the same for all created radio buttons * @param psort the sort order of the countries * @param pmessages message resolver * @param pids ids to add to listBox */ public SortableIdAndNameRadioButton(final String pwidgetId, final ListSortEnum psort, final MessagesForValues<T> pmessages, final Collection<T> pids) { super(); this.widgetId = pwidgetId; this.sortOrder = psort; this.messages = pmessages; this.entries = new ArrayList<>(pids.size()); this.flowPanel = new FlowPanel(); this.idToButtonMap = new HashMap<>(); this.enabled = true; this.fillEntries(pids); this.initWidget(this.flowPanel); this.editor = new ExtendedValueBoxEditor<>(this, null); } /** * fill entries of the radio buttons. * * @param pids list of entries */ private void fillEntries(final Collection<T> pids) { this.entries.clear(); for (final T proEnum : pids) { this.entries.add(new IdAndNameBean<>(proEnum, this.messages.name(proEnum))); } if (this.sortOrder != null) { switch (this.sortOrder) { case ID_ASC: Collections.sort(this.entries, new IdAndNameIdComperator<T>()); break; case ID_DSC: Collections.sort(this.entries, Collections.reverseOrder(new IdAndNameIdComperator<T>())); break; case NAME_ASC: Collections.sort(this.entries, new IdAndNameNameComperator<T>()); break; case NAME_DSC: Collections.sort(this.entries, Collections.reverseOrder(new IdAndNameNameComperator<T>())); break; default: break; } } this.flowPanel.clear(); for (final IdAndNameBean<T> entry : this.entries) { final RadioButton radioButton = new RadioButton(this.widgetId, entry.getName()); radioButton.setFormValue(Objects.toString(entry.getId())); radioButton.setEnabled(this.enabled); this.flowPanel.add(radioButton); this.idToButtonMap.put(entry.getId(), radioButton); } } @Override public HandlerRegistration addValueChangeHandler(final ValueChangeHandler<T> phandler) { // Is this the first value change handler? If so, time to add handlers if (!this.valueChangeHandlerInitialized) { this.ensureDomEventHandlers(); this.valueChangeHandlerInitialized = true; } return this.addHandler(phandler, ValueChangeEvent.getType()); } protected void ensureDomEventHandlers() { for (final RadioButton radioButton : this.idToButtonMap.values()) { radioButton.addValueChangeHandler(event -> ValueChangeEvent.fire(this, this.getValue())); } } @Override public T getValue() { for (final Entry<T, RadioButton> entry : this.idToButtonMap.entrySet()) { if (BooleanUtils.isTrue(entry.getValue().getValue())) { return entry.getKey(); } } return null; } @Override public void setValue(final T pvalue) { this.setValue(pvalue, false); } @Override public void setValue(final T pvalue, final boolean pfireEvents) { final T oldValue = this.getValue(); final RadioButton radioButton = this.idToButtonMap.get(pvalue); if (radioButton == null) { for (final RadioButton entry : this.idToButtonMap.values()) { entry.setValue(Boolean.FALSE); } } else { this.idToButtonMap.get(pvalue).setValue(Boolean.TRUE); } if (pfireEvents) { ValueChangeEvent.fireIfNotEqual(this, oldValue, pvalue); } } @Override public int getTabIndex() { if (this.flowPanel.getWidgetCount() > 0) { if (this.flowPanel.getWidget(0) instanceof Focusable) { return ((Focusable) this.flowPanel.getWidget(0)).getTabIndex(); } } return -1; } @Override public void setAccessKey(final char pkey) { if (this.flowPanel.getWidgetCount() > 0) { if (this.flowPanel.getWidget(0) instanceof Focusable) { ((Focusable) this.flowPanel.getWidget(0)).setAccessKey(pkey); } } } @Override public void setFocus(final boolean pfocused) { if (this.flowPanel.getWidgetCount() > 0) { if (this.flowPanel.getWidget(0) instanceof Focusable) { ((Focusable) this.flowPanel.getWidget(0)).setFocus(pfocused); } } } @Override public void setTabIndex(final int pindex) { for (int i = 0; i < this.flowPanel.getWidgetCount(); i++) { SortableIdAndNameRadioButton.IMPL.setTabIndex(this.flowPanel.getWidget(i).getElement(), pindex + i); } } @Override public void showErrors(final List<EditorError> errors) { final elemental.dom.Element headElement = this.getElement().cast(); final NodeList inputElements = headElement.getElementsByTagName("input"); final Set<String> messages = new HashSet<>(); for (final EditorError error : errors) { if (this.editorErrorMatches(error)) { messages.add(error.getMessage()); } } if (messages.isEmpty()) { for (int i = 0; i < inputElements.length(); i++) { final InputElement input = (InputElement) inputElements.at(i); if (FeatureCheck.supportCustomValidity(input)) { input.setCustomValidity(StringUtils.EMPTY); } if (this.validationMessageElement == null) { input.setTitle(StringUtils.EMPTY); } } if (this.validationMessageElement != null) { this.validationMessageElement.getElement().removeAllChildren(); } } else { final String messagesAsString = ErrorMessageFormater.messagesToString(messages); for (int i = 0; i < inputElements.length(); i++) { final InputElement input = (InputElement) inputElements.at(i); if (FeatureCheck.supportCustomValidity(input)) { input.setCustomValidity(messagesAsString); } if (this.validationMessageElement == null) { input.setTitle(messagesAsString); } } if (this.validationMessageElement != null) { this.validationMessageElement.getElement() .setInnerSafeHtml(ErrorMessageFormater.messagesToList(messages)); } } } /** * Checks if a error belongs to this widget. * * @param perror editor error to check * @return true if the error belongs to this widget */ protected boolean editorErrorMatches(final EditorError perror) { return perror != null && perror.getEditor() != null && (this.equals(perror.getEditor()) || perror.getEditor().equals(this.asEditor())); } @Override public ValueBoxEditor<T> asEditor() { return this.editor; } @Override public boolean isAutofocus() { final elemental.dom.Element headElement = this.getElement().cast(); final NodeList inputElements = headElement.getElementsByTagName("input"); final InputElement input = (InputElement) inputElements.at(0); return input.isAutofocus(); } @Override public void setAutofocus(final boolean arg) { final elemental.dom.Element headElement = this.getElement().cast(); final NodeList inputElements = headElement.getElementsByTagName("input"); final InputElement input = (InputElement) inputElements.at(0); input.setAutofocus(arg); } @Override public void setValidationMessageElement(final HTMLPanel pelement) { this.validationMessageElement = pelement; } @Override public HTMLPanel getValidationMessageElement() { return this.validationMessageElement; } @Override public boolean isEnabled() { return this.enabled; } @Override public void setEnabled(final boolean penabled) { this.enabled = penabled; for (final RadioButton entry : this.idToButtonMap.values()) { entry.setEnabled(penabled); } } }
ManfredTremmel/gwt-mt-widgets
src/main/java/de/knightsoftnet/mtwidgets/client/ui/widget/SortableIdAndNameRadioButton.java
Java
apache-2.0
12,000
# Peronospora medicaginis-orbicularis Rayss SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Peronospora medicaginis-orbicularis Rayss ### Remarks null
mdoering/backbone
life/Chromista/Oomycota/Oomycetes/Peronosporales/Peronosporaceae/Peronospora/Peronospora medicaginis-orbicularis/README.md
Markdown
apache-2.0
211
package apoc.temporal; import apoc.util.TestUtil; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.neo4j.test.rule.DbmsRule; import org.neo4j.test.rule.ImpermanentDbmsRule; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; public class TemporalProceduresTest { @Rule public ExpectedException expected = ExpectedException.none(); @ClassRule public static DbmsRule db = new ImpermanentDbmsRule(); @BeforeClass public static void setUp() throws Exception { TestUtil.registerProcedure(db, TemporalProcedures.class); } @Test public void shouldFormatDate() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( date( { year: 2018, month: 12, day: 10 } ), \"yyyy-MM-dd\" ) as output"); assertEquals("2018-12-10", output); } @Test public void shouldFormatDateTime() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( datetime( { year: 2018, month: 12, day: 10, hour: 12, minute: 34, second: 56, nanosecond: 123456789 } ), \"yyyy-MM-dd'T'HH:mm:ss.SSSS\" ) as output"); assertEquals("2018-12-10T12:34:56.1234", output); } @Test public void shouldFormatLocalDateTime() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( localdatetime( { year: 2018, month: 12, day: 10, hour: 12, minute: 34, second: 56, nanosecond: 123456789 } ), \"yyyy-MM-dd'T'HH:mm:ss.SSSS\" ) as output"); assertEquals("2018-12-10T12:34:56.1234", output); } @Test public void shouldFormatTime() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( time( { hour: 12, minute: 34, second: 56, nanosecond: 123456789, timezone: 'GMT' } ), \"HH:mm:ss.SSSSZ\" ) as output"); assertEquals("12:34:56.1234+0000", output); } @Test public void shouldFormatLocalTime() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( localtime( { hour: 12, minute: 34, second: 56, nanosecond: 123456789 } ), \"HH:mm:ss.SSSS\" ) as output"); assertEquals("12:34:56.1234", output); } @Test public void shouldFormatDuration() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( duration('P0M0DT4820.487660000S'), \"HH:mm:ss.SSSS\" ) as output"); assertEquals("01:20:20.4876", output); } @Test public void shouldFormatDurationTemporal() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.formatDuration( duration('P0M0DT4820.487660000S'), \"HH:mm:ss\" ) as output"); assertEquals("01:20:20", output); } @Test public void shouldFormatDurationTemporalISO() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.formatDuration( duration('P0M0DT4820.487660000S'), \"ISO_DATE_TIME\" ) as output"); assertEquals("0000-01-01T01:20:20.48766", output); } @Test public void shouldFormatIsoDate() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( date( { year: 2018, month: 12, day: 10 } ), 'ISO_DATE' ) as output"); assertEquals("2018-12-10", output); } @Test public void shouldFormatIsoLocalDateTime() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( localdatetime( { year: 2018, month: 12, day: 10, hour: 12, minute: 34, second: 56, nanosecond: 123456789 } ), 'ISO_LOCAL_DATE_TIME' ) as output"); assertEquals("2018-12-10T12:34:56.123456789", output); } @Test public void shouldReturnTheDateWithDefault() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( localdatetime( { year: 2018, month: 12, day: 10, hour: 12, minute: 34, second: 56, nanosecond: 123456789 } )) as output"); assertEquals("2018-12-10", output); } @Test public void shouldReturnTheDateWithDefaultElastic() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( localdatetime( { year: 2018, month: 12, day: 10, hour: 12, minute: 34, second: 56, nanosecond: 123456789 } ), 'DATE_HOUR_MINUTE_SECOND_FRACTION') as output"); assertEquals("2018-12-10T12:34:56.123", output); } @Test public void shouldFormatIsoDateWeek() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( date( { year: 2018, month: 12, day: 10 } ), 'date' ) as output"); assertEquals("2018-12-10", output); } @Test public void shouldFormatIsoYear() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( date( { year: 2018, month: 12, day: 10 } ), 'date' ) as output"); assertEquals("2018-12-10", output); } @Test public void shouldFormatIsoOrdinalDate() throws Throwable { String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( date( { year: 2018, month: 12, day: 10 } ), 'ordinal_date' ) as output"); assertEquals("2018-344", output); } @Test public void shouldFormatIsoDateWeekError(){ expected.expect(instanceOf(RuntimeException.class)); String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.format( date( { year: 2018, month: 12, day: 10 } ), 'WRONG_FORMAT' ) as output"); assertEquals("2018-12-10", output); } @Test public void shouldFormatDurationIsoDateWeekError(){ expected.expect(instanceOf(RuntimeException.class)); String output = TestUtil.singleResultFirstColumn(db, "RETURN apoc.temporal.formatDuration( date( { year: 2018, month: 12, day: 10 } ), 'wrongDuration' ) as output"); assertEquals("2018-12-10", output); } }
neo4j-contrib/neo4j-apoc-procedures
core/src/test/java/apoc/temporal/TemporalProceduresTest.java
Java
apache-2.0
6,276
/** * 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. */ package com.streamsets.datacollector.restapi.bean; public enum ThresholdTypeJson { COUNT, PERCENTAGE }
kiritbasu/datacollector
container/src/main/java/com/streamsets/datacollector/restapi/bean/ThresholdTypeJson.java
Java
apache-2.0
914
// THIS FILE IS PURPOSEFULLY EMPTY FOR R.JS COMPILER // IT IS A COMPILER TARGET FILE, AS WE CANNOT CREATE NEW FILES DYNAMICALLY FOR // THE COMPILER; define("splunkjs/compiled/js_charting", function(){}); define('js_charting/util/math_utils',['underscore', 'util/math_utils'], function(_, splunkMathUtils) { var HEX_REGEX = /^( )*(0x|-0x)/; // an extended version of parseFloat that will handle numbers encoded in hex format (i.e. "0xff") // and is stricter than native JavaScript parseFloat for decimal numbers var parseFloat = function(str) { // determine if the string is a hex number by checking if it begins with '0x' or '-0x', // in which case delegate to parseInt with a 16 radix if(HEX_REGEX.test(str)) { return parseInt(str, 16); } return splunkMathUtils.strictParseFloat(str); }; // shortcut for base-ten log, also rounds to four decimal points of precision to make pretty numbers var logBaseTen = function(num) { var result = Math.log(num) / Math.LN10; return (Math.round(result * 10000) / 10000); }; // transforms numbers to a normalized log scale that can handle negative numbers // rounds to four decimal points of precision var absLogBaseTen = function(num) { if(typeof num !== "number") { num = parseFloat(num); } if(_(num).isNaN()) { return num; } var isNegative = (num < 0), result; if(isNegative) { num = -num; } if(num < 10) { num += (10 - num) / 10; } result = logBaseTen(num); return (isNegative) ? -result : result; }; // reverses the transformation made by absLogBaseTen above // rounds to three decimal points of precision var absPowerTen = function(num) { if(typeof num !== "number") { num = parseFloat(num); } if(_(num).isNaN()) { return num; } var isNegative = (num < 0), result; if(isNegative) { num = -num; } result = Math.pow(10, num); if(result < 10) { result = 10 * (result - 1) / (10 - 1); } result = (isNegative) ? -result : result; return (Math.round(result * 1000) / 1000); }; // calculates the power of ten that is closest to but not greater than the number // negative numbers are treated as their absolute value and the sign of the result is flipped before returning var nearestPowerOfTen = function(num) { if(typeof num !== "number") { return NaN; } var isNegative = num < 0; num = (isNegative) ? -num : num; var log = logBaseTen(num), result = Math.pow(10, Math.floor(log)); return (isNegative) ? -result: result; }; var roundWithMin = function(value, min) { return Math.max(Math.round(value), min); }; var roundWithMinMax = function(value, min, max) { var roundVal = Math.round(value); if(roundVal < min) { return min; } if(roundVal > max) { return max; } return roundVal; }; var degreeToRadian = function(degree) { return (degree * Math.PI) / 180; }; // returns the number of digits of precision after the decimal point // optionally accepts a maximum number, after which point it will stop looking and return the max var getDecimalPrecision = function(num, max) { max = max || Infinity; var precision = 0; while(precision < max && num.toFixed(precision) !== num.toString()) { precision += 1; } return precision; }; return ({ parseFloat: parseFloat, logBaseTen: logBaseTen, absLogBaseTen: absLogBaseTen, absPowerTen: absPowerTen, nearestPowerOfTen: nearestPowerOfTen, roundWithMin: roundWithMin, roundWithMinMax: roundWithMinMax, degreeToRadian: degreeToRadian, getDecimalPrecision: getDecimalPrecision }); }); define('js_charting/helpers/DataSet',['jquery', 'underscore', '../util/math_utils'], function($, _, mathUtils) { var DataSet = function(data) { var fields = data.fields || {}; var series = data.columns || {}; this.fields = []; this.seriesList = []; this.fieldMetadata = {}; _(fields).each(function(field, i) { var fieldName; if(_.isObject(field)) { fieldName = field.name; this.fieldMetadata[fieldName] = field; } else { fieldName = field; } if(($.inArray(fieldName, this.ALLOWED_HIDDEN_FIELDS) > -1) || this.isDataField(fieldName)){ this.fields.push(fieldName); this.seriesList.push($.extend([], series[i])); } }, this); this.length = this.fields.length; // create an instance-specific memoized copy of getSeriesAsFloats this.getSeriesAsFloats = _.memoize(this.getSeriesAsFloats, this.seriesAsFloatsMemoizeHash); }; DataSet.prototype = { ALLOWED_HIDDEN_FIELDS: ['_span', '_lower', '_predicted', '_upper', '_tc'], DATA_FIELD_REGEX: /^[^_]|^_time/, allDataFields: function() { return _(this.fields).filter(this.isDataField, this); }, isDataField: function(field){ return this.DATA_FIELD_REGEX.test(field); }, isTotalValue: function(value) { return (value === 'ALL'); }, hasField: function(name) { return (_(this.fields).indexOf(name) > -1); }, fieldAt: function(index) { return this.fields[index]; }, fieldIsGroupby: function(name) { return (this.fieldMetadata[name] && this.fieldMetadata[name].hasOwnProperty('groupby_rank')); }, seriesAt: function(index) { return this.seriesList[index]; }, getSeries: function(name) { var index = _(this.fields).indexOf(name); if(index === -1) { return []; } return this.seriesList[index]; }, getSeriesAsFloats: function(name, options) { options = options || {}; var series = this.getSeries(name), nullsToZero = options.nullValueMode === 'zero', logScale = options.scale === 'log', asFloats = []; for(var i = 0; i < series.length; i++) { var floatVal = mathUtils.parseFloat(series[i]); if(_.isNaN(floatVal)) { asFloats.push(nullsToZero ? 0 : null); continue; } asFloats.push(logScale ? mathUtils.absLogBaseTen(floatVal) : floatVal); } return asFloats; }, // this is a targeted fix for the case where the back-end adds an 'ALL' data point to the end of a time series // but could be expanded into a more generic handler as we grow into it getSeriesAsTimestamps: function(name) { var series = this.getSeries(name); if(this.isTotalValue(_(series).last())) { return series.slice(0, -1); } return series; }, seriesAsFloatsMemoizeHash: function(name, options) { options = options || {}; return name + options.scale + options.nullValueMode; }, toJSON: function() { return ({ fields: this.fields, columns: this.seriesList }); } }; return DataSet; }); define('js_charting/util/dom_utils',['jquery', 'underscore'], function($, _) { // this is copied from the Highcharts source var hasSVG = !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect; // set up some aliases for jQuery 'on' that will work in older versions of jQuery var jqOn = _($.fn.on).isFunction() ? $.fn.on : $.fn.bind; var jqOff = _($.fn.off).isFunction() ? $.fn.off : $.fn.unbind; // a cross-renderer way to update a legend item's text content var setLegendItemText = function(legendItem, text) { if(legendItem.attr('text') === text) { return; } legendItem.added = true; // the SVG renderer needs this legendItem.attr({text: text}); }; var hideTickLabel = function(tick) { var label = tick.label, nodeName = tick.label.element.nodeName.toLowerCase(); if(nodeName === 'text') { label.hide(); } else { $(label.element).hide(); } }; var showTickLabel = function(tick) { var label = tick.label, nodeName = tick.label.element.nodeName.toLowerCase(); if(nodeName === 'text') { label.show(); } else { $(label.element).show(); } }; return ({ hasSVG: hasSVG, jQueryOn: jqOn, jQueryOff: jqOff, setLegendItemText: setLegendItemText, hideTickLabel: hideTickLabel, showTickLabel: showTickLabel }); }); define('js_charting/helpers/EventMixin',['jquery', '../util/dom_utils'], function($, domUtils) { return ({ on: function(eventType, callback) { domUtils.jQueryOn.call($(this), eventType, callback); }, off: function(eventType, callback) { domUtils.jQueryOff.call($(this), eventType, callback); }, trigger: function(eventType, extraParams) { $(this).trigger(eventType, extraParams); } }); }); define('js_charting/util/color_utils',['underscore', 'splunk.util'], function(_, splunkUtils) { // converts a hex number to its css-friendly counterpart, with optional alpha transparency field // returns null if the input is cannot be parsed to a valid number or if the number is out of range var colorFromHex = function(hexNum, alpha) { if(typeof hexNum !== 'number') { hexNum = parseInt(hexNum, 16); } if(_(hexNum).isNaN() || hexNum < 0x000000 || hexNum > 0xffffff) { return null; } var r = (hexNum & 0xff0000) >> 16, g = (hexNum & 0x00ff00) >> 8, b = hexNum & 0x0000ff; return ((alpha === undefined) ? ('rgb(' + r + ',' + g + ',' + b + ')') : ('rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')')); }; // converts an rgba value to rgb by stripping out the alpha. willl return the unchanged parameter // if an rgb value is passed rather than rgba var stripOutAlpha = function(color){ var rgb = color.split(','), thirdChar = rgb[0].charAt(3); if(thirdChar === 'a'){ rgb[0] = rgb[0].replace('rgba','rgb'); rgb[(rgb.length -1)] = ')'; rgb = rgb.join(); rgb = rgb.replace(',)',')'); return rgb; } return color; }; // coverts a color string in either hex (must be long form) or rgb format into its corresponding hex number // returns zero if the color string can't be parsed as either format // TODO: either add support for short form or emit an error var hexFromColor = function(color) { var normalizedColor = splunkUtils.normalizeColor(color); return (normalizedColor) ? parseInt(normalizedColor.replace('#', '0x'), 16) : 0; }; // given a color string (in long-form hex or rgb form) or a hex number, // formats the color as an rgba string with the given alpha transparency // TODO: currently fails somewhat silently if an un-parseable or out-of-range input is given var addAlphaToColor = function(color, alpha) { var colorAsHex = (typeof color === 'number') ? color : hexFromColor(color); return colorFromHex(colorAsHex, alpha); }; // calculate the luminance of a color based on its hex value // returns zero if the input is cannot be parsed to a valid number or if the number is out of range // equation for luminance found at http://en.wikipedia.org/wiki/Luma_(video) var getLuminance = function(hexNum) { if(typeof hexNum !== "number") { hexNum = parseInt(hexNum, 16); } if(isNaN(hexNum) || hexNum < 0x000000 || hexNum > 0xffffff) { return 0; } var r = (hexNum & 0xff0000) >> 16, g = (hexNum & 0x00ff00) >> 8, b = hexNum & 0x0000ff; return Math.round(0.2126 * r + 0.7152 * g + 0.0722 * b); }; return ({ colorFromHex: colorFromHex, stripOutAlpha: stripOutAlpha, hexFromColor: hexFromColor, addAlphaToColor: addAlphaToColor, getLuminance: getLuminance }); }); define('js_charting/util/parsing_utils',['underscore', 'splunk.util'], function(_, splunkUtils) { // normalize a boolean, a default state can optionally be defined for when the value is undefined var normalizeBoolean = function(value, defaultState) { if(_(value).isUndefined()) { return !!defaultState; } return splunkUtils.normalizeBoolean(value); }; // translates a JSON-style serialized map in to a primitive object // cannot handle nested objects // value strings should be un-quoted or double-quoted and will be stripped of leading/trailing whitespace // will not cast to numbers or booleans var stringToObject = function(str) { if(!str) { return false; } var i, propList, loopKv, loopKey, map = {}; str = trimWhitespace(str); var strLen = str.length; if(str.charAt(0) !== '{' || str.charAt(strLen - 1) !== '}') { return false; } if(/^\{\s*\}$/.test(str)) { return {}; } str = str.substr(1, strLen - 2); propList = escapeSafeSplit(str, ','); for(i = 0; i < propList.length; i++) { loopKv = escapeSafeSplit(propList[i], ':'); loopKey = trimWhitespace(loopKv[0]); if(loopKey[0] === '"') { loopKey = loopKey.substring(1); } if(_(loopKey).last() === '"') { loopKey = loopKey.substring(0, loopKey.length - 1); } loopKey = unescapeChars(loopKey, ['{', '}', '[', ']', '(', ')', ',', ':', '"']); map[loopKey] = trimWhitespace(loopKv[1]); } return map; }; // translates a JSON-style serialized list in to a primitive array // cannot handle nested arrays var stringToArray = function(str) { if(!str) { return false; } str = trimWhitespace(str); var strLen = str.length; if(str.charAt(0) !== '[' || str.charAt(strLen - 1) !== ']') { return false; } if(/^\[\s*\]$/.test(str)) { return []; } str = str.substr(1, strLen - 2); return splunkUtils.stringToFieldList(str); }; // TODO: replace with $.trim var trimWhitespace = function(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); }; var escapeSafeSplit = function(str, delimiter, escapeChar) { escapeChar = escapeChar || '\\'; var unescapedPieces = str.split(delimiter), // the escaped pieces list initially contains the first element of the unescaped pieces list // we use shift() to also remove that element from the unescaped pieces escapedPieces = [unescapedPieces.shift()]; // now loop over the remaining unescaped pieces // if the last escaped piece ends in an escape character, perform a concatenation to undo the split // otherwise append the new piece to the escaped pieces list _(unescapedPieces).each(function(piece) { var lastEscapedPiece = _(escapedPieces).last(); if(_(lastEscapedPiece).last() === escapeChar) { escapedPieces[escapedPieces.length - 1] += (delimiter + piece); } else { escapedPieces.push(piece); } }); return escapedPieces; }; var unescapeChars = function(str, charList) { _(charList).each(function(chr) { // looks weird, but the first four slashes add a single escaped '\' to the regex // and the next two escape the character itself within the regex var regex = new RegExp('\\\\\\' + chr, 'g'); str = str.replace(regex, chr); }); return str; }; // this will be improved to do some SVG-specific escaping var escapeHtml = function(input){ return splunkUtils.escapeHtml(input); }; var escapeSVG = function(input) { return ("" + input).replace(/</g, '&lt;').replace(/>/g, '&gt;'); }; var stringToHexArray = function(colorStr) { var i, hexColor, colors = stringToArray(colorStr); if(!colors) { return false; } for(i = 0; i < colors.length; i++) { hexColor = parseInt(colors[i], 16); if(isNaN(hexColor)) { return false; } colors[i] = hexColor; } return colors; }; // a simple utility method for comparing arrays, assumes one-dimensional arrays of primitives, // performs strict comparisons var arraysAreEquivalent = function(array1, array2) { // make sure these are actually arrays if(!(array1 instanceof Array) || !(array2 instanceof Array)) { return false; } if(array1 === array2) { // true if they are the same object return true; } if(array1.length !== array2.length) { // false if they are different lengths return false; } // false if any of their elements don't match for(var i = 0; i < array1.length; i++) { if(array1[i] !== array2[i]) { return false; } } return true; }; var getLegendProperties = function(properties) { var remapped = {}, legendProps = filterPropsByRegex(properties, /legend[.]/); _(legendProps).each(function(value, key) { remapped[key.replace(/^legend[.]/, '')] = value; }); return remapped; }; // returns a map of properties that apply either to the x-axis or to x-axis labels // all axis-related keys are renamed to 'axis' and all axis-label-related keys are renamed to 'axisLabels' var getXAxisProperties = function(properties) { var key, newKey, remapped = {}, axisProps = filterPropsByRegex(properties, /(axisX|primaryAxis|axisLabelsX|axisTitleX|gridLinesX)/); for(key in axisProps) { if(axisProps.hasOwnProperty(key)) { if(!xAxisKeyIsTrumped(key, properties)) { newKey = key.replace(/(axisX|primaryAxis)/, "axis"); newKey = newKey.replace(/axisLabelsX/, "axisLabels"); newKey = newKey.replace(/axisTitleX/, "axisTitle"); newKey = newKey.replace(/gridLinesX/, "gridLines"); remapped[newKey] = axisProps[key]; } } } return remapped; }; // checks if the given x-axis key is deprecated, and if so returns true if that key's // non-deprecated counterpart is set in the properties map, otherwise returns false var xAxisKeyIsTrumped = function(key, properties) { if(!(/primaryAxis/.test(key))) { return false; } if(/primaryAxisTitle/.test(key)) { return properties[key.replace(/primaryAxisTitle/, "axisTitleX")]; } return properties[key.replace(/primaryAxis/, "axisX")]; }; // returns a map of properties that apply either to the y-axis or to y-axis labels // all axis-related keys are renamed to 'axis' and all axis-label-related keys are renamed to 'axisLabels' var getYAxisProperties = function(properties) { var key, newKey, remapped = {}, axisProps = filterPropsByRegex(properties, /(axisY|secondaryAxis|axisLabelsY|axisTitleY|gridLinesY)/); for(key in axisProps) { if(axisProps.hasOwnProperty(key)) { if(!yAxisKeyIsTrumped(key, properties)) { newKey = key.replace(/(axisY|secondaryAxis)/, "axis"); newKey = newKey.replace(/axisLabelsY/, "axisLabels"); newKey = newKey.replace(/axisTitleY/, "axisTitle"); newKey = newKey.replace(/gridLinesY/, "gridLines"); remapped[newKey] = axisProps[key]; } } } return remapped; }; // checks if the given y-axis key is deprecated, and if so returns true if that key's // non-deprecated counterpart is set in the properties map, otherwise returns false var yAxisKeyIsTrumped = function(key, properties) { if(!(/secondaryAxis/.test(key))) { return false; } if(/secondaryAxisTitle/.test(key)) { return properties[key.replace(/secondaryAxisTitle/, "axisTitleY")]; } return properties[key.replace(/secondaryAxis/, "axisY")]; }; // uses the given regex to filter out any properties whose key doesn't match // will return an empty object if the props input is not a map var filterPropsByRegex = function(props, regex) { if(!(regex instanceof RegExp)) { return props; } var key, filtered = {}; for(key in props) { if(props.hasOwnProperty(key) && regex.test(key)) { filtered[key] = props[key]; } } return filtered; }; return ({ normalizeBoolean: normalizeBoolean, stringToObject: stringToObject, stringToArray: stringToArray, trimWhitespace: trimWhitespace, escapeSafeSplit: escapeSafeSplit, unescapeChars: unescapeChars, escapeHtml: escapeHtml, escapeSVG: escapeSVG, stringToHexArray: stringToHexArray, arraysAreEquivalent: arraysAreEquivalent, getLegendProperties: getLegendProperties, getXAxisProperties: getXAxisProperties, xAxisKeyIsTrumped: xAxisKeyIsTrumped, getYAxisProperties: getYAxisProperties, yAxisKeyIsTrumped: yAxisKeyIsTrumped, filterPropsByRegex: filterPropsByRegex }); }); define('js_charting/visualizations/Visualization',[ 'jquery', 'underscore', '../helpers/EventMixin', '../util/color_utils', '../util/parsing_utils' ], function( $, _, EventMixin, colorUtils, parsingUtils ) { var Visualization = function(container, properties) { this.container = container; this.$container = $(container); this.properties = $.extend(true, {}, properties); this.id = _.uniqueId('viz_'); this.updateDimensions(); // used for performance profiling this.benchmarks = []; }; Visualization.prototype = $.extend({}, EventMixin, { requiresExternalColors: false, getWidth: function() { return this.$container.width(); }, getHeight: function() { return this.$container.height(); }, getCurrentDisplayProperties: function() { return this.properties; }, updateDimensions: function() { this.width = this.getWidth(); this.height = this.getHeight(); }, getClassName: function() { return (this.type + '-chart'); }, prepare: function(dataSet, properties) { // properties is an optional parameter, will layer on top of // the properties passed to the constructor if(properties) { $.extend(true, this.properties, properties); } this.dataSet = dataSet; this.updateDimensions(); this.processProperties(); }, prepareAndDraw: function(dataSet, properties, callback) { this.prepare(dataSet, properties); this.draw(callback); }, requiresExternalColorPalette: function() { return this.requiresExternalColors; }, processProperties: function() { this.type = this.properties['chart'] || 'column'; // set up the color skinning this.backgroundColor = this.properties['chart.backgroundColor'] || this.properties['backgroundColor'] || 'rgb(255, 255, 255)'; this.foregroundColor = this.properties['chart.foregroundColor'] || this.properties['foregroundColor'] || 'rgb(0, 0, 0)'; this.fontColor = this.properties['chart.fontColor'] || this.properties['fontColor'] || 'rgb(0, 0, 0)'; this.foregroundColorSoft = colorUtils.addAlphaToColor(this.foregroundColor, 0.25); this.foregroundColorSofter = colorUtils.addAlphaToColor(this.foregroundColor, 0.15); // handle special modes this.testMode = (parsingUtils.normalizeBoolean(this.properties['chart.testMode']) || parsingUtils.normalizeBoolean(this.properties['testMode'])); this.exportMode = (parsingUtils.normalizeBoolean(this.properties['chart.exportMode']) || parsingUtils.normalizeBoolean(this.properties['exportMode'])); }, resize: function() { var oldWidth = this.width, oldHeight = this.height; this.updateDimensions(); if(this.width === oldWidth && this.height === oldHeight) { return; } this.setSize(this.width, this.height); }, // stub methods to be overridden by sub-classes draw: function() { }, destroy: function() { }, getSVG: function() { }, // this method is a no-op if we're not in test mode, otherwise adds an entry to the list of benchmarks benchmark: function(name) { if(!this.testMode) { return; } if(this.benchmarks.length === 0) { this.benchmarks.push([name, (new Date()).getTime()]); } else { var lastTimestamp = _(this.benchmarks).reduce(function(time, mark) { return time + mark[1]; }, 0); this.benchmarks.push([name, (new Date()).getTime() - lastTimestamp]); } } }); return Visualization; }); define('js_charting/components/ColorPalette',['../util/parsing_utils', '../util/color_utils'], function(parsingUtils, colorUtils) { var ColorPalette = function(colors, useInterpolation) { this.setColors(colors); this.useInterpolation = parsingUtils.normalizeBoolean(useInterpolation, false); }; ColorPalette.prototype = { setColors: function(colors) { this.colors = colors || this.BASE_COLORS; }, getColor: function(field, index, count) { var p, index1, index2, numColors = this.colors.length; if(numColors === 0) { return 0x000000; } if(index < 0) { index = 0; } if(!this.useInterpolation) { return this.colors[index % numColors]; } if (count < 1) { count = 1; } if (index > count) { index = count; } p = (count === 1) ? 0 : (numColors - 1) * (index / (count - 1)); index1 = Math.floor(p); index2 = Math.min(index1 + 1, numColors - 1); p -= index1; return this.interpolateColors(this.colors[index1], this.colors[index2], p); }, getColorAsRgb: function(field, index, count) { var hexColor = this.getColor(field, index, count); return colorUtils.colorFromHex(hexColor); }, interpolateColors: function(color1, color2, p) { var r1 = (color1 >> 16) & 0xFF, g1 = (color1 >> 8) & 0xFF, b1 = color1 & 0xFF, r2 = (color2 >> 16) & 0xFF, g2 = (color2 >> 8) & 0xFF, b2 = color2 & 0xFF, rInterp = r1 + Math.round((r2 - r1) * p), gInterp = g1 + Math.round((g2 - g1) * p), bInterp = b1 + Math.round((b2 - b1) * p); return ((rInterp << 16) | (gInterp << 8) | bInterp); }, BASE_COLORS: [ 0x6BB7C8, 0xFAC61D, 0xD85E3D, 0x956E96, 0xF7912C, 0x9AC23C, 0x998C55, 0xDD87B0, 0x5479AF, 0xE0A93B, 0x6B8930, 0xA04558, 0xA7D4DF, 0xFCDD77, 0xE89E8B, 0xBFA8C0, 0xFABD80, 0xC2DA8A, 0xC2BA99, 0xEBB7D0, 0x98AFCF, 0xECCB89, 0xA6B883, 0xC68F9B, 0x416E79, 0x967711, 0x823825, 0x59425A, 0x94571A, 0x5C7424, 0x5C5433, 0x85516A, 0x324969, 0x866523, 0x40521D, 0x602935 ] }; return ColorPalette; }); define('js_charting/helpers/Formatter',['jquery', '../util/dom_utils'], function($, domUtils) { var Formatter = function(renderer) { this.renderer = renderer; this.hasSVG = domUtils.hasSVG; }; Formatter.prototype = { ellipsize: function(text, width, fontSize, css, mode) { if(text.length <= 3) { return text; } if(!width || isNaN(parseFloat(width, 10))) { return "..."; } if(!fontSize || isNaN(parseFloat(fontSize, 10))) { return text; } if(this.predictTextWidth(text, fontSize, css) <= width) { return text; } // memoize the width of the ellipsis if(!this.ellipsisWidth) { this.ellipsisWidth = this.predictTextWidth("...", fontSize, css); } switch(mode) { case 'start': var reversedText = this.reverseString(text), reversedTrimmed = this.trimStringToWidth(reversedText, (width - this.ellipsisWidth), fontSize, css); return "..." + this.reverseString(reversedTrimmed); case 'end': return this.trimStringToWidth(text, (width - this.ellipsisWidth), fontSize, css) + "..."; default: // default to middle ellipsization var firstHalf = text.substr(0, Math.ceil(text.length / 2)), secondHalf = text.substr(Math.floor(text.length / 2)), halfFitWidth = (width - this.ellipsisWidth) / 2, secondHalfReversed = this.reverseString(secondHalf), firstHalfTrimmed = this.trimStringToWidth(firstHalf, halfFitWidth, fontSize, css), secondHalfTrimmedReversed = this.trimStringToWidth(secondHalfReversed, halfFitWidth, fontSize, css); return firstHalfTrimmed + "..." + this.reverseString(secondHalfTrimmedReversed); } }, // NOTE: it is up to caller to test that the entire string does not already fit // even if it does, this method will do log N work and may or may not truncate the last character trimStringToWidth: function(text, width, fontSize, css) { var that = this, binaryFindEndIndex = function(start, end) { var testIndex; while(end > start + 1) { testIndex = Math.floor((start + end) / 2); if(that.predictTextWidth(text.substr(0, testIndex), fontSize, css) > width) { end = testIndex; } else { start = testIndex; } } return start; }, endIndex = binaryFindEndIndex(0, text.length); return text.substr(0, endIndex); }, reverseString: function(str) { return str.split("").reverse().join(""); }, predictTextWidth: function(text, fontSize, css) { if(!fontSize || !text) { return 0; } var bBox = (this.getTextBBox(text, fontSize, css)); return (bBox) ? bBox.width : 0; }, predictTextHeight: function(text, fontSize, css) { if(!fontSize || !text) { return 0; } var bBox = (this.getTextBBox(text, fontSize, css)); return (bBox) ? bBox.height : 0; }, getTextBBox: function(text, fontSize, css) { // fontSize is required; css is any other styling that determines size (italics, bold, etc.) css = $.extend(css, { fontSize: fontSize + 'px' }); if(isNaN(parseFloat(fontSize, 10))) { return undefined; } if(this.textPredicter) { this.textPredicter.destroy(); } this.textPredicter = this.renderer.text(text, 0, 0) .attr({ visibility: 'hidden' }) .css(css) .add(); return this.textPredicter.getBBox(); }, adjustLabels: function(originalLabels, width, minFont, maxFont, ellipsisMode) { var i, fontSize, shouldEllipsize, labels = $.extend(true, [], originalLabels), maxWidths = this.getMaxWidthForFontRange(labels, minFont, maxFont); // adjust font and try to fit longest if(maxWidths[maxFont] <= width) { shouldEllipsize = false; fontSize = maxFont; } else { shouldEllipsize = true; for(fontSize = maxFont - 1; fontSize > minFont; fontSize--) { if(maxWidths[fontSize] <= width) { shouldEllipsize = false; break; } } } if(shouldEllipsize && ellipsisMode !== 'none') { for(i = 0; i < labels.length; i++) { labels[i] = this.ellipsize(labels[i], width, fontSize, {}, ellipsisMode); } } return { labels: labels, fontSize: fontSize, areEllipsized: shouldEllipsize, longestWidth: maxWidths[fontSize] }; }, getMaxWidthForFontRange: function(labels, minFont, maxFont) { var longestLabelIndex, fontSizeToWidthMap = {}; // find the longest label fontSizeToWidthMap[minFont] = 0; for(var i = 0; i < labels.length; i++) { var labelLength = this.predictTextWidth(labels[i] || '', minFont); if(labelLength > fontSizeToWidthMap[minFont]) { longestLabelIndex = i; fontSizeToWidthMap[minFont] = labelLength; } } // fill in the widths for the rest of the font sizes for(var fontSize = minFont + 1; fontSize <= maxFont; fontSize++) { fontSizeToWidthMap[fontSize] = this.predictTextWidth(labels[longestLabelIndex] || '', fontSize); } return fontSizeToWidthMap; }, bBoxesOverlap: function(bBox1, bBox2, marginX, marginY) { marginX = marginX || 0; marginY = marginY || 0; var box1Left = bBox1.x - marginX, box2Left = bBox2.x - marginX, box1Right = bBox1.x + bBox1.width + 2 * marginX, box2Right = bBox2.x + bBox2.width + 2 * marginX, box1Top = bBox1.y - marginY, box2Top = bBox2.y - marginY, box1Bottom = bBox1.y + bBox1.height + 2 * marginY, box2Bottom = bBox2.y + bBox2.height + 2 * marginY; return ((box1Left < box2Right) && (box1Right > box2Left) && (box1Top < box2Bottom) && (box1Bottom > box2Top)); }, destroy: function() { if(this.textPredicter) { this.textPredicter.destroy(); this.textPredicter = false; } } }; $.extend(Formatter, { // a cross-renderer way to read out an wrapper's element text content getElementText: function(wrapper) { return (domUtils.hasSVG) ? wrapper.textStr : $(wrapper.element).html(); }, // a cross-renderer way to update an wrapper's element text content setElementText: function(wrapper, text) { if(wrapper.attr('text') === text) { return; } wrapper.added = true; // the SVG renderer needs this wrapper.attr({text: text}); } }); return Formatter; }); define('js_charting/components/axes/Axis',[ 'jquery', 'underscore', '../../helpers/Formatter', '../../util/parsing_utils', '../../util/dom_utils', 'util/console' ], function( $, _, Formatter, parsingUtils, domUtils ) { var AxisBase = function(properties) { this.properties = properties || {}; this.id = _.uniqueId('axis_'); this.isVertical = this.properties['axis.orientation'] === 'vertical'; }; AxisBase.prototype = { clone: function() { return (new this.constructor($.extend(true, {}, this.properties))); }, getConfig: function() { var titleText = null, that = this; if(!this.properties['isEmpty'] && this.properties['axisTitle.visibility'] !== 'collapsed' && !!this.properties['axisTitle.text'] && !(/^\s+$/.test(this.properties['axisTitle.text']))) { titleText = parsingUtils.escapeSVG(this.properties['axisTitle.text']); } return $.extend(true, this.getOrientationDependentConfig(), { id: this.id, labels: { enabled: (this.properties['axisLabels.majorLabelVisibility'] !== 'hide'), formatter: function() { var formatInfo = this; return that.formatLabel(formatInfo); }, style: { color: this.properties['axis.fontColor'] || '#000000' } }, title: { style: { color: this.properties['axis.fontColor'] || '#000000' }, text: titleText }, lineColor: this.properties['axis.foregroundColorSoft'] || '#000000', lineWidth: (this.properties['axisLabels.axisVisibility'] === 'hide') ? 0 : 1, gridLineColor: this.properties['axis.foregroundColorSofter'] || '#000000', tickColor: this.properties['axis.foregroundColorSoft'] || '#000000', tickLength: parseInt(this.properties['axisLabels.majorTickSize'], 10) || 18, tickWidth: (this.properties['axisLabels.majorTickVisibility'] === 'hide') ? 0 : 1 , tickRenderPostHook: _(this.tickRenderPostHook).bind(this), tickHandleOverflowOverride: _(this.tickHandleOverflowOverride).bind(this), getOffsetPreHook: _(this.getOffsetPreHook).bind(this) }); }, getOrientationDependentConfig: function() { if(this.isVertical) { return $.extend(true, {}, this.BASE_VERT_CONFIG, this.getVerticalConfig()); } return $.extend(true, {}, this.BASE_HORIZ_CONFIG, this.getHorizontalConfig()); }, onChartLoad: function(chart) { this.hcAxis = chart.get(this.id); this.initializeTicks(); }, // convert the ticks to an array in ascending order by 'pos' initializeTicks: function() { var key, ticks = this.hcAxis.ticks, tickArray = []; for(key in ticks) { if(ticks.hasOwnProperty(key)) { tickArray.push(ticks[key]); } } tickArray.sort(function(t1, t2) { return (t1.pos - t2.pos); }); this.ticks = tickArray; }, tickRenderPostHook: function(tick, index, old) { if(!tick.label) { return; } if(!tick.handleOverflow(index, tick.label.xy)) { domUtils.hideTickLabel(tick); } else { domUtils.showTickLabel(tick); } }, getOffsetPreHook: function(axis) { if(axis.userOptions.title.text) { var chart = axis.chart, formatter = new Formatter(chart.renderer), axisTitle = axis.userOptions.title.text, fontSize = 12, elidedTitle; if(axis.horiz) { elidedTitle = formatter.ellipsize(axisTitle, chart.chartWidth - 100, fontSize, { fontWeight: 'bold' }); } else { elidedTitle = formatter.ellipsize(axisTitle, chart.chartHeight - 100, fontSize, { fontWeight: 'bold' }); } axis.options.title.text = elidedTitle; axis.setTitle({ text: elidedTitle }, false); formatter.destroy(); } }, tickHandleOverflowOverride: function(tick, index, xy) { if(tick.isFirst) { return this.handleFirstTickOverflow(tick, index, xy); } var axis = tick.axis, axisOptions = axis.options, numTicks = axis.tickPositions.length - (axisOptions.tickmarkPlacement === 'between' ? 0 : 1), labelStep = axisOptions.labels.step || 1; // take the label step into account when identifying the last visible label if(tick.isLast || index === (numTicks - (numTicks % labelStep))) { return this.handleLastTickOverflow(tick, index, xy); } return true; }, handleFirstTickOverflow: function(tick, index, xy) { // if the axis is horizontal or reversed, the first label is oriented such that it can't overflow var axis = tick.axis; if(axis.horiz || axis.reversed) { return true; } var labelBottom = this.getTickLabelExtremesY(tick)[1], axisBottom = axis.top + axis.len; return (xy.y + labelBottom <= axisBottom); }, handleLastTickOverflow: function(tick, index, xy) { var axis = tick.axis; // if the axis is vertical and not reversed, the last label is oriented such that it can't overflow if(!axis.horiz && !axis.reversed) { return true; } // handle the horizontal axis case if(axis.horiz) { var axisRight = axis.left + axis.len, labelRight = this.getTickLabelExtremesX(tick)[1]; return (xy.x + labelRight <= axisRight); } // handle the reversed vertical axis case var labelBottom = this.getTickLabelExtremesY(tick)[1], axisBottom = axis.top + axis.len; return (xy.y + labelBottom <= axisBottom); }, getTickLabelExtremesX: function(tick) { return tick.getLabelSides(); }, getTickLabelExtremesY: function(tick) { var labelTop = -(tick.axis.options.labels.y / 2); return [labelTop, labelTop + tick.labelBBox.height]; }, destroy: function() { this.hcAxis = null; }, onChartLoadOrResize: function() { }, getVerticalConfig: function() { return {}; }, getHorizontalConfig: function() { return {}; }, BASE_HORIZ_CONFIG: { title: { margin: 8 } }, BASE_VERT_CONFIG: { } }; return AxisBase; }); define('js_charting/util/lang_utils',[],function() { // very simple inheritance helper to set up the prototype chain var inherit = function(child, parent) { var F = function() { }; F.prototype = parent.prototype; child.prototype = new F(); child.prototype.constructor = child; }; return ({ inherit: inherit }); }); define('js_charting/components/axes/CategoryAxis',[ 'jquery', 'underscore', './Axis', '../../helpers/Formatter', '../../util/lang_utils', '../../util/parsing_utils' ], function( $, _, Axis, Formatter, langUtils, parsingUtils ) { var CategoryAxis = function(properties) { Axis.call(this, properties); properties = properties || {}; // the property is exposed for testing only this.skipLabelsToAvoidCollisions = parsingUtils.normalizeBoolean(properties['axis.skipLabelsToAvoidCollisions']); }; langUtils.inherit(CategoryAxis, Axis); $.extend(CategoryAxis.prototype, { DEFAULT_FONT_SIZE: 12, MIN_FONT_SIZE: 9, getConfig: function() { var that = this, config = Axis.prototype.getConfig.apply(this, arguments), hideAxis = parsingUtils.normalizeBoolean(this.properties['axisLabels.hideCategories']); $.extend(true, config, { categories: this.properties['axis.categories'], labels: { formatter: function() { return that.formatLabel(this.value); }, enabled: config.labels.enabled && !hideAxis }, startOnTick: !this.hasTickmarksBetween(), showLastLabel: this.hasTickmarksBetween(), tickWidth: hideAxis ? 0 : 1, tickmarkPlacement: this.properties['axisLabels.tickmarkPlacement'], gridLineWidth: parsingUtils.normalizeBoolean(this.properties['gridLines.showMajorLines']) ? 1 : 0 }); if(!this.hasTickmarksBetween()) { // this will trick Highcharts into rendering space for the last label config.max = this.properties['axis.categories'].length; } return config; }, getVerticalConfig: function() { var config = Axis.prototype.getVerticalConfig.call(this); return $.extend(true, config, { labels: { align: 'right', x: -8 } }); }, getHorizontalConfig: function() { var config = Axis.prototype.getHorizontalConfig.call(this); return $.extend(true, config, { labels: { align: 'left' }, endOnTick: !this.hasTickmarksBetween(), showLastLabel: false, startOnTick: true }); }, getCategories: function() { return this.properties['axis.categories']; }, /** * @author sfishel * * Do some intelligent manipulation of axis label step and ellipsization of axis labels (if needed) * before the getOffset routine runs. */ getOffsetPreHook: function(axis) { // super Axis.prototype.getOffsetPreHook.call(this, axis); var options = axis.options, chart = axis.chart; if(!options.labels.enabled) { return; } var maxWidth, tickSpacing, minLabelSpacing, labelStep, labelSpacing, formatter = new Formatter(chart.renderer), categories = options.categories; if(!options.originalCategories) { options.originalCategories = $.extend([], categories); } if(this.isVertical) { maxWidth = Math.floor(chart.chartWidth / 6); var adjustedFontSize = this.fitLabelsToWidth(options, categories, formatter, maxWidth), labelHeight = formatter.predictTextHeight('Test', adjustedFontSize), axisHeight = chart.plotHeight; tickSpacing = axisHeight / (categories.length || 1); minLabelSpacing = 25; labelStep = this.skipLabelsToAvoidCollisions ? Math.ceil(minLabelSpacing / tickSpacing) : 1; options.labels.y = (labelStep > 1) ? labelHeight - (axis.transA * axis.tickmarkOffset) : labelHeight / 3; options.labels.step = labelStep; } else { var fontSize, tickLabelPadding = 4, labelSpacingUpperBound = 100, axisWidth = chart.plotWidth, maxWidths = formatter.getMaxWidthForFontRange(categories, this.MIN_FONT_SIZE, this.DEFAULT_FONT_SIZE); // check the width of the longest label for each font // take the largest font size that will make that width less than the tick spacing if possible tickSpacing = axisWidth / (categories.length || 1); // will return the largest font size that fits in the tick spacing, or zero if none fit var subTickSpacingFont = this.findBestFontForSpacing(maxWidths, tickSpacing - 2 * tickLabelPadding); if(subTickSpacingFont > 0) { fontSize = subTickSpacingFont; options.labels.style['font-size'] = fontSize + 'px'; labelStep = 1; labelSpacing = tickSpacing; } // otherwise use the width for smallest font size as minLabelSpacing, with the upper bound else { minLabelSpacing = Math.min(maxWidths[this.MIN_FONT_SIZE] + 2 * tickLabelPadding, labelSpacingUpperBound); fontSize = this.MIN_FONT_SIZE; labelStep = this.skipLabelsToAvoidCollisions ? Math.ceil(minLabelSpacing / tickSpacing) : 1; labelSpacing = tickSpacing * labelStep; maxWidth = labelSpacing - (2 * tickLabelPadding); this.ellipsizeLabels(options, categories, formatter, maxWidth, fontSize); } options.labels.align = 'left'; options.labels.step = labelStep; if(options.tickmarkPlacement === 'between') { options.labels.x = -(labelSpacing / (2 * labelStep)) + tickLabelPadding; } else { options.labels.x = tickLabelPadding; } } formatter.destroy(); }, findBestFontForSpacing: function(fontWidths, spacing) { var bestFontSize = 0; _(fontWidths).each(function(width, fontSize) { if(width <= spacing) { bestFontSize = Math.max(bestFontSize, parseInt(fontSize, 10)); } }); return bestFontSize; }, fitLabelsToWidth: function(options, categories, formatter, maxWidth) { var i, adjusted = formatter.adjustLabels(options.originalCategories, maxWidth, this.MIN_FONT_SIZE, this.DEFAULT_FONT_SIZE, 'middle'); for(i = 0; i < adjusted.labels.length; i++) { categories[i] = adjusted.labels[i]; } options.labels.style['font-size'] = adjusted.fontSize + 'px'; return adjusted.fontSize; }, ellipsizeLabels: function(options, categories, formatter, maxWidth, fontSize) { var i, adjustedLabels = _(categories).map(function(label) { return formatter.ellipsize(label, maxWidth, fontSize, {}, 'middle'); }); for(i = 0; i < adjustedLabels.length; i++) { categories[i] = adjustedLabels[i]; } options.labels.style['font-size'] = fontSize + 'px'; }, /** * @author sfishel * * Do a custom enforcement of the label step by removing ticks that don't have a label */ tickRenderPostHook: function(tick, index, old) { var axisOptions = tick.axis.options; axisOptions.labels = axisOptions.labels || {}; if(!axisOptions.labels.enabled) { return; } Axis.prototype.tickRenderPostHook.call(this, tick, index, old); var adjustedPosition = tick.pos + (axisOptions.tickmarkPlacement === 'between' ? 1 : 0); var labelStep = axisOptions.labels.step || 1; if(adjustedPosition % labelStep !== 0) { tick.mark.hide(); } else { tick.mark.show(); } }, formatValue: function(value) { return value; }, formatLabel: function(info) { return parsingUtils.escapeSVG(info); }, hasTickmarksBetween: function() { return (this.properties['axisLabels.tickmarkPlacement'] === 'between'); }, getTickLabelExtremesY: function(tick) { return [-tick.labelBBox.height, 0]; } }); return CategoryAxis; }); define('js_charting/util/time_utils',['underscore', 'util/time_utils', 'splunk.i18n'], function(_, splunkTimeUtils, i18n) { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TimeUtils var TimeUtils = { SECS_PER_MIN: 60, SECS_PER_HOUR: 60 * 60, convertTimeToCategories: function(timeData, spanSeries, numLabelCutoff) { // debugging // un-commenting this will print the time series to console in a way that can be copy-pasted to a unit test // console.log('[\n' + JSON.stringify(timeData).replace(/\[|\]/g, '').split(',').join(',\n') + '\n]'); var i, labelIndex, prettyLabelInfo, prettyLabels, prettyLabel, // find the indexes (a list of numbers) where the labels should go labelIndexes = this.findLabelIndexes(timeData, numLabelCutoff), rawLabels = [], categories = []; // based on the label indexes, look up the raw labels from the original list _(labelIndexes).each(function(i){ rawLabels.push(timeData[i]); }); prettyLabelInfo = this.getPrettyLabelInfo(rawLabels); prettyLabels = prettyLabelInfo.prettyLabels; // now assemble the full category list to return // start with a list of all blanks _(timeData).each(function(i){ categories.push(' ');}); // then put the pretty labels in the right places _(labelIndexes).each(function(labelIndex,j){ categories[labelIndex] = prettyLabels[j]; }); return ({ categories: categories, rawLabels: rawLabels, granularity: prettyLabelInfo.granularity }); }, findLabelIndexes: function(timeData, numLabelCutoff) { var i, labelIndex, indexes = []; // if there are less data points than the cutoff, should label all points if(timeData.length <= numLabelCutoff) { i=0; while(i<timeData.length){ indexes.push(i++); } return indexes; } var pointSpan = this.getPointSpan(timeData), totalSpan = this.getTotalSpan(timeData); if(this.couldLabelFirstOfMonth(pointSpan, totalSpan)) { var firstIndexes = this.findFirstOfMonthIndexes(timeData); var indexLen = firstIndexes.length; if(indexLen >= 3){ var step = Math.ceil(indexLen / numLabelCutoff), newIndexes = []; for(i = 0; i < indexLen; i += step) { labelIndex = firstIndexes[i]; newIndexes.push(labelIndex); } firstIndexes = newIndexes; return firstIndexes; } } // find major unit (in number of points, not time) var majorUnit = this.findMajorUnit(timeData, numLabelCutoff, pointSpan, totalSpan), firstMajorSlice = timeData.slice(0, majorUnit), roundestIndex = this.getRoundestIndex(firstMajorSlice, majorUnit, pointSpan), index = roundestIndex; if(this.couldLabelMidnight(majorUnit, pointSpan)){ var midnightIndexes = this.findMidnightIndexes(timeData); if(midnightIndexes.length > numLabelCutoff){ step = Math.ceil(midnightIndexes.length / numLabelCutoff); newIndexes = []; for(i = 0; i < midnightIndexes.length; i += step) { labelIndex = midnightIndexes[i]; newIndexes.push(labelIndex); } midnightIndexes = newIndexes; } return midnightIndexes; } while(index < timeData.length) { indexes.push(index); index += majorUnit; } return indexes; }, couldLabelMidnight: function(majorUnit, pointSpan){ return ((majorUnit % 24 === 0) && (pointSpan === 60*60)); }, couldLabelFirstOfMonth: function(pointSpan, totalSpan) { if(pointSpan > this.MAX_SECS_PER_DAY) { return false; } if(pointSpan < this.SECS_PER_HOUR) { return false; } // prevent a user-defined span like 4003 seconds from derailing things if(pointSpan < this.MIN_SECS_PER_DAY && (24 * this.SECS_PER_HOUR) % pointSpan !== 0) { return false; } if(totalSpan < 2 * this.MIN_SECS_PER_MONTH) { return false; } return true; }, findMidnightIndexes: function(timeData){ var i, bdTime, bdTimes = [], midnightIndexes = []; for(i = 0; i < timeData.length; i++) { bdTimes.push(splunkTimeUtils.extractBdTime(timeData[i])); } for(i = 0; i < bdTimes.length; i++) { bdTime = bdTimes[i]; if((bdTime.hour === 0) && (bdTime.minute === 0)) { midnightIndexes.push(i); } } return midnightIndexes; }, findFirstOfMonthIndexes: function(timeData) { var bdTimes = [], firstIndexes = []; _(timeData).each(function(dataPoint, i){ bdTimes.push(splunkTimeUtils.extractBdTime(dataPoint)); }); _(bdTimes).each(function(bdTime, i){ if(bdTime.day === 1 && bdTime.hour === 0){ firstIndexes.push(i); } }); return firstIndexes; }, getPointSpan: function(timeData) { if(timeData.length < 2) { return 1; } if(timeData.length < 4) { return this.getSpanBetween(timeData[0], timeData[1]); } var firstSpan = this.getSpanBetween(timeData[0], timeData[1]), secondSpan = this.getSpanBetween(timeData[1], timeData[2]), thirdSpan = this.getSpanBetween(timeData[2], timeData[3]); // sample the three spans to avoid the case where daylight savings might produce an erroneous result if(firstSpan === secondSpan) { return firstSpan; } if(secondSpan === thirdSpan) { return secondSpan; } if(firstSpan === thirdSpan) { return firstSpan; } return firstSpan; }, getTotalSpan: function(timeData) { var i, lastPoint; for(i = timeData.length - 1; i >= 0; i--) { lastPoint = timeData[i]; if(splunkTimeUtils.isValidIsoTime(lastPoint)) { break; } } return this.getSpanBetween(timeData[0], lastPoint); }, getSpanBetween: function(start, end) { var startDate = splunkTimeUtils.isoToDateObject(start), endDate = splunkTimeUtils.isoToDateObject(end), millisDiff = endDate.getTime() - startDate.getTime(); return millisDiff / 1000; }, // use a 23-hour day as a minimum to protect against daylight savings errors MIN_SECS_PER_DAY: 23 * 60 * 60, // use a 25-hour day as a maximum to protect against daylight savings errors MAX_SECS_PER_DAY: 25 * 60 * 60, MAJOR_UNITS_SECONDS: [ 1, 2, 5, 10, 15, 30, 60, 2 * 60, 3 * 60, 5 * 60, 10 * 60, 15 * 60, 30 * 60, 60 * 60, 2 * 60 * 60, 4 * 60 * 60, 6 * 60 * 60, 12 * 60 * 60, 24 * 60 * 60, 48 * 60 * 60, 96 * 60 * 60, 168 * 60 * 60 ], MAJOR_UNIT_DAYS: [ 1, 2, 4, 7, 14, 28, 56, 112, 224, 364, 476, 728 ], // this is ok because daylight savings is never in February MIN_SECS_PER_MONTH: 28 * 24 * 60 * 60, MAJOR_UNIT_MONTHS: [ 1, 2, 4, 6, 12, 24, 48, 96 ], findMajorUnit: function(timeData, numLabelCutoff, pointSpan, totalSpan) { var i, majorUnit, unitsPerSpan; if(pointSpan < this.MIN_SECS_PER_DAY) { for(i = 0; i < this.MAJOR_UNITS_SECONDS.length; i++) { majorUnit = this.MAJOR_UNITS_SECONDS[i]; unitsPerSpan = totalSpan / majorUnit; if((unitsPerSpan >= 3) && (unitsPerSpan <= numLabelCutoff) && (majorUnit % pointSpan === 0)) { // SPL-55264, 3 minutes is included in the major units list to prevent this loop from failing to find // a major unit at all, but if 5 minutes would fit it is preferred over 3 minutes if(majorUnit === 3 * 60 && totalSpan >= 15 * 60) { continue; } return majorUnit / pointSpan; } } } else if(pointSpan < this.MIN_SECS_PER_MONTH) { var secsPerDay = 24 * 60 * 60, dayPointSpan = Math.round(pointSpan / secsPerDay), dayTotalSpan = Math.round(totalSpan / secsPerDay); for(i = 0; i < this.MAJOR_UNIT_DAYS.length; i++) { majorUnit = this.MAJOR_UNIT_DAYS[i]; unitsPerSpan = dayTotalSpan / majorUnit; if((unitsPerSpan >= 3) && (unitsPerSpan <= numLabelCutoff) && (majorUnit % dayPointSpan === 0)) { return majorUnit / dayPointSpan; } } } else { var secsPerMonth = 30 * 24 * 60 * 60, monthPointSpan = Math.round(pointSpan / secsPerMonth), monthTotalSpan = Math.round(totalSpan / secsPerMonth); for(i = 0; i < this.MAJOR_UNIT_MONTHS.length; i++) { majorUnit = this.MAJOR_UNIT_MONTHS[i]; unitsPerSpan = monthTotalSpan / majorUnit; if((unitsPerSpan >= 3) && (unitsPerSpan <= numLabelCutoff) && (majorUnit % monthPointSpan === 0)) { return majorUnit / monthPointSpan; } } } // if we exit the loop without finding a major unit, we just punt and divide the points evenly return Math.ceil(timeData.length / numLabelCutoff); }, getRoundestIndex: function(timeData, majorUnit, pointSpan) { var i, roundest, roundestIndex, bdTimes = [], secsMajorUnit = majorUnit * pointSpan; _(timeData).each(function(label){ bdTimes.push(splunkTimeUtils.extractBdTime(label)); }); roundest = bdTimes[0]; roundestIndex = 0; for(i = 1; i < bdTimes.length; i++) { if(this.isRounderThan(bdTimes[i], roundest, pointSpan) && this.bdTimeMatchesUnit(bdTimes[i], secsMajorUnit)) { roundest = bdTimes[i]; roundestIndex = i; } } return roundestIndex; }, isRounderThan: function(first, second, pointSpan) { if(first.month === 1 && first.day === 1 && first.hour === 0 && second.month !== 1 && second.day === 1 && second.hour === 0) { return true; } if(first.hour === 0 && second.hour !== 0) { return true; } if(first.hour % 12 === 0 && second.hour % 12 !== 0) { return true; } if(first.hour % 6 === 0 && second.hour % 6 !== 0) { return true; } if(first.hour % 4 === 0 && second.hour % 4 !== 0) { return true; } if(first.hour % 2 === 0 && second.hour % 2 !== 0) { return true; } if(first.minute === 0 && second.minute !== 0) { return true; } if(first.minute % 30 === 0 && second.minute % 30 !== 0) { return true; } if(first.minute % 15 === 0 && second.minute % 15 !== 0) { return true; } if(first.minute % 10 === 0 && second.minute % 10 !== 0) { return true; } if(first.minute % 5 === 0 && second.minute % 5 !== 0) { return true; } if(first.minute % 2 === 0 && second.minute % 2 !== 0) { return true; } if(first.second === 0 && second.second !== 0) { return true; } if(first.second % 30 === 0 && second.second % 30 !== 0) { return true; } if(first.second % 15 === 0 && second.second % 15 !== 0) { return true; } if(first.second % 10 === 0 && second.second % 10 !== 0) { return true; } if(first.second % 5 === 0 && second.second % 5 !== 0) { return true; } if(first.second % 2 === 0 && second.second % 2 !== 0) { return true; } return false; }, bdTimeMatchesUnit: function(bdTime, secsMajor) { if(secsMajor < 60) { return (bdTime.second % secsMajor === 0); } if(secsMajor < 60 * 60) { var minutes = Math.floor(secsMajor / 60); return (bdTime.minute % minutes === 0); } else { var hours = Math.floor(secsMajor / (60 * 60)); return (bdTime.hour % hours === 0); } return true; }, getPrettyLabelInfo: function(rawLabels) { var i, prettyLabel, bdTimes = [], prettyLabels = []; _(rawLabels).each(function(label){ bdTimes.push(splunkTimeUtils.extractBdTime(label)); }); var granularity = splunkTimeUtils.determineLabelGranularity(bdTimes); for(i = 0; i < bdTimes.length; i++) { if(i === 0) { prettyLabel = this.formatBdTimeAsAxisLabel(bdTimes[i], null, granularity); } else { prettyLabel = this.formatBdTimeAsAxisLabel(bdTimes[i], bdTimes[i - 1], granularity); } if(prettyLabel) { prettyLabels.push(prettyLabel.join('<br/>')); } else { prettyLabels.push(""); } } return { prettyLabels: prettyLabels, granularity: granularity }; }, formatBdTimeAsAxisLabel: function(time, prevBdTime, granularity) { if(time.isInvalid) { return null; } var dateTime = splunkTimeUtils.bdTimeToDateObject(time), showDay = (granularity in { 'second': true, 'minute': true, 'hour': true, 'day': true }), showTimes = (granularity in { 'second': true, 'minute': true, 'hour': true}), showSeconds = (granularity === 'second'), timeFormat = (showSeconds) ? 'medium' : 'short', dateFormat = (showDay) ? 'ccc MMM d' : 'MMMM'; if(granularity === 'year') { return [i18n.format_date(dateTime, 'YYYY')]; } if(prevBdTime && prevBdTime.year === time.year && time.month === prevBdTime.month && time.day === prevBdTime.day) { return [i18n.format_time(dateTime, timeFormat)]; } var formattedPieces = (showTimes) ? [i18n.format_time(dateTime, timeFormat), i18n.format_date(dateTime, dateFormat)] : [i18n.format_date(dateTime, dateFormat)]; if(!prevBdTime || time.year !== prevBdTime.year) { formattedPieces.push(i18n.format_date(dateTime, 'YYYY')); } return formattedPieces; }, // returns null if string cannot be parsed formatIsoStringAsTooltip: function(isoString, pointSpan) { var bdTime = splunkTimeUtils.extractBdTime(isoString), dateObject; if(bdTime.isInvalid) { return null; } dateObject = splunkTimeUtils.bdTimeToDateObject(bdTime); if(pointSpan >= this.MIN_SECS_PER_DAY) { // day or larger return i18n.format_date(dateObject); } if(pointSpan >= this.SECS_PER_MIN) { // minute or longer return i18n.format_datetime(dateObject, 'medium', 'short'); } return i18n.format_datetime(dateObject); } }; return TimeUtils; }); define('js_charting/components/axes/TimeAxis',[ 'jquery', 'underscore', './Axis', './CategoryAxis', '../../helpers/Formatter', '../../util/lang_utils', 'util/time_utils', '../../util/time_utils', '../../util/dom_utils' ], function( $, _, Axis, CategoryAxis, Formatter, langUtils, splunkTimeUtils, timeUtils, domUtils ) { var TimeAxis = function(properties) { this.originalCategories = properties['axis.categories']; this.spanData = properties['axis.spanData']; var timeCategoryInfo = timeUtils.convertTimeToCategories(this.originalCategories, this.spanData, this.NUM_LABEL_CUTOFF); this.granularity = timeCategoryInfo.granularity; this.pointSpan = timeUtils.getPointSpan(this.originalCategories); properties['axis.categories'] = timeCategoryInfo.categories; CategoryAxis.call(this, properties); }; langUtils.inherit(TimeAxis, CategoryAxis); $.extend(TimeAxis.prototype, { NUM_LABEL_CUTOFF: 6, getConfig: function() { var config = CategoryAxis.prototype.getConfig.call(this); $.extend(true, config, { showLastLabel: true, setTickPositionsPostHook: _(this.setTickPositionsPostHook).bind(this) }); return config; }, formatLabel: function(info) { return info; }, formatValue: function(value) { return timeUtils.formatIsoStringAsTooltip(value, this.pointSpan) || 'Invalid timestamp'; // TODO: localize }, /** * @author sfishel * * Before the getOffset routine runs, align the axis labels to the right of each tick */ getOffsetPreHook: function(axis) { var options = axis.options, chart = axis.chart, categories = options.categories, tickLabelPadding = (this.isVertical) ? 2 : 3, axisLength = (this.isVertical) ? chart.plotHeight : chart.plotWidth, tickSpacing = (categories.length > 1) ? (axisLength / categories.length) : axisLength + (tickLabelPadding * 2); options.adjustedTickSpacing = tickSpacing; if(this.isVertical) { var labelFontSize = parseInt((options.labels.style.fontSize.split('px'))[0], 10); options.labels.y = (tickSpacing / 2) + labelFontSize + tickLabelPadding; } else { if(options.tickmarkPlacement === 'on') { options.labels.align = 'left'; options.labels.x = tickLabelPadding; } else { options.labels.align = 'left'; options.labels.x = (tickSpacing / 2) + tickLabelPadding; } } }, /** * @author sfishel * * Make adjustments to the tick positions to label only the appropriate times */ setTickPositionsPostHook: function(axis, secondPass) { var options = axis.options, categories = options.categories; axis.tickPositions = []; if(!options.originalCategories) { options.originalCategories = $.extend(true, [], categories); } var i, originalCategories = options.originalCategories; for(i = 0; i < originalCategories.length; i++) { if(originalCategories[i] && originalCategories[i] !== " ") { if(options.tickmarkPlacement === 'on') { axis.tickPositions.push(i); } else { // if the tickmark placement is 'between', we shift everything back one // interestingly, HighCharts will allow negatives here, and in fact that's what we need to label the first point axis.tickPositions.push(i - 1); categories[i - 1] = originalCategories[i]; } } } // adjust the axis label CSS so that soft-wrapping will not occur // for the VML renderer we also have to make sure the tick labels will accurately report their own widths options.labels.style.width = 'auto'; if(!domUtils.hasSVG) { options.labels.style['white-space'] = 'nowrap'; } }, /** * @author sfishel * * Use the handleOverflow override hook to handle any collisions among the axis labels * All branches should return true, resolveCollisions will show/hide the correct ticks and labels * * NOTE: Highcharts renders the second tick first, and the first tick last */ tickHandleOverflowOverride: function(tick, index, xy) { // FIXME: this is a little hacky... // use the second tick as an indicator that we're starting a new render routine and reset the collisionDetected flag // can't do the regular collision detection because the first tick isn't there yet if(index === 1) { this.collisionDetected = false; this.lastTickFits = true; return true; } // FIXME: again a little hacky... // use the first tick as an indicator that this is the last step in rendering // only now can we check if the first and second ticks overlap (if there is a second tick) if(tick.isFirst) { if(!tick.isLast) { this.collisionDetected = this.collisionDetected || this.tickOverlapsNext(tick, index, xy); } this.resolveCollisionDetection(tick.axis, this.collisionDetected, this.lastTickFits); return true; } // if we haven't seen a collision yet, figure out if the current tick causes one this.collisionDetected = this.collisionDetected || this.tickOverlapsPrevious(tick, index, xy); // keep track of whether the last tick fits without overflow if(tick.isLast) { this.lastTickFits = CategoryAxis.prototype.tickHandleOverflowOverride.call(this, tick, index, xy); } return true; }, tickOverlapsPrevious: function(tick, index, xy) { var axis = tick.axis, // assume this won't be called with the first tick previous = axis.ticks[axis.tickPositions[index - 1]], previousXY = previous.getPosition(axis.horiz, previous.pos, axis.tickmarkOffset); // check for the vertical axis case if(this.isVertical) { var previousBottom = previousXY.y + this.getTickLabelExtremesY(previous)[1]; return (xy.y < previousBottom); } // otherwise handle the horizontal axis case var previousRight = previousXY.x + this.getTickLabelExtremesX(previous)[1]; return (xy.x < previousRight); }, tickOverlapsNext: function(tick, index, xy) { var axis = tick.axis, // assume this won't be called with the last tick next = axis.ticks[axis.tickPositions[index + 1]], nextXY = next.getPosition(axis.horiz, next.pos, axis.tickmarkOffset); if(!next) { return false; } // check for the vertical axis case if(this.isVertical) { var myBottom = xy.y + this.getTickLabelExtremesY(tick)[1]; return (myBottom > nextXY.y); } // otherwise handle the horizontal case var myRight = xy.x + this.getTickLabelExtremesX(tick)[1]; return (myRight > nextXY.x); }, resolveCollisionDetection: function(axis, hasCollisions, lastLabelFits) { var formatter = new Formatter(axis.chart.renderer), tickPositions = axis.tickPositions, collisionTickPositions = tickPositions.slice(1), ticks = axis.ticks, rawLabels = this.originalCategories, labelGranularity = this.granularity, positionOffset = this.hasTickmarksBetween() ? 1 : 0; if(hasCollisions) { _(collisionTickPositions).each(function(pos, i) { i++; // do this because we sliced out the first tick var tick = ticks[pos]; if(i % 2 === 0) { var bdTime = splunkTimeUtils.extractBdTime(rawLabels[tick.pos + positionOffset]), prevTick = ticks[tickPositions[i - 2]], prevBdTime = splunkTimeUtils.extractBdTime(rawLabels[prevTick.pos + positionOffset]), newLabel = (timeUtils.formatBdTimeAsAxisLabel(bdTime, prevBdTime, labelGranularity) || ['']).join('<br/>'); tick.label.attr({ text: newLabel }); } else { tick.label.hide(); tick.mark.hide(); } }); } else { _(collisionTickPositions).each(function(pos, i) { i++; // do this because we sliced out the first tick var tick = ticks[pos]; tick.label.show(); tick.mark.show(); if(i % 2 === 0) { var bdTime = splunkTimeUtils.extractBdTime(rawLabels[pos + positionOffset]), prevTick = ticks[tickPositions[i - 1]], prevBdTime = splunkTimeUtils.extractBdTime(rawLabels[prevTick.pos + positionOffset]), newLabel = (timeUtils.formatBdTimeAsAxisLabel(bdTime, prevBdTime, labelGranularity) || ['']).join('<br/>'); tick.label.attr({ text: newLabel }); } }); } if(!lastLabelFits && (!hasCollisions || tickPositions.length % 2 !== 0)) { axis.ticks[_(tickPositions).last()].label.hide(); } formatter.destroy(); }, // have to make some adjustments to get the correct answer when tickmarkPlacement = between getTickLabelExtremesX: function(tick) { var extremes = CategoryAxis.prototype.getTickLabelExtremesX.call(this, tick), axisOptions = tick.axis.options; if(axisOptions.tickmarkPlacement === 'between') { return _(extremes).map(function(extreme) { return extreme - (axisOptions.adjustedTickSpacing / 2); }); } return extremes; }, // inheritance gets a little weird here, the TimeAxis wants to go back to the base Axis behavior for this method getTickLabelExtremesY: function(tick) { return Axis.prototype.getTickLabelExtremesY.apply(this, arguments); } }); return TimeAxis; }); define('js_charting/components/axes/NumericAxis',[ 'jquery', 'underscore', './Axis', '../../helpers/Formatter', '../../util/parsing_utils', '../../util/lang_utils', '../../util/math_utils', 'splunk.i18n', 'util/console' ], function( $, _, Axis, Formatter, parsingUtils, langUtils, mathUtils, i18n, console ) { var NumericAxis = function(properties) { Axis.call(this, properties); // SPL-72638, always include zero if the axis has log scale this.includeZero = this.determineIncludeZero(); }; langUtils.inherit(NumericAxis, Axis); $.extend(NumericAxis.prototype, { getConfig: function() { var config = Axis.prototype.getConfig.call(this), extendAxisRange = parsingUtils.normalizeBoolean(this.properties['axisLabels.extendsAxisRange'], true); $.extend(config, { tickInterval: (this.properties['isEmpty'] && (this.properties['axis.scale'] ==='log')) ? 10: this.properties['isEmpty'] ? 10 : parseFloat(this.properties['axisLabels.majorUnit']) || null, endOnTick: extendAxisRange, startOnTick: extendAxisRange, allowDecimals: !parsingUtils.normalizeBoolean(this.properties['axisLabels.integerUnits']), minorTickColor: this.properties['axis.foregroundColorSoft'], minorTickLength: parseInt(this.properties['axisLabels.minorTickSize'], 10) || 10, // Leave this as auto because the widths of minor lines default to 0px minorTickInterval: 'auto', minorTickWidth: (this.properties['axisLabels.minorTickVisibility'] === 'show') ? 1 : 0, minorGridLineWidth: parsingUtils.normalizeBoolean(this.properties['gridLines.showMinorLines']) ? 1 : 0, //FIXME: clear min/max up so that reader can understand why we check for 'isEmpty' min: this.properties['isEmpty'] ? 0 : null, max: (this.properties['isEmpty'] && (this.properties['axis.scale'] ==='log')) ? 2 : this.properties['isEmpty'] ? 100 : null, gridLineWidth: parsingUtils.normalizeBoolean(this.properties['gridLines.showMajorLines'], true) ? 1 : 0, getSeriesExtremesPostHook: _(this.getSeriesExtremesPostHook).bind(this), setTickPositionsPreHook: _(this.setTickPositionsPreHook).bind(this) }); this.addMinAndMaxToConfig(config); return config; }, addMinAndMaxToConfig: function(config) { var min = this.properties.hasOwnProperty("axis.minimumNumber") ? parseFloat(this.properties['axis.minimumNumber']) : -Infinity, max = this.properties.hasOwnProperty("axis.maximumNumber") ? parseFloat(this.properties['axis.maximumNumber']) : Infinity; if(min > max) { var temp = min; min = max; max = temp; } if(min > -Infinity) { this.addMinToConfig(config, min, this.includeZero); } if(max < Infinity) { this.addMaxToConfig(config, max, this.includeZero); } }, addMinToConfig: function(config, min, includeZero) { if(includeZero && min > 0) { min = 0; } else if(this.isLogScale()) { min = mathUtils.absLogBaseTen(min); } config.min = min; config.minPadding = 0; config.startOnTick = false; }, addMaxToConfig: function(config, max, includeZero) { if(includeZero && max < 0) { max = 0; } else if(this.isLogScale()) { max = mathUtils.absLogBaseTen(max); } config.max = max; config.maxPadding = 0; config.endOnTick = false; }, getVerticalConfig: function() { var config = Axis.prototype.getVerticalConfig.call(this); return $.extend(true, config, { labels: { y: 13 } }); }, getHorizontalConfig: function() { var config = Axis.prototype.getHorizontalConfig.call(this); return $.extend(true, config, { labels: { align: 'left', x: 4 } }); }, formatLabel: function(info) { if(this.isLogScale()) { if(this.properties['stackMode'] === 'stacked100'){ return i18n.format_decimal(info.value); } return i18n.format_decimal(mathUtils.absPowerTen(info.value)); } return i18n.format_decimal(info.value); }, formatValue: function(value) { // handle the edge case where the value is not a valid number but the nullValueMode property has rendered it as a zero var formatted = i18n.format_decimal(value); return (formatted !== 'NaN' ? formatted : i18n.format_decimal('0')); }, isLogScale: function() { return (this.properties['axis.scale'] === 'log'); }, normalizeAxisOptions: function(axis) { var options = axis.options, extremes = axis.getExtremes(), chart = axis.chart; if(!this.properties['isEmpty']){ var formatter = new Formatter(chart.renderer); extremes.min = options.min || extremes.dataMin; extremes.max = options.max || extremes.dataMax; var tickInterval, range = Math.abs(extremes.max - extremes.min); // if we can't read a tickInterval from the options, estimate it from the tick pixel interval if(this.isVertical) { tickInterval = options.tickInterval || (options.tickPixelInterval / chart.plotHeight) * range; } else { tickInterval = options.tickInterval || (options.tickPixelInterval / chart.plotWidth) * range; } if(this.isLogScale()) { // SPL-72638, always use tick interval of 1 if the axis has log scale, since we will force the axis to start at zero options.tickInterval = 1; } else { this.checkMajorUnitFit(tickInterval, extremes, options, formatter, chart); } if(this.includeZero) { this.enforceIncludeZero(options, extremes); } else { this.adjustAxisRange(options, extremes, tickInterval); } if(options.allowDecimals !== false) { this.enforceIntegerMajorUnit(options, extremes); } formatter.destroy(); } else { this.handleNoData(options); } }, getSeriesExtremesPostHook: function(axis, secondPass) { this.normalizeAxisOptions(axis); }, setTickPositionsPreHook: function(axis, secondPass) { if(secondPass) { this.normalizeAxisOptions(axis); } }, checkMajorUnitFit: function(unit, extremes, options, formatter, chart) { var range = Math.abs(extremes.max - extremes.min), axisLength = (this.isVertical) ? chart.plotHeight : chart.plotWidth, tickSpacing = unit * axisLength / range, largestExtreme = Math.max(Math.abs(extremes.min), Math.abs(extremes.max)), tickLabelPadding = (this.isVertical) ? 5 : 15, fontSize = parseInt((options.labels.style.fontSize.split('px'))[0], 10), translatePixels = function(pixelVal) { return (pixelVal * range / axisLength); }; if(this.isVertical) { var maxHeight = formatter.predictTextHeight(this.formatValue(largestExtreme), fontSize); if(tickSpacing < (maxHeight + 2 * tickLabelPadding)) { options.tickInterval = Math.ceil(translatePixels((maxHeight + 2 * tickLabelPadding), true)); } } else { var maxWidth = formatter.predictTextWidth(this.formatValue(largestExtreme), fontSize); if(tickSpacing < (maxWidth + 2 * tickLabelPadding)) { var tickInterval = Math.ceil(translatePixels((maxWidth + 2 * tickLabelPadding), true)), magnitude = Math.pow(10, Math.floor(Math.log(tickInterval) / Math.LN10)); options.tickInterval = this.getNextHighestTickInterval(tickInterval, null, magnitude); } } }, determineIncludeZero: function() { if(parsingUtils.normalizeBoolean(this.properties['axis.includeZero'])) { return true; } // SPL-72638, always include zero if the axis has log scale, unless the user has explicitly set a min or max that contradicts if(this.isLogScale()) { var userMin = parseFloat(this.properties["axis.minimumNumber"]), userMax = parseFloat(this.properties["axis.maximumNumber"]); if((_.isNaN(userMin) || userMin <= 0) && (_.isNaN(userMax) || userMax >= 0)) { return true; } } return false; }, enforceIncludeZero: function(options, extremes) { // if there are no extremes (i.e. no meaningful data was extracted), go with 0 to 100 if(!extremes.min && !extremes.max) { this.handleNoData(options); return; } if(extremes.min >= 0) { options.min = 0; options.minPadding = 0; } else if(extremes.max <= 0) { options.max = 0; options.maxPadding = 0; } }, // clean up various issues that can arise from the axis extremes adjustAxisRange: function(options, extremes, tickInterval) { var hasUserMin = (options.min !== null), hasUserMax = (options.max !== null); // if there are no extremes (i.e. no meaningful data was extracted), go with 0 to 100 if(!extremes.min && !extremes.max) { this.handleNoData(options); return; } // if the min or max is such that no data makes it onto the chart, we hard-code some reasonable extremes if(extremes.min > extremes.dataMax && extremes.min > 0 && !hasUserMax) { options.max = (this.isLogScale()) ? extremes.min + 2 : extremes.min * 2; return; } if(extremes.max < extremes.dataMin && extremes.max < 0 && !hasUserMin) { options.min = (this.isLogScale()) ? extremes.max - 2 : extremes.max * 2; return; } // if either data extreme within one tick interval of zero, // remove the padding on that side so the axis doesn't extend beyond zero if(extremes.dataMin >= 0 && extremes.dataMin <= tickInterval) { if(!hasUserMin){ options.min = 0; } options.minPadding = 0; } if(extremes.dataMax <= 0 && extremes.dataMax >= -1 * tickInterval) { if(!hasUserMax){ options.max = 0; } options.maxPadding = 0; } }, handleNoData: function(axisOptions) { var logScale = this.isLogScale(); axisOptions.min = 0; axisOptions.max = logScale ? 2 : 100; if(logScale) { axisOptions.tickInterval = 1; } }, enforceIntegerMajorUnit: function(options, extremes) { var range = extremes.max - extremes.min; // if the axis range is ten or greater, require that the major unit be an integer if(range >= 10) { options.allowDecimals = false; } }, // This is a custom version of Highcharts' normalizeTickInterval method. For some reason, Highcharts // wasn't collapsing axis tick intervals early enough (SPL-72905), so we elected to choose one multiple // higher than what they would have recommended (e.g. choose 5,000,000 instead of 2,500,000). getNextHighestTickInterval: function(interval, multiples, magnitude) { var normalized = interval / magnitude; if (!multiples) { multiples = [1, 2, 2.5, 5, 10, 20]; } // normalize the interval to the nearest multiple for (var i = 0; i < multiples.length - 1; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { interval = multiples[i+1]; break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } }); return NumericAxis; }); define('js_charting/helpers/HoverEventThrottler',['jquery'], function($) { var Throttler = function(properties){ properties = properties || {}; this.highlightDelay = properties.highlightDelay || 200; this.unhighlightDelay = properties.unhighlightDelay || 100; this.timer = null; this.timer2 = null; this.mouseStatus = 'over'; this.isSelected = false; this.onMouseOver = properties.onMouseOver; this.onMouseOut = properties.onMouseOut; }; $.extend(Throttler.prototype, { setMouseStatus: function(status) { this.mouseStatus = status; }, getMouseStatus: function() { return this.mouseStatus; }, mouseOverHappened: function(someArgs) { var that = this, args = arguments; this.mouseOverFn = function() { that.onMouseOver.apply(null, args); }; clearTimeout(this.timer); clearTimeout(this.timer2); this.setMouseStatus('over'); this.timeOutManager(); }, mouseOutHappened: function(someArgs) { var that = this, args = arguments; this.mouseOutFn = function() { that.onMouseOut.apply(null, args); }; this.setMouseStatus('out'); this.timeOutManager(); }, timeOutManager: function(){ var that = this; clearTimeout(this.timer); if(this.isSelected) { if(this.getMouseStatus()==='over') { this.mouseEventManager(); } else { this.timer2 = setTimeout(function() { that.setMouseStatus('out'); that.mouseEventManager(); }, that.unhighlightDelay); } } else { this.timer = setTimeout(function() { that.isSelected = true; that.mouseEventManager(); }, that.highlightDelay); } }, mouseEventManager: function() { var that = this; if(this.getMouseStatus()==='over') { this.mouseOverFn(); this.isSelected = true; this.setMouseStatus('out'); } else { this.mouseOutFn(); this.isSelected = false; this.setMouseStatus('over'); } } }); return Throttler; }); define('js_charting/components/Legend',[ 'jquery', 'underscore', '../helpers/EventMixin', '../helpers/Formatter', '../helpers/HoverEventThrottler', '../util/parsing_utils', '../util/color_utils', '../util/dom_utils' ], function( $, _, EventMixin, Formatter, HoverEventThrottler, parsingUtils, colorUtils, domUtils ) { var Legend = function(properties) { this.properties = properties || {}; this.clickEnabled = parsingUtils.normalizeBoolean(this.properties['clickEnabled']); this.ellipsisMode = this.OVERFLOW_TO_ELLIPSIS_MAP[this.properties['labelStyle.overflowMode']] || this.DEFAULT_ELLIPSIS_MODE; this.UNHIGHLIGHTED_COLOR = colorUtils.addAlphaToColor(this.UNHIGHLIGHTED_BASE_COLOR, this.UNHIGHLIGHTED_OPACITY); }; Legend.prototype = $.extend({}, EventMixin, { HIGHLIGHTED_OPACITY: 1.0, UNHIGHLIGHTED_OPACITY: 0.3, UNHIGHLIGHTED_BASE_COLOR: 'rgb(150, 150, 150)', DEFAULT_PLACEMENT: 'right', DEFAULT_ELLIPSIS_MODE: 'middle', BASE_CONFIG: { borderWidth: 0 }, PLACEMENT_OPTIONS: { top: true, left: true, bottom: true, right: true, none: true }, PLACEMENT_TO_MARGIN_MAP: { top: 30, left: 15, bottom: 15, right: 15 }, OVERFLOW_TO_ELLIPSIS_MAP: { ellipsisStart: 'start', ellipsisMiddle: 'middle', ellipsisEnd: 'end', ellipsisNone: 'none', 'default': 'start' }, getConfig: function() { var placement = this.PLACEMENT_OPTIONS.hasOwnProperty(this.properties['placement']) ? this.properties['placement'] : this.DEFAULT_PLACEMENT, isVertical = { left: true, right: true }.hasOwnProperty(placement), itemCursorStyle = this.clickEnabled ? 'pointer' : 'default'; return $.extend(true, {}, this.BASE_CONFIG, { enabled: this.properties['isEmpty'] ? false : true, align: isVertical ? placement : 'center', verticalAlign: isVertical ? 'middle' : placement, layout: isVertical ? 'vertical' : 'horizontal', margin: this.PLACEMENT_TO_MARGIN_MAP[placement], itemStyle: { cursor: itemCursorStyle, color: this.properties['fontColor'] || '#000000' }, itemHoverStyle: { cursor: itemCursorStyle, color: this.properties['fontColor'] || '#000000' }, renderItemsPreHook: _(this.renderItemsPreHook).bind(this), renderItemsPostHook: _(this.renderItemsPostHook).bind(this) }); }, onChartLoad: function(chart) { // Works but may need to be changed in the future this.hcSeriesList = _(chart.series).filter(function(series){ return series.options.showInLegend !== false; }); this.addEventHandlers(); }, addEventHandlers: function() { var that = this, properties = { highlightDelay: 125, unhighlightDelay: 50, onMouseOver: function(fieldName) { that.selectField(fieldName); that.trigger('mouseover', [fieldName]); }, onMouseOut: function(fieldName) { that.unSelectField(fieldName); that.trigger('mouseout', [fieldName]); } }, throttle = new HoverEventThrottler(properties); _(this.hcSeriesList).each(function(series) { var fieldName = series.name; _(this.getSeriesLegendObjects(series)).each(function(graphic) { domUtils.jQueryOn.call($(graphic.element), 'mouseover', function() { throttle.mouseOverHappened(fieldName); }); domUtils.jQueryOn.call($(graphic.element), 'mouseout', function() { throttle.mouseOutHappened(fieldName); }); if(this.clickEnabled) { domUtils.jQueryOn.call($(graphic.element), 'click', function(e) { var clickEvent = { type: 'click', modifierKey: (e.ctrlKey || e.metaKey) }; that.trigger(clickEvent, [fieldName]); }); } }, this); }, this); }, selectField: function(fieldName) { _(this.hcSeriesList).each(function(series) { if(series.name !== fieldName) { this.unHighlightField(fieldName, series); } else { this.highlightField(fieldName, series); } }, this); }, unSelectField: function(fieldName) { _(this.hcSeriesList).each(function(series) { if(series.name !== fieldName) { this.highlightField(fieldName, series); } }, this); }, highlightField: function(fieldName, series) { series = series || this.getSeriesByFieldName(fieldName); var objects = this.getSeriesLegendObjects(series), seriesColor = series.color; if(objects.item) { objects.item.attr('fill-opacity', this.HIGHLIGHTED_OPACITY); } if(objects.line) { objects.line.attr('stroke', seriesColor); } if(objects.symbol) { objects.symbol.attr({ 'fill': seriesColor, 'stroke': seriesColor }); } }, unHighlightField: function(fieldName, series) { series = series || this.getSeriesByFieldName(fieldName); var objects = this.getSeriesLegendObjects(series); if(objects.item) { objects.item.attr('fill-opacity', this.UNHIGHLIGHTED_OPACITY); } if(objects.line) { objects.line.attr('stroke', this.UNHIGHLIGHTED_COLOR); } if(objects.symbol) { objects.symbol.attr({ 'fill': this.UNHIGHLIGHTED_COLOR, 'stroke': this.UNHIGHLIGHTED_COLOR }); } }, getSeriesByFieldName: function(fieldName) { return _(this.hcSeriesList).find(function(series) { return series.name === fieldName; }); }, getSeriesLegendObjects: function(series) { var objects = {}; if(series.legendItem) { objects.item = series.legendItem; } if(series.legendSymbol) { objects.symbol = series.legendSymbol; } if(series.legendLine) { objects.line = series.legendLine; } return objects; }, destroy: function() { this.off(); this.hcSeriesList = null; }, /** * @author sfishel * * Do some intelligent ellipsizing of the legend labels (if needed) before they are rendered. */ renderItemsPreHook: function(legend) { var i, adjusted, fixedWidth, maxWidth, options = legend.options, itemStyle = legend.itemStyle, items = legend.allItems, chart = legend.chart, renderer = chart.renderer, spacingBox = chart.spacingBox, horizontalLayout = (options.layout === 'horizontal'), defaultFontSize = 12, minFontSize = 10, symbolWidth = options.symbolWidth, symbolPadding = options.symbolPadding, boxPadding = legend.padding || 0, itemHorizSpacing = 10, labels = [], formatter = new Formatter(renderer); if(horizontalLayout) { maxWidth = (items.length > 5) ? Math.floor(spacingBox.width / 6) : Math.floor(spacingBox.width / items.length) - ((symbolWidth + symbolPadding + itemHorizSpacing) * (items.length - 1)); } else { maxWidth = Math.floor(spacingBox.width / 6) - (symbolWidth + symbolPadding + boxPadding); } // make a copy of the original formatting function, since we're going to clobber it if(!options.originalFormatter) { options.originalFormatter = options.labelFormatter; } // get all of the legend labels for(i = 0; i < items.length; i++) { labels.push(options.originalFormatter.call(items[i])); } adjusted = formatter.adjustLabels(labels, maxWidth, minFontSize, defaultFontSize, this.ellipsisMode); // in case of horizontal layout with ellipsized labels, set a fixed width for nice alignment if(adjusted.areEllipsized && horizontalLayout && items.length > 5) { fixedWidth = maxWidth + symbolWidth + symbolPadding + itemHorizSpacing; options.itemWidth = fixedWidth; } else { options.itemWidth = undefined; } // set the new labels to the name field of each item for(i = 0; i < items.length; i++) { items[i].ellipsizedName = adjusted.labels[i]; // if the legendItem is already set this is a resize event, so we need to explicitly reformat the item if(items[i].legendItem) { domUtils.setLegendItemText(items[i].legendItem, adjusted.labels[i]); items[i].legendItem.css({ 'font-size': adjusted.fontSize + 'px' }); } } // now that the ellipsizedName field has the pre-formatted labels, update the label formatter options.labelFormatter = function() { return parsingUtils.escapeSVG(this.ellipsizedName); }; // adjust the font size itemStyle['font-size'] = adjusted.fontSize + 'px'; legend.itemMarginTop = defaultFontSize - adjusted.fontSize; formatter.destroy(); }, /** * @author sfishel * * Detect if the legend items will overflow the container (in which case navigation buttons will be shown) * and adjust the default values for the vertical positioning and width * * FIXME: it would be better to do this work after the nav has been rendered instead of * hard-coding an expected width */ renderItemsPostHook: function(legend) { var NAV_WIDTH = 55, options = legend.options, padding = legend.padding, legendHeight = legend.lastItemY + legend.lastLineHeight, availableHeight = legend.chart.spacingBox.height - padding; if(legendHeight > availableHeight) { options.verticalAlign = 'top'; options.y = -padding; if(legend.offsetWidth < NAV_WIDTH) { options.width = NAV_WIDTH; } } else { // SPL-70551, make sure to set things back to defaults in case the chart was resized to a larger height var config = this.getConfig(); $.extend(options, { verticalAlign: config.verticalAlign, y: config.y, width: config.width }); } } }); return Legend; }); define('js_charting/components/PanningScrollbar',['jquery', 'underscore', '../helpers/EventMixin'], function($, _, EventMixin) { var PanningScrollbar = function(properties){ this.properties = properties || {}; }; PanningScrollbar.prototype = $.extend({}, EventMixin, { onChartLoad: function(chart){ var parent = this.getParentElement(this.properties['container']); this.createPanningSlider(parent, chart); this.setSliderPosition(chart); this.addEventHandlers(chart); }, onChartLoadOrResize: function(chart) { this.setSliderPosition(chart); }, getParentElement: function(container){ return $(container).parent(); }, createPanningSlider: function(parent){ var $panning = $(".panning"); if(!($panning.length > 0)) { $(parent).after('<div class="panning"></div>'); $panning.append('<div id="panning-slider"></div>'); } }, addEventHandlers: function() { var that = this, panning = $('.panning'), delay= 50, onPanningScroll= function(){ that.setWindowToDisplay(that.pixelToWindowValue(panning)); that.trigger('scroll', that.getWindowToDisplay()); }; $(panning).bind('scroll', _.throttle(onPanningScroll, delay)); }, setSliderPosition: function(chart) { var pointsPlottedPerSeries = Math.ceil(this.properties.truncationLimit / (this.properties.numSeries)), ptsNotPlottedPerSeries = this.properties.seriesSize - pointsPlottedPerSeries; this.numWindows = Math.ceil(ptsNotPlottedPerSeries/pointsPlottedPerSeries); this.numberOfWindows = Math.ceil(ptsNotPlottedPerSeries - pointsPlottedPerSeries); $('.panning').css({ 'width': chart.plotWidth + 'px', 'margin-left': chart.plotLeft + 'px', 'margin-top': '2px', 'overflow': 'scroll', 'z-index': '100', 'display': 'inline-block' }); $('#panning-slider').css({ 'width': (this.numWindows*100) + '%', 'height': '2px' }); }, pixelToWindowValue: function(panning){ var currentPosition, scrollWidth, winLen; scrollWidth = $("#panning-slider").width(); winLen = scrollWidth / this.numberOfWindows; currentPosition = $(panning).scrollLeft() + (winLen/2); return Math.floor(currentPosition / winLen); }, destroy: function() { this.off(); }, setWindowToDisplay: function(windowNumber){ this.windowToDisplay = windowNumber; }, getWindowToDisplay: function(){ return this.windowToDisplay; } }); return PanningScrollbar; }); define('js_charting/components/Tooltip',['jquery', 'underscore'], function($, _) { var Tooltip = function(properties) { this.properties = properties || {}; }; Tooltip.prototype = { BASE_CONFIG: { animation: false, enabled: true, backgroundColor: '#000000', borderColor: '#ffffff', style: { color: '#cccccc' }, /** * @author sfishel * * If the tooltip is too wide for the plot area, clip it left not right. * * unit test: js_charting/components/test_tooltip.html */ positioner: function(boxWidth, boxHeight, point) { var position = this.getPosition(boxWidth, boxHeight, point), plotWidth = this.chart.plotWidth; if(boxWidth > plotWidth) { var options = this.options; position.x = options.borderRadius + options.borderWidth; } return position; }, /** * @author sfishel * * Adjust the tooltip anchor position for column charts. * Use a position relative to the selected column instead of a shared one for the series group. * * unit test: js_charting/components/test_tooltip.html */ getAnchorPostHook: function(points, mouseEvent, anchor) { if(points && !_.isArray(points) && points.series.options.type === 'column') { anchor[0] = points.barX; } return anchor; } }, getConfig: function() { return $.extend(true, {}, this.BASE_CONFIG, { borderColor: this.properties['borderColor'] }); } }; return Tooltip; }); define('js_charting/series/Series',[ 'jquery', 'underscore', '../helpers/EventMixin', '../helpers/Formatter', '../util/color_utils', '../util/parsing_utils' ], function( $, _, EventMixin, Formatter, colorUtils, parsingUtils ) { var Point = function(hcPoint) { this.index = hcPoint.index; this.seriesName = hcPoint.series.name; this.name = hcPoint.name; this.y = hcPoint.y; }; var Series = function(properties) { this.properties = this.normalizeProperties(properties || {}); this.id = _.uniqueId('series_'); this.data = []; this.UNHIGHLIGHTED_COLOR = colorUtils.addAlphaToColor(this.UNHIGHLIGHTED_BASE_COLOR, this.UNHIGHLIGHTED_OPACITY); }; Series.prototype = $.extend({}, EventMixin, { STACK_MODE_MAP: { 'default': null, 'stacked': 'normal', 'stacked100': 'percent' }, CHART_PROPERTY_PREFIX_REGEX: /^chart\./, UNHIGHLIGHTED_OPACITY: 0.3, UNHIGHLIGHTED_BASE_COLOR: 'rgb(150, 150, 150)', DEFAULT_STACK_MODE: null, CHARTING_PROPERTY_WHITELIST: [], // a centralized normalization method for series properties, subclasses override or extend the // CHARTING_PROPERTY_WHITELIST with a list of property names (without the leading "chart.") // to be parsed from the chart properties passed to the constructor normalizeProperties: function(rawProps) { var normalizedProps = $.extend(true, {}, rawProps); _(normalizedProps).each(function(value, key) { if(this.CHART_PROPERTY_PREFIX_REGEX.test(key)) { delete normalizedProps[key]; var strippedKey = key.replace(this.CHART_PROPERTY_PREFIX_REGEX, ''); if(_(this.CHARTING_PROPERTY_WHITELIST).contains(strippedKey)) { normalizedProps[strippedKey] = value; } } }, this); return normalizedProps; }, getXAxisIndex: function() { return this.properties['xAxis'] || 0; }, setXAxisIndex: function(axisIndex) { this.properties['xAxis'] = axisIndex; }, getYAxisIndex: function() { return this.properties['yAxis'] || 0; }, setYAxisIndex: function(axisIndex) { this.properties['yAxis'] = axisIndex; }, getName: function() { return this.properties['name']; }, getLegendKey: function() { return this.properties['legendKey'] || this.getName(); }, getFieldList: function() { return [this.getName()]; }, matchesName: function(name) { return name === this.getName(); }, setData: function(inputData) { if(_(inputData.x).isUndefined()) { this.data = inputData.y; } else { this.data = _(inputData.x).map(function(value, i) { return [value, inputData.y[i]]; }); } }, sliceData: function(series, start, finish){ series.data = series.data.slice(start, finish); }, applyColorMapping: function(colorMapping) { this.color = colorMapping[this.getName()]; }, getColor: function() { return this.color; }, getStackMode: function() { return this.STACK_MODE_MAP[this.properties['stacking']] || this.DEFAULT_STACK_MODE; }, getType: function() { return this.type; }, getConfig: function() { var that = this, config = { type: this.type, id: this.id, name: this.getName(), color: this.color, data: this.hasPrettyData ? this.prettyData : this.data, xAxis: this.getXAxisIndex(), yAxis: this.getYAxisIndex(), stacking: this.getStackMode(), point: { events: { mouseOver: function(e) { var hcPoint = this, point = new Point(hcPoint); that.trigger('mouseover', [point, that]); }, mouseOut: function(e) { var hcPoint = this, point = new Point(hcPoint); that.trigger('mouseout', [point, that]); } } } }; if(parsingUtils.normalizeBoolean(this.properties['clickEnabled'])) { config.point.events.click = function(e) { var hcPoint = this, point = new Point(hcPoint), clickEvent = { type: 'click', modifierKey: (e.ctrlKey || e.metaKey) }; that.trigger(clickEvent, [point, that]); }; } return config; }, onChartLoad: function(chart) { this.hcSeries = chart.get(this.id); // FIXME: would be nice to find a way around this _(this.hcSeries.data).each(function(point, i) { point.index = i; }); // create a back-reference so we can get from the HighCharts series to this object this.hcSeries.splSeries = this; }, destroy: function() { this.off(); // remove the back-reference to avoid any reference loops that might confuse the GC if(this.hcSeries.splSeries) { this.hcSeries.splSeries = null; } this.hcSeries = null; }, handlePointMouseOver: function(point) { this.bringToFront(); }, handleLegendMouseOver: function(fieldName) { this.bringToFront(); this.highlight(); }, bringToFront: function() { if(this.hcSeries.group) { this.hcSeries.group.toFront(); } if(this.hcSeries.trackerGroup) { this.hcSeries.trackerGroup.toFront(); } }, estimateMaxColumnWidths: function(hcChart, leftColData, rightColData) { var formatter = new Formatter(hcChart.renderer), fontSize = hcChart.options.tooltip.style.fontSize.replace("px", ""); // Use the text in the columns to roughly estimate which column requires more space var maxLeftColWidth = -Infinity, maxRightColWidth = -Infinity; _.each(leftColData, function(datum) { var colWidth = formatter.predictTextWidth(datum, fontSize); if(colWidth > maxLeftColWidth) { maxLeftColWidth = colWidth; } }); _.each(rightColData, function(datum) { var colWidth = formatter.predictTextWidth(datum, fontSize); if(colWidth > maxRightColWidth) { maxRightColWidth = colWidth; } }); formatter.destroy(); return { maxLeftColWidth: maxLeftColWidth, maxRightColWidth: maxRightColWidth }; }, // Overridden by subclasses getLeftColData: function(info) { if(info.xAxisIsTime) { return [info.xValueDisplay, info.seriesName]; } else { return [info.xAxisName, info.seriesName]; } }, // Overridden by subclasses getRightColData: function(info) { if(info.xAxisIsTime) { return [info.yValueDisplay]; } else { return [info.xValueDisplay, info.yValueDisplay]; } }, // find a way to send the target series and target point to the handler just like a click event getTooltipHtml: function(info, hcChart) { info.seriesName = this.getName(); info.seriesColor = this.getColor(); var maxTooltipWidth = hcChart.chartWidth - 50, leftColData = this.getLeftColData(info), rightColData = this.getRightColData(info), colResults = this.estimateMaxColumnWidths(hcChart, leftColData, rightColData), leftColRatio = colResults.maxLeftColWidth / (colResults.maxLeftColWidth + colResults.maxRightColWidth); // Make sure one column doesn't completely dominate the other if(leftColRatio > 0.9) { leftColRatio = 0.9; } else if(leftColRatio < 0.1) { leftColRatio = 0.1; } info.scaledMaxLeftColWidth = (leftColRatio * maxTooltipWidth) + "px"; info.scaledMaxRightColWidth = ((1 - leftColRatio) * maxTooltipWidth) + "px"; info.willWrap = (colResults.maxLeftColWidth + colResults.maxRightColWidth > maxTooltipWidth); return _(this.tooltipTemplate).template(info); }, // stub methods to be overridden as needed by subclasses handlePointMouseOut: function(point) { }, handleLegendMouseOut: function(fieldName) { }, highlight: function() { }, unHighlight: function() { }, tooltipTemplate: '\ <table class="highcharts-tooltip"\ <% if(willWrap) { %>\ style="word-wrap: break-word; white-space: normal;"\ <% } %>>\ <% if(xAxisIsTime) { %>\ <tr>\ <td style="text-align: left; color: #ffffff;" colpsan="2"><%- xValueDisplay %></td>\ </tr>\ <% } else { %>\ <tr>\ <td style="text-align: left; color: #cccccc; max-width: <%= scaledMaxLeftColWidth %>;"><%- xAxisName %>:&nbsp;&nbsp;</td>\ <td style="text-align: right; color: #ffffff; max-width: <%= scaledMaxRightColWidth %>;"><%- xValueDisplay %></td>\ </tr>\ <% } %>\ <tr>\ <td style="text-align: left; color:<%= seriesColor %>; max-width: <%= scaledMaxLeftColWidth %>;"><%- seriesName %>:&nbsp;&nbsp;</td>\ <td style="text-align: right; color: #ffffff; max-width: <%= scaledMaxRightColWidth %>;"><%- yValueDisplay %></td>\ </tr>\ </table>\ ' }); Series.Point = Point; return Series; }); define('js_charting/series/ManyShapeSeries',[ 'jquery', 'underscore', './Series', '../util/lang_utils', '../util/color_utils' ], function( $, _, Series, langUtils, colorUtils ) { var ManyShapeSeries = function(properties) { Series.call(this, properties); this.UNHIGHLIGHTED_BORDER_COLOR = colorUtils.addAlphaToColor(this.UNHIGHLIGHTED_BORDER_BASE_COLOR, this.UNHIGHLIGHTED_OPACITY); }; langUtils.inherit(ManyShapeSeries, Series); $.extend(ManyShapeSeries.prototype, { CHARTING_PROPERTY_WHITELIST:_.union(['seriesSpacing'], Series.prototype.CHARTING_PROPERTY_WHITELIST), UNHIGHLIGHTED_BORDER_BASE_COLOR: 'rgb(200, 200, 200)', DEFAULT_COLUMN_SPACING: 0.01, DEFAULT_COLUMN_GROUP_SPACING: 0.05, DEFAULT_BAR_SPACING: 0.02, DEFAULT_BAR_GROUP_SPACING: 0.05, handlePointMouseOver: function(point) { Series.prototype.handlePointMouseOver.call(this, point); this.selectPoint(point); }, handlePointMouseOut: function(point) { Series.prototype.handlePointMouseOut.call(this, point); this.unSelectPoint(point); }, highlight: function() { Series.prototype.highlight.call(this); _(this.hcSeries.data).each(this.highlightPoint, this); }, unHighlight: function() { Series.prototype.unHighlight.call(this); _(this.hcSeries.data).each(this.unHighlightPoint, this); }, selectPoint: function(point) { var matchingPoint = this.hcSeries.data[point.index]; this.highlightPoint(matchingPoint); _(this.hcSeries.data).chain().without(matchingPoint).each(this.unHighlightPoint, this); }, unSelectPoint: function(point) { var matchingPoint = this.hcSeries.data[point.index]; _(this.hcSeries.data).chain().without(matchingPoint).each(this.highlightPoint, this); }, highlightPoint: function(hcPoint) { if(!hcPoint.graphic) { return; } var seriesColor = this.getColor(); hcPoint.graphic.attr({ 'fill': seriesColor, 'stroke-width': 0, 'stroke': seriesColor }); }, unHighlightPoint: function(hcPoint) { if(!hcPoint.graphic) { return; } hcPoint.graphic.attr({ 'fill': this.UNHIGHLIGHTED_COLOR, 'stroke-width': 1, 'stroke': this.UNHIGHLIGHTED_BORDER_COLOR }); }, computeColumnSpacing: function(str) { var value = parseFloat(str); if(_(value).isNaN()) { return this.DEFAULT_COLUMN_SPACING; } return value * this.DEFAULT_COLUMN_SPACING; }, computeColumnGroupSpacing: function(str) { var value = parseFloat(str); if(_(value).isNaN()) { return this.DEFAULT_COLUMN_GROUP_SPACING; } return this.DEFAULT_COLUMN_GROUP_SPACING * (1 + value); }, computeBarSpacing: function(str) { var value = parseFloat(str); if(_(value).isNaN()) { return this.DEFAULT_BAR_SPACING; } return value * this.DEFAULT_BAR_SPACING; }, computeBarGroupSpacing: function(str) { var value = parseFloat(str); if(_(value).isNaN()) { return this.DEFAULT_BAR_GROUP_SPACING; } return this.DEFAULT_BAR_GROUP_SPACING * (1 + value); } }); return ManyShapeSeries; }); define('js_charting/series/ColumnSeries',[ 'jquery', 'underscore', './ManyShapeSeries', '../util/lang_utils' ], function( $, _, ManyShapeSeries, langUtils ) { var ColumnSeries = function(properties) { ManyShapeSeries.call(this, properties); }; langUtils.inherit(ColumnSeries, ManyShapeSeries); $.extend(ColumnSeries.prototype, { CHARTING_PROPERTY_WHITELIST: _.union(['columnSpacing'], ManyShapeSeries.prototype.CHARTING_PROPERTY_WHITELIST), type: 'column', getConfig: function() { var config = ManyShapeSeries.prototype.getConfig.call(this); config.pointPadding = this.computeColumnSpacing(this.properties['columnSpacing']); config.groupPadding = this.computeColumnGroupSpacing(this.properties['seriesSpacing']); return config; }, // SPL-68694, this should be a no-op for column series or it will interfere with click handlers bringToFront: function() { } }); return ColumnSeries; }); define('js_charting/series/BarSeries',[ 'jquery', 'underscore', './ManyShapeSeries', '../util/lang_utils' ], function( $, _, ManyShapeSeries, langUtils ) { var BarSeries = function(properties) { ManyShapeSeries.call(this, properties); }; langUtils.inherit(BarSeries, ManyShapeSeries); $.extend(BarSeries.prototype, { CHARTING_PROPERTY_WHITELIST: _.union(['barSpacing'], ManyShapeSeries.prototype.CHARTING_PROPERTY_WHITELIST), type: 'bar', getConfig: function() { var config = ManyShapeSeries.prototype.getConfig.call(this); config.pointPadding = this.computeBarSpacing(this.properties['barSpacing']); config.groupPadding = this.computeBarGroupSpacing(this.properties['seriesSpacing']); return config; }, // SPL-68694, this should be a no-op for bar series or it will interfere with click handlers bringToFront: function() { } }); return BarSeries; }); define('js_charting/series/SingleShapeSeries',[ 'jquery', 'underscore', './Series', '../util/lang_utils' ], function( $, _, Series, langUtils ) { var SingleShapeSeries = function(properties) { Series.call(this, properties); }; langUtils.inherit(SingleShapeSeries, Series); $.extend(SingleShapeSeries.prototype, { CHARTING_PROPERTY_WHITELIST:_.union( ['lineStyle', 'nullValueMode'], Series.prototype.CHARTING_PROPERTY_WHITELIST ), HIGHLIGHTED_OPACITY: 1.0, getConfig: function() { var config = Series.prototype.getConfig.call(this); config.dashStyle = (this.properties['lineStyle'] === 'dashed') ? 'Dash' : 'Solid'; config.pointPlacement = 'on'; config.drawPointsPreHook = _(this.drawPointsPreHook).bind(this); return config; }, handlePointMouseOver: function(point) { Series.prototype.handlePointMouseOver.call(this, point); this.highlight(); }, drawPointsPreHook: function(series) { // SPL-55213, we want to handle the case where some segments contain a single point and would not be visible // if showMarkers is true, the marker will take care of what we want, so we're done if(series.options.marker && series.options.marker.enabled) { return; } var i, segment, segments = series.segments; for(i = 0; i < segments.length; i++) { // a segments with a length of one contains a single point // extend the point's options to draw a small marker on it segment = segments[i]; if(segment.length === 1) { segment[0].update({ marker: { enabled: true, radius: 4 } }, false); } } } }); return SingleShapeSeries; }); define('js_charting/series/LineSeries',[ 'jquery', 'underscore', './SingleShapeSeries', '../util/lang_utils', '../util/parsing_utils' ], function( $, _, SingleShapeSeries, langUtils, parsingUtils ) { var LineSeries = function(properties) { SingleShapeSeries.call(this, properties); }; langUtils.inherit(LineSeries, SingleShapeSeries); $.extend(LineSeries.prototype, { CHARTING_PROPERTY_WHITELIST:_.union(['showMarkers'], SingleShapeSeries.prototype.CHARTING_PROPERTY_WHITELIST), type: 'line', onChartLoad: function(chart) { SingleShapeSeries.prototype.onChartLoad.call(this, chart); this.hasMarkers = (this.hcSeries.options.marker.enabled && this.hcSeries.options.marker.radius > 0); }, highlight: function() { SingleShapeSeries.prototype.highlight.call(this); var seriesColor = this.getColor(); this.hcSeries.graph.attr({ 'stroke': seriesColor, 'stroke-opacity': this.HIGHLIGHTED_OPACITY }); _(this.hcSeries.data).each(this.highlightPoint, this); }, unHighlight: function() { SingleShapeSeries.prototype.unHighlight.call(this); this.hcSeries.graph.attr('stroke', this.UNHIGHLIGHTED_COLOR); _(this.hcSeries.data).each(this.unHighlightPoint, this); }, highlightPoint: function(hcPoint) { var seriesColor = this.getColor(); if(hcPoint.graphic) { hcPoint.graphic.attr('fill', seriesColor); } }, unHighlightPoint: function(hcPoint) { if(hcPoint.graphic) { hcPoint.graphic.attr('fill', this.UNHIGHLIGHTED_COLOR); } }, getConfig: function() { var config = SingleShapeSeries.prototype.getConfig.call(this); config.connectNulls = (this.properties['nullValueMode'] === 'connect'); $.extend(config,{ marker: {}, stacking: this.STACK_MODE_MAP['default'] }); config.marker.enabled = parsingUtils.normalizeBoolean(this.properties['showMarkers'], false); return config; } }); return LineSeries; }); define('js_charting/series/AreaSeries',[ 'jquery', 'underscore', './SingleShapeSeries', '../util/lang_utils', '../util/color_utils', '../util/parsing_utils' ], function( $, _, SingleShapeSeries, langUtils, colorUtils, parsingUtils ) { var AreaSeries = function(properties) { SingleShapeSeries.call(this, properties); this.UNHIGHLIGHTED_LINE_COLOR = colorUtils.addAlphaToColor(this.UNHIGHLIGHTED_BASE_COLOR, this.UNHIGHLIGHTED_LINE_OPACITY); }; langUtils.inherit(AreaSeries, SingleShapeSeries); $.extend(AreaSeries.prototype, { HIGHLIGHTED_OPACITY: 0.75, UNHIGHLIGHTED_LINE_OPACITY: 0.4, CHARTING_PROPERTY_WHITELIST:_.union(['showLines'], SingleShapeSeries.prototype.CHARTING_PROPERTY_WHITELIST), type: 'area', getConfig: function() { var config = SingleShapeSeries.prototype.getConfig.call(this); config.fillOpacity = this.HIGHLIGHTED_OPACITY; config.connectNulls = (this.properties['nullValueMode'] === 'connect'); config.lineWidth = parsingUtils.normalizeBoolean(this.properties['showLines'], true) ? 1 : 0; return config; }, onChartLoad: function(chart) { SingleShapeSeries.prototype.onChartLoad.call(this, chart); this.hasLines = (this.hcSeries.options.lineWidth > 0); // FIXME: shouldn't have to do this here, try to make it work with highcharts settings this.hcSeries.area.attr('fill-opacity', this.HIGHLIGHTED_OPACITY); }, highlight: function() { SingleShapeSeries.prototype.highlight.call(this); var seriesColor = this.getColor(); this.hcSeries.area.attr({ 'fill': seriesColor, 'fill-opacity': this.HIGHLIGHTED_OPACITY }); if(this.hasLines) { this.hcSeries.graph.attr({ 'stroke': seriesColor, 'stroke-opacity': 1 }); } }, unHighlight: function() { SingleShapeSeries.prototype.unHighlight.call(this); this.hcSeries.area.attr('fill', this.UNHIGHLIGHTED_COLOR); if(this.hasLines) { this.hcSeries.graph.attr('stroke', this.UNHIGHLIGHTED_LINE_COLOR); } } }); return AreaSeries; }); define('js_charting/series/PieSeries',[ 'jquery', 'underscore', './ManyShapeSeries', '../util/lang_utils', '../util/parsing_utils', '../util/time_utils', 'util/time_utils', 'splunk.i18n' ], function( $, _, ManyShapeSeries, langUtils, parsingUtils, timeUtils, splunkTimeUtils, i18n ) { var PieSeries = function(properties) { ManyShapeSeries.call(this, properties); this.collapseFieldName = this.properties.sliceCollapsingLabel || 'other'; this.collapsePercent = !this.properties.hasOwnProperty('sliceCollapsingThreshold') ? 0.01 : parseFloat(this.properties.sliceCollapsingThreshold); }; langUtils.inherit(PieSeries, ManyShapeSeries); $.extend(PieSeries.prototype, { CHARTING_PROPERTY_WHITELIST:_.union( ['sliceCollapsingThreshold', 'sliceCollapsingLabel', 'showPercent'], ManyShapeSeries.prototype.CHARTING_PROPERTY_WHITELIST ), type: 'pie', hasPrettyData: false, fieldList: [], getConfig: function() { return $.extend(ManyShapeSeries.prototype.getConfig.call(this), { translatePreHook: _(this.translatePreHook).bind(this) }); }, setData: function(inputData) { this.data = []; this.prettyData = []; var that = this, nameSeries = inputData.names, sizeSeries = inputData.sizes, spanSeries = inputData.spans, isTimeBased = inputData.isTimeBased, totalSize = _(sizeSeries).reduce(function(sum, value) { return (sum + value); }, 0), cardinality = sizeSeries.length, collapsedSize = 0, numCollapsed = 0, numLessThanThresh = 0, granularity = null, passesThreshold = function(value) { return (value > 0 && (value / totalSize) > that.collapsePercent); }; if(isTimeBased) { granularity = splunkTimeUtils.determineLabelGranularity(nameSeries); this.hasPrettyData = true; } this.fieldList = _(nameSeries).map(parsingUtils.escapeSVG, parsingUtils); _(sizeSeries).each(function(value, i) { if(!(passesThreshold(sizeSeries[i]))) { numLessThanThresh++; } }, this); _(nameSeries).each(function(name, i) { var sizeValue = sizeSeries[i]; if(passesThreshold(sizeValue) || numLessThanThresh === 1 || cardinality <=10) { if(isTimeBased) { var bdTime = splunkTimeUtils.extractBdTime(name), humanizedName = timeUtils.formatBdTimeAsAxisLabel(bdTime, null, granularity).join(' '), spanValue = spanSeries[i]; this.data.push([name, sizeValue, spanValue]); this.prettyData.push([humanizedName, sizeValue, spanValue]); } else { this.data.push([name, sizeValue]); } } else { collapsedSize += sizeValue; numCollapsed++; this.fieldList = _(this.fieldList).without(name); } }, this); if(numCollapsed > 0) { var collapsedName = this.collapseFieldName + ' (' + numCollapsed + ')'; this.data.push([collapsedName, collapsedSize]); // Doesn't make sense to attach a span value to the collapsed section this.prettyData.push([collapsedName, collapsedSize, null]); this.fieldList.push('__other'); } if(parsingUtils.normalizeBoolean(this.properties.showPercent)) { _([this.data, this.prettyData]).each(function(data) { _(data).each(function(dataPoint) { dataPoint[0] += ', ' + i18n.format_percent(dataPoint[1] / totalSize); }); }); } }, getFieldList: function() { return this.fieldList; }, // returns the series data after any processing (like slice collapsing) has been applied getData: function() { return this.data; }, getPrettyData: function() { return this.prettyData; }, highlightPoint: function(hcPoint) { var pointColor = hcPoint.color; hcPoint.graphic.attr({ 'fill': pointColor, 'stroke-width': 0, 'stroke': pointColor }); }, getLeftColData: function(info) { return [info.sliceFieldName, info.seriesName, info.seriesName + "%"]; }, getRightColData: function(info) { return [info.sliceName, info.yValue, info.yPercent]; }, /** * @author sfishel * * Dynamically adjust the pie size based on the height and width of the container */ translatePreHook: function(pieSeries) { var chart = pieSeries.chart; pieSeries.options.size = Math.min(chart.plotHeight * 0.75, chart.plotWidth / 3); }, tooltipTemplate: '\ <table class="highcharts-tooltip"\ <% if(willWrap) { %>\ style="word-wrap: break-word; white-space: normal;"\ <% } %>>\ <tr>\ <td style="text-align: left; color: #cccccc; max-width: <%= scaledMaxLeftColWidth %>;"><%- sliceFieldName %>:&nbsp;&nbsp;</td>\ <td style="text-align: right; color: #ffffff; max-width: <%= scaledMaxRightColWidth %>;"><%- sliceName %></td>\ </tr>\ <tr>\ <td style="text-align: left; color: <%= sliceColor %>; max-width: <%= scaledMaxLeftColWidth %>;"><%- seriesName %>:&nbsp;&nbsp;</td>\ <td style="text-align: right; color: #ffffff; max-width: <%= scaledMaxRightColWidth %>;"><%- yValue %></td>\ </tr>\ <tr>\ <td style="text-align: left; color: <%= sliceColor %>; max-width: <%= scaledMaxLeftColWidth %>;"><%- seriesName %>%:&nbsp;&nbsp;</td>\ <td style="text-align: right; color: #ffffff; max-width: <%= scaledMaxRightColWidth %>;"><%- yPercent %></td>\ </tr>\ </table>\ ' }); return PieSeries; }); define('js_charting/series/MultiSeries',[ 'jquery', 'underscore', './Series', '../util/lang_utils' ], function( $, _, Series, langUtils ) { var MultiSeries = function(properties) { Series.call(this, properties); this.nestedSeriesList = []; }; langUtils.inherit(MultiSeries, Series); $.extend(MultiSeries.prototype, { getFieldList: function() { return _(this.nestedSeriesList).invoke('getFieldList'); }, applyColorMapping: function(colorMapping) { _(this.nestedSeriesList).invoke('applyColorMapping', colorMapping); }, matchesName: function(name) { return _(this.nestedSeriesList).any(function(series) { return series.matchesName(name); }); }, getConfig: function() { return _(this.nestedSeriesList).invoke('getConfig'); }, bindNestedSeries: function() { var that = this; _(this.nestedSeriesList).each(function(series) { series.on('mouseover', function(e, point, targetSeries) { that.trigger(e, [point, targetSeries]); }); series.on('mouseout', function(e, point, targetSeries) { that.trigger(e, [point, targetSeries]); }); series.on('click', function(e, point, targetSeries) { that.trigger(e, [point, targetSeries]); }); }); }, handlePointMouseOver: function(point) { var seriesName = point.seriesName; _(this.nestedSeriesList).each(function(series) { if(series.matchesName(seriesName)) { series.handlePointMouseOver(point); } else { series.unHighlight(); } }); }, handlePointMouseOut: function(point) { var seriesName = point.seriesName; _(this.nestedSeriesList).each(function(series) { if(series.matchesName(seriesName)) { series.handlePointMouseOut(point); } else { series.highlight(); } }); }, handleLegendMouseOver: function(fieldName) { _(this.nestedSeriesList).each(function(series) { if(series.matchesName(fieldName)) { series.handleLegendMouseOver(fieldName); } else { series.unHighlight(); } }); }, handleLegendMouseOut: function(fieldName) { _(this.nestedSeriesList).each(function(series) { if(series.matchesName(fieldName)) { series.handleLegendMouseOut(fieldName); } else { series.highlight(); } }); }, onChartLoad: function(chart) { _(this.nestedSeriesList).invoke('onChartLoad', chart); }, destroy: function() { this.off(); _(this.nestedSeriesList).invoke('destroy'); }, bringToFront: function() { _(this.nestedSeriesList).invoke('bringToFront'); }, highlight: function() { _(this.nestedSeriesList).invoke('highlight'); }, unHighlight: function() { _(this.nestedSeriesList).invoke('unHighlight'); } }); return MultiSeries; }); define('js_charting/series/ScatterSeries',['jquery', './ManyShapeSeries', '../util/lang_utils'], function($, ManyShapeSeries, langUtils) { var ScatterSeries = function(properties) { ManyShapeSeries.call(this, properties); }; langUtils.inherit(ScatterSeries, ManyShapeSeries); $.extend(ScatterSeries.prototype, { type: 'scatter', getLeftColData: function(info) { return [info.labelSeriesName, info.xAxisName, info.yAxisName]; }, getRightColData: function(info) { return [info.seriesName, info.xValue, info.yValue]; }, tooltipTemplate: '\ <table class="highcharts-tooltip"\ <% if(willWrap) { %>\ style="word-wrap: break-word; white-space: normal;"\ <% } %>>\ <% if(isMultiSeries) { %>\ <tr>\ <td style="text-align: left; color: #cccccc; max-width: <%= scaledMaxLeftColWidth %>;"><%- labelSeriesName %>:&nbsp;&nbsp;</td>\ <td style="text-align: right; color: <%= seriesColor %>; max-width: <%= scaledMaxRightColWidth %>;"><%- seriesName %></td>\ </tr>\ <% } %>\ <% if(markName) { %>\ <tr>\ <td style="text-align: left; color: #cccccc; max-width: <%= scaledMaxLeftColWidth %>;"><%- markName %>:&nbsp;&nbsp;</td>\ <td style="text-align: right; color: #ffffff; max-width: <%= scaledMaxRightColWidth %>;"><%- markValue %></td>\ </tr>\ <% } %>\ <tr>\ <td style="text-align: left; color: #cccccc; max-width: <%= scaledMaxLeftColWidth %>;"><%- xAxisName %>:&nbsp;&nbsp;</td>\ <td style="text-align: right; color: #ffffff; max-width: <%= scaledMaxRightColWidth %>;"><%- xValue %></td>\ </tr>\ <tr>\ <td style="text-align: left; color: #cccccc; max-width: <%= scaledMaxLeftColWidth %>;"><%- yAxisName %>:&nbsp;&nbsp;</td>\ <td style="text-align: right; color: #ffffff; max-width: <%= scaledMaxRightColWidth %>;"><%- yValue %></td>\ </tr>\ </table>\ ' }); return ScatterSeries; }); define('js_charting/series/MultiScatterSeries',[ 'jquery', 'underscore', './MultiSeries', './ScatterSeries', '../util/lang_utils' ], function( $, _, MultiSeries, ScatterSeries, langUtils ) { var MultiScatterSeries = function(properties) { MultiSeries.call(this, properties); this.nestedSeriesList = []; }; langUtils.inherit(MultiScatterSeries, MultiSeries); $.extend(MultiScatterSeries.prototype, { setData: function(inputData) { var filterDataByNameMatch = function(dataSeries, name) { return _(dataSeries).filter(function(point, i) { return inputData.labels[i] === name; }); }; this.nestedSeriesList = _(inputData.labels).chain() .uniq() .filter(function(name) { return !!name; }) .map(function(name) { var seriesProps = { name: name, type: 'scatter', clickEnabled: this.properties['clickEnabled'] }; return new ScatterSeries(seriesProps); }, this) .value(); _(this.nestedSeriesList).each(function(series) { series.setData({ x: filterDataByNameMatch(inputData.x, series.getName()), y: filterDataByNameMatch(inputData.y, series.getName()) }); }, this); this.bindNestedSeries(); } }); return MultiScatterSeries; }); define('js_charting/series/RangeSeries',[ 'jquery', 'underscore', './AreaSeries', './LineSeries', './MultiSeries', '../util/lang_utils' ], function( $, _, AreaSeries, LineSeries, MultiSeries, langUtils ) { var LowerRangeSeries = function(properties) { this.threshold = 0; AreaSeries.call(this, $.extend({}, properties, { lineStyle: 'dashed', stacking: 'stacked' })); }; langUtils.inherit(LowerRangeSeries, AreaSeries); $.extend(LowerRangeSeries.prototype, { HIGHLIGHTED_OPACITY: 0, UNHIGHLIGHTED_OPACITY: 0, UNHIGHLIGHTED_LINE_OPACITY: 0.25, setData: function(inputData) { AreaSeries.prototype.setData.call(this, inputData); var minValue = _(inputData.y).min(); this.threshold = Math.min(minValue, 0); }, getConfig: function() { var config = AreaSeries.prototype.getConfig.call(this); config.showInLegend = false; config.threshold = this.threshold; return config; } }); var UpperRangeSeries = function(properties) { AreaSeries.call(this, $.extend({}, properties, { lineStyle: 'dashed', stacking: 'stacked' })); }; langUtils.inherit(UpperRangeSeries, AreaSeries); $.extend(UpperRangeSeries.prototype, { HIGHLIGHTED_OPACITY: 0.25, UNHIGHLIGHTED_OPACITY: 0.1, UNHIGHLIGHTED_LINE_OPACITY: 0.25, getConfig: function() { var config = AreaSeries.prototype.getConfig.call(this); config.showInLegend = false; return config; } }); var RangeSeries = function(properties) { MultiSeries.call(this, properties); this.rangeStackId = _.uniqueId('rangeStack_'); this.predictedSeries = new LineSeries(properties); this.lowerSeries = new LowerRangeSeries($.extend({}, properties, { name: properties.names.lower, legendKey: this.predictedSeries.getLegendKey(), stack: this.rangeStackId })); this.upperSeries = new UpperRangeSeries($.extend({}, properties, { name: properties.names.upper, legendKey: this.predictedSeries.getLegendKey(), stack: this.rangeStackId })); this.nestedSeriesList = [this.predictedSeries, this.upperSeries, this.lowerSeries]; this.bindNestedSeries(); }; langUtils.inherit(RangeSeries, MultiSeries); $.extend(RangeSeries.prototype, { type: 'range', getFieldList: function() { return this.predictedSeries.getFieldList(); }, // to get the right color effects, we have to force the upper and lower series // to take on the same color as the predicted series applyColorMapping: function(colorMapping) { this.predictedSeries.applyColorMapping(colorMapping); var predictedColor = this.predictedSeries.getColor(), lowerSeriesColorMapping = {}, upperSeriesColorMapping = {}; lowerSeriesColorMapping[this.lowerSeries.getName()] = predictedColor; this.lowerSeries.applyColorMapping(lowerSeriesColorMapping); upperSeriesColorMapping[this.upperSeries.getName()] = predictedColor; this.upperSeries.applyColorMapping(upperSeriesColorMapping); }, setData: function(inputData) { this.predictedSeries.setData({ y: inputData.predicted, x: inputData.x }); this.lowerSeries.setData({ y: inputData.lower, x: inputData.x }); // TODO: will this work for log scale? inputData.upper = _(inputData.upper).map(function(point, i) { if(_(point).isNull()) { return null; } var diff = point - inputData.lower[i]; return Math.max(diff, 0); }); this.upperSeries.setData({ y: inputData.upper, x: inputData.x }); }, handlePointMouseOver: function(point) { this.bringToFront(); this.highlight(); }, handlePointMouseOut: function(point) { }, handleLegendMouseOver: function(fieldName) { this.bringToFront(); this.highlight(); }, handleLegendMouseOut: function(fieldName) { } }); return RangeSeries; }); define('js_charting/series/series_factory',[ './ColumnSeries', './BarSeries', './LineSeries', './AreaSeries', './PieSeries', './MultiScatterSeries', './ScatterSeries', './RangeSeries' ], function( ColumnSeries, BarSeries, LineSeries, AreaSeries, PieSeries, MultiScatterSeries, ScatterSeries, RangeSeries ) { return ({ create: function(properties) { if(properties.type === 'column') { return new ColumnSeries(properties); } if(properties.type === 'bar') { return new BarSeries(properties); } if(properties.type === 'line') { return new LineSeries(properties); } if(properties.type === 'area') { return new AreaSeries(properties); } if(properties.type === 'pie') { return new PieSeries(properties); } if(properties.type === 'scatter') { if(properties.multiScatter === true) { return new MultiScatterSeries(properties); } return new ScatterSeries(properties); } if(properties.type === 'range') { return new RangeSeries(properties); } return new ColumnSeries(properties); } }); }); define('js_charting/util/testing_utils',[ 'jquery', 'underscore', 'splunk', './dom_utils' ], function( $, _, Splunk, domUtils ) { var initializeTestingMetaData = function(chartWrapper, xFields, type){ // make sure the wrapper container has an id, this will be used in createGlobalReference if(!chartWrapper.$container.attr('id')) { chartWrapper.$container.attr('id', chartWrapper.id); } var chart = chartWrapper.hcChart; $(chart.container).addClass(type); addDataClasses(chart); addAxisClasses(chart); if(chart.options.legend.enabled) { addLegendClasses(chart); } if(chart.tooltip && chart.tooltip.refresh) { var tooltipRefresh = chart.tooltip.refresh, decorateTooltip = (_.find(xFields, function(field){ return (field === '_time'); }) === '_time') ? addTimeTooltipClasses : addTooltipClasses; chart.tooltip.refresh = function(point) { tooltipRefresh.call(chart.tooltip, point); decorateTooltip(chart); }; } }; var addDataClasses = function(chart) { var that = this, seriesName, dataElements; $('.highcharts-series', $(chart.container)).each(function(i, series) { seriesName = chart.series[i].name; $(series).attr('id', seriesName + '-series'); if(domUtils.hasSVG) { dataElements = $('rect, path', $(series)); } else { dataElements = $('shape', $(series)); } dataElements.each(function(j, elem) { addClassToElement(elem, 'spl-display-object'); }); }); }; var addAxisClasses = function(chart) { var that = this, i, labelElements; $('.highcharts-axis, .highcharts-axis-labels', $(chart.container)).each(function(i, elem) { if(domUtils.hasSVG) { var loopBBox = elem.getBBox(); if(loopBBox.width > loopBBox.height) { addClassToElement(elem, 'horizontal-axis'); } else { addClassToElement(elem, 'vertical-axis'); } labelElements = $('text', $(elem)); } else { var firstSpan, secondSpan, $spans = $('span', $(elem)); if($spans.length < 2) { return; } firstSpan = $spans[0]; secondSpan = $spans[1]; if(firstSpan.style.top == secondSpan.style.top) { addClassToElement(elem, 'horizontal-axis'); } else { addClassToElement(elem, 'vertical-axis'); } labelElements = $('span', $(elem)); } labelElements.each(function(j, label) { addClassToElement(label, 'spl-text-label'); }); }); for(i = 0; i < chart.xAxis.length; i++) { if(chart.xAxis[i].axisTitle) { addClassToElement(chart.xAxis[i].axisTitle.element, 'x-axis-title'); } } for(i = 0; i < chart.yAxis.length; i++) { if(chart.yAxis[i].axisTitle) { addClassToElement(chart.yAxis[i].axisTitle.element, 'y-axis-title'); } } }; var addTooltipClasses = function(chart) { var i, loopSplit, loopKeyName, loopKeyElem, loopValElem, toolTipCells, $tooltip = $('.highcharts-tooltip'), tooltipElements = $('tr', $tooltip); for(i = 0; i < tooltipElements.length; i++) { toolTipCells = $('td', tooltipElements[i]); loopSplit = tooltipElements[i].textContent.split(':'); $(toolTipCells[0]).addClass('key'); $(toolTipCells[0]).addClass(sanitizeClassName(loopSplit[0] + '-key')); $(toolTipCells[1]).addClass('value'); $(toolTipCells[1]).addClass(sanitizeClassName(loopSplit[0] + '-value')); } }; var addTimeTooltipClasses = function(chart) { var that = this, i, loopSplit, loopKeyName, loopKeyElem, loopValElem, toolTipCells, $tooltip = $('.highcharts-tooltip'), tooltipElements = $('tr', $tooltip); for(i = 0; i < tooltipElements.length; i++) { toolTipCells = $('td', tooltipElements[i]); if(i===0){ $(toolTipCells[0]).addClass('time-value'); $(toolTipCells[0]).addClass('time'); } else { loopSplit = tooltipElements[i].textContent.split(':'); $(toolTipCells[0]).addClass('key'); $(toolTipCells[0]).addClass(sanitizeClassName(loopSplit[0] + '-key')); $(toolTipCells[1]).addClass('value'); $(toolTipCells[1]).addClass(sanitizeClassName(loopSplit[0] + '-value')); } } }; var addLegendClasses = function(chart) { var that = this, loopSeriesName; $(chart.series).each(function(i, series) { if(!series.legendItem) { return; } loopSeriesName = (domUtils.hasSVG) ? series.legendItem.textStr : $(series.legendItem.element).html(); if(series.legendSymbol) { addClassToElement(series.legendSymbol.element, 'symbol'); addClassToElement(series.legendSymbol.element, loopSeriesName + '-symbol'); } if(series.legendLine) { addClassToElement(series.legendLine.element, 'symbol'); addClassToElement(series.legendLine.element, loopSeriesName + '-symbol'); } if(series.legendItem) { addClassToElement(series.legendItem.element, 'legend-label'); } }); }; var addClassToElement = function(elem, className) { className = sanitizeClassName(className); if(className === '') { return; } if(domUtils.hasSVG) { if(elem.className.baseVal) { elem.className.baseVal += " " + className; } else { elem.className.baseVal = className; } } else { $(elem).addClass(className); } }; var sanitizeClassName = function(className) { // the className can potentially come from the search results, so make sure it is valid before // attempting to insert it... // first remove any leading white space className = className.replace(/\s/g, ''); // if the className doesn't start with a letter or a '-' followed by a letter, it should not be inserted if(!/^[-]?[A-Za-z]/.test(className)) { return ''; } // now filter out anything that is not a letter, number, '-', or '_' return className.replace(/[^A-Za-z0-9_-]/g, ""); }; ////////////////////////// // Gauge specific testing var gaugeAddTestingMetadata = function(gaugeWrapper, elements, typeName, value) { // make sure the wrapper container has an id, this will be used in createGlobalReference if(!gaugeWrapper.$container.attr('id')) { gaugeWrapper.$container.attr('id', gaugeWrapper.id); } var innerContainer = gaugeWrapper.$hcContainer; innerContainer.addClass(typeName); gaugeUpdate(innerContainer, value); if(elements.valueDisplay) { addClassToElement(elements.valueDisplay.element, 'gauge-value'); } var key; for(key in elements) { if(/^tickLabel_/.test(key)) { addClassToElement(elements[key].element, 'gauge-tick-label'); } } for(key in elements) { if(/^colorBand/.test(key)){ addClassToElement(elements[key].element, 'gauge-color-band'); } } $('.gauge-color-band').each(function() { $(this).attr('data-band-color', $(this).attr('fill')); }); // this is bad OOP but I think it's better to keep all of this code in one method if(elements.fill){ $(elements.fill.element).attr('data-indicator-color', $(elements.fill.element).attr('fill')); } if(elements.needle) { addClassToElement(elements.needle.element, 'gauge-indicator'); } if(elements.markerLine) { addClassToElement(elements.markerLine.element, 'gauge-indicator'); } }; var gaugeUpdate = function(container, value){ container.attr('data-gauge-value', value); }; var createGlobalReference = function(wrapperObject, chartObject) { Splunk.JSCharting = Splunk.JSCharting || {}; Splunk.JSCharting.chartByIdMap = Splunk.JSCharting.chartByIdMap || {}; var id = wrapperObject.$container.attr('id'); Splunk.JSCharting.chartByIdMap[id] = chartObject; }; return ({ initializeTestingMetaData: initializeTestingMetaData, gaugeAddTestingMetadata: gaugeAddTestingMetadata, createGlobalReference: createGlobalReference }); }); define('js_charting/visualizations/charts/Chart',[ 'jquery', 'underscore', 'highcharts', '../Visualization', '../../components/ColorPalette', '../../components/axes/TimeAxis', '../../components/axes/CategoryAxis', '../../components/axes/NumericAxis', '../../components/Legend', '../../components/PanningScrollbar', '../../components/Tooltip', '../../helpers/HoverEventThrottler', '../../series/series_factory', 'splunk.util', '../../util/lang_utils', '../../util/testing_utils', '../../util/parsing_utils', '../../util/color_utils', '../../util/time_utils', '../../util/dom_utils', '../../../helpers/user_agent', 'util/console' ], function( $, _, Highcharts, Visualization, ColorPalette, TimeAxis, CategoryAxis, NumericAxis, Legend, PanningScrollbar, Tooltip, HoverEventThrottler, seriesFactory, splunkUtils, langUtils, testingUtils, parsingUtils, colorUtils, timeUtils, domUtils, userAgent, console ) { var Chart = function(container, properties) { Visualization.call(this, container, properties); }; langUtils.inherit(Chart, Visualization); $.extend(Chart.prototype, { HOVER_DELAY: 160, EXPORT_WIDTH: 600, EXPORT_HEIGHT: 400, POINT_CSS_SELECTOR: domUtils.hasSVG ? '.highcharts-series > rect' : '.highcharts-series > shape', hasLegend: true, hasTooltip: true, hasXAxis: true, hasYAxis: true, requiresExternalColors: true, externalPaletteMapping: {}, externalPaletteSize: 0, prepare: function(dataSet, properties) { // FIXME: should be smart enough here to update the chart in place when possible Visualization.prototype.prepare.call(this, dataSet, properties); this.benchmark('Prepare Started'); this.initializeFields(); var isEmpty = this.isEmpty(); if(!isEmpty) { this.initializeColorPalette(); } this.initializeSeriesList(); this.axesAreInverted = _(this.seriesList).any(function(series) { return (series.getType() === 'bar'); }); if(this.hasXAxis) { this.initializeXAxisList(); } if(this.hasYAxis) { this.initializeYAxisList(); } if(!isEmpty) { if(this.hasLegend) { this.initializeLegend(); } if(this.hasTooltip) { this.initializeTooltip(); } this.setAllSeriesData(); this.bindSeriesEvents(); if(this.needsPanning){ this.initializePanning(); this.bindPanningEvents(); } } }, getFieldList: function() { return _(this.seriesList).chain().invoke('getFieldList').flatten(true).value(); }, setExternalColorPalette: function(fieldIndexMap, paletteTotalSize) { this.externalPaletteMapping = $.extend({}, fieldIndexMap); this.externalPaletteSize = paletteTotalSize; }, // TODO [sff] the callback shouldn't be called with the Highcharts object draw: function(callback) { console.debug('drawing a chart with dimensions:', { width: this.width, height: this.height }); console.debug('drawing a chart with properties:', this.properties); console.debug('drawing a chart with data:', this.dataSet.toJSON()); this.benchmark('Draw Started'); this.applyColorPalette(); this.hcConfig = $.extend(true, {}, this.BASE_CONFIG, { chart: this.getChartConfig(), series: this.getSeriesConfigList(), xAxis: this.getXAxisConfig(), yAxis: this.getYAxisConfig(), legend: this.getLegendConfig(), tooltip: this.getTooltipConfig(), plotOptions: this.getPlotOptionsConfig() }); var that = this; if(this.exportMode) { if(this.seriesIsTimeBased(this.xFields)) { _(this.hcConfig.xAxis).each(function(xAxis) { var xAxisMargin; if(that.axesAreInverted) { xAxisMargin = -50; } else { var spanSeries = that.dataSet.getSeriesAsFloats('_span'), span = (spanSeries && spanSeries.length > 0) ? parseInt(spanSeries[0], 10) : 1, secsPerDay = 60 * 60 * 24, secsPerYear = secsPerDay * 365; if(span >= secsPerYear) { xAxisMargin = 15; } else if(span >= secsPerDay) { xAxisMargin = 25; } else { xAxisMargin = 35; } } xAxis.title.margin = xAxisMargin; }); } $.extend(true, this.hcConfig, { plotOptions: { series: { enableMouseTracking: false, shadow: false } } }); } this.addEventHandlers(); console.debug('config object to be sent to highcharts:', this.hcConfig); if(this.hcChart) { this.hcChart.destroy(); } new Highcharts.Chart(this.hcConfig, function(chart) { that.hcChart = chart; if(that.testMode) { testingUtils.initializeTestingMetaData(that, that.xFields, that.getClassName()); testingUtils.createGlobalReference(that, chart); } // this event is actually coming from the push state listener in js_charting/js_charting.js // we are just using the Highcharts object as a shared event bus $(Highcharts).on('baseUriChange.' + that.id, function() { that.$container.find('[clip-path]').each(function() { // just need to unset and reset the clip-path to force a refresh with the new base URI var $this = $(this), clipPath = $this.attr('clip-path'); $this.removeAttr('clip-path'); $this.attr('clip-path', clipPath); }); }); if(callback) { that.benchmark('Draw Finished'); callback(that, that.benchmarks); } // DEBUGGING // window.chart = that }); }, setSize: function(width, height) { if(!this.hcChart) { return; } this.hcChart.setSize(width, height, false); }, destroy: function() { if(this.hcChart) { this.onChartDestroy(); this.hcChart.destroy(); this.hcChart = null; } }, getSVG: function() { var chart = this.hcChart; if(this.hcConfig.legend.enabled) { if(this.exportMode && chart.type !== 'scatter') { $(chart.series).each(function(i, loopSeries) { if(!loopSeries.legendSymbol) { return false; } loopSeries.legendSymbol.attr({ height: 8, translateY: 4 }); }); } if(chart.legend.nav) { chart.legend.nav.destroy(); } } var $svg = $('.highcharts-container').find('svg'); $svg.siblings().remove(); $svg.find('.highcharts-tracker').remove(); // SPL-65745, remove the clip path that is being applied to the legend, or it will cause labels to be hidden $svg.find('.highcharts-legend g[clip-path]').each(function() { $(this).removeAttr('clip-path'); }); return $svg.parent().html(); }, ///////////////////////////////////////////////////////////////////////////////////////// // [end of public interface] processProperties: function() { Visualization.prototype.processProperties.call(this); // handle enabling chart/legend clicks, there are an annoying number of different ways to specify this // the "drilldown" property trumps all others if(this.properties.hasOwnProperty('drilldown')) { this.chartClickEnabled = this.legendClickEnabled = this.properties['drilldown'] === 'all'; } else { if(this.properties.hasOwnProperty('chart.clickEnabled')) { this.chartClickEnabled = parsingUtils.normalizeBoolean(this.properties['chart.clickEnabled']); } else { this.chartClickEnabled = parsingUtils.normalizeBoolean(this.properties['enableChartClick']); } if(this.properties.hasOwnProperty('chart.legend.clickEnabled')) { this.legendClickEnabled = parsingUtils.normalizeBoolean(this.properties['chart.legend.clickEnabled']); } else { this.legendClickEnabled = parsingUtils.normalizeBoolean(this.properties['enableLegendClick']); } } if(this.properties['legend.placement'] === 'none') { this.hasLegend = false; } //panning disabled until further notice if(false && this.properties['resultTruncationLimit'] > 0){ this.truncationLimit = this.properties['resultTruncationLimit']; this.sliceDataForPanning = true; } else if(true || this.properties['resultTruncationLimit'] < 0) { this.sliceDataForPanning = false; } else { var actualPointsPerSeries = (this.dataSet.seriesList.length > 0) ? this.dataSet.seriesList[0].length : 0, maxColumnPoints = ($.browser.msie && {"6.0": true, "7.0": true, "8.0": true}.hasOwnProperty($.browser.version)) ? 1000 : 1200, maxLinePoints = 2000, maxPoints = ({line: true, area: true}.hasOwnProperty(this.properties.chart) ? maxLinePoints : maxColumnPoints), numSeries = this.dataSet.fields.length, pointsAllowedPerSeries = Math.floor(maxPoints / numSeries); if(actualPointsPerSeries > pointsAllowedPerSeries){ this.truncationLimit = pointsAllowedPerSeries; this.sliceDataForPanning = true; } else { this.sliceDataForPanning = false; } } if(this.hasXAxis || this.hasYAxis) { this.axisColorScheme = { 'axis.foregroundColorSoft': this.foregroundColorSoft, 'axis.foregroundColorSofter': this.foregroundColorSofter, 'axis.fontColor': this.fontColor }; } if(this.properties.hasOwnProperty('legend.masterLegend') && (!this.properties['legend.masterLegend'] || $.trim(this.properties['legend.masterLegend']) === 'null')) { this.requiresExternalColors = false; } this.stackMode = this.properties['chart.stackMode'] || 'default'; this.legendLabels = parsingUtils.stringToArray(this.properties['legend.labels'] || '[]'); this.showHideMode = this.properties['data.fieldListMode'] === 'show_hide'; this.fieldHideList = _.union( this.properties['fieldHideList'] || [], parsingUtils.stringToArray(this.properties['data.fieldHideList']) || [] ); this.fieldShowList = parsingUtils.stringToArray(this.properties['data.fieldShowList']) || []; var seriesColorsSetting = this.properties['chart.seriesColors'] || this.properties['seriesColors']; this.seriesColors = parsingUtils.stringToHexArray(seriesColorsSetting) || null; var fieldColorsSetting = this.properties['chart.fieldColors'] || this.properties['fieldColors']; this.internalFieldColors = parsingUtils.stringToObject(fieldColorsSetting || '{}'); // after the initial parse the field color will be a string representation of a hex number, // so loop through and make them true hex numbers (or zero if they can't be parsed) _(this.internalFieldColors).each(function(value, key) { var hexColor = parseInt(value, 16); this.internalFieldColors[key] = _(hexColor).isNaN() ? 0 : hexColor; }, this); // DEBUGGING: read in yAxisMapping property and yScaleMapping property for multiple y-axes this.yAxisMapping = parsingUtils.stringToObject(this.properties['yAxisMapping'] || "{}"); this.yScaleMapping = parsingUtils.stringToArray(this.properties['yScaleMapping'] || "[]"); // DEBUGGING: read in xAxisFields and xAxisMapping for multiple x-axes this.xAxisFields = parsingUtils.stringToArray(this.properties['xAxisFields'] || "[]"); this.xAxisMapping = parsingUtils.stringToObject(this.properties['xAxisMapping'] || "{}"); // DEBUGGING: read in map of field name to series types this.seriesTypeMapping = parsingUtils.stringToObject(this.properties['seriesTypeMapping'] || "{}"); }, ////////////////////////////////////////////////////////////////////////////////////////////// // methods for initializing chart components initializeFields: function() { // TODO: this is where user settings could determine the x-axis field(s) var allDataFields = this.dataSet.allDataFields(), defaultXField = allDataFields[0]; this.xFields = (this.xAxisFields && this.xAxisFields.length > 0) ? this.xAxisFields : [defaultXField]; if(this.isRangeSeriesMode()) { var rangeConfig = this.getRangeSeriesConfig(); allDataFields = _(allDataFields).without(rangeConfig.lower, rangeConfig.upper); } this.yFields = _(allDataFields).filter(function(field) { return (_(this.xFields).indexOf(field) === -1); }, this); var fieldWhiteList = $.extend([], this.fieldShowList), fieldBlackList = $.extend([], this.fieldHideList), intersection = _.intersection(fieldWhiteList, fieldBlackList); if(this.showHideMode) { fieldBlackList = _.difference(fieldBlackList, intersection); } else { fieldWhiteList = _.difference(fieldWhiteList, intersection); } this.yFields = _.difference(this.yFields, fieldBlackList); if(fieldWhiteList.length > 0) { this.yFields = _.intersection(this.yFields, fieldWhiteList); } // handle the user-specified legend labels if(this.legendLabels.length > 0) { this.yFields = _.union(this.legendLabels, this.yFields); } }, isEmpty: function() { return (this.yFields.length === 0); }, initializeColorPalette: function() { this.colorPalette = new ColorPalette(this.seriesColors); }, initializeSeriesList: function() { if(this.isEmpty()) { this.seriesList = [seriesFactory.create({ type: this.type })]; return; } var rangeFieldName, isRangeSeriesMode = this.isRangeSeriesMode(); if(isRangeSeriesMode) { rangeFieldName = this.getRangeSeriesConfig().predicted; } this.seriesList = _(this.yFields).map(function(field) { // TODO: this is where user settings could determine series type and/or axis mappings var customType; if(rangeFieldName && rangeFieldName === field) { customType = 'range'; } else if(this.seriesTypeMapping.hasOwnProperty(field)) { customType = this.seriesTypeMapping[field]; } var properties = $.extend(true, {}, this.properties, { type: customType || this.type, name: field, stacking: isRangeSeriesMode ? 'default' : this.stackMode, // TODO [sff] should we just deal with this in the chart click handler? clickEnabled: this.chartClickEnabled }); if(customType === 'range') { properties.names = this.getRangeSeriesConfig(); } // DEBUGGING: allow series to be assigned to y-axes via the 'yAxisMapping' property if(this.yAxisMapping[field]) { properties.yAxis = parseInt(this.yAxisMapping[field], 10); } // DEBUGGING: allow series to be assigned to x-axes via the 'xAxisMapping' property if(this.xAxisMapping[field]) { properties.xAxis = parseInt(this.xAxisMapping[field], 10); } return seriesFactory.create(properties); }, this); }, initializeXAxisList: function() { var isEmpty = this.isEmpty(); // TODO: this is where user settings could specify multiple x-axes // TODO: this is where the x-axis type can be inferred from the series types attached to each axis this.xAxisList = _(this.xFields).map(function(field, i) { var tickmarksBetween = _(this.seriesList).any(function(series) { return (series.getXAxisIndex() === i && { column: true, bar: true }.hasOwnProperty(series.getType())); }); var axisProperties = $.extend(parsingUtils.getXAxisProperties(this.properties), this.axisColorScheme, { 'axis.orientation': this.axesAreInverted ? 'vertical' : 'horizontal', 'axisLabels.tickmarkPlacement': tickmarksBetween ? 'between' : 'on', 'isEmpty': isEmpty }); if(!axisProperties['axisTitle.text']) { axisProperties['axisTitle.text'] = field; } if(this.seriesIsTimeBased(field)) { axisProperties['axis.spanData'] = this.dataSet.getSeriesAsFloats('_span'); axisProperties['axis.categories'] = this.dataSet.getSeriesAsTimestamps(field); return new TimeAxis(axisProperties); } axisProperties['axis.categories'] = this.dataSet.getSeries(field); return new CategoryAxis(axisProperties); }, this); }, initializeYAxisList: function() { // TODO: this is where user settings could specify multiple y-axes var that = this, isEmpty = this.isEmpty(); this.yAxisList = []; // DEBUGGING: for now just make sure there are enough y-axes to satisfy the series var maxAxisIndex = _(this.seriesList).chain().invoke('getYAxisIndex').max().value(); _(maxAxisIndex + 1).times(function(i) { var axisProperties = $.extend(parsingUtils.getYAxisProperties(that.properties), that.axisColorScheme, { 'axis.orientation': that.axesAreInverted ? 'horizontal' : 'vertical', 'isEmpty': isEmpty }); // FIXME: we should do something more intelligent here // currently if there is only one series for an axis, use that series's name as the default title if(!axisProperties['axisTitle.text']) { var axisSeries = _(that.seriesList).filter(function(series) { return series.getYAxisIndex() === i; }); if(axisSeries.length === 1) { axisProperties['axisTitle.text'] = axisSeries[0].getName(); } } // log scale is not respected if the chart has stacking if(that.stackMode !== 'default') { axisProperties['axis.scale'] = 'linear'; } // DEBUGGING: use the yScaleMapping list to assign a different scale to each y-axis if(that.yScaleMapping && that.yScaleMapping.length > i) { axisProperties['axis.scale'] = that.yScaleMapping[i]; } that.yAxisList.push(new NumericAxis(axisProperties)); }); }, initializeLegend: function() { var legendProps = parsingUtils.getLegendProperties(this.properties); if(_(legendProps['clickEnabled']).isUndefined()) { legendProps['clickEnabled'] = this.legendClickEnabled; } $.extend(legendProps, { fontColor: this.fontColor }); this.legend = new Legend(legendProps); var that = this, properties = { highlightDelay: 125, unhighlightDelay: 50, onMouseOver: function(fieldName) { that.handleLegendMouseOver(fieldName); }, onMouseOut: function(fieldName) { that.handleLegendMouseOut(fieldName); } }, throttle = new HoverEventThrottler(properties); this.legend.on('mouseover', function(e, fieldName) { throttle.mouseOverHappened(fieldName); }); this.legend.on('mouseout', function(e, fieldName) { throttle.mouseOutHappened(fieldName); }); this.legend.on('click', function(e, fieldName) { that.handleLegendClick(e, fieldName); }); }, initializePanning: function(){ var panningProperties = { truncationLimit: this.truncationLimit, numSeries: this.dataSet.seriesList.length - 2, seriesSize: this.dataSet.seriesList[0].length, container: this.$container }; this.panning = new PanningScrollbar(panningProperties); }, initializeTooltip: function() { var tooltipProps = { borderColor: this.foregroundColorSoft }; this.tooltip = new Tooltip(tooltipProps); }, setAllSeriesData: function() { var that = this, numberOfSeries = this.seriesList.length, totalDataPoints = numberOfSeries * this.dataSet.seriesList[0].length; _(this.seriesList).each(function(series) { if(series.getType() === 'range') { this.setRangeSeriesData(series); } else if (that.sliceDataForPanning && (totalDataPoints > that.truncationLimit)) { this.needsPanning = true; this.setBasicSeriesData(series); } else { this.setBasicSeriesData(series); } }, this); }, setBasicSeriesData: function(series) { var xInfo = this.getSeriesXInfo(series), yInfo = this.getSeriesYInfo(series); if(xInfo.axis instanceof NumericAxis) { series.setData({ x: this.formatAxisData(xInfo.axis, xInfo.fieldName), y: this.formatAxisData(yInfo.axis, yInfo.fieldName) }); } else if(xInfo.axis instanceof TimeAxis) { // SPL-67612, handle the case where the last data point was a total value // the axis handlers will have removed it from the timestamps, so we just have to sync the array lengths var axisTimestamps = xInfo.axis.getCategories(), rawData = this.formatAxisData(yInfo.axis, yInfo.fieldName); series.setData({ y: rawData.slice(0, axisTimestamps.length) }); } else { series.setData({ y: this.formatAxisData(yInfo.axis, yInfo.fieldName) }); } if(this.needsPanning){ this.sliceSeriesForPanning(series, this.truncationLimit); } }, setRangeSeriesData: function(series) { var xInfo = this.getSeriesXInfo(series), yInfo = this.getSeriesYInfo(series), rangeConfig = this.getRangeSeriesConfig(), rangeData = { predicted: this.formatAxisData(yInfo.axis, rangeConfig.predicted), lower: this.formatAxisData(yInfo.axis, rangeConfig.lower), upper: this.formatAxisData(yInfo.axis, rangeConfig.upper) }; if(xInfo.axis instanceof NumericAxis) { rangeData.x = this.formatAxisData(xInfo.axis, xInfo.fieldName); } series.setData(rangeData); }, bindSeriesEvents: function() { var that = this, properties = { highlightDelay: 125, unhighlightDelay: 50, onMouseOver: function(point, series) { that.handlePointMouseOver(point, series); }, onMouseOut: function(point, series) { that.handlePointMouseOut(point, series); } }, throttle = new HoverEventThrottler(properties); _(this.seriesList).each(function(series) { series.on('mouseover', function(e, targetPoint, targetSeries) { throttle.mouseOverHappened(targetPoint, targetSeries); }); series.on('mouseout', function(e, targetPoint, targetSeries) { throttle.mouseOutHappened(targetPoint, targetSeries); }); series.on('click', function(e, targetPoint, targetSeries) { that.handlePointClick(e, targetPoint, targetSeries); }); }); }, bindPanningEvents: function() { var that = this; this.panning.on('scroll', function(e, windowToDisplay){ that.panningScroll = true; that.windowToDisplay = windowToDisplay; that.setAllSeriesData(); that.setPannedData(); that.setPannedLabels(); that.hcChart.redraw(); }); }, setPannedData: function(){ var that = this; _(this.hcChart.series).each(function(oldSeries, i){ oldSeries.setData(that.seriesList[i].data, false); }); }, setPannedLabels: function() { var i, originalLabels, originalSpans, timeCategoryInfo; originalLabels = this.dataSet.getSeries('_time'); originalSpans = this.dataSet.getSeriesAsFloats('_span'); originalLabels = originalLabels .slice(this.windowToDisplay, (this.windowToDisplay) + this.pointsToPlotPerSeries); originalSpans = originalSpans .slice(this.windowToDisplay, (this.windowToDisplay) + this.pointsToPlotPerSeries); timeCategoryInfo = timeUtils.convertTimeToCategories(originalLabels, originalSpans, 6); //FIXME: we need to handle the bizarre negative indexes when creating the lookup //for tooltip formatting (this carries over) this.categoryIndexLookup = timeCategoryInfo.categories; for(i = -1; i<timeCategoryInfo.categories.length; i++){ if(i!==timeCategoryInfo.categories.length-1){ timeCategoryInfo.categories[i] = timeCategoryInfo.categories[i+1]; } } _(this.hcChart.xAxis).each(function(xAxis) { xAxis.setCategories(timeCategoryInfo.categories, false); }); }, handlePointClick: function(event, point, series) { var rowContext = {}, pointIndex = point.index, pointInfo = this.getSeriesPointInfo(series, point.index), pointClickEvent = { type: 'pointClick', modifierKey: event.modifierKey, name: pointInfo.xAxisName, // 'value' will be inserted later based on the x-axis type name2: pointInfo.yAxisName, value2: pointInfo.yValue }; if(pointInfo.xAxisIsTime) { var isoTimeString = this.dataSet.getSeries(pointInfo.xAxisName)[pointIndex]; pointClickEvent.value = splunkUtils.getEpochTimeFromISO(isoTimeString); pointClickEvent._span = this.dataSet.getSeriesAsFloats('_span')[pointIndex]; rowContext['row.' + pointInfo.xAxisName] = pointClickEvent.value; } else { pointClickEvent.value = pointInfo.xValue; rowContext['row.' + pointInfo.xAxisName] = pointInfo.xValue; } _(this.yFields).each(function(fieldName) { rowContext['row.' + fieldName] = this.dataSet.getSeries(fieldName)[pointIndex]; }, this); pointClickEvent.rowContext = rowContext; this.trigger(pointClickEvent); }, handlePointMouseOver: function(targetPoint, targetSeries) { _(this.seriesList).each(function(series) { if(series.matchesName(targetSeries.getName())) { series.handlePointMouseOver(targetPoint); } else { series.unHighlight(); } }); if(this.legend) { this.legend.selectField(targetSeries.getLegendKey()); } }, handlePointMouseOut: function(targetPoint, targetSeries) { _(this.seriesList).each(function(series) { if(series.matchesName(targetSeries.getName())) { series.handlePointMouseOut(targetPoint); } else { series.highlight(); } }); if(this.legend) { this.legend.unSelectField(targetSeries.getLegendKey()); } }, handleLegendClick: function(event, fieldName) { var legendClickEvent = { type: 'legendClick', modifierKey: event.modifierKey, name2: fieldName }; this.trigger(legendClickEvent); }, handleLegendMouseOver: function(fieldName) { _(this.seriesList).each(function(series) { if(series.matchesName(fieldName)) { series.handleLegendMouseOver(fieldName); } else { series.unHighlight(); } }); }, handleLegendMouseOut: function(fieldName) { _(this.seriesList).each(function(series) { if(series.matchesName(fieldName)) { series.handleLegendMouseOut(fieldName); } else { series.highlight(); } }); }, applyColorPalette: function() { if(this.isEmpty()) { return; } var colorMapping = {}; _(this.getFieldList()).each(function(field, i, fieldList) { colorMapping[field] = this.computeFieldColor(field, i, fieldList); }, this); _(this.seriesList).invoke('applyColorMapping', colorMapping); }, ////////////////////////////////////////////////////////////////////////////////// // methods for generating config objects from chart objects getSeriesConfigList: function() { return _(this.seriesList).chain().invoke('getConfig').flatten(true).value(); }, getXAxisConfig: function() { if(!this.hasXAxis) { return []; } return _(this.xAxisList).map(function(axis, i) { var config = axis.getConfig(); if(i > 0) { config.offset = 40; } return config; }, this); }, getYAxisConfig: function() { if(!this.hasYAxis) { return []; } return _(this.yAxisList).map(function(axis, i) { var config = axis.getConfig(); if(i % 2 !== 0) { config.opposite = true; } return config; }); }, getLegendConfig: function() { if(!this.hasLegend || !this.legend) { return {}; } return this.legend.getConfig(); }, getTooltipConfig: function() { if(!this.tooltip) { return {}; } var that = this; return $.extend(this.tooltip.getConfig(), { formatter: function() { // need to look up the instance of Splunk.JSCharting.BaseSeries, not the HighCharts series var series = this.series.splSeries; return that.formatTooltip(series, this.point); } }); }, formatTooltip: function(series, hcPoint) { var pointInfo; if(this.panningScroll){ pointInfo = this.getSeriesPointInfo(series, this.categoryIndexLookup.indexOf(hcPoint.category) + this.windowToDisplay); } else { pointInfo = this.getSeriesPointInfo(series, hcPoint.index); } return series.getTooltipHtml(pointInfo, this.hcChart); }, getChartConfig: function() { var config = { type: this.type, renderTo: this.container, backgroundColor: this.backgroundColor, borderColor: this.backgroundColor }; // in export mode we need to set explicit width and height // we'll honor the width and height of the parent node, unless they are zero if(this.exportMode) { config.width = this.width || this.EXPORT_WIDTH; config.height = this.height || this.EXPORT_HEIGHT; } return config; }, getPlotOptionsConfig: function() { return $.extend(true, {}, this.BASE_PLOT_OPTIONS_CONFIG, { series: { cursor: this.chartClickEnabled ? 'pointer' : 'default', enableMouseTracking: this.useMouseTracking() } }); }, //////////////////////////////////////////////////////////////////////////////////////// // methods for managing event handlers and effects addEventHandlers: function() { var that = this; this.hcConfig.chart.events = { load: function(e) { var chart = this; that.onChartLoad(chart, e); that.onChartLoadOrResize(chart, e); }, redraw: function(e) { var chart = this; that.onChartResize(chart, e); that.onChartLoadOrResize(chart, e); } }; }, onChartLoad: function(chart) { if(this.legend) { this.legend.onChartLoad(chart); } if(this.panning){ this.panning.onChartLoad(chart); } if(this.xAxisList) { _(this.xAxisList).each(function(axis) { axis.onChartLoad(chart); }); } if(this.yAxisList) { _(this.yAxisList).each(function(axis) { axis.onChartLoad(chart); }); } _(this.seriesList).each(function(series) { series.onChartLoad(chart); }); if(!this.useMouseTracking()) { this.addPointListeners(chart); } }, onChartResize: function() { }, onChartLoadOrResize: function(chart) { if(this.panning){ this.panning.onChartLoadOrResize(chart); } if(this.xAxisList) { _(this.xAxisList).each(function(axis) { axis.onChartLoadOrResize(chart); }); } if(this.yAxisList) { _(this.yAxisList).each(function(axis) { axis.onChartLoadOrResize(chart); }); } }, onChartDestroy: function() { $(Highcharts).off('baseUriChange.' + this.id); if(this.legend) { this.legend.destroy(); } if(this.xAxisList) { _(this.xAxisList).each(function(axis) { axis.destroy(); }); } if(this.yAxisList) { _(this.yAxisList).each(function(axis) { axis.destroy(); }); } _(this.seriesList).each(function(series) { series.destroy(); }); if(!this.useMouseTracking()) { // clean up any listeners created in addPointListeners $(this.hcChart.container).off('.splunk_jscharting'); } }, addPointListeners: function(chart) { var $chartContainer = $(chart.container), tooltipSelector = ".highcharts-tooltip *", hoveredPoint = null, // helper function to extract the corresponding point from a jQuery element extractPoint = function($el) { return (chart.series[$el.attr('data-series-index')].data[$el.attr('data-point-index')]); }; // with the VML renderer, have to explicitly destroy the tracker so it doesn't block mouse events if(!domUtils.hasSVG && chart.tracker) { chart.tracker.destroy(); } // create a closure around the tooltip hide method so that we can make sure we always hide the selected series when it is called // this is a work-around for the situation when the mouse moves out of the chart container element without triggering a mouse event if(chart.tooltip) { var tooltipHide = _(chart.tooltip.hide).bind(chart.tooltip); chart.tooltip.hide = function(silent) { tooltipHide(); if(!silent && hoveredPoint) { hoveredPoint.firePointEvent('mouseOut'); hoveredPoint = null; } }; } // decorate each point element with the info we need to map it to its corresponding data object var that = this; $(chart.series).each(function(i, series) { // SPL-71093, with the VML renderer explicitly hide the marker group so it doesn't block mouse events if(!domUtils.hasSVG && series.markerGroup && chart.options.chart.type !== 'scatter') { // it's ok to reference the element property because we know this will be VML mode $(series.markerGroup.element).hide(); } $(series.data).each(function(j, point) { if(point.graphic && point.graphic.element) { var $element = $(point.graphic.element); $element.attr('data-series-index', i); $element.attr('data-point-index', j); if(that.chartClickEnabled) { $element.css('cursor', 'pointer'); } } }); }); // we are not using mouse trackers, so attach event handlers to the chart's container element $chartContainer.on('click.splunk_jscharting', function(event) { var $target = $(event.target); if($target.is(that.POINT_CSS_SELECTOR)) { var point = extractPoint($target); point.firePointEvent('click', event); } }); // handle all mouseover events in the container here // if they are over the tooltip, ignore them (this avoids the dreaded tooltip flicker) // otherwise hide any point that is currently in a 'hover' state and 'hover' the target point as needed $chartContainer.on('mouseover.splunk_jscharting', function(event) { var $target = $(event.target); if($target.is(tooltipSelector)) { return; } var point = null; if($target.is(that.POINT_CSS_SELECTOR)) { point = extractPoint($target); } if(hoveredPoint && !(point && hoveredPoint === point)) { hoveredPoint.firePointEvent('mouseOut'); chart.tooltip.hide(true); hoveredPoint = null; } if(point) { point.firePointEvent('mouseOver'); chart.tooltip.refresh(point); hoveredPoint = point; } }); }, ///////////////////////////////////////////////////////////////////////////////////// // re-usable helpers getSeriesXInfo: function(series) { var xIndex = series.getXAxisIndex(); return ({ axis: this.xAxisList[xIndex], fieldName: this.xFields[xIndex] }); }, getSeriesYInfo: function(series) { return ({ axis: this.yAxisList[series.getYAxisIndex()], fieldName: series.getName() }); }, getSeriesPointInfo: function(series, pointIndex) { var xInfo = this.getSeriesXInfo(series), yInfo = this.getSeriesYInfo(series), xSeries = this.dataSet.getSeries(xInfo.fieldName), ySeries = this.dataSet.getSeries(yInfo.fieldName); return ({ xAxisIsTime: (xInfo.axis instanceof TimeAxis), xAxisName: xInfo.fieldName, xValue: xSeries[pointIndex], xValueDisplay: xInfo.axis.formatValue(xSeries[pointIndex]), yAxisName: yInfo.fieldName, yValue: ySeries[pointIndex], yValueDisplay: yInfo.axis.formatValue(ySeries[pointIndex]) }); }, isRangeSeriesMode: function() { return (this.dataSet.hasField('_predicted') && this.dataSet.hasField('_lower') && this.dataSet.hasField('_upper')); }, getRangeSeriesConfig: function() { var predictedName = _(this.dataSet.getSeries('_predicted')).find(function(value) { return !!value; }), lowerName = _(this.dataSet.getSeries('_lower')).find(function(value) { return !!value; }), upperName = _(this.dataSet.getSeries('_upper')).find(function(value) { return !!value; }); return ({ predicted: predictedName, lower: lowerName, upper: upperName }); }, useMouseTracking: function() { // iOS Safari does not support event delegation bubbling up the DOM for non-links like every other // browser does. This was causing drilldown click events getting lost on iPhone/iPad (SPL-66456). // So if the user is on one of those devices, just use Highcharts' mouse tracking. if(userAgent.isSafariiPhone() || userAgent.isSafariiPad()) { return true; } return _(this.seriesList).any(function(series) { return series.getType() in { line: true, area: true, range: true }; }); }, // by convention, we consider a series to be time-based if it is called _time, and there is also a _span series // with the exception that if there is only one data point _span does not need to be there seriesIsTimeBased: function(fieldName) { return (/^_time/).test(fieldName) && (this.dataSet.getSeries(fieldName).length <= 1 || this.dataSet.hasField('_span')); }, sliceSeriesForPanning: function(series, truncationLimit) { var numberOfSeries = this.seriesList.length; if(numberOfSeries > truncationLimit){ this.pointsToPlotPerSeries = 1; } else { this.pointsToPlotPerSeries = Math.ceil(truncationLimit / numberOfSeries); } if(this.windowToDisplay){ series.sliceData(series, this.windowToDisplay, (this.windowToDisplay) + this.pointsToPlotPerSeries); } else { series.sliceData(series, 0, this.pointsToPlotPerSeries); } }, formatAxisData: function(axis, fieldName) { if(!this.dataSet.hasField(fieldName)) { return []; } return this.dataSet.getSeriesAsFloats(fieldName, { scale: axis.isLogScale() ? 'log' : 'linear', nullValueMode: this.properties['chart.nullValueMode'] }); }, computeFieldColor: function(field, index, fieldList) { if(this.internalFieldColors.hasOwnProperty(field)) { return colorUtils.colorFromHex(this.internalFieldColors[field]); } var useExternalPalette = !_(this.externalPaletteMapping).isEmpty(), paletteIndex = useExternalPalette ? this.externalPaletteMapping[field] : index, paletteSize = useExternalPalette ? this.externalPaletteSize : fieldList.length; return this.colorPalette.getColorAsRgb(field, paletteIndex, paletteSize); }, ///////////////////////////////////////////////////////////////////////////////////// // templates and default settings BASE_CONFIG: { chart: { animation: false, showAxes: true, reflow: false }, credits: { enabled: false }, legend: { enabled: false }, plotOptions: { series: { animation: false, events: { legendItemClick: function() { return false; } }, borderWidth: 0, shadow: false, turboThreshold: 0 } }, title: { text: null }, tooltip: { enabled: false, useHTML: true } }, BASE_PLOT_OPTIONS_CONFIG: { line: { stickyTracking: true, marker: { states: { hover: { enabled: true, radius: 6 } }, symbol: 'square', radius: 6 } }, area: { stickyTracking: true, lineWidth: 1, trackByArea: true, marker: { states: { hover: { enabled: true, radius: 6 } }, symbol: 'square', radius: 6, enabled: false } }, column: { markers: { enabled: false }, stickyTracking: false }, bar: { markers: { enabled: false }, stickyTracking: false } } }); return Chart; }); define('js_charting/visualizations/charts/SplitSeriesChart',[ 'jquery', 'underscore', './Chart', '../../util/lang_utils' ], function( $, _, Chart, langUtils ) { var SplitSeriesChart = function(container, properties) { Chart.call(this, container, properties); }; langUtils.inherit(SplitSeriesChart, Chart); $.extend(SplitSeriesChart.prototype, { interAxisSpacing: 10, initializeSeriesList: function() { Chart.prototype.initializeSeriesList.call(this); // give each series its own y-axis _(this.seriesList).each(function(series, i) { series.setYAxisIndex(i); }, this); }, setAllSeriesData: function() { Chart.prototype.setAllSeriesData.call(this); // memoize the global min and max across all data this.globalMin = Infinity; this.globalMax = -Infinity; _(this.yFields).each(function(field, i) { var axis = this.yAxisList[i], data = this.formatAxisData(axis, field); this.globalMin = Math.min(this.globalMin, Math.min.apply(Math, data)); this.globalMax = Math.max(this.globalMax, Math.max.apply(Math, data)); }, this); }, getYAxisConfig: function() { var config = Chart.prototype.getYAxisConfig.call(this); _(config).each(function(axisConfig, i) { $.extend(axisConfig, { opposite: false, offset: 0, setSizePreHook: _(function(axis) { $.extend(axis.options, this.getAdjustedAxisPosition(axis, i, this.yAxisList.length)); }).bind(this) }); var originalExtremesHook = axisConfig.getSeriesExtremesPostHook; axisConfig.getSeriesExtremesPostHook = _(function(axis) { axis.dataMax = Math.max(axis.dataMax, this.globalMax); axis.dataMin = Math.min(axis.dataMin, this.globalMin); // make sure to invoke the original hook if it's there if(originalExtremesHook) { originalExtremesHook(axis); } }).bind(this); }, this); return config; }, getSeriesConfigList: function() { var config = Chart.prototype.getSeriesConfigList.call(this); _(config).each(function(seriesConfig) { seriesConfig.stacking = 'normal'; seriesConfig.afterAnimatePostHook = _(this.updateSeriesClipRect).bind(this); seriesConfig.renderPostHook = _(this.updateSeriesClipRect).bind(this); seriesConfig.destroyPreHook = _(this.destroySplitSeriesClipRect).bind(this); seriesConfig.plotGroupPostHook = _(this.translateSeriesGroup).bind(this); }, this); return config; }, getAdjustedAxisPosition: function(axis, index, numAxes) { var chart = axis.chart; if(chart.inverted) { var plotWidth = chart.plotWidth, axisWidth = (plotWidth - (this.interAxisSpacing * (numAxes - 1))) / numAxes; return ({ left: chart.plotLeft + (axisWidth + this.interAxisSpacing) * index, width: axisWidth }); } var plotHeight = chart.plotHeight, axisHeight = (plotHeight - (this.interAxisSpacing * (numAxes - 1))) / numAxes; return ({ top: chart.plotTop + (axisHeight + this.interAxisSpacing) * index, height: axisHeight }); }, getTooltipConfig: function() { var config = Chart.prototype.getTooltipConfig.call(this); config.getAnchorPostHook = function(points, mouseEvent, anchor) { anchor[0] = points.series.yAxis.left + points.pointWidth; return anchor; }; return config; }, updateSeriesClipRect: function(series) { var chart = series.chart, yAxis = series.yAxis; this.destroySplitSeriesClipRect(series); if(chart.inverted) { // this looks wrong, but this is happening before the 90 degree rotation so x is y and y is x series.splitSeriesClipRect = chart.renderer.clipRect(0, -0, chart.plotHeight, yAxis.width); } else { series.splitSeriesClipRect = chart.renderer.clipRect(0, 0, chart.plotWidth, yAxis.height); } series.group.clip(series.splitSeriesClipRect); }, destroySplitSeriesClipRect: function(series) { if(series.hasOwnProperty('splitSeriesClipRect')) { series.splitSeriesClipRect.destroy(); } }, translateSeriesGroup: function(series, group) { if(series.chart.inverted) { group.translate(series.yAxis.left, 0); } } }); return SplitSeriesChart; }); define('js_charting/components/DataLabels',[ 'jquery', 'underscore', '../helpers/EventMixin', '../helpers/Formatter', '../helpers/HoverEventThrottler' ], function( $, _, EventMixin, Formatter, HoverEventThrottler ) { var DataLabels = function(properties) { this.properties = properties || {}; }; DataLabels.prototype = $.extend(EventMixin, { HIGHLIGHTED_OPACITY: 1.0, UNHIGHLIGHTED_OPACITY: 0.3, getConfig: function() { return ({ color: this.properties['fontColor'] || '#000000', connectorColor: this.properties['foregroundColorSoft'], softConnector: false, distance: 20, style: { cursor: this.properties['clickEnabled'] ? 'pointer' : 'default' }, x: 0.01, drawDataLabelsPreHook: _(this.drawDataLabelsPreHook).bind(this), drawDataLabelsPostHook: _(this.drawDataLabelsPostHook).bind(this) }); }, onChartLoad: function(chart) { this.hcSeries = chart.series[0]; this.addEventHandlers(); }, addEventHandlers: function() { var that = this, properties = { highlightDelay: 125, unhighlightDelay: 50, onMouseOver: function(point){ that.selectLabel(point); that.trigger('mouseover', [point]); }, onMouseOut: function(point){ that.unSelectLabel(point); that.trigger('mouseout', [point]); } }, throttle = new HoverEventThrottler(properties); _(this.hcSeries.data).each(function(point) { var label = point.dataLabel.element; $(label).bind('mouseover', function() { throttle.mouseOverHappened(point); }); $(label).bind('mouseout', function() { throttle.mouseOutHappened(point); }); $(label).bind('click', function() { that.trigger('click', [point]); }); }); }, destroy: function() { this.off(); this.hcSeries = null; }, selectLabel: function(point) { var matchingPoint = this.hcSeries.data[point.index]; matchingPoint.dataLabel.attr('fill-opacity', this.HIGHLIGHTED_OPACITY); _(this.hcSeries.data).chain().without(matchingPoint).each(function(hcPoint) { hcPoint.dataLabel.attr('fill-opacity', this.UNHIGHLIGHTED_OPACITY); }, this); }, unSelectLabel: function(point) { var matchingPoint = this.hcSeries.data[point.index]; _(this.hcSeries.data).chain().without(matchingPoint).each(function(hcPoint) { hcPoint.dataLabel.attr('fill-opacity', this.HIGHLIGHTED_OPACITY); }, this); }, /** * @author sfishel * * Before the data label draw routine, overwrite the series getX method so that labels will be aligned vertically. * Then make sure all labels will fit in the plot area. */ drawDataLabelsPreHook: function(pieSeries) { var chart = pieSeries.chart, distance = pieSeries.options.dataLabels.distance, center = pieSeries.center, radius = center[2] / 2; pieSeries.getX = function(y, left) { return (chart.plotLeft + center[0] + (left ? (-radius - distance) : (radius + distance / 2))); }; this.fitLabelsToPlotArea(pieSeries); }, fitLabelsToPlotArea: function(series) { var i, adjusted, options = series.options, labelDistance = options.dataLabels.distance, size = options.size, // assumes size in pixels TODO: handle percents chart = series.chart, renderer = chart.renderer, formatter = new Formatter(renderer), defaultFontSize = 11, minFontSize = 9, maxWidth = (chart.plotWidth - (size + 2 * labelDistance)) / 2, labels = []; for(i = 0; i < series.data.length; i++) { labels.push(series.options.data[i][0]); } adjusted = formatter.adjustLabels(labels, maxWidth, minFontSize, defaultFontSize, 'middle'); for(i = 0; i < series.data.length; i++) { series.data[i].name = adjusted.labels[i]; // check for a redraw, update the font size in place if(series.data[i].dataLabel && series.data[i].dataLabel.css) { series.data[i].dataLabel.css({'fontSize': adjusted.fontSize + 'px'}); } } $.extend(true, options.dataLabels, { style: { 'fontSize': adjusted.fontSize + 'px' }, y: Math.floor(adjusted.fontSize / 4) - 3 }); formatter.destroy(); }, /** * @author sfishel * * After the data labels have been drawn, update the connector paths in place. */ drawDataLabelsPostHook: function(pieSeries) { _(pieSeries.points).each(function(point) { if(point.connector) { var path = point.connector.attr('d').split(' '); point.connector.attr({ d: this.updateConnectorPath(path) }); } }, this); }, updateConnectorPath: function(path) { // the default path consists of three points that create a two-segment line // we are going to move the middle point so the outer segment is horizontal // first extract the actual points from the SVG-style path declaration var firstPoint = { x: parseFloat(path[1]), y: parseFloat(path[2]) }, secondPoint = { x: parseFloat(path[4]), y: parseFloat(path[5]) }, thirdPoint = { x: parseFloat(path[7]), y: parseFloat(path[8]) }; // find the slope of the second line segment, use it to calculate the new middle point var secondSegmentSlope = (thirdPoint.y - secondPoint.y) / (thirdPoint.x - secondPoint.x), newSecondPoint = { x: thirdPoint.x + (firstPoint.y - thirdPoint.y) / secondSegmentSlope, y: firstPoint.y }; // define the update path and swap it into the original array // if the resulting path would back-track on the x-axis (or is a horizontal line), // just draw a line directly from the first point to the last var wouldBacktrack = isNaN(newSecondPoint.x) || (firstPoint.x >= newSecondPoint.x && newSecondPoint.x <= thirdPoint.x) || (firstPoint.x <= newSecondPoint.x && newSecondPoint.x >= thirdPoint.x), newPath = (wouldBacktrack) ? [ "M", firstPoint.x, firstPoint.y, "L", thirdPoint.x, thirdPoint.y ] : [ "M", firstPoint.x, firstPoint.y, "L", newSecondPoint.x, newSecondPoint.y, "L", thirdPoint.x, thirdPoint.y ]; return newPath; } }); return DataLabels; }); define('js_charting/visualizations/charts/PieChart',[ 'jquery', 'underscore', 'highcharts', 'splunk.i18n', './Chart', 'splunk.util', '../../components/DataLabels', '../../helpers/HoverEventThrottler', '../../series/series_factory', '../../util/lang_utils', '../../util/parsing_utils', '../../util/dom_utils' ], function( $, _, Highcharts, i18n, Chart, splunkUtils, DataLabels, HoverEventThrottler, seriesFactory, langUtils, parsingUtils, domUtils ) { var PieChart = function(container, properties) { Chart.call(this, container, properties); }; langUtils.inherit(PieChart, Chart); $.extend(PieChart.prototype, { POINT_CSS_SELECTOR: domUtils.hasSVG ? '.highcharts-point > path' : '.highcharts-point > shape', hasLegend: false, hasXAxis: false, hasYAxis: false, prepare: function(dataSet, properties) { Chart.prototype.prepare.call(this, dataSet, properties); this.initializeDataLabels(); }, draw: function(callback) { this.destroyCustomRenderer(); if(this.isEmpty()) { this.benchmark('Draw Started'); this.drawEmptyPieChart(); if(callback) { this.benchmark('Draw Finished'); callback(this, this.benchmarks); } } else { Chart.prototype.draw.call(this, callback); } }, processProperties: function() { Chart.prototype.processProperties.call(this); this.showLabels = this.isEmpty() ? false : parsingUtils.normalizeBoolean(this.properties['chart.showLabels'], true); }, initializeFields: function() { var dataFields = this.dataSet.allDataFields(); this.sliceNameField = dataFields[0]; this.sliceSizeField = dataFields[1]; }, isEmpty: function() { return (this.dataSet.allDataFields().length < 2); }, initializeSeriesList: function() { var seriesProps = $.extend({}, this.properties, { name: this.sliceSizeField, type: 'pie', clickEnabled: this.chartClickEnabled }); this.seriesList = [new seriesFactory.create(seriesProps)]; }, setAllSeriesData: function() { var isTimeBased = this.seriesIsTimeBased(this.sliceNameField), spans; if(isTimeBased) { spans = this.dataSet.getSeriesAsFloats("_span"); } this.seriesList[0].setData({ names: this.dataSet.getSeries(this.sliceNameField), sizes: this.dataSet.getSeriesAsFloats(this.sliceSizeField, { nullValueMode: 'zero' }), spans: spans, isTimeBased: isTimeBased }); }, handlePointMouseOver: function(targetPoint) { this.seriesList[0].handlePointMouseOver(targetPoint); if(this.dataLabels) { this.dataLabels.selectLabel(targetPoint); } }, handlePointMouseOut: function(targetPoint){ this.seriesList[0].handlePointMouseOut(targetPoint); if(this.dataLabels) { this.dataLabels.unSelectLabel(targetPoint); } }, handlePointClick: function(event, point) { var pointIndex = point.index, pointData = this.seriesList[0].getData()[pointIndex], sliceName = pointData[0], sliceSize = pointData[1].toString(), collapseFieldName = new RegExp("^" + this.seriesList[0].collapseFieldName), rowContext = {}, pointClickEvent = { type: 'pointClick', modifierKey: event.modifierKey, name: this.sliceNameField, // 'value' will be inserted later based on series type name2: this.sliceSizeField, value2: sliceSize, rowContext: rowContext }; // Clicking on the collapsed slice for a _time based pie chart should just return a normal pointClickEvent, // not the special time-based one if(this.seriesIsTimeBased(this.sliceNameField) && !collapseFieldName.test(pointData[0])) { var isoTimeString = pointData[0]; pointClickEvent.value = splunkUtils.getEpochTimeFromISO(isoTimeString); pointClickEvent._span = pointData[2]; rowContext['row.' + this.sliceNameField] = pointClickEvent.value; } else { pointClickEvent.value = sliceName; rowContext['row.' + this.sliceNameField] = sliceName; } rowContext['row.' + this.sliceSizeField] = sliceSize; this.trigger(pointClickEvent); }, initializeDataLabels: function() { var labelProps = { fontColor: this.fontColor, foregroundColorSoft: this.foregroundColorSoft, clickEnabled: parsingUtils.normalizeBoolean(this.properties['chart.clickEnabled']) || parsingUtils.normalizeBoolean(this.properties['enableChartClick']) }; this.dataLabels = new DataLabels(labelProps); var that = this, properties = { highlightDelay: 75, unhighlightDelay: 50, onMouseOver: function(point){ that.seriesList[0].selectPoint(point); }, onMouseOut: function(point){ that.seriesList[0].unSelectPoint(point); } }, throttle = new HoverEventThrottler(properties); this.dataLabels.on('mouseover', function(e, point) { throttle.mouseOverHappened(point); }); this.dataLabels.on('mouseout', function(e, point) { throttle.mouseOutHappened(point); }); // TODO [sff] add a click handler here for data label drilldown }, getPlotOptionsConfig: function() { var that = this; return ({ pie: { dataLabels: $.extend(this.getDataLabelConfig(), { formatter: function() { var formatInfo = this; return parsingUtils.escapeSVG(that.formatDataLabel(formatInfo)); } }), borderWidth: 0, stickyTracking: false, cursor: this.chartClickEnabled ? 'pointer' : 'default', enableMouseTracking: this.useMouseTracking() } }); }, getDataLabelConfig: function() { if(!this.showLabels) { return { enabled: false }; } return this.dataLabels.getConfig(); }, applyColorPalette: function() { // FIXME: this is bad, find a way to encapsulate this in the PieSeries object this.BASE_CONFIG = $.extend({}, this.BASE_CONFIG, { colors: _(this.getFieldList()).map(this.computeFieldColor, this) }); }, formatDataLabel: function(info) { return info.point.name; }, formatTooltip: function(series, hcPoint) { var pointIndex = hcPoint.index, pointData = series.hasPrettyData ? series.getPrettyData()[pointIndex] : series.getData()[pointIndex], pointName = pointData[0], pointValue = pointData[1]; return series.getTooltipHtml({ sliceFieldName: this.sliceNameField, sliceName: pointName, sliceColor: hcPoint.color, yValue: i18n.format_decimal(pointValue), yPercent: i18n.format_percent(hcPoint.percentage / 100) }, this.hcChart); }, drawEmptyPieChart: function() { var width = this.$container.width(), height = this.$container.height(), // TODO [sff] this logic is duplicated in PieSeries translatePreHook() circleRadius = Math.min(height * 0.75, width / 3) / 2; this.renderer = new Highcharts.Renderer(this.container, width, height); this.renderer.circle(width / 2, height / 2, circleRadius).attr({ fill: 'rgba(150, 150, 150, 0.3)', stroke: 'rgb(200, 200, 200)', 'stroke-width': 1 }).add(); this.renderer.text(_('No Results').t(), width / 2, height / 2) .attr({ align: 'center' }) .css({ fontSize: '20px', color: 'rgb(200, 200, 200)' }).add(); }, setSize: function(width, height) { if(this.isEmpty()) { this.destroyCustomRenderer(); this.drawEmptyPieChart(); } else { Chart.prototype.setSize.call(this, width, height); } }, destroy: function() { this.destroyCustomRenderer(); Chart.prototype.destroy.call(this); }, destroyCustomRenderer: function() { if(this.renderer) { this.renderer.destroy(); this.renderer = null; this.$container.empty(); } }, onChartLoad: function(chart) { Chart.prototype.onChartLoad.call(this, chart); if(this.dataLabels) { this.dataLabels.onChartLoad(chart); } }, onChartDestroy: function() { Chart.prototype.onChartDestroy.call(this); if(this.dataLabels) { this.dataLabels.destroy(); } } }); return PieChart; }); define('js_charting/visualizations/charts/ScatterChart',[ 'jquery', 'underscore', './Chart', '../../series/series_factory', '../../components/axes/NumericAxis', '../../util/lang_utils', '../../util/parsing_utils', '../../util/dom_utils' ], function( $, _, Chart, seriesFactory, NumericAxis, langUtils, parsingUtils, domUtils ) { var ScatterChart = function(container, properties) { Chart.call(this, container, properties); }; langUtils.inherit(ScatterChart, Chart); $.extend(ScatterChart.prototype, { POINT_CSS_SELECTOR: domUtils.hasSVG ? '.highcharts-markers > path' : '.highcharts-markers > shape', initializeFields: function() { Chart.prototype.initializeFields.call(this); // to support the pivot interface, scatter charts ignore the first column if it is the result of a group-by var dataFields = this.dataSet.allDataFields(); if(this.dataSet.fieldIsGroupby(dataFields[0])) { this.markField = dataFields[0]; dataFields = dataFields.slice(1); } if(dataFields.length > 2) { this.isMultiSeries = true; this.labelField = dataFields[0]; this.xField = dataFields[1]; this.yField = dataFields[2]; this.hasLegend = (this.properties['legend.placement'] !== 'none'); } else { this.isMultiSeries = false; this.xField = dataFields[0]; this.yField = dataFields[1]; this.hasLegend = false; } }, isEmpty: function() { return (this.dataSet.length < 2); }, initializeSeriesList: function() { var series; if(this.isMultiSeries) { series = seriesFactory.create({ type: 'scatter', clickEnabled: this.chartClickEnabled, multiScatter: true }); this.seriesList = [series]; } else { series = seriesFactory.create({ name: _.uniqueId('scatter_field_'), type: 'scatter', clickEnabled: this.chartClickEnabled }); this.seriesList = [series]; } }, initializeXAxisList: function() { var axisProps = $.extend(parsingUtils.getXAxisProperties(this.properties), this.axisColorScheme, { 'axis.orientation': 'horizontal', 'isEmpty': this.isEmpty() }); if(!axisProps['axisTitle.text']) { axisProps['axisTitle.text'] = this.xField; } axisProps['gridLines.showMajorLines'] = false; this.xAxisList = [new NumericAxis(axisProps)]; }, initializeYAxisList: function() { var axisProps = $.extend(parsingUtils.getYAxisProperties(this.properties), this.axisColorScheme, { 'axis.orientation': 'vertical', 'isEmpty': this.isEmpty() }); if(!axisProps['axisTitle.text']) { axisProps['axisTitle.text'] = this.yField; } this.yAxisList = [new NumericAxis(axisProps)]; }, setAllSeriesData: function() { var xData = this.formatAxisData(this.xAxisList[0], this.xField), yData = this.formatAxisData(this.yAxisList[0], this.yField), seriesData = { x: xData, y: yData }; if(this.isMultiSeries) { seriesData.labels = this.dataSet.getSeries(this.labelField); } this.seriesList[0].setData(seriesData); }, getPlotOptionsConfig: function() { var markerSize = parseInt(this.properties['chart.markerSize'], 10); return ({ scatter: { stickyTracking: false, marker: { radius: markerSize ? Math.ceil(markerSize * 6 / 4) : 6, symbol: 'square' }, cursor: this.chartClickEnabled ? 'pointer' : 'default', enableMouseTracking: this.useMouseTracking() } }); }, useMouseTracking: function() { return false; }, handlePointClick: function(event, point, series) { var pointIndex = point.index, seriesName = series.getName(), xSeries = this.dataSet.getSeries(this.xField), ySeries = this.dataSet.getSeries(this.yField), xValue = this.isMultiSeries ? this.filterDataByNameMatch(xSeries, seriesName)[pointIndex] : xSeries[pointIndex], yValue = this.isMultiSeries ? this.filterDataByNameMatch(ySeries, seriesName)[pointIndex] : ySeries[pointIndex], rowContext = {}, pointClickEvent = { type: 'pointClick', modifierKey: event.modifierKey, name: this.isMultiSeries ? this.labelField : this.xField, value: this.isMultiSeries ? seriesName : xValue, name2: this.isMultiSeries ? this.xField : this.yField, value2: this.isMultiSeries ? xValue : yValue, rowContext: rowContext }; rowContext['row.' + this.xField] = xValue; rowContext['row.' + this.yField] = yValue; if(this.isMultiSeries) { rowContext['row.' + this.labelField] = seriesName; } if(this.markField) { var markSeries = this.dataSet.getSeries(this.markField), markValue = this.isMultiSeries ? this.filterDataByNameMatch(markSeries, seriesName)[pointIndex] : markSeries[pointIndex]; rowContext['row.' + this.markField] = markValue; } this.trigger(pointClickEvent); }, handleLegendClick: function(event, fieldName) { var rowContext = {}, legendClickEvent = { type: 'legendClick', modifierKey: event.modifierKey, name: this.labelField, value: fieldName, rowContext: rowContext }; rowContext['row.' + this.labelField] = fieldName; this.trigger(legendClickEvent); }, formatTooltip: function(series, hcPoint) { var pointIndex = hcPoint.index, xAxis = this.xAxisList[0], yAxis = this.yAxisList[0], seriesName = series.getName(), xSeries = this.dataSet.getSeries(this.xField), ySeries = this.dataSet.getSeries(this.yField), xValue = this.isMultiSeries ? this.filterDataByNameMatch(xSeries, seriesName)[pointIndex] : xSeries[pointIndex], yValue = this.isMultiSeries ? this.filterDataByNameMatch(ySeries, seriesName)[pointIndex] : ySeries[pointIndex], templateInfo = { isMultiSeries: this.isMultiSeries, xAxisName: this.xField, xValue: xAxis.formatValue(xValue), yAxisName: this.yField, yValue: yAxis.formatValue(yValue), markName: null, markValue: null }; if(this.markField) { var markSeries = this.dataSet.getSeries(this.markField), markValue = this.isMultiSeries ? this.filterMarkByNameMatch(seriesName)[pointIndex] : markSeries[pointIndex]; $.extend(templateInfo, { markName: this.markField, markValue: markValue }); } if(this.isMultiSeries) { $.extend(templateInfo, { labelSeriesName: this.labelField }); } return series.getTooltipHtml(templateInfo, this.hcChart); }, // FIXME: this logic is duplicated inside the scatter multi-series filterDataByNameMatch: function(dataSeries, name) { var labelData = this.dataSet.getSeries(this.labelField); return _(dataSeries).filter(function(point, i) { return labelData[i] === name; }); }, filterMarkByNameMatch: function(name) { var labelData = this.dataSet.getSeries(this.labelField), markData = this.dataSet.getSeries(this.markField); return _(markData).filter(function(point, i) { return labelData[i] === name; }); } }); return ScatterChart; }); define('js_charting/visualizations/gauges/Gauge',[ 'jquery', 'underscore', 'highcharts', '../Visualization', '../../helpers/Formatter', '../../components/ColorPalette', '../../util/lang_utils', '../../util/parsing_utils', '../../util/testing_utils', '../../util/math_utils', '../../util/dom_utils', '../../util/color_utils', 'splunk.i18n' ], function( $, _, Highcharts, Visualization, Formatter, ColorPalette, langUtils, parsingUtils, testingUtils, mathUtils, domUtils, colorUtils, i18n ) { var Gauge = function(container, properties) { Visualization.call(this, container, properties); // for consistency with other chart types, create a <div> inside this container where the gauge will draw this.$hcContainer = $('<div />').addClass('highcharts-container').appendTo(this.container); this.elements = {}; this.hasRendered = false; this.needsRedraw = true; }; langUtils.inherit(Gauge, Visualization); $.extend(Gauge.prototype, { WINDOW_RESIZE_DELAY: 100, EXPORT_HEIGHT: 400, EXPORT_WIDTH: 600, MIN_GAUGE_HEIGHT: 25, RESIZED_GAUGE_HEIGHT: 200, DEFAULT_COLORS: [0x84E900, 0xFFE800, 0xBF3030], DEFAULT_RANGES: [0, 30, 70, 100], MAX_TICKS_PER_RANGE: 10, showValueByDefault: true, showMinorTicksByDefault: true, // in export mode we need to set explicit width and height // we'll honor the width and height of the parent node, unless they are zero getWidth: function() { var width = Visualization.prototype.getWidth.call(this); if(this.exportMode) { return width || this.EXPORT_WIDTH; } return width; }, getHeight: function() { var height = Visualization.prototype.getHeight.call(this); if(this.exportMode) { return height || this.EXPORT_HEIGHT; } // Fix for SPL-61657 - make sure the height of the gauge div can't be below a certain threshold height = (height < this.MIN_GAUGE_HEIGHT) ? this.RESIZED_GAUGE_HEIGHT : height; return height; }, prepare: function(dataSet, properties) { var oldRanges = $.extend([], this.ranges); Visualization.prototype.prepare.call(this, dataSet, properties); if(!parsingUtils.arraysAreEquivalent(oldRanges, this.ranges)) { this.needsRedraw = true; } }, draw: function(callback) { if(this.needsRedraw) { this.destroy(); this.renderer = new Highcharts.Renderer(this.$hcContainer[0], this.getWidth(), this.getHeight()); this.formatter = new Formatter(this.renderer); this.$container.css('backgroundColor', this.backgroundColor); this.renderGauge(); this.nudgeChart(); this.hasRendered = true; if(this.testMode) { testingUtils.gaugeAddTestingMetadata(this, this.elements, this.getClassName(), this.value); testingUtils.createGlobalReference(this, this.getChartObject()); } this.needsRedraw = false; } else { this.updateValue(this.previousValue || 0, this.value); } if(callback) { callback(this); } }, setSize: function(width, height) { if(!this.hasRendered) { return; } this.destroy(); this.renderer = new Highcharts.Renderer(this.$hcContainer[0], width, height); this.formatter = new Formatter(this.renderer); this.renderGauge(); this.nudgeChart(); this.hasRendered = true; }, destroy: function() { var key; // stop any running animations this.stopWobble(); this.$container.stop(); for(key in this.elements) { if(this.elements.hasOwnProperty(key)) { this.elements[key].destroy(); } } this.elements = {}; this.$hcContainer.empty(); this.$container.css('backgroundColor', ''); this.hasRendered = false; }, getSVG: function() { return this.$container.find('svg').eq(0).parent().html(); }, processProperties: function() { Visualization.prototype.processProperties.call(this); this.colors = this.computeColors(); this.colorPalette = new ColorPalette(this.colors, true); this.ranges = this.computeRanges(); this.previousValue = this.value; this.value = this.computeValue(); this.majorUnit = parseInt(this.properties['chart.majorUnit'], 10) || null; this.showMajorTicks = parsingUtils.normalizeBoolean(this.properties['chart.showMajorTicks'], true); this.showMinorTicks = parsingUtils.normalizeBoolean(this.properties['chart.showMinorTicks'], this.showMinorTicksByDefault); this.showLabels = parsingUtils.normalizeBoolean(this.properties['chart.showLabels'], true); this.showValue = parsingUtils.normalizeBoolean(this.properties['chart.showValue'], this.showValueByDefault); this.showRangeBand = parsingUtils.normalizeBoolean(this.properties['chart.showRangeBand'], true); this.usePercentageRange = parsingUtils.normalizeBoolean(this.properties['chart.usePercentageRange']); this.usePercentageValue = parsingUtils.normalizeBoolean(this.properties['chart.usePercentageValue']); this.isShiny = this.properties['chart.style'] !== 'minimal'; }, computeColors: function() { var userColors = parsingUtils.stringToHexArray(this.properties['chart.gaugeColors'] || this.properties['gaugeColors']); return (userColors && userColors.length > 0) ? userColors : this.DEFAULT_COLORS; }, computeRanges: function() { var ranges, userRanges = parsingUtils.stringToArray(this.properties['chart.rangeValues']); if(userRanges && userRanges.length > 1) { ranges = userRanges; } else { var dataFields = this.dataSet.allDataFields(); ranges = _(dataFields.slice(1)).map(function(field) { return this.dataSet.getSeries(field)[0]; }, this); } var prevRange = -Infinity, floatRanges = []; _(ranges).each(function(range) { var floatRange = mathUtils.parseFloat(range); if(!_(floatRange).isNaN() && floatRange > prevRange) { floatRanges.push(floatRange); prevRange = floatRange; } }); return (floatRanges.length > 1) ? floatRanges : this.DEFAULT_RANGES; }, computeValue: function() { var dataFields = this.dataSet.allDataFields(); return (dataFields.length > 0) ? mathUtils.parseFloat(this.dataSet.getSeries(dataFields[0])[0]) || 0 : 0; }, updateValue: function(oldValue, newValue) { // if the value didn't change, do nothing if(oldValue === newValue) { return; } if(this.shouldAnimateTransition(oldValue, newValue)) { this.stopWobble(); this.animateTransition(oldValue, newValue, _(this.drawIndicator).bind(this), _(this.onAnimationFinished).bind(this)); } if(this.showValue) { var valueText = this.formatValue(newValue); this.updateValueDisplay(valueText); } if(this.testMode) { testingUtils.gaugeUpdate(this.$container, newValue); } }, shouldAnimateTransition: function(oldValue, newValue) { // if we were already out of range, no need to animate the indicator return (this.normalizedTranslateValue(oldValue) !== this.normalizedTranslateValue(newValue)); }, drawTicks: function() { var i, loopTranslation, loopText, tickValues = this.calculateTickValues(this.ranges[0], this.ranges[this.ranges.length - 1], this.MAX_TICKS_PER_RANGE); for(i = 0; i < tickValues.length; i++) { loopTranslation = this.translateValue(tickValues[i]); if(this.showMajorTicks) { this.elements['tickMark_' + tickValues[i]] = this.drawMajorTick(loopTranslation); } if(this.showLabels) { loopText = this.formatTickLabel(tickValues[i]); this.elements['tickLabel_' + tickValues[i]] = this.drawMajorTickLabel(loopTranslation, loopText); } } // if the labels are visible, check for collisions and remove ticks if needed before drawing the minors if(this.showLabels) { tickValues = this.removeTicksIfOverlap(tickValues); } if(this.showMinorTicks) { var majorInterval = tickValues[1] - tickValues[0], minorInterval = majorInterval / this.minorsPerMajor, startValue = (this.usePercentageRange) ? this.ranges[0] : tickValues[0] - Math.floor((tickValues[0] - this.ranges[0]) / minorInterval) * minorInterval; for(i = startValue; i <= this.ranges[this.ranges.length - 1]; i += minorInterval) { if(!this.showMajorTicks || $.inArray(i, tickValues) < 0) { loopTranslation = this.translateValue(i); this.elements['minorTickMark_' + i] = this.drawMinorTick(loopTranslation); } } } }, removeTicksIfOverlap: function(tickValues) { while(tickValues.length > 2 && this.tickLabelsOverlap(tickValues)) { tickValues = this.removeEveryOtherTick(tickValues); } return tickValues; }, tickLabelsOverlap: function(tickValues) { var i, labelOne, labelTwo, marginX = 3, marginY = 1; for(i = 0; i < tickValues.length - 1; i++) { labelOne = this.elements['tickLabel_' + tickValues[i]]; labelTwo = this.elements['tickLabel_' + tickValues[i + 1]]; if(this.formatter.bBoxesOverlap(labelOne.getBBox(), labelTwo.getBBox(), marginX, marginY)) { return true; } } return false; }, removeEveryOtherTick: function(tickValues) { var i, newTickValues = []; for(i = 0; i < tickValues.length; i++) { if(i % 2 === 0) { newTickValues.push(tickValues[i]); } else { this.elements['tickMark_' + tickValues[i]].destroy(); this.elements['tickLabel_' + tickValues[i]].destroy(); delete this.elements['tickMark_' + tickValues[i]]; delete this.elements['tickLabel_' + tickValues[i]]; } } return newTickValues; }, // we can't use the jQuery animation library explicitly to perform complex SVG animations, but // we can take advantage of their implementation using a meaningless css property and a custom step function animateTransition: function(startVal, endVal, drawFn, finishCallback) { var animationRange = endVal - startVal, duration = 500, animationProperties = { duration: duration, step: function(now) { drawFn(startVal + now); this.nudgeChart(); }.bind(this) }; if(finishCallback) { animationProperties.complete = function() { finishCallback(endVal); }; } // for the animation start and end values, use 0 and animationRange for consistency with the way jQuery handles // css properties that it doesn't recognize this.$container .stop(true, true) .css({'animation-progress': 0}) .animate({'animation-progress': animationRange}, animationProperties); }, onAnimationFinished: function(val) { this.checkOutOfRange(val); }, checkOutOfRange: function(val) { var totalRange, wobbleCenter, wobbleRange; if(val < this.ranges[0]) { totalRange = this.ranges[this.ranges.length - 1] - this.ranges[0]; wobbleRange = totalRange * 0.005; wobbleCenter = this.ranges[0] + wobbleRange; this.wobble(wobbleCenter, wobbleRange, this.drawIndicator); } else if(val > this.ranges[this.ranges.length - 1]) { totalRange = this.ranges[this.ranges.length - 1] - this.ranges[0]; wobbleRange = totalRange * 0.005; wobbleCenter = this.ranges[this.ranges.length - 1] - wobbleRange; this.wobble(wobbleCenter, wobbleRange, this.drawIndicator); } }, formatValue: function(val) { return (this.usePercentageValue) ? this.formatPercent(((val - this.ranges[0]) / (this.ranges[this.ranges.length - 1] - this.ranges[0]))) : this.formatNumber(val); }, formatTickLabel: function(val) { return (this.usePercentageRange) ? this.formatPercent(((val - this.ranges[0]) / (this.ranges[this.ranges.length - 1] - this.ranges[0]))) : this.formatNumber(val); }, formatNumber: function(val) { var parsedVal = parseFloat(val), absVal = Math.abs(parsedVal); // if the magnitude is 1 billion or greater or less than one thousandth (and non-zero), express it in scientific notation if(absVal >= 1e9 || (absVal !== 0 && absVal < 1e-3)) { return i18n.format_scientific(parsedVal, "#.###E0"); } return i18n.format_decimal(parsedVal); }, formatPercent: function(val) { return i18n.format_percent(val); }, wobble: function(center, range, drawFn) { var self = this, wobbleCounter = 0; this.wobbleInterval = setInterval(function() { var wobbleVal = center + (wobbleCounter % 3 - 1) * range; drawFn.call(self, wobbleVal); self.nudgeChart(); wobbleCounter = (wobbleCounter + 1) % 3; }, 75); }, stopWobble: function() { clearInterval(this.wobbleInterval); }, nudgeChart: function() { // sometimes the VML renderer needs a "nudge" in the form of adding an invisible // element, this is a no-op for the SVG renderer if(domUtils.hasSVG) { return; } if(this.elements.nudgeElement) { this.elements.nudgeElement.destroy(); } this.elements.nudgeElement = this.renderer.rect(0, 0, 0, 0).add(); }, predictTextWidth: function(text, fontSize) { return this.formatter.predictTextWidth(text, fontSize); }, calculateTickValues: function(start, end, numTicks) { var i, loopStart, range = end - start, rawTickInterval = range / (numTicks - 1), nearestPowerOfTen = mathUtils.nearestPowerOfTen(rawTickInterval), roundTickInterval = nearestPowerOfTen, tickValues = []; if(this.usePercentageRange) { roundTickInterval = (this.majorUnit && !isNaN(this.majorUnit)) ? this.majorUnit : 10; for(i = 0; i <= 100; i += roundTickInterval) { tickValues.push(start + (i / 100) * range); } } else { if(this.majorUnit && !isNaN(this.majorUnit)) { roundTickInterval = this.majorUnit; } else { if(range / roundTickInterval > numTicks) { // if the tick interval creates too many ticks, bump up to a factor of two roundTickInterval *= 2; } if(range / roundTickInterval > numTicks) { // if there are still too many ticks, bump up to a factor of five (of the original) roundTickInterval *= (5 / 2); } if(range / roundTickInterval > numTicks) { // if there are still too many ticks, bump up to a factor of ten (of the original) roundTickInterval *= 2; } } // in normal mode we label in whole numbers, so the tick discovery loop starts at 0 or an appropriate negative number // but in percent mode we force it to label the first range value and go from there loopStart = (this.usePercentageRange) ? start : (start >= 0) ? 0 : (start - start % roundTickInterval); for(i = loopStart; i <= end; i += roundTickInterval) { if(i >= start) { // work-around to deal with floating-point rounding errors tickValues.push(parseFloat(i.toFixed(14))); } } } return tickValues; }, getColorByIndex: function(index) { return colorUtils.colorFromHex(this.colorPalette.getColor(null, index, this.ranges.length - 1)); }, // this is just creating a stub interface so automated tests won't fail getChartObject: function() { return { series: [ { data: [ { y: this.value, onMouseOver: function() { } } ] } ] }; }, // to be implemented by subclasses renderGauge: function() { this.updateDimensions(); }, translateValue: function() { }, normalizedTranslateValue: function() { } }); return Gauge; }); define('js_charting/visualizations/gauges/RadialGauge',[ 'jquery', 'underscore', './Gauge', '../../util/lang_utils', '../../util/math_utils' ], function( $, _, Gauge, langUtils, mathUtils ) { var RadialGauge = function(container, properties) { Gauge.call(this, container, properties); }; langUtils.inherit(RadialGauge, Gauge); $.extend(RadialGauge.prototype, { showMinorTicksByDefault: false, updateDimensions: function() { Gauge.prototype.updateDimensions.call(this); // since the gauge is circular, have to handle when the container is narrower than it is tall if(this.width < this.height) { this.$container.height(this.width); this.height = this.width; } }, processProperties: function() { Gauge.prototype.processProperties.call(this); this.verticalPadding = 10; this.minorsPerMajor = 10; this.tickWidth = 1; this.startAngle = this.computeStartAngle(); this.arcAngle = this.computeArcAngle(); }, computeStartAngle: function() { var angle = parseInt(this.properties['chart.rangeStartAngle'], 10); if(_(angle).isNaN()) { angle = 45; } // add 90 to startAngle because we start at south instead of east return mathUtils.degreeToRadian(angle + 90); }, computeArcAngle: function() { var angle = parseInt(this.properties['chart.rangeArcAngle'], 10) || 270; return mathUtils.degreeToRadian(angle); }, renderGauge: function() { Gauge.prototype.renderGauge.call(this); this.borderWidth = mathUtils.roundWithMin(this.height / 60, 3); this.tickOffset = mathUtils.roundWithMin(this.height / 100, 3); this.tickLabelOffset = this.borderWidth; this.tickFontSize = mathUtils.roundWithMin(this.height / 25, 10); // in pixels this.valueFontSize = mathUtils.roundWithMin(this.height / 15, 15); // in pixels if(this.isShiny) { this.needleTailLength = mathUtils.roundWithMin(this.height / 15, 10); this.needleTailWidth = mathUtils.roundWithMin(this.height / 50, 6); this.knobWidth = mathUtils.roundWithMin(this.height / 30, 7); } else { this.needleWidth = mathUtils.roundWithMin(this.height / 60, 3); } if(!this.isShiny) { this.bandOffset = 0; this.bandThickness = mathUtils.roundWithMin(this.height / 30, 7); } else { this.bandOffset = this.borderWidth; this.bandThickness = mathUtils.roundWithMin(this.height / 40, 4); } this.tickColor = (!this.isShiny) ? this.foregroundColor : 'silver'; this.tickFontColor = (!this.isShiny) ? this.fontColor : 'silver'; this.valueColor = (!this.isShiny) ? this.fontColor : '#b8b167'; this.tickLength = mathUtils.roundWithMin(this.height / 20, 4); this.minorTickLength = this.tickLength / 2; this.radius = (this.height - 2 * (this.verticalPadding + this.borderWidth)) / 2; this.valueHeight = this.height - ((this.radius / 4) + this.verticalPadding + this.borderWidth); this.needleLength = (!this.isShiny) ? this.radius - (this.bandThickness) / 2 : this.radius; this.tickStart = this.radius - this.bandOffset - this.bandThickness - this.tickOffset; this.tickEnd = this.tickStart - this.tickLength; this.tickLabelPosition = this.tickEnd - this.tickLabelOffset; this.minorTickEnd = this.tickStart - this.minorTickLength; if(this.isShiny) { this.elements.border = this.renderer.circle(this.width / 2, this.height / 2, this.radius + this.borderWidth) .attr({ fill: '#edede7', stroke: 'silver', 'stroke-width': 1 }) .add(); this.elements.background = this.renderer.circle(this.width / 2, this.height / 2, this.radius) .attr({ fill: '#000000' }) .add(); } if(this.showRangeBand) { this.drawColorBand(); } this.drawTicks(); this.drawIndicator(this.value); if(this.showValue) { this.drawValueDisplay(); } this.checkOutOfRange(this.value); }, updateValueDisplay: function(valueText) { this.elements.valueDisplay.attr({ text: valueText }); }, drawColorBand: function() { var i, startAngle, endAngle, outerRadius = this.radius - this.bandOffset, innerRadius = outerRadius - this.bandThickness; for(i = 0; i < this.ranges.length - 1; i++) { startAngle = this.translateValue(this.ranges[i]); endAngle = this.translateValue(this.ranges[i + 1]); this.elements['colorBand' + i] = this.renderer.arc(this.width / 2, this.height / 2, outerRadius, innerRadius, startAngle, endAngle) .attr({ fill: this.getColorByIndex(i) }) .add(); } }, drawMajorTick: function(angle) { return this.renderer.path([ 'M', (this.width / 2) + this.tickStart * Math.cos(angle), (this.height / 2) + this.tickStart * Math.sin(angle), 'L', (this.width / 2) + this.tickEnd * Math.cos(angle), (this.height / 2) + this.tickEnd * Math.sin(angle) ]) .attr({ stroke: this.tickColor, 'stroke-width': this.tickWidth }) .add(); }, drawMajorTickLabel: function(angle, text) { var sin = Math.sin(angle), labelWidth = this.predictTextWidth(text, this.tickFontSize), textAlignment = (angle < (1.5 * Math.PI)) ? 'left' : 'right', xOffset = (angle < (1.5 * Math.PI)) ? (-labelWidth / 2) * sin * sin : (labelWidth / 2) * sin * sin, yOffset = (this.tickFontSize / 4) * sin; return this.renderer.text(text, (this.width / 2) + (this.tickLabelPosition) * Math.cos(angle) + xOffset, (this.height / 2) + (this.tickLabelPosition - 4) * sin + (this.tickFontSize / 4) - yOffset ) .attr({ align: textAlignment }) .css({ color: this.tickFontColor, fontSize: this.tickFontSize + 'px' }) .add(); }, drawMinorTick: function(angle) { return this.renderer.path([ 'M', (this.width / 2) + this.tickStart * Math.cos(angle), (this.height / 2) + this.tickStart * Math.sin(angle), 'L', (this.width / 2) + this.minorTickEnd * Math.cos(angle), (this.height / 2) + this.minorTickEnd * Math.sin(angle) ]) .attr({ stroke: this.tickColor, 'stroke-width': this.tickWidth }) .add(); }, drawIndicator: function(val) { var needlePath, needleStroke, needleStrokeWidth, needleFill, needleRidgePath, knobFill, valueAngle = this.normalizedTranslateValue(val), myCos = Math.cos(valueAngle), mySin = Math.sin(valueAngle); if(!this.isShiny) { needlePath = [ 'M', (this.width / 2), (this.height / 2), 'L', (this.width / 2) + myCos * this.needleLength, (this.height / 2) + mySin * this.needleLength ]; needleStroke = this.foregroundColor; needleStrokeWidth = this.needleWidth; } else { needlePath = [ 'M', (this.width / 2) - this.needleTailLength * myCos, (this.height / 2) - this.needleTailLength * mySin, 'L', (this.width / 2) - this.needleTailLength * myCos + this.needleTailWidth * mySin, (this.height / 2) - this.needleTailLength * mySin - this.needleTailWidth * myCos, (this.width / 2) + this.needleLength * myCos, (this.height / 2) + this.needleLength * mySin, (this.width / 2) - this.needleTailLength * myCos - this.needleTailWidth * mySin, (this.height / 2) - this.needleTailLength * mySin + this.needleTailWidth * myCos, (this.width / 2) - this.needleTailLength * myCos, (this.height / 2) - this.needleTailLength * mySin ]; needleFill = { linearGradient: [(this.width / 2) - this.needleTailLength * myCos, (this.height / 2) - this.needleTailLength * mySin, (this.width / 2) - this.needleTailLength * myCos - this.needleTailWidth * mySin, (this.height / 2) - this.needleTailLength * mySin + this.needleTailWidth * myCos], stops: [ [0, '#999999'], [0.2, '#cccccc'] ] }; needleRidgePath = [ 'M', (this.width / 2) - (this.needleTailLength - 2) * myCos, (this.height / 2) - (this.needleTailLength - 2) * mySin, 'L', (this.width / 2) + (this.needleLength - (this.bandOffset / 2)) * myCos, (this.height / 2) + (this.needleLength - (this.bandOffset / 2)) * mySin ]; knobFill = { linearGradient: [(this.width / 2) + this.knobWidth * mySin, (this.height / 2) - this.knobWidth * myCos, (this.width / 2) - this.knobWidth * mySin, (this.height / 2) + this.knobWidth * myCos], stops: [ [0, 'silver'], [0.5, 'black'], [1, 'silver'] ] }; } if(this.isShiny) { if(this.elements.centerKnob) { this.elements.centerKnob.destroy(); } this.elements.centerKnob = this.renderer.circle(this.width / 2, this.height /2, this.knobWidth) .attr({ fill: knobFill }) .add(); } if(this.elements.needle) { this.elements.needle.destroy(); } this.elements.needle = this.renderer.path(needlePath) .attr({ fill: needleFill || '', stroke: needleStroke || '', 'stroke-width': needleStrokeWidth || '' }) .add(); if(this.isShiny) { if(this.elements.needleRidge) { this.elements.needleRidge.destroy(); } this.elements.needleRidge = this.renderer.path(needleRidgePath) .attr({ stroke: '#cccccc', 'stroke-width': 1 }) .add(); } }, drawValueDisplay: function() { var valueText = this.formatValue(this.value); this.elements.valueDisplay = this.renderer.text(valueText, this.width / 2, this.valueHeight) .css({ color: this.valueColor, fontSize: this.valueFontSize + 'px', lineHeight: this.valueFontSize + 'px', fontWeight: 'bold' }) .attr({ align: 'center' }) .add(); }, getSVG: function() { // a little bit of cleanup is required here since the export renderer doesn't support gradients if(this.elements.centerKnob) { this.elements.centerKnob.attr({ fill: '#999999' }); } this.elements.needle.attr({ fill: '#bbbbbb' }); if(this.elements.needleRidge) { this.elements.needleRidge.attr({ stroke: '#999999' }); } return Gauge.prototype.getSVG.call(this); }, normalizedTranslateValue: function(val) { if(val < this.ranges[0]) { return this.translateValue(this.ranges[0]); } if(val > this.ranges[this.ranges.length - 1]) { return this.translateValue(this.ranges[this.ranges.length - 1]); } return this.translateValue(val); }, translateValue: function(val) { var dataRange = this.ranges[this.ranges.length - 1] - this.ranges[0], normalizedValue = val - this.ranges[0]; return this.startAngle + ((normalizedValue / dataRange) * this.arcAngle); } }); return RadialGauge; }); define('js_charting/visualizations/gauges/FillerGauge',[ 'jquery', './Gauge', '../../util/lang_utils', '../../util/math_utils', '../../util/color_utils' ], function( $, Gauge, langUtils, mathUtils, colorUtils ) { var FillerGauge = function(container, properties) { Gauge.call(this, container, properties); this.minorsPerMajor = 5; this.minorTickWidth = 1; }; langUtils.inherit(FillerGauge, Gauge); $.extend(FillerGauge.prototype, { processProperties: function() { Gauge.prototype.processProperties.call(this); }, onAnimationFinished: function() { // no-op for filler gauges }, renderGauge: function() { Gauge.prototype.renderGauge.call(this); this.tickColor = this.foregroundColor; this.tickFontColor = this.fontColor; this.defaultValueColor = (this.isShiny) ? 'black' : this.fontColor; this.drawBackground(); this.drawTicks(); this.drawIndicator(this.value); }, // use the decimal precision of the old and new values to set things up for a smooth animation updateValue: function(oldValue, newValue) { var oldPrecision = mathUtils.getDecimalPrecision(oldValue, 3), newPrecision = mathUtils.getDecimalPrecision(newValue, 3); this.valueAnimationPrecision = Math.max(oldPrecision, newPrecision); Gauge.prototype.updateValue.call(this, oldValue, newValue); }, getDisplayValue: function(rawVal) { // unless this we are displaying a final value, round the value to the animation precision for a smooth transition var multiplier = Math.pow(10, this.valueAnimationPrecision); return ((rawVal !== this.value) ? (Math.round(rawVal * multiplier) / multiplier) : rawVal); }, updateValueDisplay: function() { // no-op, value display is updated as part of drawIndicator }, // filler gauges animate the change in the value display, // so they always animate transitions, even when the values are out of range shouldAnimateTransition: function() { return true; }, getFillColor: function(val) { var i; for(i = 0; i < this.ranges.length - 2; i++) { if(val < this.ranges[i + 1]) { break; } } return this.getColorByIndex(i); }, // use the value to determine the fill color, then use that color's luminance determine // if a light or dark font color should be used getValueColor: function(fillColor) { var fillColorHex = colorUtils.hexFromColor(fillColor), luminanceThreshold = 128, darkColor = 'black', lightColor = 'white', fillLuminance = colorUtils.getLuminance(fillColorHex); return (fillLuminance < luminanceThreshold) ? lightColor : darkColor; } }); return FillerGauge; }); define('js_charting/visualizations/gauges/HorizontalFillerGauge',[ 'jquery', './FillerGauge', '../../util/lang_utils', '../../util/math_utils' ], function( $, FillerGauge, langUtils, mathUtils ) { var HorizontalFillerGauge = function(container, properties) { FillerGauge.call(this, container, properties); this.horizontalPadding = 20; this.tickOffset = 5; this.tickLength = 15; this.tickWidth = 1; this.tickLabelOffset = 5; this.minorTickLength = Math.floor(this.tickLength / 2); }; langUtils.inherit(HorizontalFillerGauge, FillerGauge); $.extend(HorizontalFillerGauge.prototype, { renderGauge: function() { this.tickFontSize = mathUtils.roundWithMinMax(this.width / 50, 10, 20); // in pixels this.backgroundCornerRad = mathUtils.roundWithMinMax(this.width / 120, 3, 5); this.valueFontSize = mathUtils.roundWithMinMax(this.width / 40, 15, 25); // in pixels this.backgroundHeight = this.valueFontSize * 3; this.valueBottomPadding = mathUtils.roundWithMinMax(this.width / 100, 5, 10); FillerGauge.prototype.renderGauge.call(this); }, drawBackground: function() { var tickValues = this.calculateTickValues(this.ranges[0], this.ranges[this.ranges.length - 1], this.MAX_TICKS_PER_RANGE), maxTickValue = tickValues[tickValues.length - 1], maxTickWidth = this.predictTextWidth(this.formatValue(maxTickValue), this.tickFontSize); this.horizontalPadding = Math.max(this.horizontalPadding, maxTickWidth); this.backgroundWidth = this.width - (2 * this.horizontalPadding); if(this.isShiny) { this.elements.background = this.renderer.rect(this.horizontalPadding, (this.height - this.backgroundHeight) / 2, this.backgroundWidth, this.backgroundHeight, this.backgroundCornerRad) .attr({ fill: '#edede7', stroke: 'silver', 'stroke-width': 1 }) .add(); } // no actual dependency here, but want to be consistent with sibling class this.tickStartY = (this.height + this.backgroundHeight) / 2 + this.tickOffset; this.tickEndY = this.tickStartY + this.tickLength; this.tickLabelStartY = this.tickEndY + this.tickLabelOffset; }, drawMajorTick: function(offset) { var tickOffset = this.horizontalPadding + offset; return this.renderer.path([ 'M', tickOffset, this.tickStartY, 'L', tickOffset, this.tickEndY ]) .attr({ stroke: this.tickColor, 'stroke-width': this.tickWidth }) .add(); }, drawMajorTickLabel: function(offset, text) { var tickOffset = this.horizontalPadding + offset; return this.renderer.text(text, tickOffset, this.tickLabelStartY + this.tickFontSize ) .attr({ align: 'center' }) .css({ color: this.tickFontColor, fontSize: this.tickFontSize + 'px', lineHeight: this.tickFontSize + 'px' }) .add(); }, drawMinorTick: function(offset) { var tickOffset = this.horizontalPadding + offset; return this.renderer.path([ 'M', tickOffset, this.tickStartY, 'L', tickOffset, this.tickStartY + this.minorTickLength ]) .attr({ stroke: this.tickColor, 'stroke-width': this.minorTickWidth }) .add(); }, drawIndicator: function(val) { // TODO: implement calculation of gradient based on user-defined colors // for not we are using solid colors var //fillGradient = this.getFillGradient(val), fillColor = this.getFillColor(val), fillOffset = this.normalizedTranslateValue(val), fillTopX, fillPath; if(fillOffset > 0) { fillOffset = Math.max(fillOffset, this.backgroundCornerRad); fillTopX = this.horizontalPadding + fillOffset; if(!this.isShiny) { fillPath = [ 'M', this.horizontalPadding, (this.height - this.backgroundHeight) / 2, 'L', fillTopX, (this.height - this.backgroundHeight) / 2, fillTopX, (this.height + this.backgroundHeight) / 2, this.horizontalPadding, (this.height + this.backgroundHeight) / 2, this.horizontalPadding, (this.height - this.backgroundHeight) / 2 ]; } else { fillPath = [ 'M', this.horizontalPadding + this.backgroundCornerRad, (this.height - this.backgroundHeight - 2) / 2, 'C', this.horizontalPadding + this.backgroundCornerRad, (this.height - this.backgroundHeight - 2) / 2, this.horizontalPadding, (this.height - this.backgroundHeight - 2) / 2, this.horizontalPadding, (this.height - this.backgroundHeight - 2) / 2 + this.backgroundCornerRad, 'L', this.horizontalPadding, (this.height + this.backgroundHeight) / 2 - this.backgroundCornerRad, 'C', this.horizontalPadding, (this.height + this.backgroundHeight) / 2 - this.backgroundCornerRad, this.horizontalPadding, (this.height + this.backgroundHeight) / 2, this.horizontalPadding + this.backgroundCornerRad, (this.height + this.backgroundHeight) / 2, 'L', fillTopX, (this.height + this.backgroundHeight) / 2, fillTopX, (this.height - this.backgroundHeight - 2) / 2, this.horizontalPadding + this.backgroundCornerRad, (this.height - this.backgroundHeight - 2) / 2 ]; } } else { fillPath = []; } if(this.elements.fill) { this.elements.fill.destroy(); } this.elements.fill = this.renderer.path(fillPath) .attr({ fill: fillColor }) .add(); if(this.showValue) { this.drawValueDisplay(val, fillColor, fillOffset); } }, drawValueDisplay: function(val, fillColor, fillOffset) { var displayVal = this.getDisplayValue(val), fillTopX = this.horizontalPadding + fillOffset, valueColor = this.getValueColor(fillColor), valueStartX, valueText = this.formatValue(displayVal), valueTotalWidth = this.predictTextWidth(valueText, this.valueFontSize) + this.valueBottomPadding; // determine if the value display can (horizontally) fit inside the fill, // if not orient it to the right of the fill if(fillOffset >= valueTotalWidth) { valueStartX = fillTopX - valueTotalWidth; } else { valueStartX = fillTopX + this.valueBottomPadding; valueColor = this.defaultValueColor; } if(this.elements.valueDisplay) { this.elements.valueDisplay.attr({ text: valueText, x: valueStartX }) .css({ color: valueColor, fontSize: this.valueFontSize + 'px', fontWeight: 'bold' }).toFront(); } else { this.elements.valueDisplay = this.renderer.text( valueText, valueStartX, (this.height / 2) + this.valueFontSize / 4 ) .css({ color: valueColor, fontSize: this.valueFontSize + 'px', lineHeight: this.valueFontSize + 'px', fontWeight: 'bold' }) .attr({ align: 'left' }) .add(); } }, normalizedTranslateValue: function(val) { if(val < this.ranges[0]) { return 0; } if(val > this.ranges[this.ranges.length - 1]) { return this.translateValue(this.ranges[this.ranges.length - 1]); } return this.translateValue(val); }, translateValue: function(val) { var dataRange = this.ranges[this.ranges.length - 1] - this.ranges[0], normalizedValue = val - this.ranges[0]; return Math.round((normalizedValue / dataRange) * this.backgroundWidth); } }); return HorizontalFillerGauge; }); define('js_charting/visualizations/gauges/VerticalFillerGauge',[ 'jquery', './FillerGauge', '../../util/lang_utils', '../../util/math_utils' ], function( $, FillerGauge, langUtils, mathUtils ) { var VerticalFillerGauge = function(container, properties) { FillerGauge.call(this, container, properties); this.tickWidth = 1; }; langUtils.inherit(VerticalFillerGauge, FillerGauge); $.extend(VerticalFillerGauge.prototype, { renderGauge: function() { this.tickOffset = mathUtils.roundWithMin(this.height / 100, 3); this.tickLength = mathUtils.roundWithMin(this.height / 20, 4); this.tickLabelOffset = mathUtils.roundWithMin(this.height / 60, 3); this.tickFontSize = mathUtils.roundWithMin(this.height / 20, 10); // in pixels this.minorTickLength = this.tickLength / 2; this.backgroundCornerRad = mathUtils.roundWithMin(this.height / 60, 3); this.valueBottomPadding = mathUtils.roundWithMin(this.height / 30, 5); this.valueFontSize = mathUtils.roundWithMin(this.height / 20, 12); // in pixels FillerGauge.prototype.renderGauge.call(this); }, drawBackground: function() { this.verticalPadding = 10 + this.tickFontSize / 2; this.backgroundWidth = mathUtils.roundWithMin(this.height / 4, 50); this.backgroundHeight = this.height - (2 * this.verticalPadding); // rather than trying to dynamically increase the width as the values come in, we // provide enough room for an order of magnitude greater than the highest range value var maxValueWidth = this.determineMaxValueWidth(this.ranges, this.valueFontSize) + 10; this.backgroundWidth = Math.max(this.backgroundWidth, maxValueWidth); if(this.isShiny) { this.elements.background = this.renderer.rect((this.width - this.backgroundWidth) / 2, this.verticalPadding, this.backgroundWidth, this.backgroundHeight, this.backgroundCornerRad) .attr({ fill: '#edede7', stroke: 'silver', 'stroke-width': 1 }) .add(); } // these values depend on the adjusted width of the background this.tickStartX = (this.width + this.backgroundWidth) / 2 + this.tickOffset; this.tickEndX = this.tickStartX + this.tickLength; this.tickLabelStartX = this.tickEndX + this.tickLabelOffset; }, determineMaxValueWidth: function(ranges, fontSize) { // in percent mode, we can hard-code what the max-width value can be if(this.usePercentageValue) { return this.predictTextWidth("100.00%", fontSize); } var i, valueString, maxWidth = 0; // loop through all ranges and determine which has the greatest width (because of scientific notation, we can't just look at the extremes) // additionally add an extra digit to the min and max ranges to accomodate out-of-range values for(i = 0; i < ranges.length; i++) { valueString = "" + ranges[i]; if(i === 0 || i === ranges.length - 1) { valueString += "0"; } maxWidth = Math.max(maxWidth, this.predictTextWidth(valueString, fontSize)); } return maxWidth; }, drawMajorTick: function(height) { var tickHeight = this.verticalPadding + this.backgroundHeight - height; return this.renderer.path([ 'M', this.tickStartX, tickHeight, 'L', this.tickEndX, tickHeight ]) .attr({ stroke: this.tickColor, 'stroke-width': this.tickWidth }) .add(); }, drawMajorTickLabel: function(height, text) { var tickHeight = this.verticalPadding + this.backgroundHeight - height; return this.renderer.text(text, this.tickLabelStartX, tickHeight + (this.tickFontSize / 4) ) .attr({ align: 'left' }) .css({ color: this.tickFontColor, fontSize: this.tickFontSize + 'px', lineHeight: this.tickFontSize + 'px' }) .add(); }, drawMinorTick: function(height) { var tickHeight = this.verticalPadding + this.backgroundHeight - height; return this.renderer.path([ 'M', this.tickStartX, tickHeight, 'L', this.tickStartX + this.minorTickLength, tickHeight ]) .attr({ stroke: this.tickColor, 'stroke-width': this.minorTickWidth }) .add(); }, drawIndicator: function(val) { // TODO: implement calculation of gradient based on user-defined colors // for now we are using solid colors var //fillGradient = this.getFillGradient(val), fillColor = this.getFillColor(val), fillHeight = this.normalizedTranslateValue(val), fillTopY, fillPath; if(fillHeight > 0) { fillHeight = Math.max(fillHeight, this.backgroundCornerRad); fillTopY = this.verticalPadding + this.backgroundHeight - fillHeight; if(!this.isShiny) { fillPath = [ 'M', (this.width - this.backgroundWidth) / 2, this.height - this.verticalPadding, 'L', (this.width + this.backgroundWidth) / 2, this.height - this.verticalPadding, (this.width + this.backgroundWidth) / 2, fillTopY, (this.width - this.backgroundWidth) / 2, fillTopY, (this.width - this.backgroundWidth) / 2, this.height - this.verticalPadding ]; } else { fillPath = [ 'M', (this.width - this.backgroundWidth - 2) / 2, this.height - this.verticalPadding - this.backgroundCornerRad, 'C', (this.width - this.backgroundWidth - 2) / 2, this.height - this.verticalPadding - this.backgroundCornerRad, (this.width - this.backgroundWidth - 2) / 2, this.height - this.verticalPadding, (this.width - this.backgroundWidth - 2) / 2 + this.backgroundCornerRad, this.height - this.verticalPadding, 'L', (this.width + this.backgroundWidth - 2) / 2 - this.backgroundCornerRad, this.height - this.verticalPadding, 'C', (this.width + this.backgroundWidth - 2) / 2 - this.backgroundCornerRad, this.height - this.verticalPadding, (this.width + this.backgroundWidth - 2) / 2, this.height - this.verticalPadding, (this.width + this.backgroundWidth - 2) / 2, this.height - this.verticalPadding - this.backgroundCornerRad, 'L', (this.width + this.backgroundWidth - 2) / 2, fillTopY, (this.width - this.backgroundWidth - 2) / 2, fillTopY, (this.width - this.backgroundWidth - 2) / 2, this.height - this.verticalPadding - this.backgroundCornerRad ]; } } else { fillPath = []; } if(this.elements.fill) { this.elements.fill.destroy(); } this.elements.fill = this.renderer.path(fillPath) .attr({ fill: fillColor }) .add(); if(this.showValue) { this.drawValueDisplay(val, fillColor); } }, drawValueDisplay: function(val, fillColor) { var displayVal = this.getDisplayValue(val), fillHeight = this.normalizedTranslateValue(val), fillTopY = this.verticalPadding + this.backgroundHeight - fillHeight, valueTotalHeight = this.valueFontSize + this.valueBottomPadding, valueColor = this.getValueColor(fillColor), valueBottomY, valueText = this.formatValue(displayVal); // determine if the value display can (vertically) fit inside the fill, // if not orient it to the bottom of the fill if(fillHeight >= valueTotalHeight) { valueBottomY = fillTopY + valueTotalHeight - this.valueBottomPadding; } else { valueBottomY = fillTopY - this.valueBottomPadding; valueColor = this.defaultValueColor; } if(this.elements.valueDisplay) { this.elements.valueDisplay.attr({ text: valueText, y: valueBottomY }) .css({ color: valueColor, fontSize: this.valueFontSize + 'px', fontWeight: 'bold' }).toFront(); } else { this.elements.valueDisplay = this.renderer.text( valueText, this.width / 2, valueBottomY ) .css({ color: valueColor, fontSize: this.valueFontSize + 'px', lineHeight: this.valueFontSize + 'px', fontWeight: 'bold' }) .attr({ align: 'center' }) .add(); } }, normalizedTranslateValue: function(val) { if(val < this.ranges[0]) { return 0; } if(val > this.ranges[this.ranges.length - 1]) { return this.translateValue(this.ranges[this.ranges.length - 1]) + 5; } return this.translateValue(val); }, translateValue: function(val) { var dataRange = this.ranges[this.ranges.length - 1] - this.ranges[0], normalizedValue = val - this.ranges[0]; return Math.round((normalizedValue / dataRange) * this.backgroundHeight); } }); return VerticalFillerGauge; }); define('js_charting/visualizations/gauges/MarkerGauge',[ 'jquery', './Gauge', '../../util/lang_utils' ], function( $, Gauge, langUtils ) { var MarkerGauge = function(container, properties) { Gauge.call(this, container, properties); this.bandCornerRad = 0; this.tickLabelPaddingRight = 10; this.minorsPerMajor = 5; this.minorTickWidth = 1; this.tickWidth = 1; }; langUtils.inherit(MarkerGauge, Gauge); $.extend(MarkerGauge.prototype, { showValueByDefault: false, renderGauge: function() { Gauge.prototype.renderGauge.call(this); this.tickColor = (this.isShiny) ? 'black' : this.foregroundColor; this.tickFontColor = (this.isShiny) ? 'black' : this.fontColor; this.valueOffset = (this.isShiny) ? this.markerSideWidth + 10 : this.valueFontSize; this.drawBackground(); if(this.showRangeBand) { this.drawBand(); } this.drawTicks(); this.drawIndicator(this.value); this.checkOutOfRange(this.value); }, updateValueDisplay: function() { // no-op, value display is updated as part of drawIndicator } }); return MarkerGauge; }); define('js_charting/visualizations/gauges/HorizontalMarkerGauge',[ 'jquery', './MarkerGauge', '../../util/lang_utils', '../../util/math_utils' ], function( $, MarkerGauge, langUtils, mathUtils ) { var HorizontalMarkerGauge = function(container, properties) { MarkerGauge.call(this, container, properties); this.horizontalPadding = 20; this.tickOffset = 5; this.tickLength = 15; this.tickWidth = 1; this.tickLabelOffset = 5; this.minorTickLength = Math.floor(this.tickLength / 2); this.bandHeight = (!this.isShiny) ? 35 : 15; }; langUtils.inherit(HorizontalMarkerGauge, MarkerGauge); $.extend(HorizontalMarkerGauge.prototype, { renderGauge: function() { this.markerWindowHeight = mathUtils.roundWithMinMax(this.width / 30, 30, 80); this.markerSideWidth = this.markerWindowHeight / 2; this.markerSideCornerRad = this.markerSideWidth / 3; this.bandOffsetBottom = 5 + this.markerWindowHeight / 2; this.bandOffsetTop = 5 + this.markerWindowHeight / 2; this.tickFontSize = mathUtils.roundWithMinMax(this.width / 50, 10, 20); // in pixels this.backgroundCornerRad = mathUtils.roundWithMinMax(this.width / 120, 3, 5); this.valueFontSize = mathUtils.roundWithMinMax(this.width / 40, 15, 25); // in pixels this.valueOffset = this.markerSideWidth + 10; this.tickLabelPadding = this.tickFontSize / 2; this.bandOffsetX = (!this.isShiny) ? 0 : this.tickLabelPadding; this.backgroundHeight = this.bandOffsetX + this.bandHeight + this.tickOffset + this.tickLength + this.tickLabelOffset + this.tickFontSize + this.tickLabelPadding; MarkerGauge.prototype.renderGauge.call(this); }, drawBackground: function(tickValues) { tickValues = this.calculateTickValues(this.ranges[0], this.ranges[this.ranges.length - 1], this.MAX_TICKS_PER_RANGE); var maxTickValue = tickValues[tickValues.length - 1], maxTickWidth = this.predictTextWidth(this.formatValue(maxTickValue), this.tickFontSize); this.bandOffsetBottom = Math.max(this.bandOffsetBottom, maxTickWidth); this.bandOffsetTop = Math.max(this.bandOffsetTop, maxTickWidth); this.backgroundWidth = this.width - (2 * this.horizontalPadding); this.bandWidth = this.backgroundWidth - (this.bandOffsetBottom + this.bandOffsetTop); if(this.isShiny) { this.elements.background = this.renderer.rect(this.horizontalPadding, (this.height - this.backgroundHeight) / 2, this.backgroundWidth, this.backgroundHeight, this.backgroundCornerRad) .attr({ fill: '#edede7', stroke: 'silver', 'stroke-width': 1 }) .add(); } }, drawBand: function() { var i, startOffset, endOffset, bandStartX = this.horizontalPadding + this.bandOffsetBottom, bandTopY = ((this.height - this.backgroundHeight) / 2) + this.bandOffsetX; for(i = 0; i < this.ranges.length - 1; i++) { startOffset = this.translateValue(this.ranges[i]); endOffset = this.translateValue(this.ranges[i + 1]); this.elements['colorBand' + i] = this.renderer.rect( bandStartX + startOffset, bandTopY, endOffset - startOffset, this.bandHeight, this.bandCornerRad ) .attr({ fill: this.getColorByIndex(i) }) .add(); } this.tickStartY = (this.height - this.backgroundHeight) / 2 + (this.bandOffsetX + this.bandHeight) + this.tickOffset; this.tickEndY = this.tickStartY + this.tickLength; this.tickLabelStartY = this.tickEndY + this.tickLabelOffset; }, drawMajorTick: function(offset) { var tickOffset = this.horizontalPadding + this.bandOffsetBottom + offset; return this.renderer.path([ 'M', tickOffset, this.tickStartY, 'L', tickOffset, this.tickEndY ]) .attr({ stroke: this.tickColor, 'stroke-width': this.tickWidth }) .add(); }, drawMajorTickLabel: function(offset, text) { var tickOffset = this.horizontalPadding + this.bandOffsetBottom + offset; return this.renderer.text(text, tickOffset, this.tickLabelStartY + this.tickFontSize ) .attr({ align: 'center' }) .css({ color: this.tickFontColor, fontSize: this.tickFontSize + 'px', lineHeight: this.tickFontSize + 'px' }) .add(); }, drawMinorTick: function(offset) { var tickOffset = this.horizontalPadding + this.bandOffsetBottom + offset; return this.renderer.path([ 'M', tickOffset, this.tickStartY, 'L', tickOffset, this.tickStartY + this.minorTickLength ]) .attr({ stroke: this.tickColor, 'stroke-width': this.minorTickWidth }) .add(); }, drawIndicator: function(val) { var markerOffset = this.normalizedTranslateValue(val), markerStartY = (!this.isShiny) ? (this.height - this.backgroundHeight) / 2 - 10 : (this.height - this.backgroundHeight) / 2, markerEndY = (!this.isShiny) ? markerStartY + this.bandHeight + 20 : markerStartY + this.backgroundHeight, markerStartX = this.horizontalPadding + this.bandOffsetBottom + markerOffset, markerLineWidth = 3, // set to 1 for shiny markerLineStroke = this.foregroundColor, // set to red for shiny markerLinePath = [ 'M', markerStartX, markerStartY, 'L', markerStartX, markerEndY ]; if(this.isShiny) { var markerLHSPath = [ 'M', markerStartX - this.markerWindowHeight / 2, markerStartY, 'L', markerStartX - this.markerWindowHeight / 2, markerStartY - (this.markerSideWidth - this.markerSideCornerRad), 'C', markerStartX - this.markerWindowHeight / 2, markerStartY - (this.markerSideWidth - this.markerSideCornerRad), markerStartX - this.markerWindowHeight / 2, markerStartY - this.markerSideWidth, markerStartX - (this.markerWindowHeight / 2) + this.markerSideCornerRad, markerStartY - this.markerSideWidth, 'L', markerStartX + (this.markerWindowHeight / 2) - this.markerSideCornerRad, markerStartY - this.markerSideWidth, 'C', markerStartX + (this.markerWindowHeight / 2) - this.markerSideCornerRad, markerStartY - this.markerSideWidth, markerStartX + (this.markerWindowHeight / 2), markerStartY - this.markerSideWidth, markerStartX + (this.markerWindowHeight / 2), markerStartY - (this.markerSideWidth - this.markerSideCornerRad), 'L', markerStartX + this.markerWindowHeight / 2, markerStartY, markerStartX - this.markerWindowHeight, markerStartY ], markerRHSPath = [ 'M', markerStartX - this.markerWindowHeight / 2, markerEndY, 'L', markerStartX - this.markerWindowHeight / 2, markerEndY + (this.markerSideWidth - this.markerSideCornerRad), 'C', markerStartX - this.markerWindowHeight / 2, markerEndY + (this.markerSideWidth - this.markerSideCornerRad), markerStartX - this.markerWindowHeight / 2, markerEndY + this.markerSideWidth, markerStartX - (this.markerWindowHeight / 2) + this.markerSideCornerRad, markerEndY + this.markerSideWidth, 'L', markerStartX + (this.markerWindowHeight / 2) - this.markerSideCornerRad, markerEndY + this.markerSideWidth, 'C', markerStartX + (this.markerWindowHeight / 2) - this.markerSideCornerRad, markerEndY + this.markerSideWidth, markerStartX + (this.markerWindowHeight / 2), markerEndY + this.markerSideWidth, markerStartX + (this.markerWindowHeight / 2), markerEndY + (this.markerSideWidth - this.markerSideCornerRad), 'L', markerStartX + this.markerWindowHeight / 2, markerEndY, markerStartX - this.markerWindowHeight, markerEndY ], markerBorderPath = [ 'M', markerStartX - this.markerWindowHeight / 2, markerStartY, 'L', markerStartX - this.markerWindowHeight / 2, markerEndY, markerStartX + this.markerWindowHeight / 2, markerEndY, markerStartX + this.markerWindowHeight / 2, markerStartY, markerStartX - this.markerWindowHeight / 2, markerStartY ], markerUnderlinePath = [ 'M', markerStartX - 1, markerStartY, 'L', markerStartX - 1, markerEndY ]; markerLineStroke = 'red'; markerLineWidth = 1; if(this.elements.markerLHS) { this.elements.markerLHS.destroy(); } this.elements.markerLHS = this.renderer.path(markerLHSPath) .attr({ fill: '#cccccc' }) .add(); if(this.elements.markerRHS) { this.elements.markerRHS.destroy(); } this.elements.markerRHS = this.renderer.path(markerRHSPath) .attr({ fill: '#cccccc' }) .add(); if(this.elements.markerWindow) { this.elements.markerWindow.destroy(); } this.elements.markerWindow = this.renderer.rect(markerStartX - this.markerWindowHeight / 2, markerStartY, this.markerWindowHeight, this.backgroundHeight, 0) .attr({ fill: 'rgba(255, 255, 255, 0.3)' }) .add(); if(this.elements.markerBorder) { this.elements.markerBorder.destroy(); } this.elements.markerBorder = this.renderer.path(markerBorderPath) .attr({ stroke: 'white', 'stroke-width': 2 }) .add(); if(this.elements.markerUnderline) { this.elements.markerUnderline.destroy(); } this.elements.markerUnderline = this.renderer.path(markerUnderlinePath) .attr({ stroke: 'white', 'stroke-width': 2 }) .add(); } if(this.elements.markerLine) { this.elements.markerLine.destroy(); } this.elements.markerLine = this.renderer.path(markerLinePath) .attr({ stroke: markerLineStroke, 'stroke-width': markerLineWidth }) .add(); if(this.showValue) { this.drawValueDisplay(val); } }, drawValueDisplay: function(val) { var valueText = this.formatValue(val), markerOffset = this.normalizedTranslateValue(val), valueX = this.horizontalPadding + this.bandOffsetBottom + markerOffset; if(this.elements.valueDisplay) { this.elements.valueDisplay.attr({ text: valueText, x: valueX }); } else { this.elements.valueDisplay = this.renderer.text( valueText, valueX, (this.height - this.backgroundHeight) / 2 - this.valueOffset ) .css({ color: 'black', fontSize: this.valueFontSize + 'px', lineHeight: this.valueFontSize + 'px', fontWeight: 'bold' }) .attr({ align: 'center' }) .add(); } }, normalizedTranslateValue: function(val) { if(val < this.ranges[0]) { return 0; } if(val > this.ranges[this.ranges.length - 1]) { return this.translateValue(this.ranges[this.ranges.length - 1]); } return this.translateValue(val); }, translateValue: function(val) { var dataRange = this.ranges[this.ranges.length - 1] - this.ranges[0], normalizedValue = val - this.ranges[0]; return Math.round((normalizedValue / dataRange) * this.bandWidth); } }); return HorizontalMarkerGauge; }); define('js_charting/visualizations/gauges/VerticalMarkerGauge',[ 'jquery', './MarkerGauge', '../../util/lang_utils', '../../util/math_utils' ], function( $, MarkerGauge, langUtils, mathUtils ) { var VerticalMarkerGauge = function(container, properties) { MarkerGauge.call(this, container, properties); this.verticalPadding = 10; }; langUtils.inherit(VerticalMarkerGauge, MarkerGauge); $.extend(VerticalMarkerGauge.prototype, { renderGauge: function() { this.markerWindowHeight = mathUtils.roundWithMin(this.height / 7, 20); this.markerSideWidth = this.markerWindowHeight / 2; this.markerSideCornerRad = this.markerSideWidth / 3; this.bandOffsetBottom = 5 + this.markerWindowHeight / 2; this.bandOffsetTop = 5 + this.markerWindowHeight / 2; this.tickOffset = mathUtils.roundWithMin(this.height / 100, 3); this.tickLength = mathUtils.roundWithMin(this.height / 20, 4); this.tickLabelOffset = mathUtils.roundWithMin(this.height / 60, 3); this.tickFontSize = mathUtils.roundWithMin(this.height / 20, 10); // in pixels this.minorTickLength = this.tickLength / 2; this.backgroundCornerRad = mathUtils.roundWithMin(this.height / 60, 3); this.valueFontSize = mathUtils.roundWithMin(this.height / 15, 15); // in pixels this.bandOffsetX = (!this.isShiny) ? 0 : mathUtils.roundWithMin(this.height / 60, 3); MarkerGauge.prototype.renderGauge.call(this); }, drawBackground: function() { this.backgroundWidth = mathUtils.roundWithMin(this.height / 4, 50); var tickValues = this.calculateTickValues(this.ranges[0], this.ranges[this.ranges.length - 1], this.MAX_TICKS_PER_RANGE); this.backgroundHeight = this.height - (2 * this.verticalPadding); this.bandHeight = this.backgroundHeight - (this.bandOffsetBottom + this.bandOffsetTop); this.bandWidth = (!this.isShiny) ? 30 : 10; var maxLabelWidth, totalWidthNeeded, maxTickValue = tickValues[tickValues.length - 1]; maxLabelWidth = this.predictTextWidth(this.formatValue(maxTickValue), this.tickFontSize); totalWidthNeeded = this.bandOffsetX + this.bandWidth + this.tickOffset + this.tickLength + this.tickLabelOffset + maxLabelWidth + this.tickLabelPaddingRight; this.backgroundWidth = Math.max(this.backgroundWidth, totalWidthNeeded); if(this.isShiny) { this.elements.background = this.renderer.rect((this.width - this.backgroundWidth) / 2, this.verticalPadding, this.backgroundWidth, this.backgroundHeight, this.backgroundCornerRad) .attr({ fill: '#edede7', stroke: 'silver', 'stroke-width': 1 }) .add(); } // these values depend on the adjusted background width this.tickStartX = (this.width - this.backgroundWidth) / 2 + (this.bandOffsetX + this.bandWidth) + this.tickOffset; this.tickEndX = this.tickStartX + this.tickLength; this.tickLabelStartX = this.tickEndX + this.tickLabelOffset; }, drawBand: function() { var i, startHeight, endHeight, bandLeftX = ((this.width - this.backgroundWidth) / 2) + this.bandOffsetX, bandBottomY = this.height - this.verticalPadding - this.bandOffsetBottom; for(i = 0; i < this.ranges.length - 1; i++) { startHeight = this.translateValue(this.ranges[i]); endHeight = this.translateValue(this.ranges[i + 1]); this.elements['colorBand' + i] = this.renderer.rect( bandLeftX, bandBottomY - endHeight, this.bandWidth, endHeight - startHeight, this.bandCornerRad ) .attr({ fill: this.getColorByIndex(i) }) .add(); } }, drawMajorTick: function(height) { var tickHeight = this.verticalPadding + this.backgroundHeight - (this.bandOffsetBottom + height); return this.renderer.path([ 'M', this.tickStartX, tickHeight, 'L', this.tickEndX, tickHeight ]) .attr({ stroke: this.tickColor, 'stroke-width': this.tickWidth }) .add(); }, drawMajorTickLabel: function(height, text) { var tickHeight = this.verticalPadding + this.backgroundHeight - (this.bandOffsetBottom + height); return this.renderer.text(text, this.tickLabelStartX, tickHeight + (this.tickFontSize / 4) ) .attr({ align: 'left' }) .css({ color: this.tickFontColor, fontSize: this.tickFontSize + 'px', lineHeight: this.tickFontSize + 'px' }) .add(); }, drawMinorTick: function(height) { var tickHeight = this.verticalPadding + this.backgroundHeight - (this.bandOffsetBottom + height); return this.renderer.path([ 'M', this.tickStartX, tickHeight, 'L', this.tickStartX + this.minorTickLength, tickHeight ]) .attr({ stroke: this.tickColor, 'stroke-width': this.minorTickWidth }) .add(); }, drawIndicator: function(val) { var markerLHSPath, markerRHSPath, markerBorderPath, markerUnderlinePath, markerHeight = this.normalizedTranslateValue(val), markerStartY = this.verticalPadding + this.backgroundHeight - (this.bandOffsetBottom + markerHeight), markerStartX = (!this.isShiny) ? (this.width - this.backgroundWidth) / 2 - 10 : (this.width - this.backgroundWidth) / 2, markerEndX = (!this.isShiny) ? markerStartX + this.bandWidth + 20 : markerStartX + this.backgroundWidth, markerLineStroke = this.foregroundColor, // will be changed to red for shiny markerLineWidth = 3, // wil be changed to 1 for shiny markerLinePath = [ 'M', markerStartX, markerStartY, 'L', markerEndX, markerStartY ]; if(this.isShiny) { markerLHSPath = [ 'M', markerStartX, markerStartY - this.markerWindowHeight / 2, 'L', markerStartX - (this.markerSideWidth - this.markerSideCornerRad), markerStartY - this.markerWindowHeight / 2, 'C', markerStartX - (this.markerSideWidth - this.markerSideCornerRad), markerStartY - this.markerWindowHeight / 2, markerStartX - this.markerSideWidth, markerStartY - this.markerWindowHeight / 2, markerStartX - this.markerSideWidth, markerStartY - (this.markerWindowHeight / 2) + this.markerSideCornerRad, 'L', markerStartX - this.markerSideWidth, markerStartY + (this.markerWindowHeight / 2) - this.markerSideCornerRad, 'C', markerStartX - this.markerSideWidth, markerStartY + (this.markerWindowHeight / 2) - this.markerSideCornerRad, markerStartX - this.markerSideWidth, markerStartY + (this.markerWindowHeight / 2), markerStartX - (this.markerSideWidth - this.markerSideCornerRad), markerStartY + (this.markerWindowHeight / 2), 'L', markerStartX, markerStartY + this.markerWindowHeight / 2, markerStartX, markerStartY - this.markerWindowHeight / 2 ]; markerRHSPath = [ 'M', markerEndX, markerStartY - this.markerWindowHeight / 2, 'L', markerEndX + (this.markerSideWidth - this.markerSideCornerRad), markerStartY - this.markerWindowHeight / 2, 'C', markerEndX + (this.markerSideWidth - this.markerSideCornerRad), markerStartY - this.markerWindowHeight / 2, markerEndX + this.markerSideWidth, markerStartY - this.markerWindowHeight / 2, markerEndX + this.markerSideWidth, markerStartY - (this.markerWindowHeight / 2) + this.markerSideCornerRad, 'L', markerEndX + this.markerSideWidth, markerStartY + (this.markerWindowHeight / 2) - this.markerSideCornerRad, 'C', markerEndX + this.markerSideWidth, markerStartY + (this.markerWindowHeight / 2) - this.markerSideCornerRad, markerEndX + this.markerSideWidth, markerStartY + (this.markerWindowHeight / 2), markerEndX + (this.markerSideWidth - this.markerSideCornerRad), markerStartY + (this.markerWindowHeight / 2), 'L', markerEndX, markerStartY + this.markerWindowHeight / 2, markerEndX, markerStartY - this.markerWindowHeight / 2 ]; markerBorderPath = [ 'M', markerStartX, markerStartY - this.markerWindowHeight / 2, 'L', markerEndX, markerStartY - this.markerWindowHeight / 2, markerEndX, markerStartY + this.markerWindowHeight / 2, markerStartX, markerStartY + this.markerWindowHeight / 2, markerStartX, markerStartY - this.markerWindowHeight / 2 ]; markerUnderlinePath = [ 'M', markerStartX, markerStartY + 1, 'L', markerEndX, markerStartY + 1 ]; markerLineStroke = 'red'; markerLineWidth = 1; } if(this.isShiny) { if(this.elements.markerLHS) { this.elements.markerLHS.destroy(); } this.elements.markerLHS = this.renderer.path(markerLHSPath) .attr({ fill: '#cccccc' }) .add(); if(this.elements.markerRHS) { this.elements.markerRHS.destroy(); } this.elements.markerRHS = this.renderer.path(markerRHSPath) .attr({ fill: '#cccccc' }) .add(); if(this.elements.markerWindow) { this.elements.markerWindow.destroy(); } this.elements.markerWindow = this.renderer.rect(markerStartX, markerStartY - this.markerWindowHeight / 2, this.backgroundWidth, this.markerWindowHeight, 0) .attr({ fill: 'rgba(255, 255, 255, 0.3)' }) .add(); if(this.elements.markerBorder) { this.elements.markerBorder.destroy(); } this.elements.markerBorder = this.renderer.path(markerBorderPath) .attr({ stroke: 'white', 'stroke-width': 2 }) .add(); if(this.elements.markerUnderline) { this.elements.markerUnderline.destroy(); } this.elements.markerUnderline = this.renderer.path(markerUnderlinePath) .attr({ stroke: 'white', 'stroke-width': 2 }) .add(); } if(this.elements.markerLine) { this.elements.markerLine.destroy(); } this.elements.markerLine = this.renderer.path(markerLinePath) .attr({ stroke: markerLineStroke, 'stroke-width': markerLineWidth }) .add(); if(this.showValue) { this.drawValueDisplay(val); } }, drawValueDisplay: function(val) { var valueText = this.formatValue(val), markerHeight = this.normalizedTranslateValue(val), valueY = this.verticalPadding + this.backgroundHeight - this.bandOffsetBottom - markerHeight; if(this.elements.valueDisplay) { this.elements.valueDisplay.attr({ text: valueText, y: valueY + this.valueFontSize / 4 }); } else { this.elements.valueDisplay = this.renderer.text( valueText, (this.width - this.backgroundWidth) / 2 - this.valueOffset, valueY + this.valueFontSize / 4 ) .css({ color: 'black', fontSize: this.valueFontSize + 'px', lineHeight: this.valueFontSize + 'px', fontWeight: 'bold' }) .attr({ align: 'right' }) .add(); } }, normalizedTranslateValue: function(val) { if(val < this.ranges[0]) { return 0; } if(val > this.ranges[this.ranges.length - 1]) { return this.translateValue(this.ranges[this.ranges.length - 1]); } return this.translateValue(val); }, translateValue: function(val) { var dataRange = this.ranges[this.ranges.length - 1] - this.ranges[0], normalizedValue = val - this.ranges[0]; return Math.round((normalizedValue / dataRange) * this.bandHeight); } }); return VerticalMarkerGauge; }); define('js_charting/js_charting',[ 'jquery', 'underscore', 'highcharts', 'helpers/user_agent', './helpers/DataSet', './visualizations/charts/Chart', './visualizations/charts/SplitSeriesChart', './visualizations/charts/PieChart', './visualizations/charts/ScatterChart', './visualizations/gauges/RadialGauge', './visualizations/gauges/HorizontalFillerGauge', './visualizations/gauges/VerticalFillerGauge', './visualizations/gauges/HorizontalMarkerGauge', './visualizations/gauges/VerticalMarkerGauge', './util/parsing_utils' ], function( $, _, Highcharts, userAgent, DataSet, Chart, SplitSeriesChart, PieChart, ScatterChart, RadialGauge, HorizontalFillerGauge, VerticalFillerGauge, HorizontalMarkerGauge, VerticalMarkerGauge, parsingUtils ) { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // support for push-state (SPL-64487) // // In Firefox, a local reference to another node (e.g. <g clip-path="url(#clipPathId)">) will break whenever a push-state // or replace-state action is taken (https://bugzilla.mozilla.org/show_bug.cgi?id=652991). // // We will hook in to the 'pushState' and 'replaceState' methods on the window.history object and fire an event to // notify any listeners that they need to update all local references in their SVG. if(userAgent.isFirefox()) { // this local reference to the window.history is vital, otherwise it can potentially be garbage collected // and our changes lost (https://bugzilla.mozilla.org/show_bug.cgi?id=593910) var history = window.history; _(['pushState', 'replaceState']).each(function(fnName) { var original = history[fnName]; history[fnName] = function() { original.apply(history, arguments); // kind of hacky to use Highcharts as an event bus, but not sure what else to do $(Highcharts).trigger('baseUriChange'); }; }); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // namespace-level methods // TODO [sff] does this really need to be a public method, or could it be called under the hood from prepare()? var extractChartReadyData = function(rawData) { if(!rawData || !rawData.fields || !rawData.columns) { throw new Error('The data object passed to extractChartReadyData did not contain fields and columns'); } if(rawData.fields.length !== rawData.columns.length) { throw new Error('The data object passed to extractChartReadyData must have the same number of fields and columns'); } return new DataSet(rawData); }; var createChart = function(container, properties) { if(container instanceof $) { container = container[0]; } if(!_(container).isElement()) { throw new Error("Invalid first argument to createChart, container must be a valid DOM element or a jQuery object"); } properties = properties || {}; var chartType = properties['chart']; if(chartType === 'pie') { return new PieChart(container, properties); } if(chartType === 'scatter') { return new ScatterChart(container, properties); } if(chartType === 'radialGauge') { return new RadialGauge(container, properties); } if(chartType === 'fillerGauge') { return (properties['chart.orientation'] === 'x') ? (new HorizontalFillerGauge(container, properties)) : (new VerticalFillerGauge(container, properties)); } if(chartType === 'markerGauge') { return (properties['chart.orientation'] === 'x') ? (new HorizontalMarkerGauge(container, properties)) : (new VerticalMarkerGauge(container, properties)); } // only the basic cartesian chart types (bar/column/line/area) support split-series mode return (parsingUtils.normalizeBoolean(properties['layout.splitSeries'])) ? (new SplitSeriesChart(container, properties)) : (new Chart(container, properties)); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // public interface return ({ extractChartReadyData: extractChartReadyData, createChart: createChart }); });
splunk/splunk-webframework
server/static/splunkjs/compiled/js_charting.js
JavaScript
apache-2.0
351,320
/* * Copyright 2014 defrac inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package defrac.intellij.sdk; import com.google.common.collect.Lists; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.io.FileUtil; import defrac.intellij.DefracBundle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.lang.ref.SoftReference; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * */ public final class DefracSdkData { @NotNull private static final List<SoftReference<DefracSdkData>> instances = Lists.newArrayList(); @NotNull public static final String FILE_SDK = DefracBundle.message("sdk.file.sdk"); @Nullable public static DefracSdkData getSdkData(@NotNull final File sdkLocation) { return getSdkData(sdkLocation, false); } @Nullable public static DefracSdkData getSdkData(@NotNull final File sdkLocation, final boolean forceReparse) { final File canonicalLocation = new File(FileUtil.toCanonicalPath(sdkLocation.getPath())); if(!forceReparse) { for(final Iterator<SoftReference<DefracSdkData>> iterator = instances.iterator(); iterator.hasNext();) { final DefracSdkData sdkData = iterator.next().get(); // Lazily remove stale soft references if(sdkData == null) { iterator.remove(); continue; } if(FileUtil.filesEqual(sdkData.getLocation(), canonicalLocation)) { return sdkData; } } } if(!DefracSdkUtil.isValidSdkHome(canonicalLocation)) { return null; } final DefracSdkData sdkData = new DefracSdkData(canonicalLocation); instances.add(0, new SoftReference<DefracSdkData>(sdkData)); return instances.get(0).get(); } @Nullable public static DefracSdkData getSdkData(@NotNull final String sdkPath) { final File file = new File(FileUtil.toSystemDependentName(sdkPath)); return getSdkData(file); } @Nullable public static DefracSdkData getSdkData(@NotNull final Sdk sdk) { final String sdkHomePath = sdk.getHomePath(); return sdkHomePath == null ? null : getSdkData(sdk.getHomePath()); } @Nullable public static DefracSdkData getSdkData(@NotNull final Project project) { final Sdk sdk = ProjectRootManager.getInstance(project).getProjectSdk(); return sdk == null ? null : getSdkData(sdk); } @Nullable public static DefracSdkData getSdkData(@NotNull final Module module) { return getSdkData(module.getProject()); } @NotNull private final File location; private DefracSdkData(@NotNull File location) { this.location = location; } @NotNull public File getLocation() { return location; } @NotNull public List<DefracVersion> getVersions() { final File sdk = new File(location, FILE_SDK); if(!sdk.isDirectory()) { return Collections.emptyList(); } final LinkedList<DefracVersion> versions = Lists.newLinkedList(); final File[] files = sdk.listFiles(); if(files == null) { return Collections.emptyList(); } for(final File file : files) { if(!file.isDirectory()) { continue; } versions.add(new DefracVersion(file.getName(), file)); } return versions; } }
defrac/defrac-plugin-intellij
src/defrac/intellij/sdk/DefracSdkData.java
Java
apache-2.0
4,029
/******************************************************************************* * Copyright (c) 2014 Chaupal. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0.html *******************************************************************************/ package net.jp2p.container.persistence; import net.jp2p.container.context.IJp2pServiceManager; public interface IContextFactory { public abstract void setManager( IJp2pServiceManager manager); }
chaupal/jp2p
Workspace/net.jp2p.container/src/net/jp2p/container/persistence/IContextFactory.java
Java
apache-2.0
660
/* * 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. */ package org.jclouds.blobstore; import static org.testng.Assert.assertEquals; import java.io.IOException; import javax.inject.Provider; import org.jclouds.apis.ApiMetadata; import org.jclouds.blobstore.config.LocalBlobStore; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.BlobBuilder; import org.jclouds.http.HttpRequest; import org.jclouds.rest.internal.BaseRestAnnotationProcessingTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import com.google.common.io.ByteSource; /** * Tests behavior of {@code LocalBlobRequestSigner} */ // NOTE:without testName, this will not call @Before* and fail w/NPE during surefire @Test(groups = "unit", testName = "TransientBlobRequestSignerTest") public class TransientBlobRequestSignerTest extends BaseRestAnnotationProcessingTest<LocalBlobStore> { private BlobRequestSigner signer; private Provider<BlobBuilder> blobFactory; private final String endpoint = new TransientApiMetadata().getDefaultEndpoint().get(); private final String containerName = "container"; private final String blobName = "blob"; private final String fullUrl = String.format("%s/%s/%s", endpoint, containerName, blobName); public void testSignGetBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, NoSuchMethodException, IOException { HttpRequest request = signer.signGetBlob(containerName, blobName); assertRequestLineEquals(request, "GET " + fullUrl + " HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n"); assertPayloadEquals(request, null, null, false); assertEquals(request.getFilters().size(), 0); } public void testSignRemoveBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, NoSuchMethodException, IOException { HttpRequest request = signer.signRemoveBlob(containerName, blobName); assertRequestLineEquals(request, "DELETE " + fullUrl + " HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n"); assertPayloadEquals(request, null, null, false); assertEquals(request.getFilters().size(), 0); } public void testSignPutBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, NoSuchMethodException, IOException { HashCode hashCode = HashCode.fromBytes(new byte[16]); Blob blob = blobFactory.get().name(blobName).forSigning().contentLength(2l).contentMD5(hashCode) .contentType("text/plain").build(); assertEquals(blob.getPayload().getContentMetadata().getContentMD5AsHashCode(), hashCode); HttpRequest request = signer.signPutBlob(containerName, blob); assertRequestLineEquals(request, "PUT " + fullUrl + " HTTP/1.1"); assertNonPayloadHeadersEqual( request, "Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n" + "Content-Length: 2\n" + "Content-MD5: AAAAAAAAAAAAAAAAAAAAAA==\n" + "Content-Type: text/plain\n"); assertContentHeadersEqual(request, "text/plain", null, null, null, 2L, hashCode.asBytes(), null); assertEquals(request.getFilters().size(), 0); } public void testSignPutBlobWithGenerate() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, NoSuchMethodException, IOException { ByteSource byteSource = ByteSource.wrap("foo".getBytes(Charsets.UTF_8)); Blob blob = blobFactory.get().name(blobName) .payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()) .contentType("text/plain").build(); byte[] md5 = { -84, -67, 24, -37, 76, -62, -8, 92, -19, -17, 101, 79, -52, -60, -92, -40 }; assertEquals(blob.getPayload().getContentMetadata().getContentMD5(), md5); HttpRequest request = signer.signPutBlob(containerName, blob); assertRequestLineEquals(request, "PUT " + fullUrl + " HTTP/1.1"); assertNonPayloadHeadersEqual( request, "Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\nContent-Length: 3\nContent-MD5: rL0Y20zC+Fzt72VPzMSk2A==\nContent-Type: text/plain\n"); assertContentHeadersEqual(request, "text/plain", null, null, null, 3L, md5, null); assertEquals(request.getFilters().size(), 0); } @BeforeClass protected void setupFactory() throws IOException { super.setupFactory(); this.blobFactory = injector.getProvider(BlobBuilder.class); this.signer = injector.getInstance(BlobRequestSigner.class); } @Override protected void checkFilters(HttpRequest request) { } @Override public ApiMetadata createApiMetadata() { return new TransientApiMetadata(); } }
yanzhijun/jclouds-aliyun
blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java
Java
apache-2.0
5,864
/* * Copyright: mperhez (2015) * License: The Apache Software License, Version 2.0 */ package org.mp.em4so.utils; /** * The Class GnutellaProtocol. */ public class GnutellaProtocol { }
uol-cs-multiot/em4so-java
core/src/main/java/org/mp/em4so/utils/GnutellaProtocol.java
Java
apache-2.0
192
# # Create tests for examples # if (BUILD_TESTING) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set(MyTests "") foreach(SOURCE_FILE ${ALL_FILES}) string(REPLACE ".cxx" "" TMP ${SOURCE_FILE}) string(REPLACE ${CMAKE_CURRENT_SOURCE_DIR}/ "" EXAMPLE ${TMP}) list(FIND EXCLUDE_TEST ${EXAMPLE} EXCLUDED) set(MyTests ${MyTests} Test${EXAMPLE}.cxx) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/Test${EXAMPLE}.cxx "#define main Test${EXAMPLE}\n#include \"${EXAMPLE}.cxx\"\n") if(EXCLUDED EQUAL -1) list(FIND NEEDS_ARGS ${EXAMPLE} SKIP_ADD) if(SKIP_ADD EQUAL -1) add_test(${KIT}-${EXAMPLE} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${KIT}CxxTests Test${EXAMPLE}) endif() set_property(TEST ${KIT}-${EXAMPLE} PROPERTY LABELS WikiExamples) endif() endforeach() set(VTK_BINARY_DIR ${WikiExamples_BINARY_DIR}) set(VTK_DATA_ROOT ${WikiExamples_SOURCE_DIR}/src/Testing) include(${WikiExamples_SOURCE_DIR}/CMake/vtkTestingObjectFactory.cmake) add_executable(${KIT}CxxTests ${KIT}CxxTests.cxx ${MyTests}) target_link_libraries(${KIT}CxxTests ${KIT_LIBS}) if (VTK_VERSION VERSION_GREATER "8.8") vtk_module_autoinit( TARGETS ${KIT}CxxTests MODULES ${VTK_LIBRARIES} ) endif() endif()
lorensen/VTKExamples
CMake/ExamplesTesting.cmake
CMake
apache-2.0
1,220
<?php /* =========================================================================== * File generated automatically by nabu-3. * You can modify this file if you need to add more functionalities. * --------------------------------------------------------------------------- * Created: 2019/10/10 11:56:23 UTC * =========================================================================== * Copyright 2009-2011 Rafael Gutierrez Martinez * Copyright 2012-2013 Welma WEB MKT LABS, S.L. * Copyright 2014-2016 Where Ideas Simply Come True, S.L. * Copyright 2017-2019 nabu-3 Group * * 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. */ namespace nabu\data\messaging\base; use \nabu\core\CNabuEngine; use \nabu\data\CNabuDataObjectList; use \nabu\data\messaging\CNabuMessagingServiceTemplate; /** * Class to manage a list of Messaging Service Template instances. * @author Rafael Gutiérrez <[email protected]> * @version 3.0.12 Surface * @package \nabu\data\messaging\base */ abstract class CNabuMessagingServiceTemplateListBase extends CNabuDataObjectList { /** * Instantiates the class. */ public function __construct() { parent::__construct('nb_messaging_template_id'); } /** * Creates alternate indexes for this list. */ protected function createSecondaryIndexes() { } /** * Acquires an instance of class CNabuMessagingServiceTemplate from the database. * @param string $key Id or reference field in the instance to acquire. * @param string $index Secondary index to be used if needed. * @return mixed Returns the unserialized instance if exists or false if not. */ public function acquireItem($key, $index = false) { $retval = false; if ($index === false && CNabuEngine::getEngine()->isMainDBAvailable()) { $item = new CNabuMessagingServiceTemplate($key); if ($item->isFetched()) { $retval = $item; } } return $retval; } }
nabu-3/core
nabu/data/messaging/base/CNabuMessagingServiceTemplateListBase.php
PHP
apache-2.0
2,556
package unix import ( "bufio" "fmt" "net" "os" "syscall" ) func debugCheckpoint(msg string, args ...interface{}) { if os.Getenv("DEBUG") == "" { return } os.Stdout.Sync() tty, _ := os.OpenFile("/dev/tty", os.O_RDWR, 0700) fmt.Fprintf(tty, msg, args...) bufio.NewScanner(tty).Scan() tty.Close() } type UnixConn struct { *net.UnixConn fds []*os.File } // Framing: // In order to handle framing in Send/Recieve, as these give frame // boundaries we use a very simple 4 bytes header. It is a big endiand // uint32 where the high bit is set if the message includes a file // descriptor. The rest of the uint32 is the length of the next frame. // We need the bit in order to be able to assign recieved fds to // the right message, as multiple messages may be coalesced into // a single recieve operation. func makeHeader(data []byte, fds []int) ([]byte, error) { header := make([]byte, 4) length := uint32(len(data)) if length > 0x7fffffff { return nil, fmt.Errorf("Data to large") } if len(fds) != 0 { length = length | 0x80000000 } header[0] = byte((length >> 24) & 0xff) header[1] = byte((length >> 16) & 0xff) header[2] = byte((length >> 8) & 0xff) header[3] = byte((length >> 0) & 0xff) return header, nil } func parseHeader(header []byte) (uint32, bool) { length := uint32(header[0])<<24 | uint32(header[1])<<16 | uint32(header[2])<<8 | uint32(header[3]) hasFd := length&0x80000000 != 0 length = length & ^uint32(0x80000000) return length, hasFd } func FileConn(f *os.File) (*UnixConn, error) { conn, err := net.FileConn(f) if err != nil { return nil, err } uconn, ok := conn.(*net.UnixConn) if !ok { conn.Close() return nil, fmt.Errorf("%d: not a unix connection", f.Fd()) } return &UnixConn{UnixConn: uconn}, nil } // Send sends a new message on conn with data and f as payload and // attachment, respectively. // On success, f is closed func (conn *UnixConn) Send(data []byte, f *os.File) error { { var fd int = -1 if f != nil { fd = int(f.Fd()) } debugCheckpoint("===DEBUG=== about to send '%s'[%d]. Hit enter to confirm: ", data, fd) } var fds []int if f != nil { fds = append(fds, int(f.Fd())) } if err := conn.sendUnix(data, fds...); err != nil { return err } if f != nil { f.Close() } return nil } // Receive waits for a new message on conn, and receives its payload // and attachment, or an error if any. // // If more than 1 file descriptor is sent in the message, they are all // closed except for the first, which is the attachment. // It is legal for a message to have no attachment or an empty payload. func (conn *UnixConn) Receive() (rdata []byte, rf *os.File, rerr error) { defer func() { var fd int = -1 if rf != nil { fd = int(rf.Fd()) } debugCheckpoint("===DEBUG=== Receive() -> '%s'[%d]. Hit enter to continue.\n", rdata, fd) }() // Read header header := make([]byte, 4) nRead := uint32(0) for nRead < 4 { n, err := conn.receiveUnix(header[nRead:]) if err != nil { return nil, nil, err } nRead = nRead + uint32(n) } length, hasFd := parseHeader(header) if hasFd { if len(conn.fds) == 0 { return nil, nil, fmt.Errorf("No expected file descriptor in message") } rf = conn.fds[0] conn.fds = conn.fds[1:] } rdata = make([]byte, length) nRead = 0 for nRead < length { n, err := conn.receiveUnix(rdata[nRead:]) if err != nil { return nil, nil, err } nRead = nRead + uint32(n) } return } func (conn *UnixConn) receiveUnix(buf []byte) (int, error) { oob := make([]byte, syscall.CmsgSpace(4)) bufn, oobn, _, _, err := conn.ReadMsgUnix(buf, oob) if err != nil { return 0, err } fd := extractFd(oob[:oobn]) if fd != -1 { f := os.NewFile(uintptr(fd), "") conn.fds = append(conn.fds, f) } return bufn, nil } func (conn *UnixConn) sendUnix(data []byte, fds ...int) error { header, err := makeHeader(data, fds) if err != nil { return err } // There is a bug in conn.WriteMsgUnix where it doesn't correctly return // the number of bytes writte (http://code.google.com/p/go/issues/detail?id=7645) // So, we can't rely on the return value from it. However, we must use it to // send the fds. In order to handle this we only write one byte using WriteMsgUnix // (when we have to), as that can only ever block or fully suceed. We then write // the rest with conn.Write() // The reader side should not rely on this though, as hopefully this gets fixed // in go later. written := 0 if len(fds) != 0 { oob := syscall.UnixRights(fds...) wrote, _, err := conn.WriteMsgUnix(header[0:1], oob, nil) if err != nil { return err } written = written + wrote } for written < len(header) { wrote, err := conn.Write(header[written:]) if err != nil { return err } written = written + wrote } written = 0 for written < len(data) { wrote, err := conn.Write(data[written:]) if err != nil { return err } written = written + wrote } return nil } func extractFd(oob []byte) int { // Grab forklock to make sure no forks accidentally inherit the new // fds before they are made CLOEXEC // There is a slight race condition between ReadMsgUnix returns and // when we grap the lock, so this is not perfect. Unfortunately // There is no way to pass MSG_CMSG_CLOEXEC to recvmsg() nor any // way to implement non-blocking i/o in go, so this is hard to fix. syscall.ForkLock.Lock() defer syscall.ForkLock.Unlock() scms, err := syscall.ParseSocketControlMessage(oob) if err != nil { return -1 } foundFd := -1 for _, scm := range scms { fds, err := syscall.ParseUnixRights(&scm) if err != nil { continue } for _, fd := range fds { if foundFd == -1 { syscall.CloseOnExec(fd) foundFd = fd } else { syscall.Close(fd) } } } return foundFd } func socketpair() ([2]int, error) { return syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM|syscall.FD_CLOEXEC, 0) } // SocketPair is a convenience wrapper around the socketpair(2) syscall. // It returns a unix socket of type SOCK_STREAM in the form of 2 file descriptors // not bound to the underlying filesystem. // Messages sent on one end are received on the other, and vice-versa. // It is the caller's responsibility to close both ends. func SocketPair() (a *os.File, b *os.File, err error) { defer func() { var ( fdA int = -1 fdB int = -1 ) if a != nil { fdA = int(a.Fd()) } if b != nil { fdB = int(b.Fd()) } debugCheckpoint("===DEBUG=== SocketPair() = [%d-%d]. Hit enter to confirm: ", fdA, fdB) }() pair, err := socketpair() if err != nil { return nil, nil, err } return os.NewFile(uintptr(pair[0]), ""), os.NewFile(uintptr(pair[1]), ""), nil } func USocketPair() (*UnixConn, *UnixConn, error) { debugCheckpoint("===DEBUG=== USocketPair(). Hit enter to confirm: ") defer debugCheckpoint("===DEBUG=== USocketPair() returned. Hit enter to confirm ") a, b, err := SocketPair() if err != nil { return nil, nil, err } defer a.Close() defer b.Close() uA, err := FileConn(a) if err != nil { return nil, nil, err } uB, err := FileConn(b) if err != nil { uA.Close() return nil, nil, err } return uA, uB, nil } // FdConn wraps a file descriptor in a standard *net.UnixConn object, or // returns an error if the file descriptor does not point to a unix socket. // This creates a duplicate file descriptor. It's the caller's responsibility // to close both. func FdConn(fd int) (n *net.UnixConn, err error) { { debugCheckpoint("===DEBUG=== FdConn([%d]) = (unknown fd). Hit enter to confirm: ", fd) } f := os.NewFile(uintptr(fd), fmt.Sprintf("%d", fd)) conn, err := net.FileConn(f) if err != nil { return nil, err } uconn, ok := conn.(*net.UnixConn) if !ok { conn.Close() return nil, fmt.Errorf("%d: not a unix connection", fd) } return uconn, nil }
philips/libswarm2
beam/unix/unix.go
GO
apache-2.0
7,828
/** * Copyright 2020 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. */ export * from './conversation' export * from './conv' export * from './prompt'
actions-on-google/assistant-conversation-nodejs
src/conversation/index.ts
TypeScript
apache-2.0
674
/* * Copyright 2016 Jspare.org. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.jspare.vertx.web.annotation.subrouter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.jspare.vertx.web.handler.APIHandler; import io.vertx.ext.web.Router; /** * The Namespace Annotation. * * <p> * The namespace module is used for mapping one namespace of one * {@link APIHandler}. When one type are annotated with this module and * registered on {@link Router} when your HttpServer will be started your * mappings will be registered with prefix defined on value field, if your field * are empty the convention that follow will be used: * * <br> * [Prefix]Controller: [prefix]/[your mapping] <b>e.g: UsersController: * users/</b> * </p> * * @author <a href="https://pflima92.github.io/">Paulo Lima</a> * @since 30/03/2016 */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE }) public @interface SubRouter { /** * Value. * * @return the string */ String value(); }
jspare-projects/vertx-jspare
vertx-jspare-web/src/main/java/org/jspare/vertx/web/annotation/subrouter/SubRouter.java
Java
apache-2.0
1,643
--- layout: post title: 기레기들과의 전면전이다. author: drkim date: 2017-12-15 15:49:57 +0900 tags: [컬럼] --- 기레기들과의 전면전이다. http://v.media.daum.net/v/20171215043107283?d=y 머니투데이가 보수살리기 기사를 시리즈로 내니까 시사저널은 또 장하성을 어찌할꼬, 낙하산을 어찌할꼬 하며 문재인흔들기 시리즈로 받는다. JTBC의 삐딱선 타기는 대선 직후부터다. 미국과 중국에서 연거푸 난동을 부리질 않나. 요즘 기레기들 하는 짓 보면 아주 작당을 한 거다. 한경오든 조중동이든 닥치는대로 때려잡아야 한다. 위엄으로 통치해야 한다. 우리를 만만하게 보고 기어오르는 거다. 간단하다. 권력서열이다. 이건 원시의 본능이다. 진보니 보수니 하는 건 가져다붙인 말이고 본질은 침팬지의 권력행동이다. 말 안 통한다. 군기잡아야 한다. 우리편 언론의 활약을 기대할 수는 없고 우리 스스로가 대체재가 되어야 한다. SNS 대 언론의 전면전이다. 일전에 말한대로 문예사조가 고전주의에서 낭만주의로 틀었다가 리얼리즘으로 수렴되는 이치와 같다. 봉건시대에는 지식인과 무식인의 수준차가 컸다. 그때는 시키는대로 해야 했다. 스승의 그림자도 못 밟던 시절이다. 점차 학문이 발달하여 지식의 격차가 좁혀진다. 식민지에서 황금을 약탈해온 깡패들이 득세하는 시대가 된다. 학문의 권위가 떨어진다. 이에 낭만주의가 요구된다. 인간에서 답을 찾는다. 그러다가 최종단계는 리얼리즘으로 수렴된다. 신의 질서에서 답을 찾다가 안 되니까 인간의 내면에서 답을 찾다가 다시 자연의 사실로 돌아가는게 리얼리즘이다. 이념도 이와 같다. 노무현은 리얼리즘이다. 이념이 별건가? 야 가자! 하고 부르면 이념이다. 요즘 고딩들이 비트코인갤러리에서 가즈아~ 하고 동료를 꼬신다는데 그런 게 이념이다. 가즈아~ 어디로 갈까? 전쟁터로 갈까? 은행털러 갈까? 자유 평등 평화로 갈까? 그건 중요한 게 아니다. 과연 갈 수 있는가이다. 봉건시대 농노들은 거주이전의 자유가 없었다. 일본은 사무라이라도 봉건영주가 다스리는 번을 벗어날 수 없었다. 다이묘에게 억압받다가 탈번한 자들이 변혁을 일으켰다. 탈주를 일으켜야 한다. 그런데 갈 수 있는가? 타고갈 배는 있고? 여자도 갈 수 있고 흑인도 갈 수 있고 누구나 갈 수 있나? 처음에는 어디로 갈 지를 논한다. 천국에 가자. 거길 왜 가? 깨달음으로 가자. 난 안 갈래. 자유평등평화로 가자. 너나 가라고. 이걸로 하루종일 논쟁한다. 왜? 어차피 못 가니깐. 그러다가 슬슬 희망이 보인다. 갈 수 있다. 이때는사람이 문제로 된다. 모두 갈 수는 없다. 남자만 가자. 경상도만 가자. 흑인도 가야 한다. 여자는 따로 가자. 진보니 보수니 하는 게 그렇다. 가즈아~ 어디로 가는가? 왕들은 옛날부터 가 있었다. 그다음은 귀족이 가고 다음은 부르주아가 간다. 다 함께는 못 간다. 100명이 있는데 승차정원에 걸려 50명만 갈 수 있다면? 성적순으로 짜르자. 공부잘하는 넘이다. 피부색으로 짜르자. 백인이다. 성별로 짜르자. 남자 혹은 여자다. 키 순서로 짜르자. 롱다리다. 이런 짓을 하는 게 보수다. 이들은 가즈아~ 를 외쳐 이념인 척하지만 뒤에 슬그머니 '우리만'을 붙인다. 쟤네들 빼고.우리끼리 몰래 가자. 이런 수법 먹힌다.문제는 이게 이념이 아니라는 거다. 이념은 '가자!' 이지 '쟤는 빼라!'가 아니다. 그런데 이념도 아니면서 이념인 척한다. 대개 지역주의로 가서 우리지역만 가자. 예산빼먹기다. 기독교만 가자. 종교집단이다. 우리민족만 가자. 민족주의다. 이념인 척하지만 가짜다. 진실을 말하자. 최종적으로 이동수단이 문제로 된다. 말이 있어야 말 타고 간다.배가 있어야 배 타고 가고 자동차가 있어야 차 타고 간다. 지금은 인터넷시대라 네트워크를 타고 간다. 리얼리즘은 그 자동차를 조직하고 배를 건조하는 것이다. 이건 옳고 그름의 문제가 아니다. 현실성의 문제다. 그럴 때가 된 것이다. 그래서? 문재인은 다르다. 지금 보수와 기레기들은 당황해하고 있다. 과거의 낡은 진보와 문재인 진보가 다르기 때문이다.과거의 진보는 어디를 가느냐가 중요했다. 천국에 가자. 지옥에 가자. 평화로 가자. 평등으로 가자. 목적지가 중요했다. 왜냐면 어차피 갈 수 없기 때문에. 본질은 권력이다. 차가 있으면 자연히 운전수의 권력이 생긴다. 누가 강제로 안 시켜도 다들 얌전하게 버스 앞에 줄을 선다. 차도 없으면서 패거리 조직하고 권력을 휘둘러 억지로 사람을 줄 세우려 하니 공허한 노선타령이 된다.차라고는 한 대도 오지 않는 허허벌판에 아무데나 표시를 해서 깃발을 꽂아놓고. 여기다 줄을 서보라고. 아냐 난 여기에 설래. 니가 내 뒤에 와서 서라니깐. 공허한 줄 세우기 논쟁은 끝나지 않는다. 가짜 진보의 참담함 모습이다. 낡은 보수는 누군가를 빼려고만 한다. 여자는 빼고 가자고. 부자는 무상급식에서 빼고 가자고. 흑인은 빼고 가자고. 이게 먹혔다. 누군가는 빠져야 한다면 누구를 빼지? 약자를 빼는 게 보수다. 이게 이념인가? 아니다. 권력욕이다. 보수이념 같은 건 원리적으로 없다. 우주 안에 없다. 가짜 진보의 삽질 덕에 보수가 이념처럼 보인 거다. 문재인은 차를 바꿔 승차정원을 늘렸다. 완전히 다른 게임이 시작된다. 이것이 리얼리즘이다. 무엇인가? 80년대 이념과잉의 시대는 사실이지 지식과 비지식의 격차에서 비롯된 것이다. 그때 한국 성인의 평균학력이 중 2였다. 그래서 그런 것이 먹혔다. 그러다가 한국이 조금 먹고살게 되자 자기만 먹겠다는 일베충들이 나타났다. 가짜 진보 – 지식과 비지식의 격차가 클 때, 현실적인 수단의 제시는 없이 막연히 어디론가 가자고 한다. 본질은 권력만들기, 집단 내부의 서열 정하기다. 인위적인 서열만들기는 실패한다. 가짜 보수 – 예산따먹기로 가자. 지역주의로 가자. 종교집단으로 가자. 군부체제로 가자. 민족주의로 가자. 인종차별로 가자. 이걸 이념으로 포장한다. 누구를 배제하고 독식하려는 욕심이다. 진짜 진보 – 산업의 발전과 연계하여 인류가 하나의 단일한 의사결정단위로 작동하도록 통합을 유도한다. 경제환경의 실질적 변화를 디딤돌로 삼아 사회의 의사결정구조 변화를 추동한다. 진짜 보수 – 그런 거 없다. 진짜 진보가 좋은 것을 성취하면 사실은 그게 내 생각이었어 하고 뒷북친다. 가짜 보수를 가려내는 수단으로만 사용된다. 모든 보수는 가짜고 일부 진보만 진짜다. 세상은 단순하다. 권력이다. 새로운 권력을 조직하는 게 진보이고 있는 권력을 휘두르는 게 보수다. 이념은 권력의 조직을 위해 사람을 동원하는 것이고 이는 진보에만 해당되며 보수는 해당사항 없다. 가짜 진보는 권력장악을 목적으로 진보장사를 하는 것이고 억지로 사람을 동원하려고 한다. 타고 갈 마차도 준비하지 않고 말이다. 보수주의는 사실 지역주의라든가, 종교집단이라든가, 군벌세력이라든가, 관료집단이라든가, 민족주의라든가 이런 거다. 잡다한 세력이 모여있으며 구체적인 이념이나 공통분모는 없다. 현실에 권력이 존재하는 한 보수는 사라지지 않는다. 진보가 잘하면 보수가 따라붙기 때문이다. 노무현이 해낸 것을 이명박도 할 수 있다고 믿는다. 흑인 오바마가 잘하니까 백인도 그걸 해보고 싶어서 트럼프 찍었다. 진보는 이념이 있고 보수는 현실이 있으며 진짜 진보는 그 현실을 변화시킨다. 진보는 진짜와 가짜고 있고 보수는 가짜만 있다. 보수이념은 없으며 이념이라 주장되는 것은 예산빼먹기 지역세력, 군벌세력, 종교세력, 재벌세력이 정체를 숨기려고 꾸며낸 거짓이다. 진짜 보수정당을 하고 싶으면 솔직하게 지역당, 민족당, 백인당, 남자당, 여자당, 종교당, 재벌당, 군부당을 하면 된다. 이들은 보수주의가 아니라 그냥 기득권 텃세조합일 뿐이다. 특권집단의 텃세나 행패를 이념이라고 부르면 안 된다. 그런 거 없다. 보수기질이나 '보수적'인 스타일은 있지만 보수이념은 원래 없다. 진보의 찌꺼기다. 세상은 변한다. 손해 보는 사람은 반드시 생긴다.자동차가 다니면 마차는 어쩌나? 전화가 되면 편지는 어쩌나?교육이 되면 교회는 어쩌나? 남북통일하면 군대는 어쩌나?이런 걸로 어거지 생떼에 찐따붙는 너절한 쓰레기들이 보수다. 이건 이념이 아니다. 진보는 그 자동차와 전화와 교육과 통일에 맞는 의사결정구조의 건설이다. ![](/files/attach/images/198/820/909/00.jpg)
gujoron/gujoron.github.io
_posts/2017-12-15-기레기들과의-전면전이다.md
Markdown
apache-2.0
9,900
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.service; import com.thoughtworks.go.config.BasicCruiseConfig; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.CruiseConfig; import com.thoughtworks.go.config.exceptions.BadRequestException; import com.thoughtworks.go.config.exceptions.NotAuthorizedException; import com.thoughtworks.go.config.exceptions.RecordNotFoundException; import com.thoughtworks.go.config.materials.MaterialConfigs; import com.thoughtworks.go.domain.*; import com.thoughtworks.go.domain.activity.JobStatusCache; import com.thoughtworks.go.helper.JobInstanceMother; import com.thoughtworks.go.helper.PipelineConfigMother; import com.thoughtworks.go.server.dao.FeedModifier; import com.thoughtworks.go.server.dao.JobInstanceDao; import com.thoughtworks.go.server.dao.StageDao; import com.thoughtworks.go.server.domain.JobStatusListener; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.messaging.JobResultMessage; import com.thoughtworks.go.server.messaging.JobResultTopic; import com.thoughtworks.go.server.service.result.HttpOperationResult; import com.thoughtworks.go.server.transaction.TestTransactionSynchronizationManager; import com.thoughtworks.go.server.transaction.TestTransactionTemplate; import com.thoughtworks.go.server.transaction.TransactionTemplate; import com.thoughtworks.go.server.ui.JobInstancesModel; import com.thoughtworks.go.server.ui.SortOrder; import com.thoughtworks.go.server.util.Pagination; import com.thoughtworks.go.serverhealth.HealthStateScope; import com.thoughtworks.go.serverhealth.HealthStateType; import com.thoughtworks.go.serverhealth.ServerHealthService; import com.thoughtworks.go.serverhealth.ServerHealthState; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.thoughtworks.go.helper.JobInstanceMother.completed; import static com.thoughtworks.go.helper.JobInstanceMother.scheduled; import static org.assertj.core.api.Assertions.assertThatCode; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; public class JobInstanceServiceTest { @Mock private JobInstanceDao jobInstanceDao; @Mock private JobResultTopic topic; @Mock private StageDao stageDao; @Mock private GoConfigService goConfigService; @Mock private CruiseConfig cruiseConfig; @Mock private SecurityService securityService; @Mock private ServerHealthService serverHealthService; private JobInstance job; private TestTransactionSynchronizationManager transactionSynchronizationManager; private TransactionTemplate transactionTemplate; private JobStatusCache jobStatusCache; @BeforeEach public void setUp() throws Exception { initMocks(this); job = JobInstanceMother.building("dev"); transactionSynchronizationManager = new TestTransactionSynchronizationManager(); transactionTemplate = new TestTransactionTemplate(transactionSynchronizationManager); jobStatusCache = new JobStatusCache(stageDao); } @AfterEach public void after() { Mockito.verifyNoMoreInteractions(jobInstanceDao, stageDao); } @Test public void shouldNotifyListenerWhenJobStatusChanged() throws Exception { final JobStatusListener listener = Mockito.mock(JobStatusListener.class); JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService, listener); jobService.updateStateAndResult(job); verify(jobInstanceDao).updateStateAndResult(job); verify(listener).jobStatusChanged(job); } @Test public void shouldNotifyAllListenersWhenUpdateJobStatus() throws Exception { final JobStatusListener listener1 = Mockito.mock(JobStatusListener.class, "listener1"); final JobStatusListener listener2 = Mockito.mock(JobStatusListener.class, "listener2"); JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService, listener1, listener2); jobService.updateStateAndResult(job); verify(jobInstanceDao).updateStateAndResult(job); verify(listener1).jobStatusChanged(job); verify(listener2).jobStatusChanged(job); } @Test public void shouldNotifyListenerWhenUpdateAssignedInfo() throws Exception { final JobStatusListener listener1 = Mockito.mock(JobStatusListener.class, "listener1"); final JobStatusListener listener2 = Mockito.mock(JobStatusListener.class, "listener2"); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService, listener1, listener2); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jobService.updateAssignedInfo(job); } }); verify(listener1).jobStatusChanged(job); verify(listener2).jobStatusChanged(job); verify(jobInstanceDao).updateAssignedInfo(job); } @Test public void shouldNotifyAllListenersWhenSaveJob() throws Exception { final JobStatusListener listener1 = Mockito.mock(JobStatusListener.class, "listener1"); final JobStatusListener listener2 = Mockito.mock(JobStatusListener.class, "listener2"); final Pipeline pipeline = new NullPipeline(); final Stage stage = new Stage(); stage.setId(1); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService, listener1, listener2); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { jobService.save(new StageIdentifier(pipeline.getName(), null, pipeline.getLabel(), stage.getName(), String.valueOf(stage.getCounter())), stage.getId(), job); } }); verify(jobInstanceDao).save(1l, job); verify(listener1).jobStatusChanged(job); verify(listener2).jobStatusChanged(job); } @Test public void shouldIgnoreErrorsWhenNotifyingListenersDuringSave() throws Exception { final JobStatusListener failingListener = Mockito.mock(JobStatusListener.class, "listener1"); final JobStatusListener passingListener = Mockito.mock(JobStatusListener.class, "listener2"); doThrow(new RuntimeException("Should not be rethrown by save")).when(failingListener).jobStatusChanged(job); final Pipeline pipeline = new NullPipeline(); final Stage stage = new Stage(); stage.setId(1); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService, failingListener, passingListener); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { jobService.save(new StageIdentifier(pipeline.getName(), null, pipeline.getLabel(), stage.getName(), String.valueOf(stage.getCounter())), stage.getId(), job); } }); verify(jobInstanceDao).save(1l, job); verify(passingListener).jobStatusChanged(job); } @Test public void shouldNotifyListenersWhenAssignedJobIsCancelled() { final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); job.setAgentUuid("dummy agent"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jobService.cancelJob(job); } }); verify(jobInstanceDao).updateStateAndResult(job); verify(topic).post(new JobResultMessage(job.getIdentifier(), JobResult.Cancelled, job.getAgentUuid())); } @Test public void shouldNotNotifyListenersWhenScheduledJobIsCancelled() { final JobInstance scheduledJob = scheduled("dev"); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jobService.cancelJob(scheduledJob); } }); jobService.cancelJob(scheduledJob); verify(jobInstanceDao).updateStateAndResult(scheduledJob); verify(topic, never()).post(any(JobResultMessage.class)); } @Test public void shouldNotNotifyListenersWhenACompletedJobIsCancelled() { final JobInstance completedJob = completed("dev"); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jobService.cancelJob(completedJob); } }); jobService.cancelJob(completedJob); verify(jobInstanceDao, never()).updateStateAndResult(completedJob); verify(topic, never()).post(any(JobResultMessage.class)); } @Test public void shouldNotNotifyListenersWhenAssignedJobCancellationTransactionRollsback() { final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); job.setAgentUuid("dummy agent"); try { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jobService.cancelJob(job); throw new RuntimeException("to rollback txn"); } }); } catch (RuntimeException e) { //ignore } verify(jobInstanceDao).updateStateAndResult(job); verify(topic, never()).post(any(JobResultMessage.class)); } @Test public void shouldNotNotifyListenersWhenScheduledJobIsFailed() { final JobInstance scheduledJob = scheduled("dev"); scheduledJob.setId(10); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); when(jobInstanceDao.buildByIdWithTransitions(scheduledJob.getId())).thenReturn(scheduledJob); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { JobInstance jobInstance = jobService.buildByIdWithTransitions(scheduledJob.getId()); jobService.failJob(jobInstance); } }); verify(jobInstanceDao).buildByIdWithTransitions(scheduledJob.getId()); verify(jobInstanceDao).updateStateAndResult(scheduledJob); assertThat(scheduledJob.isFailed(), is(true)); } @Test public void shouldDelegateToDAO_getJobHistoryCount() { final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); jobService.getJobHistoryCount("pipeline", "stage", "job"); verify(jobInstanceDao).getJobHistoryCount("pipeline", "stage", "job"); } @Test public void shouldDelegateToDAO_findJobHistoryPage() { when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString("pipeline"))).thenReturn(true); when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(securityService.hasViewPermissionForPipeline(Username.valueOf("looser"), "pipeline")).thenReturn(true); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, securityService, serverHealthService); Pagination pagination = Pagination.pageStartingAt(1, 1, 1); jobService.findJobHistoryPage("pipeline", "stage", "job", pagination, "looser", new HttpOperationResult()); verify(jobInstanceDao).findJobHistoryPage("pipeline", "stage", "job", pagination.getPageSize(), pagination.getOffset()); } @Test public void shouldPopulateErrorWhenPipelineNotFound_findJobHistoryPage() { when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString("pipeline"))).thenReturn(false); when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(securityService.hasViewPermissionForPipeline(Username.valueOf("looser"), "pipeline")).thenReturn(true); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, securityService, serverHealthService); Pagination pagination = Pagination.pageStartingAt(1, 1, 1); HttpOperationResult result = new HttpOperationResult(); JobInstances jobHistoryPage = jobService.findJobHistoryPage("pipeline", "stage", "job", pagination, "looser", result); assertThat(jobHistoryPage, is(nullValue())); assertThat(result.httpCode(), is(404)); } @Test public void shouldPopulateErrorWhenUnauthorized_findJobHistoryPage() { when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString("pipeline"))).thenReturn(true); when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(securityService.hasViewPermissionForPipeline(Username.valueOf("looser"), "pipeline")).thenReturn(false); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, securityService, serverHealthService); Pagination pagination = Pagination.pageStartingAt(1, 1, 1); HttpOperationResult result = new HttpOperationResult(); JobInstances jobHistoryPage = jobService.findJobHistoryPage("pipeline", "stage", "job", pagination, "looser", result); assertThat(jobHistoryPage, is(nullValue())); assertThat(result.canContinue(), is(false)); } @Test public void shouldLoadOriginalJobPlan() { JobResolverService resolver = mock(JobResolverService.class); final JobInstanceService jobService = new JobInstanceService(jobInstanceDao, topic, jobStatusCache, transactionTemplate, transactionSynchronizationManager, resolver, null, goConfigService, null, serverHealthService); DefaultJobPlan expectedPlan = new DefaultJobPlan(new Resources(), new ArrayList<>(), 7, new JobIdentifier(), null, new EnvironmentVariables(), new EnvironmentVariables(), null, null); when(jobInstanceDao.loadPlan(7l)).thenReturn(expectedPlan); JobIdentifier givenId = new JobIdentifier("pipeline-name", 9, "label-9", "stage-name", "2", "job-name", 10l); when(resolver.actualJobIdentifier(givenId)).thenReturn(new JobIdentifier("pipeline-name", 8, "label-8", "stage-name", "1", "job-name", 7l)); assertThat(jobService.loadOriginalJobPlan(givenId), sameInstance(expectedPlan)); verify(jobInstanceDao).loadPlan(7l); } @Test public void shouldRegisterANewListener() throws SQLException { JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); JobStatusListener listener = mock(JobStatusListener.class); jobService.registerJobStateChangeListener(listener); jobService.updateStateAndResult(job); verify(jobInstanceDao).updateStateAndResult(job); verify(listener).jobStatusChanged(job); } @Test public void shouldGetCompletedJobsOnAgentOnTheGivenPage() { JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); ArrayList<JobInstance> expected = new ArrayList<>(); when(jobInstanceDao.totalCompletedJobsOnAgent("uuid")).thenReturn(500); when(jobInstanceDao.completedJobsOnAgent("uuid", JobInstanceService.JobHistoryColumns.pipeline, SortOrder.ASC, 50, 50)).thenReturn(expected); JobInstancesModel actualModel = jobService.completedJobsOnAgent("uuid", JobInstanceService.JobHistoryColumns.pipeline, SortOrder.ASC, 2, 50); assertThat(actualModel, is(new JobInstancesModel(new JobInstances(expected), Pagination.pageByNumber(2, 500, 50)))); verify(jobInstanceDao).totalCompletedJobsOnAgent("uuid"); verify(jobInstanceDao).completedJobsOnAgent("uuid", JobInstanceService.JobHistoryColumns.pipeline, SortOrder.ASC, 50, 50); } @Test public void shouldRemoveJobRelatedServerHealthMessagesOnConfigChange() { ServerHealthService serverHealthService = new ServerHealthService(); serverHealthService.update(ServerHealthState.error("message", "description", HealthStateType.general(HealthStateScope.forJob("p1", "s1", "j1")))); serverHealthService.update(ServerHealthState.error("message", "description", HealthStateType.general(HealthStateScope.forJob("p2", "s2", "j2")))); assertThat(serverHealthService.logs().errorCount(), is(2)); JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); jobService.onConfigChange(new BasicCruiseConfig()); assertThat(serverHealthService.logs().errorCount(), is(0)); } @Test public void shouldRemoveJobRelatedServerHealthMessagesOnPipelineConfigChange() { ServerHealthService serverHealthService = new ServerHealthService(); serverHealthService.update(ServerHealthState.error("message", "description", HealthStateType.general(HealthStateScope.forJob("p1", "s1", "j1")))); serverHealthService.update(ServerHealthState.error("message", "description", HealthStateType.general(HealthStateScope.forJob("p2", "s2", "j2")))); assertThat(serverHealthService.logs().errorCount(), is(2)); JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); JobInstanceService.PipelineConfigChangedListener pipelineConfigChangedListener = jobService.new PipelineConfigChangedListener(); pipelineConfigChangedListener.onEntityConfigChange(PipelineConfigMother.pipelineConfig("p1", "s_new", new MaterialConfigs(), "j1")); assertThat(serverHealthService.logs().errorCount(), is(1)); assertThat(serverHealthService.logs().get(0).getType().getScope().getScope(), is("p2/s2/j2")); } @Test public void shouldGetRunningJobsFromJobInstanceDao() { List<JobInstance> expectedRunningJobs = Arrays.asList(job); when(jobInstanceDao.getRunningJobs()).thenReturn(expectedRunningJobs); JobInstanceService jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); List<JobInstance> jobInstances = jobService.allRunningJobs(); assertThat(jobInstances, is(expectedRunningJobs)); verify(jobInstanceDao).getRunningJobs(); } @Test void shouldThrowExceptionIfPipelineDoesNotExistForJobInstance() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString("pipeline"))).thenReturn(false); JobInstanceService jobInstanceService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, null, serverHealthService); assertThatCode(() -> jobInstanceService.findJobInstance("pipeline", "stage", "job", 1, 1, new Username("admin"))) .isInstanceOf(RecordNotFoundException.class) .hasMessage("Pipeline with name 'pipeline' was not found!"); } @Test void shouldThrowExceptionIfTheUserDoesNotHaveAccessToViewPipelineForJobInstance() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString("pipeline"))).thenReturn(true); when(securityService.hasViewPermissionForPipeline(Username.valueOf("user"), "pipeline")).thenReturn(false); JobInstanceService jobInstanceService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, securityService, serverHealthService); assertThatCode(() -> jobInstanceService.findJobInstance("pipeline", "stage", "job", 1, 1, new Username("user"))) .isInstanceOf(NotAuthorizedException.class) .hasMessage("Not authorized to view pipeline"); } @Nested class JobHistoryViaCursor { private JobInstanceService jobService; ; private Username username = Username.valueOf("user"); String pipelineName = "pipeline"; String stageName = "stage"; String jobConfigName = "job"; @BeforeEach void setUp() { jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, securityService, serverHealthService); } @Test void shouldFetchLatestRecords() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipelineName))).thenReturn(true); when(securityService.hasViewPermissionForPipeline(username, pipelineName)).thenReturn(true); jobService.getJobHistoryViaCursor(username, pipelineName, stageName, jobConfigName, 0, 0, 10); verify(jobInstanceDao).findDetailedJobHistoryViaCursor(pipelineName, stageName, jobConfigName, FeedModifier.Latest, 0, 10); } @Test void shouldFetchRecordsAfterTheSpecifiedCursor() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipelineName))).thenReturn(true); when(securityService.hasViewPermissionForPipeline(username, pipelineName)).thenReturn(true); jobService.getJobHistoryViaCursor(username, pipelineName, stageName, jobConfigName, 2, 0, 10); verify(jobInstanceDao).findDetailedJobHistoryViaCursor(pipelineName, stageName, jobConfigName, FeedModifier.After, 2, 10); } @Test void shouldFetchRecordsBeforeTheSpecifiedCursor() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipelineName))).thenReturn(true); when(securityService.hasViewPermissionForPipeline(username, pipelineName)).thenReturn(true); jobService.getJobHistoryViaCursor(username, pipelineName, stageName, jobConfigName, 0, 2, 10); verify(jobInstanceDao).findDetailedJobHistoryViaCursor(pipelineName, stageName, jobConfigName, FeedModifier.Before, 2, 10); } @Test void shouldThrowErrorIfPipelineDoesNotExist() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); assertThatCode(() -> jobService.getJobHistoryViaCursor(username, pipelineName, stageName, jobConfigName, 0, 0, 10)) .isInstanceOf(RecordNotFoundException.class) .hasMessage("Pipeline with name 'pipeline' was not found!"); } @Test void shouldThrowErrorIfUserDoesNotHaveAccessRights() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipelineName))).thenReturn(true); assertThatCode(() -> jobService.getJobHistoryViaCursor(username, pipelineName, stageName, jobConfigName, 0, 0, 10)) .isInstanceOf(NotAuthorizedException.class) .hasMessage("User 'user' does not have permission to view pipeline with name 'pipeline'"); } @Test void shouldThrowErrorIfCursorIsANegativeInteger() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipelineName))).thenReturn(true); when(securityService.hasViewPermissionForPipeline(username, pipelineName)).thenReturn(true); assertThatCode(() -> jobService.getJobHistoryViaCursor(username, pipelineName, stageName, jobConfigName, -10, 0, 10)) .isInstanceOf(BadRequestException.class) .hasMessage("The query parameter 'after', if specified, must be a positive integer."); assertThatCode(() -> jobService.getJobHistoryViaCursor(username, pipelineName, stageName, jobConfigName, 0, -10, 10)) .isInstanceOf(BadRequestException.class) .hasMessage("The query parameter 'before', if specified, must be a positive integer."); } } @Nested class LatestAndOldestStageInstanceId { private JobInstanceService jobService; private Username username = Username.valueOf("user"); String pipelineName = "pipeline"; String stageName = "stage"; String jobConfigName = "job"; @BeforeEach void setUp() { jobService = new JobInstanceService(jobInstanceDao, null, jobStatusCache, transactionTemplate, transactionSynchronizationManager, null, null, goConfigService, securityService, serverHealthService); } @Test void shouldReturnTheLatestAndOldestRunID() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipelineName))).thenReturn(true); when(securityService.hasViewPermissionForPipeline(username, pipelineName)).thenReturn(true); jobService.getOldestAndLatestJobInstanceId(username, pipelineName, stageName, jobConfigName); verify(jobInstanceDao).getOldestAndLatestJobInstanceId(pipelineName, stageName, jobConfigName); } @Test void shouldThrowErrorIfPipelineDoesNotExist() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); assertThatCode(() -> jobService.getOldestAndLatestJobInstanceId(username, pipelineName, stageName, jobConfigName)) .isInstanceOf(RecordNotFoundException.class) .hasMessage("Pipeline with name 'pipeline' was not found!"); } @Test void shouldThrowErrorIfUserDoesNotHaveAccessRights() { when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipelineName))).thenReturn(true); assertThatCode(() -> jobService.getOldestAndLatestJobInstanceId(username, pipelineName, stageName, jobConfigName)) .isInstanceOf(NotAuthorizedException.class) .hasMessage("User 'user' does not have permission to view pipeline with name 'pipeline'"); } } }
marques-work/gocd
server/src/test-fast/java/com/thoughtworks/go/server/service/JobInstanceServiceTest.java
Java
apache-2.0
30,546
/* * 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. */ package org.apache.geode.management.internal.cli.commands; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.List; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.Logger; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.xml.sax.SAXException; import org.apache.geode.cache.execute.ResultCollector; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.internal.ClusterConfigurationService; import org.apache.geode.distributed.internal.InternalLocator; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.logging.LogService; import org.apache.geode.management.cli.CliMetaData; import org.apache.geode.management.cli.Result; import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor; import org.apache.geode.management.internal.cli.CliUtil; import org.apache.geode.management.internal.cli.GfshParseResult; import org.apache.geode.management.internal.cli.functions.CliFunctionResult; import org.apache.geode.management.internal.cli.i18n.CliStrings; import org.apache.geode.management.internal.cli.remote.CommandExecutionContext; import org.apache.geode.management.internal.cli.result.ErrorResultData; import org.apache.geode.management.internal.cli.result.FileResult; import org.apache.geode.management.internal.cli.result.InfoResultData; import org.apache.geode.management.internal.cli.result.ResultBuilder; import org.apache.geode.management.internal.cli.shell.Gfsh; import org.apache.geode.management.internal.configuration.domain.Configuration; import org.apache.geode.management.internal.configuration.functions.GetRegionNamesFunction; import org.apache.geode.management.internal.configuration.functions.RecreateCacheFunction; import org.apache.geode.management.internal.configuration.utils.ZipUtils; import org.apache.geode.management.internal.security.ResourceOperation; import org.apache.geode.security.ResourcePermission.Operation; import org.apache.geode.security.ResourcePermission.Resource; /** * Commands for the cluster configuration */ @SuppressWarnings("unused") public class ExportImportClusterConfigurationCommands implements GfshCommand { @CliCommand(value = {CliStrings.EXPORT_SHARED_CONFIG}, help = CliStrings.EXPORT_SHARED_CONFIG__HELP) @CliMetaData( interceptor = "org.apache.geode.management.internal.cli.commands.ExportImportClusterConfigurationCommands$ExportInterceptor", relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG}) @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ) public Result exportSharedConfig(@CliOption(key = {CliStrings.EXPORT_SHARED_CONFIG__FILE}, mandatory = true, help = CliStrings.EXPORT_SHARED_CONFIG__FILE__HELP) String zipFileName) { InternalLocator locator = InternalLocator.getLocator(); if (locator == null || !locator.isSharedConfigurationRunning()) { return ResultBuilder.createGemFireErrorResult(CliStrings.SHARED_CONFIGURATION_NOT_STARTED); } Path tempDir; try { tempDir = Files.createTempDirectory("clusterConfig"); } catch (IOException e) { if (Gfsh.getCurrentInstance() != null) { Gfsh.getCurrentInstance().logSevere(e.getMessage(), e); } ErrorResultData errorData = ResultBuilder.createErrorResultData().addLine("Unable to create temp directory"); return ResultBuilder.buildResult(errorData); } File zipFile = tempDir.resolve("exportedCC.zip").toFile(); ClusterConfigurationService sc = locator.getSharedConfiguration(); Result result; try { for (Configuration config : sc.getConfigurationRegion().values()) { sc.writeConfigToFile(config); } ZipUtils.zipDirectory(sc.getSharedConfigurationDirPath(), zipFile.getCanonicalPath()); InfoResultData infoData = ResultBuilder.createInfoResultData(); byte[] byteData = FileUtils.readFileToByteArray(zipFile); infoData.addAsFile(zipFileName, byteData, InfoResultData.FILE_TYPE_BINARY, CliStrings.EXPORT_SHARED_CONFIG__DOWNLOAD__MSG, false); result = ResultBuilder.buildResult(infoData); } catch (Exception e) { ErrorResultData errorData = ResultBuilder.createErrorResultData(); errorData.addLine("Export failed"); if (Gfsh.getCurrentInstance() != null) { Gfsh.getCurrentInstance().logSevere(e.getMessage(), e); } result = ResultBuilder.buildResult(errorData); } finally { zipFile.delete(); } return result; } @CliCommand(value = {CliStrings.IMPORT_SHARED_CONFIG}, help = CliStrings.IMPORT_SHARED_CONFIG__HELP) @CliMetaData( interceptor = "org.apache.geode.management.internal.cli.commands.ExportImportClusterConfigurationCommands$ImportInterceptor", isFileUploaded = true, relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG}) @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE) @SuppressWarnings("unchecked") public Result importSharedConfig( @CliOption(key = {CliStrings.IMPORT_SHARED_CONFIG__ZIP}, mandatory = true, help = CliStrings.IMPORT_SHARED_CONFIG__ZIP__HELP) String zip) throws IOException, TransformerException, SAXException, ParserConfigurationException { InternalLocator locator = InternalLocator.getLocator(); if (!locator.isSharedConfigurationRunning()) { ErrorResultData errorData = ResultBuilder.createErrorResultData(); errorData.addLine(CliStrings.SHARED_CONFIGURATION_NOT_STARTED); return ResultBuilder.buildResult(errorData); } InternalCache cache = getCache(); Set<DistributedMember> servers = CliUtil.getAllNormalMembers(cache); Set<String> regionsWithData = servers.stream().map(this::getRegionNamesOnServer) .flatMap(Collection::stream).collect(toSet()); if (!regionsWithData.isEmpty()) { return ResultBuilder .createGemFireErrorResult("Cannot import cluster configuration with existing regions: " + regionsWithData.stream().collect(joining(","))); } List<String> filePathFromShell = CommandExecutionContext.getFilePathFromShell(); Result result; InfoResultData infoData = ResultBuilder.createInfoResultData(); String zipFilePath = filePathFromShell.get(0); ClusterConfigurationService sc = locator.getSharedConfiguration(); // backup the old config for (Configuration config : sc.getConfigurationRegion().values()) { sc.writeConfigToFile(config); } sc.renameExistingSharedConfigDirectory(); ZipUtils.unzip(zipFilePath, sc.getSharedConfigurationDirPath()); // load it from the disk sc.loadSharedConfigurationFromDisk(); infoData.addLine(CliStrings.IMPORT_SHARED_CONFIG__SUCCESS__MSG); // Bounce the cache of each member Set<CliFunctionResult> functionResults = servers.stream().map(this::reCreateCache).collect(toSet()); for (CliFunctionResult functionResult : functionResults) { if (functionResult.isSuccessful()) { infoData.addLine("Successfully applied the imported cluster configuration on " + functionResult.getMemberIdOrName()); } else { infoData.addLine("Failed to apply the imported cluster configuration on " + functionResult.getMemberIdOrName() + " due to " + functionResult.getMessage()); } } result = ResultBuilder.buildResult(infoData); return result; } private Set<String> getRegionNamesOnServer(DistributedMember server) { ResultCollector rc = executeFunction(new GetRegionNamesFunction(), null, server); List<Set<String>> results = (List<Set<String>>) rc.getResult(); return results.get(0); } private CliFunctionResult reCreateCache(DistributedMember server) { ResultCollector rc = executeFunction(new RecreateCacheFunction(), null, server); List<CliFunctionResult> results = (List<CliFunctionResult>) rc.getResult(); return results.get(0); } /** * Interceptor used by gfsh to intercept execution of export shared config command at "shell". */ public static class ExportInterceptor extends AbstractCliAroundInterceptor { private String saveDirString; private static final Logger logger = LogService.getLogger(); @Override public Result preExecution(GfshParseResult parseResult) { String zip = parseResult.getParamValueAsString(CliStrings.EXPORT_SHARED_CONFIG__FILE); if (!zip.endsWith(".zip")) { return ResultBuilder .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, ".zip")); } return ResultBuilder.createInfoResult("OK"); } @Override public Result postExecution(GfshParseResult parseResult, Result commandResult, Path tempFile) { if (commandResult.hasIncomingFiles()) { try { commandResult.saveIncomingFiles(System.getProperty("user.dir")); return commandResult; } catch (IOException ioex) { logger.error(ioex); return ResultBuilder.createShellClientErrorResult( CliStrings.EXPORT_SHARED_CONFIG__UNABLE__TO__EXPORT__CONFIG + ": " + ioex.getMessage()); } } return null; } } public static class ImportInterceptor extends AbstractCliAroundInterceptor { public Result preExecution(GfshParseResult parseResult) { String zip = parseResult.getParamValueAsString(CliStrings.IMPORT_SHARED_CONFIG__ZIP); zip = StringUtils.trim(zip); if (zip == null) { return ResultBuilder.createUserErrorResult(CliStrings.format( CliStrings.IMPORT_SHARED_CONFIG__PROVIDE__ZIP, CliStrings.IMPORT_SHARED_CONFIG__ZIP)); } if (!zip.endsWith(CliStrings.ZIP_FILE_EXTENSION)) { return ResultBuilder.createUserErrorResult( CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, CliStrings.ZIP_FILE_EXTENSION)); } FileResult fileResult = new FileResult(); File zipFile = new File(zip); if (!zipFile.exists()) { return ResultBuilder.createUserErrorResult(zip + " not found"); } fileResult.addFile(zipFile); return fileResult; } } }
smanvi-pivotal/geode
geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportImportClusterConfigurationCommands.java
Java
apache-2.0
11,416
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>My Data Hub</title> <!-- Bootstrap Core CSS --> <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- MetisMenu CSS --> <link href="../bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="../dist/css/sb-admin-2.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400'> <link rel="stylesheet" href="css/style.css"> </head> <body> <div id="wrapper"> <!-- Navigation --> <nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html">My Data Hub</a> </div> <!-- /.navbar-header --> <ul class="nav navbar-top-links navbar-right"> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-envelope fa-fw"></i> <i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu dropdown-messages"> <li> <a href="#"> <div> <strong>John Smith</strong> <span class="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div>Hey I love your blueberry muffin recipe! It's amazing and I would...</div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <strong>Tommy Trojan</strong> <span class="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div>I saw that you've made this cheesecake recipe a lot! Could you...</div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <strong>Tim Cook</strong> <span class="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div>Hey do you take orders? Your cakes look really amazing and my...</div> </a> </li> <li class="divider"></li> <li> <a class="text-center" href="#"> <strong>Read All Messages</strong> <i class="fa fa-angle-right"></i> </a> </li> </ul> <!-- /.dropdown-messages --> </li> <!-- /.dropdown --> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-tasks fa-fw"></i> <i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu dropdown-tasks"> <li> <a href="#"> <div> <p> <strong>Task 1</strong> <span class="pull-right text-muted">40% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"> <span class="sr-only">40% Complete (success)</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <p> <strong>Task 2</strong> <span class="pull-right text-muted">20% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> <span class="sr-only">20% Complete</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <p> <strong>Task 3</strong> <span class="pull-right text-muted">60% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"> <span class="sr-only">60% Complete (warning)</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <p> <strong>Task 4</strong> <span class="pull-right text-muted">80% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> <span class="sr-only">80% Complete (danger)</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a class="text-center" href="#"> <strong>See All Tasks</strong> <i class="fa fa-angle-right"></i> </a> </li> </ul> <!-- /.dropdown-tasks --> </li> <!-- /.dropdown --> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-bell fa-fw"></i> <i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu dropdown-alerts"> <li> <a href="#"> <div> <i class="fa fa-comment fa-fw"></i> New Comment <span class="pull-right text-muted small">4 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <i class="fa fa-twitter fa-fw"></i> 3 New Followers <span class="pull-right text-muted small">12 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <i class="fa fa-envelope fa-fw"></i> Message Sent <span class="pull-right text-muted small">4 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <i class="fa fa-tasks fa-fw"></i> New Task <span class="pull-right text-muted small">4 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <i class="fa fa-upload fa-fw"></i> Server Rebooted <span class="pull-right text-muted small">4 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a class="text-center" href="#"> <strong>See All Alerts</strong> <i class="fa fa-angle-right"></i> </a> </li> </ul> <!-- /.dropdown-alerts --> </li> <!-- /.dropdown --> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu dropdown-user"> <li><a href="#"><i class="fa fa-user fa-fw"></i> User Profile</a> </li> <li><a href="#"><i class="fa fa-gear fa-fw"></i> Settings</a> </li> <li class="divider"></li> <li><a href="login.html"><i class="fa fa-sign-out fa-fw"></i> Logout</a> </li> </ul> <!-- /.dropdown-user --> </li> <!-- /.dropdown --> </ul> <!-- /.navbar-top-links --> <div class="navbar-default sidebar" role="navigation"> <div class="sidebar-nav navbar-collapse"> <ul class="nav" id="side-menu"> <li class="sidebar-search"> <div class="input-group custom-search-form"> <input type="text" class="form-control" placeholder="Search..."> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <i class="fa fa-search"></i> </button> </span> </div> <!-- /input-group --> </li> <li> <a href="index.html"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a> </li> <li> <a href="#"><i class="fa fa-bar-chart-o fa-fw"></i> Charts<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li> <a href="flot.html">Global Charts</a> </li> <li> <a href="morris.html">Personal Charts</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href="tables.html"><i class="fa fa-table fa-fw"></i> Usage</a> </li> <li> <a href="forms.html"><i class="fa fa-edit fa-fw"></i> Forms</a> </li> <li> <a href="#"><i class="fa fa-wrench fa-fw"></i> UI Elements<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li> <a href="panels-wells.html">Panels and Wells</a> </li> <li> <a href="buttons.html">Buttons</a> </li> <li> <a href="notifications.html">Notifications</a> </li> <li> <a href="typography.html">Typography</a> </li> <li> <a href="icons.html"> Icons</a> </li> <li> <a href="grid.html">Grid</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href="#"><i class="fa fa-files-o fa-fw"></i> More Data<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li> <a href="blank.html">Average Step Frequecy</a> </li> <li> <a href="login.html">Ingredient Frequency</a> </li> </ul> <!-- /.nav-second-level --> </li> </ul> </div> <!-- /.sidebar-collapse --> </div> <!-- /.navbar-static-side --> </nav> <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Icons</h1> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> All available icons (font-awesome) </div> <div class="panel-body"> <div class="row"> <div class="fa col-lg-3"> <p class="fa fa-glass"> fa-glass </p><br/> <p class="fa fa-music"> fa-music </p><br/> <p class="fa fa-search"> fa-search </p><br/> <p class="fa fa-envelope-o"> fa-envelope-o </p><br/> <p class="fa fa-heart"> fa-heart </p><br/> <p class="fa fa-star"> fa-star </p><br/> <p class="fa fa-star-o"> fa-star-o </p><br/> <p class="fa fa-user"> fa-user </p><br/> <p class="fa fa-film"> fa-film </p><br/> <p class="fa fa-th-large"> fa-th-large </p><br/> <p class="fa fa-th"> fa-th </p><br/> <p class="fa fa-th-list"> fa-th-list </p><br/> <p class="fa fa-check"> fa-check </p><br/> <p class="fa fa-times"> fa-times </p><br/> <p class="fa fa-search-plus"> fa-search-plus </p><br/> <p class="fa fa-search-minus"> fa-search-minus </p><br/> <p class="fa fa-power-off"> fa-power-off </p><br/> <p class="fa fa-signal"> fa-signal </p><br/> <p class="fa fa-gear"> fa-gear </p><br/> <p class="fa fa-cog"> fa-cog </p><br/> <p class="fa fa-trash-o"> fa-trash-o </p><br/> <p class="fa fa-home"> fa-home </p><br/> <p class="fa fa-file-o"> fa-file-o </p><br/> <p class="fa fa-clock-o"> fa-clock-o </p><br/> <p class="fa fa-road"> fa-road </p><br/> <p class="fa fa-download"> fa-download </p><br/> <p class="fa fa-arrow-circle-o-down"> fa-arrow-circle-o-down </p><br/> <p class="fa fa-arrow-circle-o-up"> fa-arrow-circle-o-up </p><br/> <p class="fa fa-inbox"> fa-inbox </p><br/> <p class="fa fa-play-circle-o"> fa-play-circle-o </p><br/> <p class="fa fa-rotate-right"> fa-rotate-right </p><br/> <p class="fa fa-repeat"> fa-repeat </p><br/> <p class="fa fa-refresh"> fa-refresh </p><br/> <p class="fa fa-list-alt"> fa-list-alt </p><br/> <p class="fa fa-lock"> fa-lock </p><br/> <p class="fa fa-flag"> fa-flag </p><br/> <p class="fa fa-headphones"> fa-headphones </p><br/> <p class="fa fa-volume-off"> fa-volume-off </p><br/> <p class="fa fa-volume-down"> fa-volume-down </p><br/> <p class="fa fa-volume-up"> fa-volume-up </p><br/> <p class="fa fa-qrcode"> fa-qrcode </p><br/> <p class="fa fa-barcode"> fa-barcode </p><br/> <p class="fa fa-tag"> fa-tag </p><br/> <p class="fa fa-tags"> fa-tags </p><br/> <p class="fa fa-book"> fa-book </p><br/> <p class="fa fa-bookmark"> fa-bookmark </p><br/> <p class="fa fa-print"> fa-print </p><br/> <p class="fa fa-camera"> fa-camera </p><br/> <p class="fa fa-font"> fa-font </p><br/> <p class="fa fa-bold"> fa-bold </p><br/> <p class="fa fa-italic"> fa-italic </p><br/> <p class="fa fa-text-height"> fa-text-height </p><br/> <p class="fa fa-text-width"> fa-text-width </p><br/> <p class="fa fa-align-left"> fa-align-left </p><br/> <p class="fa fa-align-center"> fa-align-center </p><br/> <p class="fa fa-align-right"> fa-align-right </p><br/> <p class="fa fa-align-justify"> fa-align-justify </p><br/> <p class="fa fa-list"> fa-list </p><br/> <p class="fa fa-dedent"> fa-dedent </p><br/> <p class="fa fa-outdent"> fa-outdent </p><br/> <p class="fa fa-indent"> fa-indent </p><br/> <p class="fa fa-video-camera"> fa-video-camera </p><br/> <p class="fa fa-photo"> fa-photo </p><br/> <p class="fa fa-image"> fa-image </p><br/> <p class="fa fa-picture-o"> fa-picture-o </p><br/> <p class="fa fa-pencil"> fa-pencil </p><br/> <p class="fa fa-map-marker"> fa-map-marker </p><br/> <p class="fa fa-adjust"> fa-adjust </p><br/> <p class="fa fa-tint"> fa-tint </p><br/> <p class="fa fa-edit"> fa-edit </p><br/> <p class="fa fa-pencil-square-o"> fa-pencil-square-o </p><br/> <p class="fa fa-share-square-o"> fa-share-square-o </p><br/> <p class="fa fa-check-square-o"> fa-check-square-o </p><br/> <p class="fa fa-arrows"> fa-arrows </p><br/> <p class="fa fa-step-backward"> fa-step-backward </p><br/> <p class="fa fa-fast-backward"> fa-fast-backward </p><br/> <p class="fa fa-backward"> fa-backward </p><br/> <p class="fa fa-play"> fa-play </p><br/> <p class="fa fa-pause"> fa-pause </p><br/> <p class="fa fa-stop"> fa-stop </p><br/> <p class="fa fa-forward"> fa-forward </p><br/> <p class="fa fa-fast-forward"> fa-fast-forward </p><br/> <p class="fa fa-step-forward"> fa-step-forward </p><br/> <p class="fa fa-eject"> fa-eject </p><br/> <p class="fa fa-chevron-left"> fa-chevron-left </p><br/> <p class="fa fa-chevron-right"> fa-chevron-right </p><br/> <p class="fa fa-plus-circle"> fa-plus-circle </p><br/> <p class="fa fa-minus-circle"> fa-minus-circle </p><br/> <p class="fa fa-times-circle"> fa-times-circle </p><br/> <p class="fa fa-check-circle"> fa-check-circle </p><br/> <p class="fa fa-question-circle"> fa-question-circle </p><br/> <p class="fa fa-info-circle"> fa-info-circle </p><br/> <p class="fa fa-crosshairs"> fa-crosshairs </p><br/> <p class="fa fa-times-circle-o"> fa-times-circle-o </p><br/> <p class="fa fa-check-circle-o"> fa-check-circle-o </p><br/> <p class="fa fa-ban"> fa-ban </p><br/> <p class="fa fa-arrow-left"> fa-arrow-left </p><br/> <p class="fa fa-arrow-right"> fa-arrow-right </p><br/> <p class="fa fa-arrow-up"> fa-arrow-up </p><br/> <p class="fa fa-arrow-down"> fa-arrow-down </p><br/> <p class="fa fa-mail-forward"> fa-mail-forward </p><br/> <p class="fa fa-share"> fa-share </p><br/> <p class="fa fa-expand"> fa-expand </p><br/> <p class="fa fa-compress"> fa-compress </p><br/> <p class="fa fa-plus"> fa-plus </p><br/> <p class="fa fa-minus"> fa-minus </p><br/> <p class="fa fa-asterisk"> fa-asterisk </p><br/> <p class="fa fa-exclamation-circle"> fa-exclamation-circle </p><br/> <p class="fa fa-gift"> fa-gift </p><br/> <p class="fa fa-leaf"> fa-leaf </p><br/> <p class="fa fa-fire"> fa-fire </p><br/> <p class="fa fa-eye"> fa-eye </p><br/> <p class="fa fa-eye-slash"> fa-eye-slash </p><br/> <p class="fa fa-warning"> fa-warning </p><br/> <p class="fa fa-exclamation-triangle"> fa-exclamation-triangle </p><br/> <p class="fa fa-plane"> fa-plane </p><br/> <p class="fa fa-calendar"> fa-calendar </p><br/> <p class="fa fa-random"> fa-random </p><br/> <p class="fa fa-comment"> fa-comment </p><br/> <p class="fa fa-magnet"> fa-magnet </p><br/> <p class="fa fa-chevron-up"> fa-chevron-up </p><br/> <p class="fa fa-chevron-down"> fa-chevron-down </p><br/> <p class="fa fa-retweet"> fa-retweet </p><br/> <p class="fa fa-shopping-cart"> fa-shopping-cart </p><br/> <p class="fa fa-folder"> fa-folder </p><br/> <p class="fa fa-folder-open"> fa-folder-open </p><br/> </div> <!-- /.col-lg-6 (nested) --> <div class="fa col-lg-3"> <p class="fa fa-arrows-v"> fa-arrows-v </p><br/> <p class="fa fa-arrows-h"> fa-arrows-h </p><br/> <p class="fa fa-bar-chart-o"> fa-bar-chart-o </p><br/> <p class="fa fa-twitter-square"> fa-twitter-square </p><br/> <p class="fa fa-facebook-square"> fa-facebook-square </p><br/> <p class="fa fa-camera-retro"> fa-camera-retro </p><br/> <p class="fa fa-key"> fa-key </p><br/> <p class="fa fa-gears"> fa-gears </p><br/> <p class="fa fa-cogs"> fa-cogs </p><br/> <p class="fa fa-comments"> fa-comments </p><br/> <p class="fa fa-thumbs-o-up"> fa-thumbs-o-up </p><br/> <p class="fa fa-thumbs-o-down"> fa-thumbs-o-down </p><br/> <p class="fa fa-star-half"> fa-star-half </p><br/> <p class="fa fa-heart-o"> fa-heart-o </p><br/> <p class="fa fa-sign-out"> fa-sign-out </p><br/> <p class="fa fa-linkedin-square"> fa-linkedin-square </p><br/> <p class="fa fa-thumb-tack"> fa-thumb-tack </p><br/> <p class="fa fa-external-link"> fa-external-link </p><br/> <p class="fa fa-sign-in"> fa-sign-in </p><br/> <p class="fa fa-trophy"> fa-trophy </p><br/> <p class="fa fa-github-square"> fa-github-square </p><br/> <p class="fa fa-upload"> fa-upload </p><br/> <p class="fa fa-lemon-o"> fa-lemon-o </p><br/> <p class="fa fa-phone"> fa-phone </p><br/> <p class="fa fa-square-o"> fa-square-o </p><br/> <p class="fa fa-bookmark-o"> fa-bookmark-o </p><br/> <p class="fa fa-phone-square"> fa-phone-square </p><br/> <p class="fa fa-twitter"> fa-twitter </p><br/> <p class="fa fa-facebook"> fa-facebook </p><br/> <p class="fa fa-github"> fa-github </p><br/> <p class="fa fa-unlock"> fa-unlock </p><br/> <p class="fa fa-credit-card"> fa-credit-card </p><br/> <p class="fa fa-rss"> fa-rss </p><br/> <p class="fa fa-hdd-o"> fa-hdd-o </p><br/> <p class="fa fa-bullhorn"> fa-bullhorn </p><br/> <p class="fa fa-bell"> fa-bell </p><br/> <p class="fa fa-certificate"> fa-certificate </p><br/> <p class="fa fa-hand-o-right"> fa-hand-o-right </p><br/> <p class="fa fa-hand-o-left"> fa-hand-o-left </p><br/> <p class="fa fa-hand-o-up"> fa-hand-o-up </p><br/> <p class="fa fa-hand-o-down"> fa-hand-o-down </p><br/> <p class="fa fa-arrow-circle-left"> fa-arrow-circle-left </p><br/> <p class="fa fa-arrow-circle-right"> fa-arrow-circle-right </p><br/> <p class="fa fa-arrow-circle-up"> fa-arrow-circle-up </p><br/> <p class="fa fa-arrow-circle-down"> fa-arrow-circle-down </p><br/> <p class="fa fa-globe"> fa-globe </p><br/> <p class="fa fa-wrench"> fa-wrench </p><br/> <p class="fa fa-tasks"> fa-tasks </p><br/> <p class="fa fa-filter"> fa-filter </p><br/> <p class="fa fa-briefcase"> fa-briefcase </p><br/> <p class="fa fa-arrows-alt"> fa-arrows-alt </p><br/> <p class="fa fa-group"> fa-group </p><br/> <p class="fa fa-users"> fa-users </p><br/> <p class="fa fa-chain"> fa-chain </p><br/> <p class="fa fa-link"> fa-link </p><br/> <p class="fa fa-cloud"> fa-cloud </p><br/> <p class="fa fa-flask"> fa-flask </p><br/> <p class="fa fa-cut"> fa-cut </p><br/> <p class="fa fa-scissors"> fa-scissors </p><br/> <p class="fa fa-copy"> fa-copy </p><br/> <p class="fa fa-files-o"> fa-files-o </p><br/> <p class="fa fa-paperclip"> fa-paperclip </p><br/> <p class="fa fa-save"> fa-save </p><br/> <p class="fa fa-floppy-o"> fa-floppy-o </p><br/> <p class="fa fa-square"> fa-square </p><br/> <p class="fa fa-navicon"> fa-navicon </p><br/> <p class="fa fa-reorder"> fa-reorder </p><br/> <p class="fa fa-bars"> fa-bars </p><br/> <p class="fa fa-list-ul"> fa-list-ul </p><br/> <p class="fa fa-list-ol"> fa-list-ol </p><br/> <p class="fa fa-strikethrough"> fa-strikethrough </p><br/> <p class="fa fa-underline"> fa-underline </p><br/> <p class="fa fa-table"> fa-table </p><br/> <p class="fa fa-magic"> fa-magic </p><br/> <p class="fa fa-truck"> fa-truck </p><br/> <p class="fa fa-pinterest"> fa-pinterest </p><br/> <p class="fa fa-pinterest-square"> fa-pinterest-square </p><br/> <p class="fa fa-google-plus-square"> fa-google-plus-square </p><br/> <p class="fa fa-google-plus"> fa-google-plus </p><br/> <p class="fa fa-money"> fa-money </p><br/> <p class="fa fa-caret-down"> fa-caret-down </p><br/> <p class="fa fa-caret-up"> fa-caret-up </p><br/> <p class="fa fa-caret-left"> fa-caret-left </p><br/> <p class="fa fa-caret-right"> fa-caret-right </p><br/> <p class="fa fa-columns"> fa-columns </p><br/> <p class="fa fa-unsorted"> fa-unsorted </p><br/> <p class="fa fa-sort"> fa-sort </p><br/> <p class="fa fa-sort-down"> fa-sort-down </p><br/> <p class="fa fa-sort-desc"> fa-sort-desc </p><br/> <p class="fa fa-sort-up"> fa-sort-up </p><br/> <p class="fa fa-sort-asc"> fa-sort-asc </p><br/> <p class="fa fa-envelope"> fa-envelope </p><br/> <p class="fa fa-linkedin"> fa-linkedin </p><br/> <p class="fa fa-rotate-left"> fa-rotate-left </p><br/> <p class="fa fa-undo"> fa-undo </p><br/> <p class="fa fa-legal"> fa-legal </p><br/> <p class="fa fa-gavel"> fa-gavel </p><br/> <p class="fa fa-dashboard"> fa-dashboard </p><br/> <p class="fa fa-tachometer"> fa-tachometer </p><br/> <p class="fa fa-comment-o"> fa-comment-o </p><br/> <p class="fa fa-comments-o"> fa-comments-o </p><br/> <p class="fa fa-flash"> fa-flash </p><br/> <p class="fa fa-bolt"> fa-bolt </p><br/> <p class="fa fa-sitemap"> fa-sitemap </p><br/> <p class="fa fa-umbrella"> fa-umbrella </p><br/> <p class="fa fa-paste"> fa-paste </p><br/> <p class="fa fa-clipboard"> fa-clipboard </p><br/> <p class="fa fa-lightbulb-o"> fa-lightbulb-o </p><br/> <p class="fa fa-exchange"> fa-exchange </p><br/> <p class="fa fa-cloud-download"> fa-cloud-download </p><br/> <p class="fa fa-cloud-upload"> fa-cloud-upload </p><br/> <p class="fa fa-user-md"> fa-user-md </p><br/> <p class="fa fa-stethoscope"> fa-stethoscope </p><br/> <p class="fa fa-suitcase"> fa-suitcase </p><br/> <p class="fa fa-bell-o"> fa-bell-o </p><br/> <p class="fa fa-coffee"> fa-coffee </p><br/> <p class="fa fa-cutlery"> fa-cutlery </p><br/> <p class="fa fa-file-text-o"> fa-file-text-o </p><br/> <p class="fa fa-building-o"> fa-building-o </p><br/> <p class="fa fa-hospital-o"> fa-hospital-o </p><br/> <p class="fa fa-ambulance"> fa-ambulance </p><br/> <p class="fa fa-medkit"> fa-medkit </p><br/> <p class="fa fa-fighter-jet"> fa-fighter-jet </p><br/> <p class="fa fa-beer"> fa-beer </p><br/> <p class="fa fa-h-square"> fa-h-square </p><br/> <p class="fa fa-plus-square"> fa-plus-square </p><br/> </div> <div class="fa col-lg-3"> <p class="fa fa-angle-double-left"> fa-angle-double-left </p><br/> <p class="fa fa-angle-double-right"> fa-angle-double-right </p><br/> <p class="fa fa-angle-double-up"> fa-angle-double-up </p><br/> <p class="fa fa-angle-double-down"> fa-angle-double-down </p><br/> <p class="fa fa-angle-left"> fa-angle-left </p><br/> <p class="fa fa-angle-right"> fa-angle-right </p><br/> <p class="fa fa-angle-up"> fa-angle-up </p><br/> <p class="fa fa-angle-down"> fa-angle-down </p><br/> <p class="fa fa-desktop"> fa-desktop </p><br/> <p class="fa fa-laptop"> fa-laptop </p><br/> <p class="fa fa-tablet"> fa-tablet </p><br/> <p class="fa fa-mobile-phone"> fa-mobile-phone </p><br/> <p class="fa fa-mobile"> fa-mobile </p><br/> <p class="fa fa-circle-o"> fa-circle-o </p><br/> <p class="fa fa-quote-left"> fa-quote-left </p><br/> <p class="fa fa-quote-right"> fa-quote-right </p><br/> <p class="fa fa-spinner"> fa-spinner </p><br/> <p class="fa fa-circle"> fa-circle </p><br/> <p class="fa fa-mail-reply"> fa-mail-reply </p><br/> <p class="fa fa-reply"> fa-reply </p><br/> <p class="fa fa-github-alt"> fa-github-alt </p><br/> <p class="fa fa-folder-o"> fa-folder-o </p><br/> <p class="fa fa-folder-open-o"> fa-folder-open-o </p><br/> <p class="fa fa-smile-o"> fa-smile-o </p><br/> <p class="fa fa-frown-o"> fa-frown-o </p><br/> <p class="fa fa-meh-o"> fa-meh-o </p><br/> <p class="fa fa-gamepad"> fa-gamepad </p><br/> <p class="fa fa-keyboard-o"> fa-keyboard-o </p><br/> <p class="fa fa-flag-o"> fa-flag-o </p><br/> <p class="fa fa-flag-checkered"> fa-flag-checkered </p><br/> <p class="fa fa-terminal"> fa-terminal </p><br/> <p class="fa fa-code"> fa-code </p><br/> <p class="fa fa-mail-reply-all"> fa-mail-reply-all </p><br/> <p class="fa fa-reply-all"> fa-reply-all </p><br/> <p class="fa fa-star-half-empty"> fa-star-half-empty </p><br/> <p class="fa fa-star-half-full"> fa-star-half-full </p><br/> <p class="fa fa-star-half-o"> fa-star-half-o </p><br/> <p class="fa fa-location-arrow"> fa-location-arrow </p><br/> <p class="fa fa-crop"> fa-crop </p><br/> <p class="fa fa-code-fork"> fa-code-fork </p><br/> <p class="fa fa-unlink"> fa-unlink </p><br/> <p class="fa fa-chain-broken"> fa-chain-broken </p><br/> <p class="fa fa-question"> fa-question </p><br/> <p class="fa fa-info"> fa-info </p><br/> <p class="fa fa-exclamation"> fa-exclamation </p><br/> <p class="fa fa-superscript"> fa-superscript </p><br/> <p class="fa fa-subscript"> fa-subscript </p><br/> <p class="fa fa-eraser"> fa-eraser </p><br/> <p class="fa fa-puzzle-piece"> fa-puzzle-piece </p><br/> <p class="fa fa-microphone"> fa-microphone </p><br/> <p class="fa fa-microphone-slash"> fa-microphone-slash </p><br/> <p class="fa fa-shield"> fa-shield </p><br/> <p class="fa fa-calendar-o"> fa-calendar-o </p><br/> <p class="fa fa-fire-extinguisher"> fa-fire-extinguisher </p><br/> <p class="fa fa-rocket"> fa-rocket </p><br/> <p class="fa fa-maxcdn"> fa-maxcdn </p><br/> <p class="fa fa-chevron-circle-left"> fa-chevron-circle-left </p><br/> <p class="fa fa-chevron-circle-right"> fa-chevron-circle-right </p><br/> <p class="fa fa-chevron-circle-up"> fa-chevron-circle-up </p><br/> <p class="fa fa-chevron-circle-down"> fa-chevron-circle-down </p><br/> <p class="fa fa-html5"> fa-html5 </p><br/> <p class="fa fa-css3"> fa-css3 </p><br/> <p class="fa fa-anchor"> fa-anchor </p><br/> <p class="fa fa-unlock-alt"> fa-unlock-alt </p><br/> <p class="fa fa-bullseye"> fa-bullseye </p><br/> <p class="fa fa-ellipsis-h"> fa-ellipsis-h </p><br/> <p class="fa fa-ellipsis-v"> fa-ellipsis-v </p><br/> <p class="fa fa-rss-square"> fa-rss-square </p><br/> <p class="fa fa-play-circle"> fa-play-circle </p><br/> <p class="fa fa-ticket"> fa-ticket </p><br/> <p class="fa fa-minus-square"> fa-minus-square </p><br/> <p class="fa fa-minus-square-o"> fa-minus-square-o </p><br/> <p class="fa fa-level-up"> fa-level-up </p><br/> <p class="fa fa-level-down"> fa-level-down </p><br/> <p class="fa fa-check-square"> fa-check-square </p><br/> <p class="fa fa-pencil-square"> fa-pencil-square </p><br/> <p class="fa fa-external-link-square"> fa-external-link-square </p><br/> <p class="fa fa-share-square"> fa-share-square </p><br/> <p class="fa fa-compass"> fa-compass </p><br/> <p class="fa fa-toggle-down"> fa-toggle-down </p><br/> <p class="fa fa-caret-square-o-down"> fa-caret-square-o-down </p><br/> <p class="fa fa-toggle-up"> fa-toggle-up </p><br/> <p class="fa fa-caret-square-o-up"> fa-caret-square-o-up </p><br/> <p class="fa fa-toggle-right"> fa-toggle-right </p><br/> <p class="fa fa-caret-square-o-right"> fa-caret-square-o-right </p><br/> <p class="fa fa-euro"> fa-euro </p><br/> <p class="fa fa-eur"> fa-eur </p><br/> <p class="fa fa-gbp"> fa-gbp </p><br/> <p class="fa fa-dollar"> fa-dollar </p><br/> <p class="fa fa-usd"> fa-usd </p><br/> <p class="fa fa-rupee"> fa-rupee </p><br/> <p class="fa fa-inr"> fa-inr </p><br/> <p class="fa fa-cny"> fa-cny </p><br/> <p class="fa fa-rmb"> fa-rmb </p><br/> <p class="fa fa-yen"> fa-yen </p><br/> <p class="fa fa-jpy"> fa-jpy </p><br/> <p class="fa fa-ruble"> fa-ruble </p><br/> <p class="fa fa-rouble"> fa-rouble </p><br/> <p class="fa fa-rub"> fa-rub </p><br/> <p class="fa fa-won"> fa-won </p><br/> <p class="fa fa-krw"> fa-krw </p><br/> <p class="fa fa-bitcoin"> fa-bitcoin </p><br/> <p class="fa fa-btc"> fa-btc </p><br/> <p class="fa fa-file"> fa-file </p><br/> <p class="fa fa-file-text"> fa-file-text </p><br/> <p class="fa fa-sort-alpha-asc"> fa-sort-alpha-asc </p><br/> <p class="fa fa-sort-alpha-desc"> fa-sort-alpha-desc </p><br/> <p class="fa fa-sort-amount-asc"> fa-sort-amount-asc </p><br/> <p class="fa fa-sort-amount-desc"> fa-sort-amount-desc </p><br/> <p class="fa fa-sort-numeric-asc"> fa-sort-numeric-asc </p><br/> <p class="fa fa-sort-numeric-desc"> fa-sort-numeric-desc </p><br/> <p class="fa fa-thumbs-up"> fa-thumbs-up </p><br/> <p class="fa fa-thumbs-down"> fa-thumbs-down </p><br/> <p class="fa fa-youtube-square"> fa-youtube-square </p><br/> <p class="fa fa-youtube"> fa-youtube </p><br/> <p class="fa fa-xing"> fa-xing </p><br/> <p class="fa fa-xing-square"> fa-xing-square </p><br/> <p class="fa fa-youtube-play"> fa-youtube-play </p><br/> <p class="fa fa-dropbox"> fa-dropbox </p><br/> <p class="fa fa-stack-overflow"> fa-stack-overflow </p><br/> <p class="fa fa-instagram"> fa-instagram </p><br/> <p class="fa fa-flickr"> fa-flickr </p><br/> <p class="fa fa-adn"> fa-adn </p><br/> <p class="fa fa-bitbucket"> fa-bitbucket </p><br/> <p class="fa fa-bitbucket-square"> fa-bitbucket-square </p><br/> <p class="fa fa-tumblr"> fa-tumblr </p><br/> </div> <div class="fa col-lg-3"> <p class="fa fa-tumblr-square"> fa-tumblr-square </p><br/> <p class="fa fa-long-arrow-down"> fa-long-arrow-down </p><br/> <p class="fa fa-long-arrow-up"> fa-long-arrow-up </p><br/> <p class="fa fa-long-arrow-left"> fa-long-arrow-left </p><br/> <p class="fa fa-long-arrow-right"> fa-long-arrow-right </p><br/> <p class="fa fa-apple"> fa-apple </p><br/> <p class="fa fa-windows"> fa-windows </p><br/> <p class="fa fa-android"> fa-android </p><br/> <p class="fa fa-linux"> fa-linux </p><br/> <p class="fa fa-dribbble"> fa-dribbble </p><br/> <p class="fa fa-skype"> fa-skype </p><br/> <p class="fa fa-foursquare"> fa-foursquare </p><br/> <p class="fa fa-trello"> fa-trello </p><br/> <p class="fa fa-female"> fa-female </p><br/> <p class="fa fa-male"> fa-male </p><br/> <p class="fa fa-gittip"> fa-gittip </p><br/> <p class="fa fa-sun-o"> fa-sun-o </p><br/> <p class="fa fa-moon-o"> fa-moon-o </p><br/> <p class="fa fa-archive"> fa-archive </p><br/> <p class="fa fa-bug"> fa-bug </p><br/> <p class="fa fa-vk"> fa-vk </p><br/> <p class="fa fa-weibo"> fa-weibo </p><br/> <p class="fa fa-renren"> fa-renren </p><br/> <p class="fa fa-pagelines"> fa-pagelines </p><br/> <p class="fa fa-stack-exchange"> fa-stack-exchange </p><br/> <p class="fa fa-arrow-circle-o-right"> fa-arrow-circle-o-right </p><br/> <p class="fa fa-arrow-circle-o-left"> fa-arrow-circle-o-left </p><br/> <p class="fa fa-toggle-left"> fa-toggle-left </p><br/> <p class="fa fa-caret-square-o-left"> fa-caret-square-o-left </p><br/> <p class="fa fa-dot-circle-o"> fa-dot-circle-o </p><br/> <p class="fa fa-wheelchair"> fa-wheelchair </p><br/> <p class="fa fa-vimeo-square"> fa-vimeo-square </p><br/> <p class="fa fa-turkish-lira"> fa-turkish-lira </p><br/> <p class="fa fa-try"> fa-try </p><br/> <p class="fa fa-plus-square-o"> fa-plus-square-o </p><br/> <p class="fa fa-space-shuttle"> fa-space-shuttle </p><br/> <p class="fa fa-slack"> fa-slack </p><br/> <p class="fa fa-envelope-square"> fa-envelope-square </p><br/> <p class="fa fa-wordpress"> fa-wordpress </p><br/> <p class="fa fa-openid"> fa-openid </p><br/> <p class="fa fa-institution"> fa-institution </p><br/> <p class="fa fa-bank"> fa-bank </p><br/> <p class="fa fa-university"> fa-university </p><br/> <p class="fa fa-mortar-board"> fa-mortar-board </p><br/> <p class="fa fa-graduation-cap"> fa-graduation-cap </p><br/> <p class="fa fa-yahoo"> fa-yahoo </p><br/> <p class="fa fa-google"> fa-google </p><br/> <p class="fa fa-reddit"> fa-reddit </p><br/> <p class="fa fa-reddit-square"> fa-reddit-square </p><br/> <p class="fa fa-stumbleupon-circle"> fa-stumbleupon-circle </p><br/> <p class="fa fa-stumbleupon"> fa-stumbleupon </p><br/> <p class="fa fa-delicious"> fa-delicious </p><br/> <p class="fa fa-digg"> fa-digg </p><br/> <p class="fa fa-pied-piper-square"> fa-pied-piper-square </p><br/> <p class="fa fa-pied-piper"> fa-pied-piper </p><br/> <p class="fa fa-pied-piper-alt"> fa-pied-piper-alt </p><br/> <p class="fa fa-drupal"> fa-drupal </p><br/> <p class="fa fa-joomla"> fa-joomla </p><br/> <p class="fa fa-language"> fa-language </p><br/> <p class="fa fa-fax"> fa-fax </p><br/> <p class="fa fa-building"> fa-building </p><br/> <p class="fa fa-child"> fa-child </p><br/> <p class="fa fa-paw"> fa-paw </p><br/> <p class="fa fa-spoon"> fa-spoon </p><br/> <p class="fa fa-cube"> fa-cube </p><br/> <p class="fa fa-cubes"> fa-cubes </p><br/> <p class="fa fa-behance"> fa-behance </p><br/> <p class="fa fa-behance-square"> fa-behance-square </p><br/> <p class="fa fa-steam"> fa-steam </p><br/> <p class="fa fa-steam-square"> fa-steam-square </p><br/> <p class="fa fa-recycle"> fa-recycle </p><br/> <p class="fa fa-automobile"> fa-automobile </p><br/> <p class="fa fa-car"> fa-car </p><br/> <p class="fa fa-cab"> fa-cab </p><br/> <p class="fa fa-taxi"> fa-taxi </p><br/> <p class="fa fa-tree"> fa-tree </p><br/> <p class="fa fa-spotify"> fa-spotify </p><br/> <p class="fa fa-deviantart"> fa-deviantart </p><br/> <p class="fa fa-soundcloud"> fa-soundcloud </p><br/> <p class="fa fa-database"> fa-database </p><br/> <p class="fa fa-file-pdf-o"> fa-file-pdf-o </p><br/> <p class="fa fa-file-word-o"> fa-file-word-o </p><br/> <p class="fa fa-file-excel-o"> fa-file-excel-o </p><br/> <p class="fa fa-file-powerpoint-o"> fa-file-powerpoint-o </p><br/> <p class="fa fa-file-photo-o"> fa-file-photo-o </p><br/> <p class="fa fa-file-picture-o"> fa-file-picture-o </p><br/> <p class="fa fa-file-image-o"> fa-file-image-o </p><br/> <p class="fa fa-file-zip-o"> fa-file-zip-o </p><br/> <p class="fa fa-file-archive-o"> fa-file-archive-o </p><br/> <p class="fa fa-file-sound-o"> fa-file-sound-o </p><br/> <p class="fa fa-file-audio-o"> fa-file-audio-o </p><br/> <p class="fa fa-file-movie-o"> fa-file-movie-o </p><br/> <p class="fa fa-file-video-o"> fa-file-video-o </p><br/> <p class="fa fa-file-code-o"> fa-file-code-o </p><br/> <p class="fa fa-vine"> fa-vine </p><br/> <p class="fa fa-codepen"> fa-codepen </p><br/> <p class="fa fa-jsfiddle"> fa-jsfiddle </p><br/> <p class="fa fa-life-bouy"> fa-life-bouy </p><br/> <p class="fa fa-life-saver"> fa-life-saver </p><br/> <p class="fa fa-support"> fa-support </p><br/> <p class="fa fa-life-ring"> fa-life-ring </p><br/> <p class="fa fa-circle-o-notch"> fa-circle-o-notch </p><br/> <p class="fa fa-ra"> fa-ra </p><br/> <p class="fa fa-rebel"> fa-rebel </p><br/> <p class="fa fa-ge"> fa-ge </p><br/> <p class="fa fa-empire"> fa-empire </p><br/> <p class="fa fa-git-square"> fa-git-square </p><br/> <p class="fa fa-git"> fa-git </p><br/> <p class="fa fa-hacker-news"> fa-hacker-news </p><br/> <p class="fa fa-tencent-weibo"> fa-tencent-weibo </p><br/> <p class="fa fa-qq"> fa-qq </p><br/> <p class="fa fa-wechat"> fa-wechat </p><br/> <p class="fa fa-weixin"> fa-weixin </p><br/> <p class="fa fa-send"> fa-send </p><br/> <p class="fa fa-paper-plane"> fa-paper-plane </p><br/> <p class="fa fa-send-o"> fa-send-o </p><br/> <p class="fa fa-paper-plane-o"> fa-paper-plane-o </p><br/> <p class="fa fa-history"> fa-history </p><br/> <p class="fa fa-circle-thin"> fa-circle-thin </p><br/> <p class="fa fa-header"> fa-header </p><br/> <p class="fa fa-paragraph"> fa-paragraph </p><br/> <p class="fa fa-sliders"> fa-sliders </p><br/> <p class="fa fa-share-alt"> fa-share-alt </p><br/> <p class="fa fa-share-alt-square"> fa-share-alt-square </p><br/> <p class="fa fa-bomb"> fa-bomb </p><br/> </div> <!-- /.col-lg-6 (nested) --> </div> <!-- /.row (nested) --> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> All available icons (bootstrap) </div> <div class="panel-body"> <div class="row"> <div class="bs-glyphicons col-lg-4"> <span class="glyphicon glyphicon-asterisk"> glyphicon-asterisk </span><br/> <span class="glyphicon glyphicon-plus"> glyphicon-plus </span><br/> <span class="glyphicon glyphicon-euro"> glyphicon-euro </span><br/> <span class="glyphicon glyphicon-eur"> glyphicon-eur </span><br/> <span class="glyphicon glyphicon-minus"> glyphicon-minus </span><br/> <span class="glyphicon glyphicon-cloud"> glyphicon-cloud </span><br/> <span class="glyphicon glyphicon-envelope"> glyphicon-envelope </span><br/> <span class="glyphicon glyphicon-pencil"> glyphicon-pencil </span><br/> <span class="glyphicon glyphicon-glass"> glyphicon-glass </span><br/> <span class="glyphicon glyphicon-music"> glyphicon-music </span><br/> <span class="glyphicon glyphicon-search"> glyphicon-search </span><br/> <span class="glyphicon glyphicon-heart"> glyphicon-heart </span><br/> <span class="glyphicon glyphicon-star"> glyphicon-star </span><br/> <span class="glyphicon glyphicon-star-empty"> glyphicon-star-empty </span><br/> <span class="glyphicon glyphicon-user"> glyphicon-user </span><br/> <span class="glyphicon glyphicon-film"> glyphicon-film </span><br/> <span class="glyphicon glyphicon-th-large"> glyphicon-th-large </span><br/> <span class="glyphicon glyphicon-th"> glyphicon-th </span><br/> <span class="glyphicon glyphicon-th-list"> glyphicon-th-list </span><br/> <span class="glyphicon glyphicon-ok"> glyphicon-ok </span><br/> <span class="glyphicon glyphicon-remove"> glyphicon-remove </span><br/> <span class="glyphicon glyphicon-zoom-in"> glyphicon-zoom-in </span><br/> <span class="glyphicon glyphicon-zoom-out"> glyphicon-zoom-out </span><br/> <span class="glyphicon glyphicon-off"> glyphicon-off </span><br/> <span class="glyphicon glyphicon-signal"> glyphicon-signal </span><br/> <span class="glyphicon glyphicon-cog"> glyphicon-cog </span><br/> <span class="glyphicon glyphicon-trash"> glyphicon-trash </span><br/> <span class="glyphicon glyphicon-home"> glyphicon-home </span><br/> <span class="glyphicon glyphicon-file"> glyphicon-file </span><br/> <span class="glyphicon glyphicon-time"> glyphicon-time </span><br/> <span class="glyphicon glyphicon-road"> glyphicon-road </span><br/> <span class="glyphicon glyphicon-download-alt"> glyphicon-download-alt </span><br/> <span class="glyphicon glyphicon-download"> glyphicon-download </span><br/> <span class="glyphicon glyphicon-upload"> glyphicon-upload </span><br/> <span class="glyphicon glyphicon-inbox"> glyphicon-inbox </span><br/> <span class="glyphicon glyphicon-play-circle"> glyphicon-play-circle </span><br/> <span class="glyphicon glyphicon-repeat"> glyphicon-repeat </span><br/> <span class="glyphicon glyphicon-refresh"> glyphicon-refresh </span><br/> <span class="glyphicon glyphicon-list-alt"> glyphicon-list-alt </span><br/> <span class="glyphicon glyphicon-lock"> glyphicon-lock </span><br/> <span class="glyphicon glyphicon-flag"> glyphicon-flag </span><br/> <span class="glyphicon glyphicon-headphones"> glyphicon-headphones </span><br/> <span class="glyphicon glyphicon-volume-off"> glyphicon-volume-off </span><br/> <span class="glyphicon glyphicon-volume-down"> glyphicon-volume-down </span><br/> <span class="glyphicon glyphicon-volume-up"> glyphicon-volume-up </span><br/> <span class="glyphicon glyphicon-qrcode"> glyphicon-qrcode </span><br/> <span class="glyphicon glyphicon-barcode"> glyphicon-barcode </span><br/> <span class="glyphicon glyphicon-tag"> glyphicon-tag </span><br/> <span class="glyphicon glyphicon-tags"> glyphicon-tags </span><br/> <span class="glyphicon glyphicon-book"> glyphicon-book </span><br/> <span class="glyphicon glyphicon-bookmark"> glyphicon-bookmark </span><br/> <span class="glyphicon glyphicon-print"> glyphicon-print </span><br/> <span class="glyphicon glyphicon-camera"> glyphicon-camera </span><br/> <span class="glyphicon glyphicon-font"> glyphicon-font </span><br/> <span class="glyphicon glyphicon-bold"> glyphicon-bold </span><br/> <span class="glyphicon glyphicon-italic"> glyphicon-italic </span><br/> <span class="glyphicon glyphicon-text-height"> glyphicon-text-height </span><br/> <span class="glyphicon glyphicon-text-width"> glyphicon-text-width </span><br/> <span class="glyphicon glyphicon-align-left"> glyphicon-align-left </span><br/> <span class="glyphicon glyphicon-align-center"> glyphicon-align-center </span><br/> <span class="glyphicon glyphicon-align-right"> glyphicon-align-right </span><br/> <span class="glyphicon glyphicon-align-justify"> glyphicon-align-justify </span><br/> <span class="glyphicon glyphicon-list"> glyphicon-list </span><br/> <span class="glyphicon glyphicon-indent-left"> glyphicon-indent-left </span><br/> <span class="glyphicon glyphicon-indent-right"> glyphicon-indent-right </span><br/> <span class="glyphicon glyphicon-facetime-video"> glyphicon-facetime-video </span><br/> <span class="glyphicon glyphicon-picture"> glyphicon-picture </span><br/> <span class="glyphicon glyphicon-map-marker"> glyphicon-map-marker </span><br/> <span class="glyphicon glyphicon-adjust"> glyphicon-adjust </span><br/> <span class="glyphicon glyphicon-tint"> glyphicon-tint </span><br/> <span class="glyphicon glyphicon-edit"> glyphicon-edit </span><br/> <span class="glyphicon glyphicon-share"> glyphicon-share </span><br/> <span class="glyphicon glyphicon-check"> glyphicon-check </span><br/> <span class="glyphicon glyphicon-move"> glyphicon-move </span><br/> <span class="glyphicon glyphicon-step-backward"> glyphicon-step-backward </span><br/> <span class="glyphicon glyphicon-fast-backward"> glyphicon-fast-backward </span><br/> <span class="glyphicon glyphicon-backward"> glyphicon-backward </span><br/> <span class="glyphicon glyphicon-play"> glyphicon-play </span><br/> <span class="glyphicon glyphicon-pause"> glyphicon-pause </span><br/> <span class="glyphicon glyphicon-stop"> glyphicon-stop </span><br/> <span class="glyphicon glyphicon-forward"> glyphicon-forward </span><br/> <span class="glyphicon glyphicon-fast-forward"> glyphicon-fast-forward </span><br/> <span class="glyphicon glyphicon-step-forward"> glyphicon-step-forward </span><br/> <span class="glyphicon glyphicon-eject"> glyphicon-eject </span><br/> <span class="glyphicon glyphicon-chevron-left"> glyphicon-chevron-left </span><br/> <span class="glyphicon glyphicon-chevron-right"> glyphicon-chevron-right </span><br/> <span class="glyphicon glyphicon-plus-sign"> glyphicon-plus-sign </span><br/> </div> <div class="bs-glyphicons col-lg-4"> <span class="glyphicon glyphicon-minus-sign"> glyphicon-minus-sign </span><br/> <span class="glyphicon glyphicon-remove-sign"> glyphicon-remove-sign </span><br/> <span class="glyphicon glyphicon-ok-sign"> glyphicon-ok-sign </span><br/> <span class="glyphicon glyphicon-question-sign"> glyphicon-question-sign </span><br/> <span class="glyphicon glyphicon-info-sign"> glyphicon-info-sign </span><br/> <span class="glyphicon glyphicon-screenshot"> glyphicon-screenshot </span><br/> <span class="glyphicon glyphicon-remove-circle"> glyphicon-remove-circle </span><br/> <span class="glyphicon glyphicon-ok-circle"> glyphicon-ok-circle </span><br/> <span class="glyphicon glyphicon-ban-circle"> glyphicon-ban-circle </span><br/> <span class="glyphicon glyphicon-arrow-left"> glyphicon-arrow-left </span><br/> <span class="glyphicon glyphicon-arrow-right"> glyphicon-arrow-right </span><br/> <span class="glyphicon glyphicon-arrow-up"> glyphicon-arrow-up </span><br/> <span class="glyphicon glyphicon-arrow-down"> glyphicon-arrow-down </span><br/> <span class="glyphicon glyphicon-share-alt"> glyphicon-share-alt </span><br/> <span class="glyphicon glyphicon-resize-full"> glyphicon-resize-full </span><br/> <span class="glyphicon glyphicon-resize-small"> glyphicon-resize-small </span><br/> <span class="glyphicon glyphicon-exclamation-sign"> glyphicon-exclamation-sign </span><br/> <span class="glyphicon glyphicon-gift"> glyphicon-gift </span><br/> <span class="glyphicon glyphicon-leaf"> glyphicon-leaf </span><br/> <span class="glyphicon glyphicon-fire"> glyphicon-fire </span><br/> <span class="glyphicon glyphicon-eye-open"> glyphicon-eye-open </span><br/> <span class="glyphicon glyphicon-eye-close"> glyphicon-eye-close </span><br/> <span class="glyphicon glyphicon-warning-sign"> glyphicon-warning-sign </span><br/> <span class="glyphicon glyphicon-plane"> glyphicon-plane </span><br/> <span class="glyphicon glyphicon-calendar"> glyphicon-calendar </span><br/> <span class="glyphicon glyphicon-random"> glyphicon-random </span><br/> <span class="glyphicon glyphicon-comment"> glyphicon-comment </span><br/> <span class="glyphicon glyphicon-magnet"> glyphicon-magnet </span><br/> <span class="glyphicon glyphicon-chevron-up"> glyphicon-chevron-up </span><br/> <span class="glyphicon glyphicon-chevron-down"> glyphicon-chevron-down </span><br/> <span class="glyphicon glyphicon-retweet"> glyphicon-retweet </span><br/> <span class="glyphicon glyphicon-shopping-cart"> glyphicon-shopping-cart </span><br/> <span class="glyphicon glyphicon-folder-close"> glyphicon-folder-close </span><br/> <span class="glyphicon glyphicon-folder-open"> glyphicon-folder-open </span><br/> <span class="glyphicon glyphicon-resize-vertical"> glyphicon-resize-vertical </span><br/> <span class="glyphicon glyphicon-resize-horizontal"> glyphicon-resize-horizontal </span><br/> <span class="glyphicon glyphicon-hdd"> glyphicon-hdd </span><br/> <span class="glyphicon glyphicon-bullhorn"> glyphicon-bullhorn </span><br/> <span class="glyphicon glyphicon-bell"> glyphicon-bell </span><br/> <span class="glyphicon glyphicon-certificate"> glyphicon-certificate </span><br/> <span class="glyphicon glyphicon-thumbs-up"> glyphicon-thumbs-up </span><br/> <span class="glyphicon glyphicon-thumbs-down"> glyphicon-thumbs-down </span><br/> <span class="glyphicon glyphicon-hand-right"> glyphicon-hand-right </span><br/> <span class="glyphicon glyphicon-hand-left"> glyphicon-hand-left </span><br/> <span class="glyphicon glyphicon-hand-up"> glyphicon-hand-up </span><br/> <span class="glyphicon glyphicon-hand-down"> glyphicon-hand-down </span><br/> <span class="glyphicon glyphicon-circle-arrow-right"> glyphicon-circle-arrow-right </span><br/> <span class="glyphicon glyphicon-circle-arrow-left"> glyphicon-circle-arrow-left </span><br/> <span class="glyphicon glyphicon-circle-arrow-up"> glyphicon-circle-arrow-up </span><br/> <span class="glyphicon glyphicon-circle-arrow-down"> glyphicon-circle-arrow-down </span><br/> <span class="glyphicon glyphicon-globe"> glyphicon-globe </span><br/> <span class="glyphicon glyphicon-wrench"> glyphicon-wrench </span><br/> <span class="glyphicon glyphicon-tasks"> glyphicon-tasks </span><br/> <span class="glyphicon glyphicon-filter"> glyphicon-filter </span><br/> <span class="glyphicon glyphicon-briefcase"> glyphicon-briefcase </span><br/> <span class="glyphicon glyphicon-fullscreen"> glyphicon-fullscreen </span><br/> <span class="glyphicon glyphicon-dashboard"> glyphicon-dashboard </span><br/> <span class="glyphicon glyphicon-paperclip"> glyphicon-paperclip </span><br/> <span class="glyphicon glyphicon-heart-empty"> glyphicon-heart-empty </span><br/> <span class="glyphicon glyphicon-link"> glyphicon-link </span><br/> <span class="glyphicon glyphicon-phone"> glyphicon-phone </span><br/> <span class="glyphicon glyphicon-pushpin"> glyphicon-pushpin </span><br/> <span class="glyphicon glyphicon-usd"> glyphicon-usd </span><br/> <span class="glyphicon glyphicon-gbp"> glyphicon-gbp </span><br/> <span class="glyphicon glyphicon-sort"> glyphicon-sort </span><br/> <span class="glyphicon glyphicon-sort-by-alphabet"> glyphicon-sort-by-alphabet </span><br/> <span class="glyphicon glyphicon-sort-by-alphabet-alt"> glyphicon-sort-by-alphabet-alt </span><br/> <span class="glyphicon glyphicon-sort-by-order"> glyphicon-sort-by-order </span><br/> <span class="glyphicon glyphicon-sort-by-order-alt"> glyphicon-sort-by-order-alt </span><br/> <span class="glyphicon glyphicon-sort-by-attributes"> glyphicon-sort-by-attributes </span><br/> <span class="glyphicon glyphicon-sort-by-attributes-alt"> glyphicon-sort-by-attributes-alt </span><br/> <span class="glyphicon glyphicon-unchecked"> glyphicon-unchecked </span><br/> <span class="glyphicon glyphicon-expand"> glyphicon-expand </span><br/> <span class="glyphicon glyphicon-collapse-down"> glyphicon-collapse-down </span><br/> <span class="glyphicon glyphicon-collapse-up"> glyphicon-collapse-up </span><br/> <span class="glyphicon glyphicon-log-in"> glyphicon-log-in </span><br/> <span class="glyphicon glyphicon-flash"> glyphicon-flash </span><br/> <span class="glyphicon glyphicon-log-out"> glyphicon-log-out </span><br/> <span class="glyphicon glyphicon-new-window"> glyphicon-new-window </span><br/> <span class="glyphicon glyphicon-record"> glyphicon-record </span><br/> <span class="glyphicon glyphicon-save"> glyphicon-save </span><br/> <span class="glyphicon glyphicon-open"> glyphicon-open </span><br/> <span class="glyphicon glyphicon-saved"> glyphicon-saved </span><br/> <span class="glyphicon glyphicon-import"> glyphicon-import </span><br/> <span class="glyphicon glyphicon-export"> glyphicon-export </span><br/> <span class="glyphicon glyphicon-send"> glyphicon-send </span><br/> </div> <div class="bs-glyphicons col-lg-4"> <span class="glyphicon glyphicon-floppy-disk"> glyphicon-floppy-disk </span><br/> <span class="glyphicon glyphicon-floppy-saved"> glyphicon-floppy-saved </span><br/> <span class="glyphicon glyphicon-floppy-remove"> glyphicon-floppy-remove </span><br/> <span class="glyphicon glyphicon-floppy-save"> glyphicon-floppy-save </span><br/> <span class="glyphicon glyphicon-floppy-open"> glyphicon-floppy-open </span><br/> <span class="glyphicon glyphicon-credit-card"> glyphicon-credit-card </span><br/> <span class="glyphicon glyphicon-transfer"> glyphicon-transfer </span><br/> <span class="glyphicon glyphicon-cutlery"> glyphicon-cutlery </span><br/> <span class="glyphicon glyphicon-header"> glyphicon-header </span><br/> <span class="glyphicon glyphicon-compressed"> glyphicon-compressed </span><br/> <span class="glyphicon glyphicon-earphone"> glyphicon-earphone </span><br/> <span class="glyphicon glyphicon-phone-alt"> glyphicon-phone-alt </span><br/> <span class="glyphicon glyphicon-tower"> glyphicon-tower </span><br/> <span class="glyphicon glyphicon-stats"> glyphicon-stats </span><br/> <span class="glyphicon glyphicon-sd-video"> glyphicon-sd-video </span><br/> <span class="glyphicon glyphicon-hd-video"> glyphicon-hd-video </span><br/> <span class="glyphicon glyphicon-subtitles"> glyphicon-subtitles </span><br/> <span class="glyphicon glyphicon-sound-stereo"> glyphicon-sound-stereo </span><br/> <span class="glyphicon glyphicon-sound-dolby"> glyphicon-sound-dolby </span><br/> <span class="glyphicon glyphicon-sound-5-1"> glyphicon-sound-5-1 </span><br/> <span class="glyphicon glyphicon-sound-6-1"> glyphicon-sound-6-1 </span><br/> <span class="glyphicon glyphicon-sound-7-1"> glyphicon-sound-7-1 </span><br/> <span class="glyphicon glyphicon-copyright-mark"> glyphicon-copyright-mark </span><br/> <span class="glyphicon glyphicon-registration-mark"> glyphicon-registration-mark </span><br/> <span class="glyphicon glyphicon-cloud-download"> glyphicon-cloud-download </span><br/> <span class="glyphicon glyphicon-cloud-upload"> glyphicon-cloud-upload </span><br/> <span class="glyphicon glyphicon-tree-conifer"> glyphicon-tree-conifer </span><br/> <span class="glyphicon glyphicon-tree-deciduous"> glyphicon-tree-deciduous </span><br/> <span class="glyphicon glyphicon-cd"> glyphicon-cd </span><br/> <span class="glyphicon glyphicon-save-file"> glyphicon-save-file </span><br/> <span class="glyphicon glyphicon-open-file"> glyphicon-open-file </span><br/> <span class="glyphicon glyphicon-level-up"> glyphicon-level-up </span><br/> <span class="glyphicon glyphicon-copy"> glyphicon-copy </span><br/> <span class="glyphicon glyphicon-paste"> glyphicon-paste </span><br/> <span class="glyphicon glyphicon-alert"> glyphicon-alert </span><br/> <span class="glyphicon glyphicon-equalizer"> glyphicon-equalizer </span><br/> <span class="glyphicon glyphicon-king"> glyphicon-king </span><br/> <span class="glyphicon glyphicon-queen"> glyphicon-queen </span><br/> <span class="glyphicon glyphicon-pawn"> glyphicon-pawn </span><br/> <span class="glyphicon glyphicon-bishop"> glyphicon-bishop </span><br/> <span class="glyphicon glyphicon-knight"> glyphicon-knight </span><br/> <span class="glyphicon glyphicon-baby-formula"> glyphicon-baby-formula </span><br/> <span class="glyphicon glyphicon-tent"> glyphicon-tent </span><br/> <span class="glyphicon glyphicon-blackboard"> glyphicon-blackboard </span><br/> <span class="glyphicon glyphicon-bed"> glyphicon-bed </span><br/> <span class="glyphicon glyphicon-apple"> glyphicon-apple </span><br/> <span class="glyphicon glyphicon-erase"> glyphicon-erase </span><br/> <span class="glyphicon glyphicon-hourglass"> glyphicon-hourglass </span><br/> <span class="glyphicon glyphicon-lamp"> glyphicon-lamp </span><br/> <span class="glyphicon glyphicon-duplicate"> glyphicon-duplicate </span><br/> <span class="glyphicon glyphicon-piggy-bank"> glyphicon-piggy-bank </span><br/> <span class="glyphicon glyphicon-scissors"> glyphicon-scissors </span><br/> <span class="glyphicon glyphicon-bitcoin"> glyphicon-bitcoin </span><br/> <span class="glyphicon glyphicon-yen"> glyphicon-yen </span><br/> <span class="glyphicon glyphicon-ruble"> glyphicon-ruble </span><br/> <span class="glyphicon glyphicon-scale"> glyphicon-scale </span><br/> <span class="glyphicon glyphicon-ice-lolly"> glyphicon-ice-lolly </span><br/> <span class="glyphicon glyphicon-ice-lolly-tasted"> glyphicon-ice-lolly-tasted </span><br/> <span class="glyphicon glyphicon-education"> glyphicon-education </span><br/> <span class="glyphicon glyphicon-option-horizontal"> glyphicon-option-horizontal </span><br/> <span class="glyphicon glyphicon-option-vertical"> glyphicon-option-vertical </span><br/> <span class="glyphicon glyphicon-menu-hamburger"> glyphicon-menu-hamburger </span><br/> <span class="glyphicon glyphicon-modal-window"> glyphicon-modal-window </span><br/> <span class="glyphicon glyphicon-oil"> glyphicon-oil </span><br/> <span class="glyphicon glyphicon-grain"> glyphicon-grain </span><br/> <span class="glyphicon glyphicon-sunglasses"> glyphicon-sunglasses </span><br/> <span class="glyphicon glyphicon-text-size"> glyphicon-text-size </span><br/> <span class="glyphicon glyphicon-text-color"> glyphicon-text-color </span><br/> <span class="glyphicon glyphicon-text-background"> glyphicon-text-background </span><br/> <span class="glyphicon glyphicon-object-align-top"> glyphicon-object-align-top </span><br/> <span class="glyphicon glyphicon-object-align-bottom"> glyphicon-object-align-bottom </span><br/> <span class="glyphicon glyphicon-object-align-horizontal"> glyphicon-object-align-horizontal </span><br/> <span class="glyphicon glyphicon-object-align-left"> glyphicon-object-align-left </span><br/> <span class="glyphicon glyphicon-object-align-vertical"> glyphicon-object-align-vertical </span><br/> <span class="glyphicon glyphicon-object-align-right"> glyphicon-object-align-right </span><br/> <span class="glyphicon glyphicon-triangle-right"> glyphicon-triangle-right </span><br/> <span class="glyphicon glyphicon-triangle-left"> glyphicon-triangle-left </span><br/> <span class="glyphicon glyphicon-triangle-bottom"> glyphicon-triangle-bottom </span><br/> <span class="glyphicon glyphicon-triangle-top"> glyphicon-triangle-top </span><br/> <span class="glyphicon glyphicon-console"> glyphicon-console </span><br/> <span class="glyphicon glyphicon-superscript"> glyphicon-superscript </span><br/> <span class="glyphicon glyphicon-subscript"> glyphicon-subscript </span><br/> <span class="glyphicon glyphicon-menu-left"> glyphicon-menu-left </span><br/> <span class="glyphicon glyphicon-menu-right"> glyphicon-menu-right </span><br/> <span class="glyphicon glyphicon-menu-down"> glyphicon-menu-down </span><br/> <span class="glyphicon glyphicon-menu-up"> glyphicon-menu-up </span><br/> </div> <!-- /.col-lg-6 (nested) --> </div> <!-- /.row (nested) --> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <!-- jQuery --> <script src="../bower_components/jquery/dist/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- Metis Menu Plugin JavaScript --> <script src="../bower_components/metisMenu/dist/metisMenu.min.js"></script> <!-- Custom Theme JavaScript --> <script src="../dist/js/sb-admin-2.js"></script> </body> </html>
bzcen/TreeHacks2016
pages/icons.html
HTML
apache-2.0
83,213
#------------------------------------------------------------------------- # # Copyright (c) Microsoft and contributors. 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. #-------------------------------------------------------------------------- require 'integration/storage/test_helper' require "azure_storage/blob/blob_service" describe Azure::Storage::Blob::BlobService do subject { Azure::Storage::Blob::BlobService.new } after { TableNameHelper.clean } describe '#get_blob' do let(:container_name) { ContainerNameHelper.name } let(:blob_name) { "blobname" } let(:content) { content = ""; 1024.times.each{|i| content << "@" }; content } let(:metadata) { { "CustomMetadataProperty"=>"CustomMetadataValue" } } let(:options) { { :blob_content_type=>"application/foo", :metadata => metadata } } before { subject.create_container container_name subject.create_block_blob container_name, blob_name, content, options } it 'retrieves the blob properties, metadata, and contents' do blob, returned_content = subject.get_blob container_name, blob_name returned_content.must_equal content blob.metadata.must_include "custommetadataproperty" blob.metadata["custommetadataproperty"].must_equal "CustomMetadataValue" blob.properties[:content_type].must_equal "application/foo" end it 'retrieves a range of data from the blob' do blob, returned_content = subject.get_blob container_name, blob_name, { :start_range => 0, :end_range => 511 } returned_content.length.must_equal 512 returned_content.must_equal content[0..511] end it 'retrieves a snapshot of data from the blob' do snapshot = subject.create_blob_snapshot container_name, blob_name content2= "" 1024.times.each{|i| content2 << "!" } subject.create_block_blob container_name, blob_name, content2, options blob, returned_content = subject.get_blob container_name, blob_name, { :start_range => 0, :end_range => 511 } returned_content.length.must_equal 512 returned_content.must_equal content2[0..511] blob, returned_content = subject.get_blob container_name, blob_name, { :start_range => 0, :end_range => 511, :snapshot => snapshot } returned_content.length.must_equal 512 returned_content.must_equal content[0..511] end end end
wastoresh/azure-sdk-for-ruby
test/integration/storage/blob/get_blob_test.rb
Ruby
apache-2.0
2,874
#### Contact Info * [Famous Peppers](http://www.famouspeppers.ca/) - 902-370-7070 * [Royal Canadian Legion Branch #1 Charlottetown](http://charlottetownlegion.sharepoint.com/Pages/0default.aspx) - 902-892-6022
peidevs/Event_Resources
ContactInfo.md
Markdown
apache-2.0
215
# Copyright The OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import abc from typing import Optional, Sequence from opentelemetry.exporter.jaeger.thrift.gen.jaeger import ( Collector as TCollector, ) from opentelemetry.sdk.trace import ReadableSpan, StatusCode from opentelemetry.trace import SpanKind from opentelemetry.util import types OTLP_JAEGER_SPAN_KIND = { SpanKind.CLIENT: "client", SpanKind.SERVER: "server", SpanKind.CONSUMER: "consumer", SpanKind.PRODUCER: "producer", SpanKind.INTERNAL: "internal", } NAME_KEY = "otel.library.name" VERSION_KEY = "otel.library.version" def _nsec_to_usec_round(nsec: int) -> int: """Round nanoseconds to microseconds""" return (nsec + 500) // 10**3 def _convert_int_to_i64(val): """Convert integer to signed int64 (i64)""" if val > 0x7FFFFFFFFFFFFFFF: val -= 0x10000000000000000 return val def _append_dropped(tags, key, val): if val: tags.append(_get_long_tag(key, val)) class Translator(abc.ABC): def __init__(self, max_tag_value_length: Optional[int] = None): self._max_tag_value_length = max_tag_value_length @abc.abstractmethod def _translate_span(self, span): """Translates span to jaeger format. Args: span: span to translate """ @abc.abstractmethod def _extract_tags(self, span): """Extracts tags from span and returns list of jaeger Tags. Args: span: span to extract tags """ @abc.abstractmethod def _extract_refs(self, span): """Extracts references from span and returns list of jaeger SpanRefs. Args: span: span to extract references """ @abc.abstractmethod def _extract_logs(self, span): """Extracts logs from span and returns list of jaeger Logs. Args: span: span to extract logs """ class Translate: def __init__(self, spans): self.spans = spans def _translate(self, translator: Translator): translated_spans = [] for span in self.spans: # pylint: disable=protected-access translated_span = translator._translate_span(span) translated_spans.append(translated_span) return translated_spans def _get_string_tag(key, value: str) -> TCollector.Tag: """Returns jaeger string tag.""" return TCollector.Tag(key=key, vStr=value, vType=TCollector.TagType.STRING) def _get_bool_tag(key: str, value: bool) -> TCollector.Tag: """Returns jaeger boolean tag.""" return TCollector.Tag(key=key, vBool=value, vType=TCollector.TagType.BOOL) def _get_long_tag(key: str, value: int) -> TCollector.Tag: """Returns jaeger long tag.""" return TCollector.Tag(key=key, vLong=value, vType=TCollector.TagType.LONG) def _get_double_tag(key: str, value: float) -> TCollector.Tag: """Returns jaeger double tag.""" return TCollector.Tag( key=key, vDouble=value, vType=TCollector.TagType.DOUBLE ) def _get_trace_id_low(trace_id): return _convert_int_to_i64(trace_id & 0xFFFFFFFFFFFFFFFF) def _get_trace_id_high(trace_id): return _convert_int_to_i64((trace_id >> 64) & 0xFFFFFFFFFFFFFFFF) def _translate_attribute( key: str, value: types.AttributeValue, max_length: Optional[int] ) -> Optional[TCollector.Tag]: """Convert the attributes to jaeger tags.""" if isinstance(value, bool): return _get_bool_tag(key, value) if isinstance(value, str): if max_length is not None: value = value[:max_length] return _get_string_tag(key, value) if isinstance(value, int): return _get_long_tag(key, value) if isinstance(value, float): return _get_double_tag(key, value) if isinstance(value, tuple): value = str(value) if max_length is not None: value = value[:max_length] return _get_string_tag(key, value) return None class ThriftTranslator(Translator): def _translate_span(self, span: ReadableSpan) -> TCollector.Span: ctx = span.get_span_context() trace_id = ctx.trace_id span_id = ctx.span_id start_time_us = _nsec_to_usec_round(span.start_time) duration_us = _nsec_to_usec_round(span.end_time - span.start_time) parent_id = span.parent.span_id if span.parent else 0 tags = self._extract_tags(span) refs = self._extract_refs(span) logs = self._extract_logs(span) flags = int(ctx.trace_flags) jaeger_span = TCollector.Span( traceIdHigh=_get_trace_id_high(trace_id), traceIdLow=_get_trace_id_low(trace_id), spanId=_convert_int_to_i64(span_id), operationName=span.name, startTime=start_time_us, duration=duration_us, tags=tags, logs=logs, references=refs, flags=flags, parentSpanId=_convert_int_to_i64(parent_id), ) return jaeger_span def _extract_tags(self, span: ReadableSpan) -> Sequence[TCollector.Tag]: # pylint: disable=too-many-branches translated = [] if span.attributes: for key, value in span.attributes.items(): tag = _translate_attribute( key, value, self._max_tag_value_length ) if tag: translated.append(tag) if span.resource.attributes: for key, value in span.resource.attributes.items(): tag = _translate_attribute( key, value, self._max_tag_value_length ) if tag: translated.append(tag) status = span.status if status.status_code is not StatusCode.UNSET: translated.append( _get_string_tag("otel.status_code", status.status_code.name) ) if status.description is not None: translated.append( _get_string_tag( "otel.status_description", status.description ) ) translated.append( _get_string_tag("span.kind", OTLP_JAEGER_SPAN_KIND[span.kind]) ) # Instrumentation info tags if span.instrumentation_info: name = _get_string_tag(NAME_KEY, span.instrumentation_info.name) version = _get_string_tag( VERSION_KEY, span.instrumentation_info.version ) translated.extend([name, version]) # Make sure to add "error" tag if span status is not OK if not span.status.is_ok: translated.append(_get_bool_tag("error", True)) _append_dropped( translated, "otel.dropped_attributes_count", span.dropped_attributes, ) _append_dropped( translated, "otel.dropped_events_count", span.dropped_events ) _append_dropped( translated, "otel.dropped_links_count", span.dropped_links ) return translated def _extract_refs( self, span: ReadableSpan ) -> Optional[Sequence[TCollector.SpanRef]]: if not span.links: return None refs = [] for link in span.links: trace_id = link.context.trace_id span_id = link.context.span_id refs.append( TCollector.SpanRef( refType=TCollector.SpanRefType.FOLLOWS_FROM, traceIdHigh=_get_trace_id_high(trace_id), traceIdLow=_get_trace_id_low(trace_id), spanId=_convert_int_to_i64(span_id), ) ) return refs def _extract_logs( self, span: ReadableSpan ) -> Optional[Sequence[TCollector.Log]]: """Returns jaeger logs if events exists, otherwise None. Args: span: span to extract logs """ if not span.events: return None logs = [] for event in span.events: fields = [] for key, value in event.attributes.items(): tag = _translate_attribute( key, value, self._max_tag_value_length ) if tag: fields.append(tag) _append_dropped( fields, "otel.dropped_attributes_count", event.attributes.dropped, ) fields.append( TCollector.Tag( key="message", vType=TCollector.TagType.STRING, vStr=event.name, ) ) event_timestamp_us = _nsec_to_usec_round(event.timestamp) logs.append( TCollector.Log( timestamp=int(event_timestamp_us), fields=fields ) ) return logs
open-telemetry/opentelemetry-python
exporter/opentelemetry-exporter-jaeger-thrift/src/opentelemetry/exporter/jaeger/thrift/translate/__init__.py
Python
apache-2.0
9,548
package net.katsuster.strview.media.m2v; import net.katsuster.strview.util.*; import net.katsuster.strview.util.bit.*; import net.katsuster.strview.media.bit.*; /** * <p> * MPEG2 Video データ。 * </p> */ public class M2VData<T extends LargeList<?>> extends BitPacketAdapter { public M2VData() { this(new M2VHeader()); } public M2VData(M2VHeader h) { super(h); } @Override public String getTypeName() { if (getHeader() instanceof M2VHeaderExt) { M2VHeaderExt h = (M2VHeaderExt)getHeader(); return getHeader().getStartCodeName() + " (" + h.getExtensionStartCodeName() + ")"; } else { return getHeader().getStartCodeName(); } } /** * <p> * MPEG2 Video データのヘッダを取得します。 * </p> * * @return MPEG2 Video データのヘッダ */ @Override public M2VHeader getHeader() { return (M2VHeader)super.getHeader(); } @Override protected void readHeaderBits(BitStreamReader c) { getHeader().read(c); } @Override protected void readBodyBits(BitStreamReader c) { long orgpos; int size_f = 0; int stepback = 0; int acc = 0xffffff; //次のスタートコードを探す c.align(8); orgpos = c.position(); while (c.hasNext(8)) { acc <<= 8; acc |= c.readLong(8); if ((acc & 0xffffff) == 0x000001) { stepback = 24; break; } } size_f = (int)(c.position() - orgpos - stepback); c.position(orgpos); setBody(c.readBitList(size_f, (LargeBitList) getBody())); } @Override protected void writeHeaderBits(BitStreamWriter c) { getHeader().write(c); } @Override protected void writeBodyBits(BitStreamWriter c) { long size_f = getBody().length(); //FIXME: tentative c.writeBitList(size_f, (LargeBitList) getBody(), "body"); } }
katsuster/strview
view/src/net/katsuster/strview/media/m2v/M2VData.java
Java
apache-2.0
2,063
--- layout: page title: About permalink: /about/ desc: 關於・について・Introduction --- <p>This is an example About page.</p> <p>Sparanoid is a one-man design studio operated by Tunghsiao Liu, currently located in China. You can ping me on <a href="http://twitter.com/tunghsiao">Twitter</a> or send correspondence to <a href="mailto:{{ site.profile.email }}">{{ site.profile.email }}</a>.</p> <h3>Colophon</h3> <p> <a href="http://jekyllrb.com/">Jekyll</a> (<a href="http://github.com/sparanoid/sparanoid.com">Source</a>) - <a href="http://github.com/">GitHub</a> - <a href="http://aws.amazon.com/cloudfront/">CloudFront</a> - <a href="http://macromates.com/">Textmate</a> </p> <p>All posts are &copy; Tunghsiao Liu, all rights reserved. The views expressed on this site are mine alone and not those of my employers and clients, past and present.</p>
virtualnz/virtualnz.github.io
_amsf/_app/page-about.html
HTML
apache-2.0
872
# Rhipsalis agudoensis N.P.Taylor SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Rhipsalis/Rhipsalis agudoensis/README.md
Markdown
apache-2.0
181
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>riak-c-driver: Main Page</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javaScript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body onload='searchBox.OnSelectItem(0);'> <!-- Generated by Doxygen 1.7.1 --> <script type="text/javascript"><!-- var searchBox = new SearchBox("searchBox", "search",false,'Search'); --></script> <div class="navigation" id="top"> <div class="tabs"> <ul class="tablist"> <li class="current"><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="annotated.html"><span>Data&nbsp;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li id="searchli"> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <h1>riak-c-driver Documentation</h1> </div> </div> <div class="contents"> <h3 class="version">0.01 </h3></div> <!--- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&nbsp;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&nbsp;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&nbsp;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&nbsp;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&nbsp;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&nbsp;</span>Defines</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr class="footer"/><address class="footer"><small>Generated on Wed Jan 19 2011 for riak-c-driver by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.1 </small></address> </body> </html>
fenek/riak-c-driver
doc/html/index.html
HTML
apache-2.0
3,572
// Copyright 2013 Ghais Issa // // 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. // Package goresque provides a client for working with the Resuque package goresque import ( "encoding/json" "github.com/garyburd/redigo/redis" ) type Client struct { conn redis.Conn } type job struct { Class string `json:"class"` Args []interface{} `json:"args"` } // Dial establishes a connection to the redis instance at url func Dial(url string) (*Client, error) { c, err := redis.Dial("tcp", url) if err != nil { return nil, err } return &Client{c}, nil } func (c *Client) Enqueue(class, queue string, args ...interface{}) error { var j = &job{class, makeJobArgs(args)} job_json, _ := json.Marshal(j) if err := c.conn.Send("LPUSH", "resque:queue:"+queue, job_json); err != nil { return err } return c.conn.Flush() } func (c *Client) Close() error { return c.conn.Close() } //A trick to make [{}] json struct for empty args func makeJobArgs(args []interface{}) []interface{} { if len(args) == 0 { // NOTE: Dirty hack to make a [{}] JSON struct return append(make([]interface{}, 0), make(map[string]interface{}, 0)) } return args }
ghais/goresque
resque.go
GO
apache-2.0
1,668
package org.example.fogbeam.blackboard.agent; import org.example.fogbeam.blackboard.BlackboardFrame; import org.example.fogbeam.blackboard.Conversation; public class GOLEMAgent extends SimpleBlackboardAgent { @Override protected void process(Conversation conversation, BlackboardFrame frame) { // TODO Auto-generated method stub } }
mindcrime/AISandbox
xmpp-aiml-osgi-blackboard-bot/src/main/java/org/example/fogbeam/blackboard/agent/GOLEMAgent.java
Java
apache-2.0
348
+++ pre = "<b>3.4.2.1 </b>" toc = true title = "Local Transaction" weight = 1 +++ ## Function * Fully support none-cross-database transactions, for example, sharding table or sharding database with its route result in one database. * Fully support cross-database transactions caused by logic exceptions, for example, the update of two databases in one transaction, after which, databases will throw null cursor and the content in both databases can be rolled back. * Do not support the cross-database transactions caused by network or hardware exceptions. For example, after the update of two databases in one transaction, if one database is down before submitted, then only the data of the other database can be submitted. ## Support * Sharding-JDBC and Sharding-Proxy can innately support local transaction.
shardingjdbc/sharding-jdbc
docs/document/content/features/transaction/function/local-transaction.en.md
Markdown
apache-2.0
817
package ru.sdroman.jdbc.tracker.input; import ru.sdroman.jdbc.tracker.exception.MenuOutException; import java.util.Scanner; /** * Class for console input. */ public class ConsoleInput implements Input { /** * Scanner. */ private Scanner scanner = new Scanner(System.in); /** * Asks the question and returns a answer. * * @param question String * @return String answer */ public String ask(String question) { System.out.print(question); return scanner.nextLine(); } /** * Asks the question and returns a answer. * * @param question String * @param range int[] * @return int * @throws MenuOutException exception */ public int ask(String question, int[] range) { int key = Integer.valueOf(this.ask(question)); boolean exist = false; for (int value : range) { if (value == key) { exist = true; break; } } if (exist) { return key; } else { throw new MenuOutException("Out of menu range."); } } }
roman-sd/java-a-to-z
chapter_008/src/main/java/ru/sdroman/jdbc/tracker/input/ConsoleInput.java
Java
apache-2.0
1,156
APP = cmd-clip OBJS = clip.o searcher.o main.o all: $(APP) %.o: %.cpp @echo "C++ $<" @g++ --std=c++11 -g $^ -c -o $@ $(APP): $(OBJS) @echo "LD $(APP)" @g++ $(LDFLAGS) -g $^ -o $@ clean: @for obj in "$(OBJS) $(APP)"; do\ echo "RM $${obj}"; \ rm $${obj} 2>/dev/null; \ done;
gordski/cmd-clip
src/Makefile
Makefile
apache-2.0
287
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_11) on Mon Mar 17 10:51:58 PDT 2014 --> <title>Uses of Class com.box.boxjavalibv2.requests.CreateEnterpriseUserRequestTest</title> <meta name="date" content="2014-03-17"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.box.boxjavalibv2.requests.CreateEnterpriseUserRequestTest"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/box/boxjavalibv2/requests/CreateEnterpriseUserRequestTest.html" title="class in com.box.boxjavalibv2.requests">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/box/boxjavalibv2/requests/class-use/CreateEnterpriseUserRequestTest.html" target="_top">Frames</a></li> <li><a href="CreateEnterpriseUserRequestTest.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.box.boxjavalibv2.requests.CreateEnterpriseUserRequestTest" class="title">Uses of Class<br>com.box.boxjavalibv2.requests.CreateEnterpriseUserRequestTest</h2> </div> <div class="classUseContainer">No usage of com.box.boxjavalibv2.requests.CreateEnterpriseUserRequestTest</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/box/boxjavalibv2/requests/CreateEnterpriseUserRequestTest.html" title="class in com.box.boxjavalibv2.requests">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/box/boxjavalibv2/requests/class-use/CreateEnterpriseUserRequestTest.html" target="_top">Frames</a></li> <li><a href="CreateEnterpriseUserRequestTest.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
shelsonjava/box-java-sdk-v2
javadoc/com/box/boxjavalibv2/requests/class-use/CreateEnterpriseUserRequestTest.html
HTML
apache-2.0
4,416
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // This file is based on or incorporates material from the project Selenium, licensed under the Apache License, Version 2.0. More info in THIRD-PARTY-NOTICES file. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Zu.WebBrowser.AsyncInteractions; namespace Zu.AsyncWebDriver.Interactions { /// <summary> /// Defines an action that consists of a list of other actions to be performed in the browser. /// </summary> public class CompositeAction : IAction { private readonly List<IAction> actionsList = new List<IAction>(); /// <summary> /// Performs the actions defined in this list of actions. /// </summary> public async Task Perform(CancellationToken cancellationToken = new CancellationToken()) { foreach (var action in actionsList) await action.Perform(cancellationToken).ConfigureAwait(false); } /// <summary> /// Adds an action to the list of actions to be performed. /// </summary> /// <param name = "action"> /// An <see cref = "IAction"/> to be appended to the /// list of actions to be performed. /// </param> /// <returns>A self reference.</returns> public CompositeAction AddAction(IAction action) { actionsList.Add(action); return this; } } }
ToCSharp/AsyncWebDriver
AsyncWebDriver/Interactions/CompositeAction.cs
C#
apache-2.0
1,599
<?php namespace PivotLibre\Tideman; use InvalidArgumentException; class CandidateRankingSerializer { private const ORDERED_DELIM = ">"; private const EQUAL_DELIM = "="; private const PROHIBITED_CHARACTERS = [ '<', // only one direction of comparison is supported '*', // asterisks are used elsewhere to separate a ballot from how many times the same ballot occurred self::EQUAL_DELIM, self::ORDERED_DELIM ]; /** * @param CandidateRanking $candidateRanking * @return string in BFF * @throws InvalidArgumentException if the ranking could not be serialized. */ public function serialize(CandidateRanking $candidateRanking) : string { $flattenedCandidateList = array_map( function ($candidateList) { return $this->serializeEqualCandidates($candidateList); }, $candidateRanking->toArray() ); $serializedCandidateRanking = implode(self::ORDERED_DELIM, $flattenedCandidateList); return $serializedCandidateRanking; } /** * @param CandidateList $candidateList a list of candidates whose candidates' ranks are equal * @return string an '='-delimited sequence of candidate ids */ public function serializeEqualCandidates(CandidateList $candidateList) : string { $candidateIds = array_map( function ($candidate) { return $this->getCandidateId($candidate); }, $candidateList->toArray() ); $serializedEquals = implode(self::EQUAL_DELIM, $candidateIds); return $serializedEquals; } /** * @param Candidate $candidate the candidate to extract the id from * @return string candidate id * @throws InvalidArgumentException if the candidate id is not serializable */ public function getCandidateId(Candidate $candidate) : string { $id = $candidate->getId(); $this->throwIfBlank($id); $this->throwIfProhibitedCharactersPresent($id); return $id; } /** * @throws InvalidArgumentException if trimmed string is of zero length * @param string $str */ private function throwIfBlank(string $str) : void { if ('' === trim($str)) { throw new InvalidArgumentException( "Error serializing ranking of Candidates -- found blank where candidate id was expected" ); } } /** * @param string $text * @throws InvalidArgumentException if $text contains anything in CandidateRankingParser::PROHIBITED_CHARACTERS */ private function throwIfProhibitedCharactersPresent(string $text) : void { foreach (CandidateRankingSerializer::PROHIBITED_CHARACTERS as $prohibitedCharacter) { if ($this->contains($prohibitedCharacter, $text)) { throw new InvalidArgumentException( "Found illegal character '$prohibitedCharacter' in candidate id '$text'" ); } } } /** * @param string $needle * @param string $haystack * @return bool - true if $needle in $haystack, false otherwise */ private function contains(string $needle, string $haystack) { return strpos($haystack, $needle) !== false; } }
pivot-libre/tideman
src/CandidateRankingSerializer.php
PHP
apache-2.0
3,343
package fr.javatronic.blog.processor; import java.util.Collections; import java.util.Set; import javax.annotation.processing.Completion; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; /** * Processor_013 - * * @author Sébastien Lesaint */ public class Processor_013 implements Processor { @Override public Set<String> getSupportedOptions() { return Collections.emptySet(); } @Override public Set<String> getSupportedAnnotationTypes() { return Collections.singleton(Annotation_013.class.getCanonicalName()); } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.RELEASE_6; } @Override public void init(ProcessingEnvironment processingEnv) { // nothing to do } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { return true; // supported annotations belong to this Annotation Proessor, so we claim them by returning true } @Override public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) { return null; //To change body of implemented methods use File | Settings | File Templates. } }
lesaint/experimenting-annotation-processing
experimenting-rounds/processor/src/main/java/fr/javatronic/blog/processor/Processor_013.java
Java
apache-2.0
1,615
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mediatailor.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mediatailor-2018-04-23/CreatePrefetchSchedule" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreatePrefetchScheduleResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The Amazon Resource Name (ARN) of the prefetch schedule. * </p> */ private String arn; /** * <p> * Consumption settings determine how, and when, MediaTailor places the prefetched ads into ad breaks. Ad * consumption occurs within a span of time that you define, called a <i>consumption window</i>. You can designate * which ad breaks that MediaTailor fills with prefetch ads by setting avail matching criteria. * </p> */ private PrefetchConsumption consumption; /** * <p> * The name of the prefetch schedule. The name must be unique among all prefetch schedules that are associated with * the specified playback configuration. * </p> */ private String name; /** * <p> * The name of the playback configuration to create the prefetch schedule for. * </p> */ private String playbackConfigurationName; /** * <p> * A complex type that contains settings for prefetch retrieval from the ad decision server (ADS). * </p> */ private PrefetchRetrieval retrieval; /** * <p> * An optional stream identifier that you can specify in order to prefetch for multiple streams that use the same * playback configuration. * </p> */ private String streamId; /** * <p> * The Amazon Resource Name (ARN) of the prefetch schedule. * </p> * * @param arn * The Amazon Resource Name (ARN) of the prefetch schedule. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The Amazon Resource Name (ARN) of the prefetch schedule. * </p> * * @return The Amazon Resource Name (ARN) of the prefetch schedule. */ public String getArn() { return this.arn; } /** * <p> * The Amazon Resource Name (ARN) of the prefetch schedule. * </p> * * @param arn * The Amazon Resource Name (ARN) of the prefetch schedule. * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePrefetchScheduleResult withArn(String arn) { setArn(arn); return this; } /** * <p> * Consumption settings determine how, and when, MediaTailor places the prefetched ads into ad breaks. Ad * consumption occurs within a span of time that you define, called a <i>consumption window</i>. You can designate * which ad breaks that MediaTailor fills with prefetch ads by setting avail matching criteria. * </p> * * @param consumption * Consumption settings determine how, and when, MediaTailor places the prefetched ads into ad breaks. Ad * consumption occurs within a span of time that you define, called a <i>consumption window</i>. You can * designate which ad breaks that MediaTailor fills with prefetch ads by setting avail matching criteria. */ public void setConsumption(PrefetchConsumption consumption) { this.consumption = consumption; } /** * <p> * Consumption settings determine how, and when, MediaTailor places the prefetched ads into ad breaks. Ad * consumption occurs within a span of time that you define, called a <i>consumption window</i>. You can designate * which ad breaks that MediaTailor fills with prefetch ads by setting avail matching criteria. * </p> * * @return Consumption settings determine how, and when, MediaTailor places the prefetched ads into ad breaks. Ad * consumption occurs within a span of time that you define, called a <i>consumption window</i>. You can * designate which ad breaks that MediaTailor fills with prefetch ads by setting avail matching criteria. */ public PrefetchConsumption getConsumption() { return this.consumption; } /** * <p> * Consumption settings determine how, and when, MediaTailor places the prefetched ads into ad breaks. Ad * consumption occurs within a span of time that you define, called a <i>consumption window</i>. You can designate * which ad breaks that MediaTailor fills with prefetch ads by setting avail matching criteria. * </p> * * @param consumption * Consumption settings determine how, and when, MediaTailor places the prefetched ads into ad breaks. Ad * consumption occurs within a span of time that you define, called a <i>consumption window</i>. You can * designate which ad breaks that MediaTailor fills with prefetch ads by setting avail matching criteria. * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePrefetchScheduleResult withConsumption(PrefetchConsumption consumption) { setConsumption(consumption); return this; } /** * <p> * The name of the prefetch schedule. The name must be unique among all prefetch schedules that are associated with * the specified playback configuration. * </p> * * @param name * The name of the prefetch schedule. The name must be unique among all prefetch schedules that are * associated with the specified playback configuration. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the prefetch schedule. The name must be unique among all prefetch schedules that are associated with * the specified playback configuration. * </p> * * @return The name of the prefetch schedule. The name must be unique among all prefetch schedules that are * associated with the specified playback configuration. */ public String getName() { return this.name; } /** * <p> * The name of the prefetch schedule. The name must be unique among all prefetch schedules that are associated with * the specified playback configuration. * </p> * * @param name * The name of the prefetch schedule. The name must be unique among all prefetch schedules that are * associated with the specified playback configuration. * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePrefetchScheduleResult withName(String name) { setName(name); return this; } /** * <p> * The name of the playback configuration to create the prefetch schedule for. * </p> * * @param playbackConfigurationName * The name of the playback configuration to create the prefetch schedule for. */ public void setPlaybackConfigurationName(String playbackConfigurationName) { this.playbackConfigurationName = playbackConfigurationName; } /** * <p> * The name of the playback configuration to create the prefetch schedule for. * </p> * * @return The name of the playback configuration to create the prefetch schedule for. */ public String getPlaybackConfigurationName() { return this.playbackConfigurationName; } /** * <p> * The name of the playback configuration to create the prefetch schedule for. * </p> * * @param playbackConfigurationName * The name of the playback configuration to create the prefetch schedule for. * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePrefetchScheduleResult withPlaybackConfigurationName(String playbackConfigurationName) { setPlaybackConfigurationName(playbackConfigurationName); return this; } /** * <p> * A complex type that contains settings for prefetch retrieval from the ad decision server (ADS). * </p> * * @param retrieval * A complex type that contains settings for prefetch retrieval from the ad decision server (ADS). */ public void setRetrieval(PrefetchRetrieval retrieval) { this.retrieval = retrieval; } /** * <p> * A complex type that contains settings for prefetch retrieval from the ad decision server (ADS). * </p> * * @return A complex type that contains settings for prefetch retrieval from the ad decision server (ADS). */ public PrefetchRetrieval getRetrieval() { return this.retrieval; } /** * <p> * A complex type that contains settings for prefetch retrieval from the ad decision server (ADS). * </p> * * @param retrieval * A complex type that contains settings for prefetch retrieval from the ad decision server (ADS). * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePrefetchScheduleResult withRetrieval(PrefetchRetrieval retrieval) { setRetrieval(retrieval); return this; } /** * <p> * An optional stream identifier that you can specify in order to prefetch for multiple streams that use the same * playback configuration. * </p> * * @param streamId * An optional stream identifier that you can specify in order to prefetch for multiple streams that use the * same playback configuration. */ public void setStreamId(String streamId) { this.streamId = streamId; } /** * <p> * An optional stream identifier that you can specify in order to prefetch for multiple streams that use the same * playback configuration. * </p> * * @return An optional stream identifier that you can specify in order to prefetch for multiple streams that use the * same playback configuration. */ public String getStreamId() { return this.streamId; } /** * <p> * An optional stream identifier that you can specify in order to prefetch for multiple streams that use the same * playback configuration. * </p> * * @param streamId * An optional stream identifier that you can specify in order to prefetch for multiple streams that use the * same playback configuration. * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePrefetchScheduleResult withStreamId(String streamId) { setStreamId(streamId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getArn() != null) sb.append("Arn: ").append(getArn()).append(","); if (getConsumption() != null) sb.append("Consumption: ").append(getConsumption()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getPlaybackConfigurationName() != null) sb.append("PlaybackConfigurationName: ").append(getPlaybackConfigurationName()).append(","); if (getRetrieval() != null) sb.append("Retrieval: ").append(getRetrieval()).append(","); if (getStreamId() != null) sb.append("StreamId: ").append(getStreamId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreatePrefetchScheduleResult == false) return false; CreatePrefetchScheduleResult other = (CreatePrefetchScheduleResult) obj; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; if (other.getConsumption() == null ^ this.getConsumption() == null) return false; if (other.getConsumption() != null && other.getConsumption().equals(this.getConsumption()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getPlaybackConfigurationName() == null ^ this.getPlaybackConfigurationName() == null) return false; if (other.getPlaybackConfigurationName() != null && other.getPlaybackConfigurationName().equals(this.getPlaybackConfigurationName()) == false) return false; if (other.getRetrieval() == null ^ this.getRetrieval() == null) return false; if (other.getRetrieval() != null && other.getRetrieval().equals(this.getRetrieval()) == false) return false; if (other.getStreamId() == null ^ this.getStreamId() == null) return false; if (other.getStreamId() != null && other.getStreamId().equals(this.getStreamId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); hashCode = prime * hashCode + ((getConsumption() == null) ? 0 : getConsumption().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getPlaybackConfigurationName() == null) ? 0 : getPlaybackConfigurationName().hashCode()); hashCode = prime * hashCode + ((getRetrieval() == null) ? 0 : getRetrieval().hashCode()); hashCode = prime * hashCode + ((getStreamId() == null) ? 0 : getStreamId().hashCode()); return hashCode; } @Override public CreatePrefetchScheduleResult clone() { try { return (CreatePrefetchScheduleResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
aws/aws-sdk-java
aws-java-sdk-mediatailor/src/main/java/com/amazonaws/services/mediatailor/model/CreatePrefetchScheduleResult.java
Java
apache-2.0
15,633
#region License /* * Copyright 2017 Rodimiro Cerrato Espinal. * * 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. */ #endregion using System; using System.Reflection; using Spring.Context; using Spring.Context.Support; using Spring.Objects.Factory; using Spring.Objects.Factory.Config; namespace NDeepSubrogate.Spring { internal static class ExtensionMethods { public static void RemoveSingleton(this IConfigurableObjectFactory objectFactory, string name) { objectFactory.GetType() .InvokeMember("RemoveSingleton", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, objectFactory, new object[] { name }); } public static IFactoryObject GetFactoryObject(this IConfigurableApplicationContext applicationContext, string name) { // In Spring.NET the factory object itself of an object can be retrieved by prefixing its name // with an ampersand "&". var factoryObjectName = $"&{name}"; return (IFactoryObject) applicationContext.GetObject(factoryObjectName); } public static IObjectDefinition GetObjectDefinition(this IConfigurableApplicationContext applicationContext, string name) { try { return ((AbstractApplicationContext)applicationContext).GetObjectDefinition(name); } catch (InvalidCastException e) { throw new InvalidOperationException($"Cannot register object definition with name: {name}", e); } } public static void RegisterObjectDefinition(this IConfigurableApplicationContext applicationContext, string name, IObjectDefinition definition) { try { ((AbstractApplicationContext)applicationContext).RegisterObjectDefinition(name, definition); } catch (InvalidCastException e) { throw new InvalidOperationException($"Cannot register object definition with name: {name}", e); } } public static void ReplaceObjectDefinition(this IConfigurableApplicationContext applicationContext, string name, IObjectDefinition definition) { if (definition?.ObjectType != typeof(SurrogateFactoryObject)) { // Proceed here if the object definition will replace the object definition of the // SurrogateFactoryObject type. var factoryObject = applicationContext.GetFactoryObject(name); if (factoryObject is SurrogateFactoryObject && factoryObject.IsSingleton) { // If it happens that Sprint.NET decides to cache this singleton object, then // proceed to clear its state, like call counters. This is to make sure that // a new test starts with a clean mock/spy surrogate. var fakeObject = applicationContext.GetObject(name); FakeItEasy.Fake.ClearRecordedCalls(fakeObject); } } applicationContext.ObjectFactory.RemoveSingleton(name); applicationContext.RegisterObjectDefinition(name, definition); } } }
rodyce/NDeepSubrogate
NDeepSubrogate.Spring/ExtensionMethods.cs
C#
apache-2.0
3,906
package com.shuframework.javaeedemo.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import org.springframework.core.annotation.Order; /** * 使用注解标注过滤器 * // * @WebFilter将一个实现了javax.servlet.Filter接口的类定义为过滤器 * 属性filterName声明过滤器的名称,可选 * 属性urlPatterns指定要过滤的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性) */ //@WebFilter(filterName = "aFilter", urlPatterns = "/*") public class AFilter implements Filter { @Override public void init(FilterConfig config) throws ServletException { System.out.println("aFilter过滤器初始化"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("aFilter执行过滤操作"); chain.doFilter(request, response); } @Override public void destroy() { System.out.println("aFilter过滤器销毁"); } }
shuxiaoxiao/springboot-maven
springboot-init/src/main/java/com/shuframework/javaeedemo/filter/AFilter.java
Java
apache-2.0
1,240
<?php declare(strict_types=1); /** * DO NOT EDIT THIS FILE as it will be overwritten by the Pbj compiler. * @link https://github.com/gdbots/pbjc-php * * Returns an array of curies using mixin "gdbots:ncr:mixin:edge:v1" * @link http://schemas.triniti.io/json-schema/gdbots/ncr/mixin/edge/1-0-0.json# */ return [ ];
triniti/schemas
build/php/src/manifests/gdbots/ncr/mixin/edge/v1.php
PHP
apache-2.0
322
package com.sage.cerberus.core.validators; import com.sage.cerberus.controller.resourceItems.GameResourceItem; import com.sage.cerberus.validation.MessageInvalidationReason; import com.sage.cerberus.validation.ValidationResult; import com.sage.cerberus.validation.Validator; public class GameResourceItemValidator implements Validator<GameResourceItem> { @Override public ValidationResult validate(GameResourceItem candidate) { ValidationResult result = new ValidationResult(); if(candidate.getPlatforms().isEmpty() ){ result.addReason(MessageInvalidationReason.error("Invalid platforms for Game")); // maybe could be more specific to empty list } if(candidate.getName().isEmpty()){ result.addReason(MessageInvalidationReason.error("Invalid name for Game")); } return result; } }
hhennies/Cerberus
src/main/java/com/sage/cerberus/core/validators/GameResourceItemValidator.java
Java
apache-2.0
814
/** * @file Resource.java * @brief shiro16-colligate's file * @author 许立亢 * @date 2015年9月16日 * @par Copyright (c) 2015 , [email protected] All Rights Reserved */ package com.github.star45.shiro.chapter16.entity; import java.io.Serializable; /** * @brief 类简短说明 * @details 详细说明 * @warning 注意事项 * @date 2015年9月16日 * @author 许立亢 * @version 1.0 * @ingroup g_scmcc_power_model */ @SuppressWarnings("serial") public class Resource implements Serializable{ private Long id; //编号 private String name; //资源名称 private ResourceType type = ResourceType.menu; //资源类型 private String url; //资源路径 private String permission; //权限字符串 private Long parentId; //父编号 private String parentIds; //父编号列表 private Boolean available = Boolean.FALSE; public static enum ResourceType { menu("菜单"), button("按钮"); private final String info; private ResourceType(String info) { this.info = info; } public String getInfo() { return info; } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ResourceType getType() { return type; } public void setType(ResourceType type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentIds() { return parentIds; } public void setParentIds(String parentIds) { this.parentIds = parentIds; } public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } public boolean isRootNode() { return parentId == 0; } public String makeSelfAsParentIds() { return getParentIds() + getId() + "/"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Resource resource = (Resource) o; if (id != null ? !id.equals(resource.id) : resource.id != null) return false; return true; } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } @Override public String toString() { return "Resource{" + "id=" + id + ", name='" + name + '\'' + ", type=" + type + ", permission='" + permission + '\'' + ", parentId=" + parentId + ", parentIds='" + parentIds + '\'' + ", available=" + available + '}'; } }
star45/shiro
shiro16-colligate/src/main/java/com/github/star45/shiro/chapter16/entity/Resource.java
Java
apache-2.0
3,396
package it.unibz.inf.ontop.parser; /* * #%L * ontop-obdalib-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * 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. * #L% */ import it.unibz.inf.ontop.io.ModelIOManager; import it.unibz.inf.ontop.model.OBDADataFactory; import it.unibz.inf.ontop.model.OBDAMappingAxiom; import it.unibz.inf.ontop.model.OBDAModel; import it.unibz.inf.ontop.model.impl.OBDADataFactoryImpl; import it.unibz.inf.ontop.sql.DBMetadata; import it.unibz.inf.ontop.sql.DBMetadataExtractor; import it.unibz.inf.ontop.sql.QuotedIDFactory; import it.unibz.inf.ontop.sql.api.ParsedSQLQuery; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Hashtable; import junit.framework.TestCase; import net.sf.jsqlparser.JSQLParserException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ParserFileTest extends TestCase { private static final String ROOT = "src/test/resources/scenario/"; final static Logger log = LoggerFactory .getLogger(ParserFileTest.class); // @Test public void testStockExchange_Pgsql() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/stockexchange-pgsql.owl"); execute(model, new URI("RandBStockExchange")); } // @Test public void testImdbGroup4_Pgsql() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/imdb-group4-pgsql.owl"); execute(model, new URI("kbdb_imdb")); } // @Test public void testImdbGroup4_Oracle() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/imdb-group4-oracle.owl"); execute(model, new URI("kbdb_imdb")); } // @Test public void testAdolenaSlim_Pgsql() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/adolena-slim-pgsql.owl"); execute(model, new URI("nap")); } // @Test public void testBooksApril20_Pgsql() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/books-april20-pgsql.owl"); execute(model, new URI("datasource")); } // @Test public void testHgt090303_Mysql() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/hgt-090303-mysql.owl"); execute(model, new URI("HGT")); } // @Test public void testHgt090324_Pgsql() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/hgt-090324-pgsql.owl"); execute(model, new URI("HGT")); } // @Test public void testHgt091007_Oracle() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/hgt-091007-oracle.owl"); execute(model, new URI("HGT")); } // @Test public void testMpsOntologiaGcc_DB2() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/mps-ontologiagcc-db2.owl"); execute(model, new URI("sourceGCC")); } // @Test public void testOperationNoyauV5_Oracle() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/operation-noyau-v5-oracle.owl"); execute(model, new URI("PgmOpe")); } // @Test public void testOperationNoyauV6_Oracle() throws URISyntaxException { OBDAModel model = load(ROOT + "virtual/operation-noyau-v6-oracle.owl"); execute(model, new URI("CORIOLIS-CRAQ")); execute(model, new URI("PROGOS-CRAQ")); } // ------- Utility methods private void execute(OBDAModel model, URI identifier) { DBMetadata dbMetadata = DBMetadataExtractor.createDummyMetadata(); QuotedIDFactory idfac = dbMetadata.getQuotedIDFactory(); OBDAModel controller = model; Hashtable<URI, ArrayList<OBDAMappingAxiom>> mappingList = controller.getMappings(); ArrayList<OBDAMappingAxiom> mappings = mappingList.get(identifier); log.debug("=========== " + identifier + " ==========="); for (OBDAMappingAxiom axiom : mappings) { String query = axiom.getSourceQuery().toString(); boolean result = parse(query, idfac); if (!result) { log.error("Cannot parse query: " + query); assertFalse(result); } else { assertTrue(result); } } } private OBDAModel load(String file) { final String obdafile = file.substring(0, file.length() - 3) + "obda"; OBDADataFactory factory = OBDADataFactoryImpl.getInstance(); OBDAModel model = factory.getOBDAModel(); ModelIOManager ioManager = new ModelIOManager(model); try { ioManager.load(obdafile); } catch (Exception e) { log.debug(e.toString()); } return model; } private static boolean parse(String input, QuotedIDFactory idfac) { ParsedSQLQuery queryP; try { queryP = new ParsedSQLQuery(input, true, idfac); } catch (JSQLParserException e) { log.debug(e.getMessage()); return false; } return true; } }
srapisarda/ontop
obdalib-core/src/test/java/it/unibz/inf/ontop/parser/ParserFileTest.java
Java
apache-2.0
5,099
/* * Copyright 2014 Lars Edenbrandt * * 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. */ package se.nimsa.sbx.anonymization import akka.NotUsed import akka.stream.scaladsl.Source import se.nimsa.dicom.data.TagPath import se.nimsa.dicom.data.TagPath.TagPathTag import se.nimsa.sbx.anonymization.AnonymizationProtocol._ import se.nimsa.sbx.dicom.DicomProperty import se.nimsa.sbx.metadata.MetaDataProtocol._ import se.nimsa.sbx.util.DbUtil.{checkColumnExists, createTables} import slick.basic.DatabaseConfig import slick.jdbc.{GetResult, JdbcProfile} import scala.concurrent.{ExecutionContext, Future} class AnonymizationDAO(val dbConf: DatabaseConfig[JdbcProfile])(implicit ec: ExecutionContext) { import dbConf.profile.api._ val db = dbConf.db class AnonymizationKeyTable(tag: Tag) extends Table[AnonymizationKey](tag, AnonymizationKeyTable.name) { def id = column[Long]("id", O.PrimaryKey, O.AutoInc) def created = column[Long]("created") def imageId = column[Long]("imageId") def patientName = column[String](DicomProperty.PatientName.name, O.Length(512)) def anonPatientName = column[String]("anonPatientName", O.Length(512)) def patientID = column[String](DicomProperty.PatientID.name, O.Length(128)) def anonPatientID = column[String]("anonPatientID", O.Length(128)) def studyInstanceUID = column[String](DicomProperty.StudyInstanceUID.name, O.Length(128)) def anonStudyInstanceUID = column[String]("anonStudyInstanceUID", O.Length(128)) def seriesInstanceUID = column[String](DicomProperty.SeriesInstanceUID.name, O.Length(128)) def anonSeriesInstanceUID = column[String]("anonSeriesInstanceUID", O.Length(128)) def sopInstanceUID = column[String](DicomProperty.SOPInstanceUID.name, O.Length(128)) def anonSOPInstanceUID = column[String]("anonSOPInstanceUID", O.Length(128)) def idxPatientName = index("idx_anon_patient_name", patientName) def idxPatientID = index("idx_anon_patient_id", patientID) def idxStudyInstanceUID = index("idx_anon_study_uid", studyInstanceUID) def idxSeriesInstanceUID = index("idx_anon_series_uid", seriesInstanceUID) def idxSOPInstanceUID = index("idx_anon_sop_uid", sopInstanceUID) def idxAnonPatientName = index("idx_anon_anon_patient_name", anonPatientName) def idxAnonPatientID = index("idx_anon_anon_patient_id", anonPatientID) def idxAnonStudyInstanceUID = index("idx_anon_anon_study_uid", anonStudyInstanceUID) def idxAnonSeriesInstanceUID = index("idx_anon_anon_series_uid", anonSeriesInstanceUID) def idxAnonSOPInstanceUID = index("idx_anon_anon_sop_uid", anonSOPInstanceUID) def * = (id, created, imageId, patientName, anonPatientName, patientID, anonPatientID, studyInstanceUID, anonStudyInstanceUID, seriesInstanceUID, anonSeriesInstanceUID, sopInstanceUID, anonSOPInstanceUID) <> (AnonymizationKey.tupled, AnonymizationKey.unapply) } object AnonymizationKeyTable { val name = "AnonymizationKeys" } val anonymizationKeyQuery = TableQuery[AnonymizationKeyTable] val anonymizationKeysGetResult = GetResult(r => AnonymizationKey(r.nextLong, r.nextLong, r.nextLong, r.nextString, r.nextString, r.nextString, r.nextString, r.nextString, r.nextString, r.nextString, r.nextString, r.nextString, r.nextString)) val toKeyValue: (Long, Long, String, String, String) => AnonymizationKeyValue = (id: Long, anonymizationKeyId: Long, tagPath: String, value: String, anonymizedValue: String) => AnonymizationKeyValue(id, anonymizationKeyId, TagPathTag.parse(tagPath), value, anonymizedValue) val fromKeyValue: AnonymizationKeyValue => Option[(Long, Long, String, String, String)] = (keyValue: AnonymizationKeyValue) => Option((keyValue.id, keyValue.anonymizationKeyId, keyValue.tagPath.toString, keyValue.value, keyValue.anonymizedValue)) class AnonymizationKeyValueTable(tag: Tag) extends Table[AnonymizationKeyValue](tag, AnonymizationKeyValueTable.name) { def id = column[Long]("id", O.PrimaryKey, O.AutoInc) def anonymizationKeyId = column[Long]("anonymizationkeyid") def tagPath = column[String]("tagpath") def value = column[String]("value") def anonymizedValue = column[String]("anonymizedvalue") def fkAnonymizationKey = foreignKey("fk_anonymization_key", anonymizationKeyId, anonymizationKeyQuery)(_.id, onDelete = ForeignKeyAction.Cascade) def * = (id, anonymizationKeyId, tagPath, value, anonymizedValue) <> (toKeyValue.tupled, fromKeyValue) } object AnonymizationKeyValueTable { val name = "AnonymizationKeyValues" } val anonymizationKeyValueQuery = TableQuery[AnonymizationKeyValueTable] def create(): Future[Unit] = createTables(dbConf, (AnonymizationKeyTable.name, anonymizationKeyQuery), (AnonymizationKeyValueTable.name, anonymizationKeyValueQuery)) def drop(): Future[Unit] = db.run { (anonymizationKeyQuery.schema ++ anonymizationKeyValueQuery.schema).drop } def clear(): Future[Unit] = db.run { DBIO.seq(anonymizationKeyQuery.delete, anonymizationKeyValueQuery.delete) } def listAnonymizationKeys: Future[Seq[AnonymizationKey]] = db.run(anonymizationKeyQuery.result) def listAnonymizationKeyValues: Future[Seq[AnonymizationKeyValue]] = db.run(anonymizationKeyValueQuery.result) def anonymizationKeys(startIndex: Long, count: Long, orderBy: Option[String], orderAscending: Boolean, filter: Option[String]): Future[Seq[AnonymizationKey]] = checkColumnExists(dbConf, orderBy, AnonymizationKeyTable.name).flatMap { _ => db.run { implicit val getResult: GetResult[AnonymizationKey] = anonymizationKeysGetResult var query = """select * from "AnonymizationKeys"""" filter.foreach { filterValue => val filterValueLike = s"'$filterValue%'".toLowerCase query += s""" where lcase("patientName") like $filterValueLike or lcase("anonPatientName") like $filterValueLike or lcase("patientID") like $filterValueLike or lcase("anonPatientID") like $filterValueLike or lcase("studyInstanceUID") like $filterValueLike or lcase("anonStudyInstanceUID") like $filterValueLike or lcase("seriesInstanceUID") like $filterValueLike or lcase("anonSeriesInstanceUID") like $filterValueLike or lcase("sopInstanceUID") like $filterValueLike or lcase("anonSOPInstanceUID") like $filterValueLike""" } orderBy.foreach(orderByValue => query += s""" order by "$orderByValue" ${if (orderAscending) "asc" else "desc"}""") query += s""" limit $count offset $startIndex""" sql"#$query".as[AnonymizationKey] } } def anonymizationKeyForId(id: Long): Future[Option[AnonymizationKey]] = db.run { anonymizationKeyQuery.filter(_.id === id).result.headOption } def insertAnonymizationKey(entry: AnonymizationKey): Future[AnonymizationKey] = db.run { (anonymizationKeyQuery returning anonymizationKeyQuery.map(_.id) += entry) .map(generatedId => entry.copy(id = generatedId)) } def insertAnonymizationKeyValues(values: Seq[AnonymizationKeyValue]): Future[Unit] = db.run { (anonymizationKeyValueQuery ++= values).map(_ => {}) } def deleteAnonymizationKey(anonymizationKeyId: Long): Future[Unit] = db.run { anonymizationKeyQuery.filter(_.id === anonymizationKeyId).delete.map(_ => Unit) } def deleteAnonymizationKeysForImageIds(imageIds: Seq[Long]): Future[Unit] = db.run { anonymizationKeyQuery.filter(_.imageId inSetBind imageIds).delete.map(_ => {}) } def anonymizationKeyForImage(patientName: String, patientID: String, studyInstanceUID: String, seriesInstanceUID: String, sopInstanceUID: String): Future[Option[AnonymizationKey]] = db.run { anonymizationKeyQuery .filter(_.patientName === patientName) .filter(_.patientID === patientID) .filter(_.studyInstanceUID === studyInstanceUID) .filter(_.seriesInstanceUID === seriesInstanceUID) .filter(_.sopInstanceUID === sopInstanceUID) .sortBy(_.created.desc) .result .headOption } def anonymizationKeyForSeries(patientName: String, patientID: String, studyInstanceUID: String, seriesInstanceUID: String): Future[Option[AnonymizationKey]] = db.run { anonymizationKeyQuery .filter(_.patientName === patientName) .filter(_.patientID === patientID) .filter(_.studyInstanceUID === studyInstanceUID) .filter(_.seriesInstanceUID === seriesInstanceUID) .sortBy(_.created.desc) .result .headOption } def anonymizationKeyForStudy(patientName: String, patientID: String, studyInstanceUID: String): Future[Option[AnonymizationKey]] = db.run { anonymizationKeyQuery .filter(_.patientName === patientName) .filter(_.patientID === patientID) .filter(_.studyInstanceUID === studyInstanceUID) .sortBy(_.created.desc) .result .headOption } def anonymizationKeyForPatient(patientName: String, patientID: String): Future[Option[AnonymizationKey]] = db.run { anonymizationKeyQuery .filter(_.patientName === patientName) .filter(_.patientID === patientID) .sortBy(_.created.desc) .result .headOption } def anonymizationKeyForImageForAnonInfo(anonPatientName: String, anonPatientID: String, anonStudyInstanceUID: String, anonSeriesInstanceUID: String, anonSOPInstanceUID: String): Future[Option[AnonymizationKey]] = db.run { anonymizationKeyQuery .filter(_.anonPatientName === anonPatientName) .filter(_.anonPatientID === anonPatientID) .filter(_.anonStudyInstanceUID === anonStudyInstanceUID) .filter(_.anonSeriesInstanceUID === anonSeriesInstanceUID) .filter(_.anonSOPInstanceUID === anonSOPInstanceUID) .sortBy(_.created.desc) .result .headOption } def anonymizationKeyForSeriesForAnonInfo(anonPatientName: String, anonPatientID: String, anonStudyInstanceUID: String, anonSeriesInstanceUID: String): Future[Option[AnonymizationKey]] = db.run { anonymizationKeyQuery .filter(_.anonPatientName === anonPatientName) .filter(_.anonPatientID === anonPatientID) .filter(_.anonStudyInstanceUID === anonStudyInstanceUID) .filter(_.anonSeriesInstanceUID === anonSeriesInstanceUID) .sortBy(_.created.desc) .result .headOption } def anonymizationKeyForStudyForAnonInfo(anonPatientName: String, anonPatientID: String, anonStudyInstanceUID: String): Future[Option[AnonymizationKey]] = db.run { anonymizationKeyQuery .filter(_.anonPatientName === anonPatientName) .filter(_.anonPatientID === anonPatientID) .filter(_.anonStudyInstanceUID === anonStudyInstanceUID) .sortBy(_.created.desc) .result .headOption } def anonymizationKeyForPatientForAnonInfo(anonPatientName: String, anonPatientID: String): Future[Option[AnonymizationKey]] = db.run { anonymizationKeyQuery .filter(_.anonPatientName === anonPatientName) .filter(_.anonPatientID === anonPatientID) .sortBy(_.created.desc) .result .headOption } def anonymizationKeyValuesForAnonymizationKeyId(anonymizationKeyId: Long): Future[Seq[AnonymizationKeyValue]] = { val query = for { anonKey <- anonymizationKeyQuery if anonKey.id === anonymizationKeyId keyValue <- anonymizationKeyValueQuery if keyValue.anonymizationKeyId === anonKey.id } yield keyValue db.run(query.result) } private val queryAnonymizationKeysSelectPart = s"""select * from "${AnonymizationKeyTable.name}"""" def queryAnonymizationKeys(startIndex: Long, count: Long, orderBy: Option[String], orderAscending: Boolean, queryProperties: Seq[QueryProperty]): Future[Seq[AnonymizationKey]] = checkColumnExists(dbConf, orderBy, AnonymizationKeyTable.name).flatMap { _ => Future.sequence(queryProperties.map(qp => checkColumnExists(dbConf, qp.propertyName, AnonymizationKeyTable.name))).flatMap { _ => db.run { import se.nimsa.sbx.metadata.MetaDataDAO._ implicit val getResult: GetResult[AnonymizationKey] = anonymizationKeysGetResult val query = queryAnonymizationKeysSelectPart + wherePart(queryPart(queryProperties)) + orderByPart(orderBy.map(o => s""""$o""""), orderAscending) + pagePart(startIndex, count) sql"#$query".as[AnonymizationKey] } } } def anonymizationKeyValueSource: Source[(AnonymizationKey, AnonymizationKeyValue), NotUsed] = Source.fromPublisher(db.stream( anonymizationKeyQuery.joinLeft(anonymizationKeyValueQuery).on(_.id === _.anonymizationKeyId).result )).map { case (anonKey, maybeKeyValue) => (anonKey, maybeKeyValue.getOrElse(AnonymizationKeyValue(-1, anonKey.id, TagPath.fromTag(0), "", ""))) } }
slicebox/slicebox
src/main/scala/se/nimsa/sbx/anonymization/AnonymizationDAO.scala
Scala
apache-2.0
13,830
namespace WorkerInformations.DataList { public partial class FormDataListUseFpSpreadBaseFromAbstract { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Text = "FormDataListUseFpSpreadBaseFromAbstract"; } #endregion } }
haowenbiao/His6C-
App/职工信息/WorkerInformations/DataList/FormDataListUseFpSpreadBaseFromAbstract.Designer.cs
C#
apache-2.0
1,225
require 'test_helper' class ElectoratesPostcodesTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
open-letter/open-letter
test/models/electorates_postcodes_test.rb
Ruby
apache-2.0
134