repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
wolfzero1314/ReactDemo
node_modules/autoprefixer/lib/hacks/text-emphasis-position.js
1165
(function() { var Declaration, TextEmphasisPosition, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Declaration = require('../declaration'); TextEmphasisPosition = (function(superClass) { extend(TextEmphasisPosition, superClass); function TextEmphasisPosition() { return TextEmphasisPosition.__super__.constructor.apply(this, arguments); } TextEmphasisPosition.names = ['text-emphasis-position']; TextEmphasisPosition.prototype.set = function(decl, prefix) { if (prefix === '-webkit-') { decl.value = decl.value.replace(/\s*(right|left)\s*/i, ''); return TextEmphasisPosition.__super__.set.call(this, decl, prefix); } else { return TextEmphasisPosition.__super__.set.apply(this, arguments); } }; return TextEmphasisPosition; })(Declaration); module.exports = TextEmphasisPosition; }).call(this);
apache-2.0
lucafavatella/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/MavenDomProperties.java
941
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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. */ // Generated on Mon Mar 17 18:02:09 MSK 2008 // DTD/Schema : http://maven.apache.org/POM/4.0.0 package org.jetbrains.idea.maven.dom.model; import org.jetbrains.idea.maven.dom.MavenDomElement; /** * http://maven.apache.org/POM/4.0.0:propertiesElemType interface. */ public interface MavenDomProperties extends MavenDomElement { }
apache-2.0
d4rksy/dbweblearning
vendor/doctrine/cache/tests/Doctrine/Tests/Common/Cache/SQLite3CacheTest.php
1074
<?php namespace Doctrine\Tests\Common\Cache; use Doctrine\Common\Cache\Cache; use Doctrine\Common\Cache\SQLite3Cache; use SQLite3; class SQLite3Test extends CacheTest { /** * @var SQLite3 */ private $file, $sqlite; protected function setUp() { $this->file = tempnam(null, 'doctrine-cache-test-'); unlink($this->file); $this->sqlite = new SQLite3($this->file); } protected function tearDown() { $this->sqlite = null; // DB must be closed before unlink($this->file); } public function testGetStats() { $this->assertNull($this->_getCacheDriver()->getStats()); } public function testFetchSingle() { $id = uniqid('sqlite3_id_'); $data = "\0"; // produces null bytes in serialized format $this->_getCacheDriver()->save($id, $data, 30); $this->assertEquals($data, $this->_getCacheDriver()->fetch($id)); } protected function _getCacheDriver() { return new SQLite3Cache($this->sqlite, 'test_table'); } }
bsd-3-clause
northumberlandtourism/survey
admin/scripts/ckeditor.36/plugins/docprops/plugin.js
452
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add('docprops',{init:function(a){var b=new CKEDITOR.dialogCommand('docProps');b.modes={wysiwyg:a.config.fullPage};a.addCommand('docProps',b);CKEDITOR.dialog.add('docProps',this.path+'dialogs/docprops.js');a.ui.addButton('DocProps',{label:a.lang.docprops.label,command:'docProps'});}});
gpl-2.0
gmile/elasticsearch
src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/SignificanceHeuristicParserMapper.java
1762
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.significant.heuristics; import com.google.common.collect.ImmutableMap; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.inject.Inject; import java.util.Set; public class SignificanceHeuristicParserMapper { protected ImmutableMap<String, SignificanceHeuristicParser> significanceHeuristicParsers; @Inject public SignificanceHeuristicParserMapper(Set<SignificanceHeuristicParser> parsers) { MapBuilder<String, SignificanceHeuristicParser> builder = MapBuilder.newMapBuilder(); for (SignificanceHeuristicParser parser : parsers) { for (String name : parser.getNames()) { builder.put(name, parser); } } significanceHeuristicParsers = builder.immutableMap(); } public SignificanceHeuristicParser get(String parserName) { return significanceHeuristicParsers.get(parserName); } }
apache-2.0
liggitt/source-to-image
vendor/github.com/docker/docker/image/cache/compare_test.go
3899
package cache import ( "testing" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/strslice" "github.com/docker/go-connections/nat" ) // Just to make life easier func newPortNoError(proto, port string) nat.Port { p, _ := nat.NewPort(proto, port) return p } func TestCompare(t *testing.T) { ports1 := make(nat.PortSet) ports1[newPortNoError("tcp", "1111")] = struct{}{} ports1[newPortNoError("tcp", "2222")] = struct{}{} ports2 := make(nat.PortSet) ports2[newPortNoError("tcp", "3333")] = struct{}{} ports2[newPortNoError("tcp", "4444")] = struct{}{} ports3 := make(nat.PortSet) ports3[newPortNoError("tcp", "1111")] = struct{}{} ports3[newPortNoError("tcp", "2222")] = struct{}{} ports3[newPortNoError("tcp", "5555")] = struct{}{} volumes1 := make(map[string]struct{}) volumes1["/test1"] = struct{}{} volumes2 := make(map[string]struct{}) volumes2["/test2"] = struct{}{} volumes3 := make(map[string]struct{}) volumes3["/test1"] = struct{}{} volumes3["/test3"] = struct{}{} envs1 := []string{"ENV1=value1", "ENV2=value2"} envs2 := []string{"ENV1=value1", "ENV3=value3"} entrypoint1 := strslice.StrSlice{"/bin/sh", "-c"} entrypoint2 := strslice.StrSlice{"/bin/sh", "-d"} entrypoint3 := strslice.StrSlice{"/bin/sh", "-c", "echo"} cmd1 := strslice.StrSlice{"/bin/sh", "-c"} cmd2 := strslice.StrSlice{"/bin/sh", "-d"} cmd3 := strslice.StrSlice{"/bin/sh", "-c", "echo"} labels1 := map[string]string{"LABEL1": "value1", "LABEL2": "value2"} labels2 := map[string]string{"LABEL1": "value1", "LABEL2": "value3"} labels3 := map[string]string{"LABEL1": "value1", "LABEL2": "value2", "LABEL3": "value3"} sameConfigs := map[*container.Config]*container.Config{ // Empty config {}: {}, // Does not compare hostname, domainname & image { Hostname: "host1", Domainname: "domain1", Image: "image1", User: "user", }: { Hostname: "host2", Domainname: "domain2", Image: "image2", User: "user", }, // only OpenStdin {OpenStdin: false}: {OpenStdin: false}, // only env {Env: envs1}: {Env: envs1}, // only cmd {Cmd: cmd1}: {Cmd: cmd1}, // only labels {Labels: labels1}: {Labels: labels1}, // only exposedPorts {ExposedPorts: ports1}: {ExposedPorts: ports1}, // only entrypoints {Entrypoint: entrypoint1}: {Entrypoint: entrypoint1}, // only volumes {Volumes: volumes1}: {Volumes: volumes1}, } differentConfigs := map[*container.Config]*container.Config{ nil: nil, { Hostname: "host1", Domainname: "domain1", Image: "image1", User: "user1", }: { Hostname: "host1", Domainname: "domain1", Image: "image1", User: "user2", }, // only OpenStdin {OpenStdin: false}: {OpenStdin: true}, {OpenStdin: true}: {OpenStdin: false}, // only env {Env: envs1}: {Env: envs2}, // only cmd {Cmd: cmd1}: {Cmd: cmd2}, // not the same number of parts {Cmd: cmd1}: {Cmd: cmd3}, // only labels {Labels: labels1}: {Labels: labels2}, // not the same number of labels {Labels: labels1}: {Labels: labels3}, // only exposedPorts {ExposedPorts: ports1}: {ExposedPorts: ports2}, // not the same number of ports {ExposedPorts: ports1}: {ExposedPorts: ports3}, // only entrypoints {Entrypoint: entrypoint1}: {Entrypoint: entrypoint2}, // not the same number of parts {Entrypoint: entrypoint1}: {Entrypoint: entrypoint3}, // only volumes {Volumes: volumes1}: {Volumes: volumes2}, // not the same number of labels {Volumes: volumes1}: {Volumes: volumes3}, } for config1, config2 := range sameConfigs { if !compare(config1, config2) { t.Fatalf("Compare should be true for [%v] and [%v]", config1, config2) } } for config1, config2 := range differentConfigs { if compare(config1, config2) { t.Fatalf("Compare should be false for [%v] and [%v]", config1, config2) } } }
apache-2.0
fengshao0907/zipkin
zipkin-web/src/main/resources/app/libs/flight/lib/compose.js
2117
// ========================================== // Copyright 2013 Twitter, Inc // Licensed under The MIT License // http://opensource.org/licenses/MIT // ========================================== define( [ './utils', './debug' ], function(utils, debug) { 'use strict'; //enumerables are shims - getOwnPropertyDescriptor shim doesn't work var canWriteProtect = debug.enabled && !utils.isEnumerable(Object, 'getOwnPropertyDescriptor'); //whitelist of unlockable property names var dontLock = ['mixedIn']; if (canWriteProtect) { //IE8 getOwnPropertyDescriptor is built-in but throws exeption on non DOM objects try { Object.getOwnPropertyDescriptor(Object, 'keys'); } catch(e) { canWriteProtect = false; } } function setPropertyWritability(obj, isWritable) { if (!canWriteProtect) { return; } var props = Object.create(null); Object.keys(obj).forEach( function (key) { if (dontLock.indexOf(key) < 0) { var desc = Object.getOwnPropertyDescriptor(obj, key); desc.writable = isWritable; props[key] = desc; } } ); Object.defineProperties(obj, props); } function unlockProperty(obj, prop, op) { var writable; if (!canWriteProtect || !obj.hasOwnProperty(prop)) { op.call(obj); return; } writable = Object.getOwnPropertyDescriptor(obj, prop).writable; Object.defineProperty(obj, prop, { writable: true }); op.call(obj); Object.defineProperty(obj, prop, { writable: writable }); } function mixin(base, mixins) { base.mixedIn = base.hasOwnProperty('mixedIn') ? base.mixedIn : []; mixins.forEach(function(mixin) { if (base.mixedIn.indexOf(mixin) == -1) { setPropertyWritability(base, false); mixin.call(base); base.mixedIn.push(mixin); } }); setPropertyWritability(base, true); } return { mixin: mixin, unlockProperty: unlockProperty }; } );
apache-2.0
bpowers/TypeScript
tests/baselines/reference/functionWithDefaultParameterWithNoStatements6.js
290
//// [functionWithDefaultParameterWithNoStatements6.ts] function foo(a = true) { } function bar(a = true) { } //// [functionWithDefaultParameterWithNoStatements6.js] function foo(a) { if (a === void 0) { a = true; } } function bar(a) { if (a === void 0) { a = true; } }
apache-2.0
mu4ddi3/gajdaw-zad-29-01
vendor/gedmo/doctrine-extensions/tests/Gedmo/Tree/TranslatableSluggableTreeTest.php
5247
<?php namespace Gedmo\Tree; use Doctrine\Common\EventManager; use Tool\BaseTestCaseORM; use Doctrine\Common\Util\Debug, Tree\Fixture\BehavioralCategory, Tree\Fixture\Article, Tree\Fixture\Comment, Gedmo\Translatable\TranslatableListener, Gedmo\Translatable\Entity\Translation, Gedmo\Sluggable\SluggableListener, Doctrine\ORM\Proxy\Proxy; /** * These are tests for Tree behavior * * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com> * @link http://www.gediminasm.org * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ class TranslatableSluggableTreeTest extends BaseTestCaseORM { const CATEGORY = "Tree\\Fixture\\BehavioralCategory"; const ARTICLE = "Tree\\Fixture\\Article"; const COMMENT = "Tree\\Fixture\\Comment"; const TRANSLATION = "Gedmo\\Translatable\\Entity\\Translation"; private $translatableListener; protected function setUp() { parent::setUp(); $evm = new EventManager; $evm->addEventSubscriber(new TreeListener); $this->translatableListener = new TranslatableListener; $this->translatableListener->setTranslatableLocale('en_US'); $evm->addEventSubscriber(new SluggableListener); $evm->addEventSubscriber($this->translatableListener); $this->getMockSqliteEntityManager($evm); $this->populate(); } public function testNestedBehaviors() { $vegies = $this->em->getRepository(self::CATEGORY) ->findOneByTitle('Vegitables'); $childCount = $this->em->getRepository(self::CATEGORY) ->childCount($vegies); $this->assertEquals(2, $childCount); // test slug $this->assertEquals('vegitables', $vegies->getSlug()); // run second translation test $this->translatableListener->setTranslatableLocale('de_DE'); $vegies->setTitle('Deutschebles'); $this->em->persist($vegies); $this->em->flush(); $this->em->clear(); $this->translatableListener->setTranslatableLocale('en_US'); $vegies = $this->em->getRepository(self::CATEGORY) ->find($vegies->getId()); $translations = $this->em->getRepository(self::TRANSLATION) ->findTranslations($vegies); $this->assertCount(1, $translations); $this->assertArrayHasKey('de_DE', $translations); $this->assertArrayHasKey('title', $translations['de_DE']); $this->assertEquals('Deutschebles', $translations['de_DE']['title']); $this->assertArrayHasKey('slug', $translations['de_DE']); $this->assertEquals('deutschebles', $translations['de_DE']['slug']); } public function testTranslations() { $this->populateDeTranslations(); $repo = $this->em->getRepository(self::CATEGORY); $vegies = $repo->find(4); $this->assertEquals('Vegitables', $vegies->getTitle()); $food = $vegies->getParent(); // test if proxy triggers postLoad event $this->assertTrue($food instanceof Proxy); $this->assertEquals('Food', $food->getTitle()); $this->em->clear(); $this->translatableListener->setTranslatableLocale('de_DE'); $vegies = $repo->find(4); $this->assertEquals('Gemüse', $vegies->getTitle()); $food = $vegies->getParent(); $this->assertTrue($food instanceof Proxy); $this->assertEquals('Lebensmittel', $food->getTitle()); } protected function getUsedEntityFixtures() { return array( self::CATEGORY, self::ARTICLE, self::COMMENT, self::TRANSLATION ); } private function populateDeTranslations() { $this->translatableListener->setTranslatableLocale('de_DE'); $repo = $this->em->getRepository(self::CATEGORY); $food = $repo->findOneByTitle('Food'); $food->setTitle('Lebensmittel'); $vegies = $repo->findOneByTitle('Vegitables'); $vegies->setTitle('Gemüse'); $this->em->persist($food); $this->em->persist($vegies); $this->em->flush(); $this->em->clear(); $this->translatableListener->setTranslatableLocale('en_US'); } private function populate() { $root = new BehavioralCategory(); $root->setTitle("Food"); $root2 = new BehavioralCategory(); $root2->setTitle("Sports"); $child = new BehavioralCategory(); $child->setTitle("Fruits"); $child->setParent($root); $child2 = new BehavioralCategory(); $child2->setTitle("Vegitables"); $child2->setParent($root); $childsChild = new BehavioralCategory(); $childsChild->setTitle("Carrots"); $childsChild->setParent($child2); $potatoes = new BehavioralCategory(); $potatoes->setTitle("Potatoes"); $potatoes->setParent($child2); $this->em->persist($root); $this->em->persist($root2); $this->em->persist($child); $this->em->persist($child2); $this->em->persist($childsChild); $this->em->persist($potatoes); $this->em->flush(); $this->em->clear(); } }
mit
QinerTech/QinerApps
openerp/addons/website/static/lib/pdfjs/src/core/evaluator.js
98080
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ /* Copyright 2012 Mozilla 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. */ /* globals assert, CMapFactory, ColorSpace, DecodeStream, Dict, Encodings, error, ErrorFont, Font, FONT_IDENTITY_MATRIX, fontCharsToUnicode, FontFlags, ImageKind, info, isArray, isCmd, isDict, isEOF, isName, isNum, isStream, isString, JpegStream, Lexer, Metrics, IdentityCMap, MurmurHash3_64, Name, Parser, Pattern, PDFImage, PDFJS, serifFonts, stdFontMap, symbolsFonts, getTilingPatternIR, warn, Util, Promise, RefSetCache, isRef, TextRenderingMode, IdentityToUnicodeMap, OPS, UNSUPPORTED_FEATURES, UnsupportedManager, NormalizedUnicodes, IDENTITY_MATRIX, reverseIfRtl, createPromiseCapability, ToUnicodeMap, getFontType */ 'use strict'; var PartialEvaluator = (function PartialEvaluatorClosure() { function PartialEvaluator(pdfManager, xref, handler, pageIndex, uniquePrefix, idCounters, fontCache) { this.pdfManager = pdfManager; this.xref = xref; this.handler = handler; this.pageIndex = pageIndex; this.uniquePrefix = uniquePrefix; this.idCounters = idCounters; this.fontCache = fontCache; } // Trying to minimize Date.now() usage and check every 100 time var TIME_SLOT_DURATION_MS = 20; var CHECK_TIME_EVERY = 100; function TimeSlotManager() { this.reset(); } TimeSlotManager.prototype = { check: function TimeSlotManager_check() { if (++this.checked < CHECK_TIME_EVERY) { return false; } this.checked = 0; return this.endTime <= Date.now(); }, reset: function TimeSlotManager_reset() { this.endTime = Date.now() + TIME_SLOT_DURATION_MS; this.checked = 0; } }; var deferred = Promise.resolve(); var TILING_PATTERN = 1, SHADING_PATTERN = 2; PartialEvaluator.prototype = { hasBlendModes: function PartialEvaluator_hasBlendModes(resources) { if (!isDict(resources)) { return false; } var processed = Object.create(null); if (resources.objId) { processed[resources.objId] = true; } var nodes = [resources]; while (nodes.length) { var key; var node = nodes.shift(); // First check the current resources for blend modes. var graphicStates = node.get('ExtGState'); if (isDict(graphicStates)) { graphicStates = graphicStates.getAll(); for (key in graphicStates) { var graphicState = graphicStates[key]; var bm = graphicState['BM']; if (isName(bm) && bm.name !== 'Normal') { return true; } } } // Descend into the XObjects to look for more resources and blend modes. var xObjects = node.get('XObject'); if (!isDict(xObjects)) { continue; } xObjects = xObjects.getAll(); for (key in xObjects) { var xObject = xObjects[key]; if (!isStream(xObject)) { continue; } if (xObject.dict.objId) { if (processed[xObject.dict.objId]) { // stream has objId and is processed already continue; } processed[xObject.dict.objId] = true; } var xResources = xObject.dict.get('Resources'); // Checking objId to detect an infinite loop. if (isDict(xResources) && (!xResources.objId || !processed[xResources.objId])) { nodes.push(xResources); if (xResources.objId) { processed[xResources.objId] = true; } } } } return false; }, buildFormXObject: function PartialEvaluator_buildFormXObject(resources, xobj, smask, operatorList, initialState) { var matrix = xobj.dict.get('Matrix'); var bbox = xobj.dict.get('BBox'); var group = xobj.dict.get('Group'); if (group) { var groupOptions = { matrix: matrix, bbox: bbox, smask: smask, isolated: false, knockout: false }; var groupSubtype = group.get('S'); var colorSpace; if (isName(groupSubtype) && groupSubtype.name === 'Transparency') { groupOptions.isolated = (group.get('I') || false); groupOptions.knockout = (group.get('K') || false); colorSpace = (group.has('CS') ? ColorSpace.parse(group.get('CS'), this.xref, resources) : null); } if (smask && smask.backdrop) { colorSpace = colorSpace || ColorSpace.singletons.rgb; smask.backdrop = colorSpace.getRgb(smask.backdrop, 0); } operatorList.addOp(OPS.beginGroup, [groupOptions]); } operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]); return this.getOperatorList(xobj, (xobj.dict.get('Resources') || resources), operatorList, initialState). then(function () { operatorList.addOp(OPS.paintFormXObjectEnd, []); if (group) { operatorList.addOp(OPS.endGroup, [groupOptions]); } }); }, buildPaintImageXObject: function PartialEvaluator_buildPaintImageXObject(resources, image, inline, operatorList, cacheKey, imageCache) { var self = this; var dict = image.dict; var w = dict.get('Width', 'W'); var h = dict.get('Height', 'H'); if (!(w && isNum(w)) || !(h && isNum(h))) { warn('Image dimensions are missing, or not numbers.'); return; } if (PDFJS.maxImageSize !== -1 && w * h > PDFJS.maxImageSize) { warn('Image exceeded maximum allowed size and was removed.'); return; } var imageMask = (dict.get('ImageMask', 'IM') || false); var imgData, args; if (imageMask) { // This depends on a tmpCanvas being filled with the // current fillStyle, such that processing the pixel // data can't be done here. Instead of creating a // complete PDFImage, only read the information needed // for later. var width = dict.get('Width', 'W'); var height = dict.get('Height', 'H'); var bitStrideLength = (width + 7) >> 3; var imgArray = image.getBytes(bitStrideLength * height); var decode = dict.get('Decode', 'D'); var inverseDecode = (!!decode && decode[0] > 0); imgData = PDFImage.createMask(imgArray, width, height, image instanceof DecodeStream, inverseDecode); imgData.cached = true; args = [imgData]; operatorList.addOp(OPS.paintImageMaskXObject, args); if (cacheKey) { imageCache[cacheKey] = { fn: OPS.paintImageMaskXObject, args: args }; } return; } var softMask = (dict.get('SMask', 'SM') || false); var mask = (dict.get('Mask') || false); var SMALL_IMAGE_DIMENSIONS = 200; // Inlining small images into the queue as RGB data if (inline && !softMask && !mask && !(image instanceof JpegStream) && (w + h) < SMALL_IMAGE_DIMENSIONS) { var imageObj = new PDFImage(this.xref, resources, image, inline, null, null); // We force the use of RGBA_32BPP images here, because we can't handle // any other kind. imgData = imageObj.createImageData(/* forceRGBA = */ true); operatorList.addOp(OPS.paintInlineImageXObject, [imgData]); return; } // If there is no imageMask, create the PDFImage and a lot // of image processing can be done here. var uniquePrefix = (this.uniquePrefix || ''); var objId = 'img_' + uniquePrefix + (++this.idCounters.obj); operatorList.addDependency(objId); args = [objId, w, h]; if (!softMask && !mask && image instanceof JpegStream && image.isNativelySupported(this.xref, resources)) { // These JPEGs don't need any more processing so we can just send it. operatorList.addOp(OPS.paintJpegXObject, args); this.handler.send('obj', [objId, this.pageIndex, 'JpegStream', image.getIR()]); return; } PDFImage.buildImage(self.handler, self.xref, resources, image, inline). then(function(imageObj) { var imgData = imageObj.createImageData(/* forceRGBA = */ false); self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData], [imgData.data.buffer]); }).then(undefined, function (reason) { warn('Unable to decode image: ' + reason); self.handler.send('obj', [objId, self.pageIndex, 'Image', null]); }); operatorList.addOp(OPS.paintImageXObject, args); if (cacheKey) { imageCache[cacheKey] = { fn: OPS.paintImageXObject, args: args }; } }, handleSMask: function PartialEvaluator_handleSmask(smask, resources, operatorList, stateManager) { var smaskContent = smask.get('G'); var smaskOptions = { subtype: smask.get('S').name, backdrop: smask.get('BC') }; return this.buildFormXObject(resources, smaskContent, smaskOptions, operatorList, stateManager.state.clone()); }, handleTilingType: function PartialEvaluator_handleTilingType(fn, args, resources, pattern, patternDict, operatorList) { // Create an IR of the pattern code. var tilingOpList = new OperatorList(); return this.getOperatorList(pattern, (patternDict.get('Resources') || resources), tilingOpList). then(function () { // Add the dependencies to the parent operator list so they are // resolved before sub operator list is executed synchronously. operatorList.addDependencies(tilingOpList.dependencies); operatorList.addOp(fn, getTilingPatternIR({ fnArray: tilingOpList.fnArray, argsArray: tilingOpList.argsArray }, patternDict, args)); }); }, handleSetFont: function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef, operatorList, state) { // TODO(mack): Not needed? var fontName; if (fontArgs) { fontArgs = fontArgs.slice(); fontName = fontArgs[0].name; } var self = this; return this.loadFont(fontName, fontRef, this.xref, resources).then( function (translated) { if (!translated.font.isType3Font) { return translated; } return translated.loadType3Data(self, resources, operatorList).then( function () { return translated; }); }).then(function (translated) { state.font = translated.font; translated.send(self.handler); return translated.loadedName; }); }, handleText: function PartialEvaluator_handleText(chars, state) { var font = state.font; var glyphs = font.charsToGlyphs(chars); var isAddToPathSet = !!(state.textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); if (font.data && (isAddToPathSet || PDFJS.disableFontFace)) { var buildPath = function (fontChar) { if (!font.renderer.hasBuiltPath(fontChar)) { var path = font.renderer.getPathJs(fontChar); this.handler.send('commonobj', [ font.loadedName + '_path_' + fontChar, 'FontPath', path ]); } }.bind(this); for (var i = 0, ii = glyphs.length; i < ii; i++) { var glyph = glyphs[i]; if (glyph === null) { continue; } buildPath(glyph.fontChar); // If the glyph has an accent we need to build a path for its // fontChar too, otherwise CanvasGraphics_paintChar will fail. var accent = glyph.accent; if (accent && accent.fontChar) { buildPath(accent.fontChar); } } } return glyphs; }, setGState: function PartialEvaluator_setGState(resources, gState, operatorList, xref, stateManager) { // This array holds the converted/processed state data. var gStateObj = []; var gStateMap = gState.map; var self = this; var promise = Promise.resolve(); for (var key in gStateMap) { var value = gStateMap[key]; switch (key) { case 'Type': break; case 'LW': case 'LC': case 'LJ': case 'ML': case 'D': case 'RI': case 'FL': case 'CA': case 'ca': gStateObj.push([key, value]); break; case 'Font': promise = promise.then(function () { return self.handleSetFont(resources, null, value[0], operatorList, stateManager.state). then(function (loadedName) { operatorList.addDependency(loadedName); gStateObj.push([key, [loadedName, value[1]]]); }); }); break; case 'BM': gStateObj.push([key, value]); break; case 'SMask': if (isName(value) && value.name === 'None') { gStateObj.push([key, false]); break; } var dict = xref.fetchIfRef(value); if (isDict(dict)) { promise = promise.then(function () { return self.handleSMask(dict, resources, operatorList, stateManager); }); gStateObj.push([key, true]); } else { warn('Unsupported SMask type'); } break; // Only generate info log messages for the following since // they are unlikely to have a big impact on the rendering. case 'OP': case 'op': case 'OPM': case 'BG': case 'BG2': case 'UCR': case 'UCR2': case 'TR': case 'TR2': case 'HT': case 'SM': case 'SA': case 'AIS': case 'TK': // TODO implement these operators. info('graphic state operator ' + key); break; default: info('Unknown graphic state operator ' + key); break; } } return promise.then(function () { if (gStateObj.length >= 0) { operatorList.addOp(OPS.setGState, [gStateObj]); } }); }, loadFont: function PartialEvaluator_loadFont(fontName, font, xref, resources) { function errorFont() { return Promise.resolve(new TranslatedFont('g_font_error', new ErrorFont('Font ' + fontName + ' is not available'), font)); } var fontRef; if (font) { // Loading by ref. assert(isRef(font)); fontRef = font; } else { // Loading by name. var fontRes = resources.get('Font'); if (fontRes) { fontRef = fontRes.getRaw(fontName); } else { warn('fontRes not available'); return errorFont(); } } if (!fontRef) { warn('fontRef not available'); return errorFont(); } if (this.fontCache.has(fontRef)) { return this.fontCache.get(fontRef); } font = xref.fetchIfRef(fontRef); if (!isDict(font)) { return errorFont(); } // We are holding font.translated references just for fontRef that are not // dictionaries (Dict). See explanation below. if (font.translated) { return font.translated; } var fontCapability = createPromiseCapability(); var preEvaluatedFont = this.preEvaluateFont(font, xref); var descriptor = preEvaluatedFont.descriptor; var fontID = fontRef.num + '_' + fontRef.gen; if (isDict(descriptor)) { if (!descriptor.fontAliases) { descriptor.fontAliases = Object.create(null); } var fontAliases = descriptor.fontAliases; var hash = preEvaluatedFont.hash; if (fontAliases[hash]) { var aliasFontRef = fontAliases[hash].aliasRef; if (aliasFontRef && this.fontCache.has(aliasFontRef)) { this.fontCache.putAlias(fontRef, aliasFontRef); return this.fontCache.get(fontRef); } } if (!fontAliases[hash]) { fontAliases[hash] = { fontID: Font.getFontID() }; } fontAliases[hash].aliasRef = fontRef; fontID = fontAliases[hash].fontID; } // Workaround for bad PDF generators that don't reference fonts // properly, i.e. by not using an object identifier. // Check if the fontRef is a Dict (as opposed to a standard object), // in which case we don't cache the font and instead reference it by // fontName in font.loadedName below. var fontRefIsDict = isDict(fontRef); if (!fontRefIsDict) { this.fontCache.put(fontRef, fontCapability.promise); } // Keep track of each font we translated so the caller can // load them asynchronously before calling display on a page. font.loadedName = 'g_font_' + (fontRefIsDict ? fontName.replace(/\W/g, '') : fontID); font.translated = fontCapability.promise; // TODO move promises into translate font var translatedPromise; try { translatedPromise = Promise.resolve( this.translateFont(preEvaluatedFont, xref)); } catch (e) { translatedPromise = Promise.reject(e); } translatedPromise.then(function (translatedFont) { if (translatedFont.fontType !== undefined) { var xrefFontStats = xref.stats.fontTypes; xrefFontStats[translatedFont.fontType] = true; } fontCapability.resolve(new TranslatedFont(font.loadedName, translatedFont, font)); }, function (reason) { // TODO fontCapability.reject? UnsupportedManager.notify(UNSUPPORTED_FEATURES.font); try { // error, but it's still nice to have font type reported var descriptor = preEvaluatedFont.descriptor; var fontFile3 = descriptor && descriptor.get('FontFile3'); var subtype = fontFile3 && fontFile3.get('Subtype'); var fontType = getFontType(preEvaluatedFont.type, subtype && subtype.name); var xrefFontStats = xref.stats.fontTypes; xrefFontStats[fontType] = true; } catch (ex) { } fontCapability.resolve(new TranslatedFont(font.loadedName, new ErrorFont(reason instanceof Error ? reason.message : reason), font)); }); return fontCapability.promise; }, buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) { var lastIndex = operatorList.length - 1; if (!args) { args = []; } if (lastIndex < 0 || operatorList.fnArray[lastIndex] !== OPS.constructPath) { operatorList.addOp(OPS.constructPath, [[fn], args]); } else { var opArgs = operatorList.argsArray[lastIndex]; opArgs[0].push(fn); Array.prototype.push.apply(opArgs[1], args); } }, handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args, cs, patterns, resources, xref) { // compile tiling patterns var patternName = args[args.length - 1]; // SCN/scn applies patterns along with normal colors var pattern; if (isName(patternName) && (pattern = patterns.get(patternName.name))) { var dict = (isStream(pattern) ? pattern.dict : pattern); var typeNum = dict.get('PatternType'); if (typeNum === TILING_PATTERN) { var color = cs.base ? cs.base.getRgb(args, 0) : null; return this.handleTilingType(fn, color, resources, pattern, dict, operatorList); } else if (typeNum === SHADING_PATTERN) { var shading = dict.get('Shading'); var matrix = dict.get('Matrix'); pattern = Pattern.parseShading(shading, matrix, xref, resources); operatorList.addOp(fn, pattern.getIR()); return Promise.resolve(); } else { return Promise.reject('Unknown PatternType: ' + typeNum); } } // TODO shall we fail here? operatorList.addOp(fn, args); return Promise.resolve(); }, getOperatorList: function PartialEvaluator_getOperatorList(stream, resources, operatorList, initialState) { var self = this; var xref = this.xref; var imageCache = {}; assert(operatorList); resources = (resources || Dict.empty); var xobjs = (resources.get('XObject') || Dict.empty); var patterns = (resources.get('Pattern') || Dict.empty); var stateManager = new StateManager(initialState || new EvalState()); var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager); var timeSlotManager = new TimeSlotManager(); return new Promise(function next(resolve, reject) { timeSlotManager.reset(); var stop, operation = {}, i, ii, cs; while (!(stop = timeSlotManager.check())) { // The arguments parsed by read() are used beyond this loop, so we // cannot reuse the same array on each iteration. Therefore we pass // in |null| as the initial value (see the comment on // EvaluatorPreprocessor_read() for why). operation.args = null; if (!(preprocessor.read(operation))) { break; } var args = operation.args; var fn = operation.fn; switch (fn | 0) { case OPS.paintXObject: if (args[0].code) { break; } // eagerly compile XForm objects var name = args[0].name; if (imageCache[name] !== undefined) { operatorList.addOp(imageCache[name].fn, imageCache[name].args); args = null; continue; } var xobj = xobjs.get(name); if (xobj) { assert(isStream(xobj), 'XObject should be a stream'); var type = xobj.dict.get('Subtype'); assert(isName(type), 'XObject should have a Name subtype'); if (type.name === 'Form') { stateManager.save(); return self.buildFormXObject(resources, xobj, null, operatorList, stateManager.state.clone()). then(function () { stateManager.restore(); next(resolve, reject); }, reject); } else if (type.name === 'Image') { self.buildPaintImageXObject(resources, xobj, false, operatorList, name, imageCache); args = null; continue; } else if (type.name === 'PS') { // PostScript XObjects are unused when viewing documents. // See section 4.7.1 of Adobe's PDF reference. info('Ignored XObject subtype PS'); continue; } else { error('Unhandled XObject subtype ' + type.name); } } break; case OPS.setFont: var fontSize = args[1]; // eagerly collect all fonts return self.handleSetFont(resources, args, null, operatorList, stateManager.state). then(function (loadedName) { operatorList.addDependency(loadedName); operatorList.addOp(OPS.setFont, [loadedName, fontSize]); next(resolve, reject); }, reject); case OPS.endInlineImage: var cacheKey = args[0].cacheKey; if (cacheKey) { var cacheEntry = imageCache[cacheKey]; if (cacheEntry !== undefined) { operatorList.addOp(cacheEntry.fn, cacheEntry.args); args = null; continue; } } self.buildPaintImageXObject(resources, args[0], true, operatorList, cacheKey, imageCache); args = null; continue; case OPS.showText: args[0] = self.handleText(args[0], stateManager.state); break; case OPS.showSpacedText: var arr = args[0]; var combinedGlyphs = []; var arrLength = arr.length; for (i = 0; i < arrLength; ++i) { var arrItem = arr[i]; if (isString(arrItem)) { Array.prototype.push.apply(combinedGlyphs, self.handleText(arrItem, stateManager.state)); } else if (isNum(arrItem)) { combinedGlyphs.push(arrItem); } } args[0] = combinedGlyphs; fn = OPS.showText; break; case OPS.nextLineShowText: operatorList.addOp(OPS.nextLine); args[0] = self.handleText(args[0], stateManager.state); fn = OPS.showText; break; case OPS.nextLineSetSpacingShowText: operatorList.addOp(OPS.nextLine); operatorList.addOp(OPS.setWordSpacing, [args.shift()]); operatorList.addOp(OPS.setCharSpacing, [args.shift()]); args[0] = self.handleText(args[0], stateManager.state); fn = OPS.showText; break; case OPS.setTextRenderingMode: stateManager.state.textRenderingMode = args[0]; break; case OPS.setFillColorSpace: stateManager.state.fillColorSpace = ColorSpace.parse(args[0], xref, resources); continue; case OPS.setStrokeColorSpace: stateManager.state.strokeColorSpace = ColorSpace.parse(args[0], xref, resources); continue; case OPS.setFillColor: cs = stateManager.state.fillColorSpace; args = cs.getRgb(args, 0); fn = OPS.setFillRGBColor; break; case OPS.setStrokeColor: cs = stateManager.state.strokeColorSpace; args = cs.getRgb(args, 0); fn = OPS.setStrokeRGBColor; break; case OPS.setFillGray: stateManager.state.fillColorSpace = ColorSpace.singletons.gray; args = ColorSpace.singletons.gray.getRgb(args, 0); fn = OPS.setFillRGBColor; break; case OPS.setStrokeGray: stateManager.state.strokeColorSpace = ColorSpace.singletons.gray; args = ColorSpace.singletons.gray.getRgb(args, 0); fn = OPS.setStrokeRGBColor; break; case OPS.setFillCMYKColor: stateManager.state.fillColorSpace = ColorSpace.singletons.cmyk; args = ColorSpace.singletons.cmyk.getRgb(args, 0); fn = OPS.setFillRGBColor; break; case OPS.setStrokeCMYKColor: stateManager.state.strokeColorSpace = ColorSpace.singletons.cmyk; args = ColorSpace.singletons.cmyk.getRgb(args, 0); fn = OPS.setStrokeRGBColor; break; case OPS.setFillRGBColor: stateManager.state.fillColorSpace = ColorSpace.singletons.rgb; args = ColorSpace.singletons.rgb.getRgb(args, 0); break; case OPS.setStrokeRGBColor: stateManager.state.strokeColorSpace = ColorSpace.singletons.rgb; args = ColorSpace.singletons.rgb.getRgb(args, 0); break; case OPS.setFillColorN: cs = stateManager.state.fillColorSpace; if (cs.name === 'Pattern') { return self.handleColorN(operatorList, OPS.setFillColorN, args, cs, patterns, resources, xref).then(function() { next(resolve, reject); }, reject); } args = cs.getRgb(args, 0); fn = OPS.setFillRGBColor; break; case OPS.setStrokeColorN: cs = stateManager.state.strokeColorSpace; if (cs.name === 'Pattern') { return self.handleColorN(operatorList, OPS.setStrokeColorN, args, cs, patterns, resources, xref).then(function() { next(resolve, reject); }, reject); } args = cs.getRgb(args, 0); fn = OPS.setStrokeRGBColor; break; case OPS.shadingFill: var shadingRes = resources.get('Shading'); if (!shadingRes) { error('No shading resource found'); } var shading = shadingRes.get(args[0].name); if (!shading) { error('No shading object found'); } var shadingFill = Pattern.parseShading(shading, null, xref, resources); var patternIR = shadingFill.getIR(); args = [patternIR]; fn = OPS.shadingFill; break; case OPS.setGState: var dictName = args[0]; var extGState = resources.get('ExtGState'); if (!isDict(extGState) || !extGState.has(dictName.name)) { break; } var gState = extGState.get(dictName.name); return self.setGState(resources, gState, operatorList, xref, stateManager).then(function() { next(resolve, reject); }, reject); case OPS.moveTo: case OPS.lineTo: case OPS.curveTo: case OPS.curveTo2: case OPS.curveTo3: case OPS.closePath: self.buildPath(operatorList, fn, args); continue; case OPS.rectangle: self.buildPath(operatorList, fn, args); continue; } operatorList.addOp(fn, args); } if (stop) { deferred.then(function () { next(resolve, reject); }); return; } // Some PDFs don't close all restores inside object/form. // Closing those for them. for (i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) { operatorList.addOp(OPS.restore, []); } resolve(); }); }, getTextContent: function PartialEvaluator_getTextContent(stream, resources, stateManager) { stateManager = (stateManager || new StateManager(new TextState())); var textContent = { items: [], styles: Object.create(null) }; var bidiTexts = textContent.items; var SPACE_FACTOR = 0.3; var MULTI_SPACE_FACTOR = 1.5; var self = this; var xref = this.xref; resources = (xref.fetchIfRef(resources) || Dict.empty); // The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd. var xobjs = null; var xobjsCache = {}; var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager); var textState; function newTextChunk() { var font = textState.font; if (!(font.loadedName in textContent.styles)) { textContent.styles[font.loadedName] = { fontFamily: font.fallbackName, ascent: font.ascent, descent: font.descent, vertical: font.vertical }; } return { // |str| is initially an array which we push individual chars to, and // then runBidi() overwrites it with the final string. str: [], dir: null, width: 0, height: 0, transform: null, fontName: font.loadedName }; } function runBidi(textChunk) { var str = textChunk.str.join(''); var bidiResult = PDFJS.bidi(str, -1, textState.font.vertical); textChunk.str = bidiResult.str; textChunk.dir = bidiResult.dir; return textChunk; } function handleSetFont(fontName, fontRef) { return self.loadFont(fontName, fontRef, xref, resources). then(function (translated) { textState.font = translated.font; textState.fontMatrix = translated.font.fontMatrix || FONT_IDENTITY_MATRIX; }); } function buildTextGeometry(chars, textChunk) { var font = textState.font; textChunk = textChunk || newTextChunk(); if (!textChunk.transform) { // 9.4.4 Text Space Details var tsm = [textState.fontSize * textState.textHScale, 0, 0, textState.fontSize, 0, textState.textRise]; var trm = textChunk.transform = Util.transform(textState.ctm, Util.transform(textState.textMatrix, tsm)); if (!font.vertical) { textChunk.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]); } else { textChunk.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]); } } var width = 0; var height = 0; var glyphs = font.charsToGlyphs(chars); var defaultVMetrics = font.defaultVMetrics; for (var i = 0; i < glyphs.length; i++) { var glyph = glyphs[i]; if (!glyph) { // Previous glyph was a space. width += textState.wordSpacing * textState.textHScale; continue; } var vMetricX = null; var vMetricY = null; var glyphWidth = null; if (font.vertical) { if (glyph.vmetric) { glyphWidth = glyph.vmetric[0]; vMetricX = glyph.vmetric[1]; vMetricY = glyph.vmetric[2]; } else { glyphWidth = glyph.width; vMetricX = glyph.width * 0.5; vMetricY = defaultVMetrics[2]; } } else { glyphWidth = glyph.width; } var glyphUnicode = glyph.unicode; if (NormalizedUnicodes[glyphUnicode] !== undefined) { glyphUnicode = NormalizedUnicodes[glyphUnicode]; } glyphUnicode = reverseIfRtl(glyphUnicode); // The following will calculate the x and y of the individual glyphs. // if (font.vertical) { // tsm[4] -= vMetricX * Math.abs(textState.fontSize) * // textState.fontMatrix[0]; // tsm[5] -= vMetricY * textState.fontSize * // textState.fontMatrix[0]; // } // var trm = Util.transform(textState.textMatrix, tsm); // var pt = Util.applyTransform([trm[4], trm[5]], textState.ctm); // var x = pt[0]; // var y = pt[1]; var tx = 0; var ty = 0; if (!font.vertical) { var w0 = glyphWidth * textState.fontMatrix[0]; tx = (w0 * textState.fontSize + textState.charSpacing) * textState.textHScale; width += tx; } else { var w1 = glyphWidth * textState.fontMatrix[0]; ty = w1 * textState.fontSize + textState.charSpacing; height += ty; } textState.translateTextMatrix(tx, ty); textChunk.str.push(glyphUnicode); } var a = textState.textLineMatrix[0]; var b = textState.textLineMatrix[1]; var scaleLineX = Math.sqrt(a * a + b * b); a = textState.ctm[0]; b = textState.ctm[1]; var scaleCtmX = Math.sqrt(a * a + b * b); if (!font.vertical) { textChunk.width += width * scaleCtmX * scaleLineX; } else { textChunk.height += Math.abs(height * scaleCtmX * scaleLineX); } return textChunk; } var timeSlotManager = new TimeSlotManager(); return new Promise(function next(resolve, reject) { timeSlotManager.reset(); var stop, operation = {}, args = []; while (!(stop = timeSlotManager.check())) { // The arguments parsed by read() are not used beyond this loop, so // we can reuse the same array on every iteration, thus avoiding // unnecessary allocations. args.length = 0; operation.args = args; if (!(preprocessor.read(operation))) { break; } textState = stateManager.state; var fn = operation.fn; args = operation.args; switch (fn | 0) { case OPS.setFont: textState.fontSize = args[1]; return handleSetFont(args[0].name).then(function() { next(resolve, reject); }, reject); case OPS.setTextRise: textState.textRise = args[0]; break; case OPS.setHScale: textState.textHScale = args[0] / 100; break; case OPS.setLeading: textState.leading = args[0]; break; case OPS.moveText: textState.translateTextLineMatrix(args[0], args[1]); textState.textMatrix = textState.textLineMatrix.slice(); break; case OPS.setLeadingMoveText: textState.leading = -args[1]; textState.translateTextLineMatrix(args[0], args[1]); textState.textMatrix = textState.textLineMatrix.slice(); break; case OPS.nextLine: textState.carriageReturn(); break; case OPS.setTextMatrix: textState.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); textState.setTextLineMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.setCharSpacing: textState.charSpacing = args[0]; break; case OPS.setWordSpacing: textState.wordSpacing = args[0]; break; case OPS.beginText: textState.textMatrix = IDENTITY_MATRIX.slice(); textState.textLineMatrix = IDENTITY_MATRIX.slice(); break; case OPS.showSpacedText: var items = args[0]; var textChunk = newTextChunk(); var offset; for (var j = 0, jj = items.length; j < jj; j++) { if (typeof items[j] === 'string') { buildTextGeometry(items[j], textChunk); } else { var val = items[j] / 1000; if (!textState.font.vertical) { offset = -val * textState.fontSize * textState.textHScale * textState.textMatrix[0]; textState.translateTextMatrix(offset, 0); textChunk.width += offset; } else { offset = -val * textState.fontSize * textState.textMatrix[3]; textState.translateTextMatrix(0, offset); textChunk.height += offset; } if (items[j] < 0 && textState.font.spaceWidth > 0) { var fakeSpaces = -items[j] / textState.font.spaceWidth; if (fakeSpaces > MULTI_SPACE_FACTOR) { fakeSpaces = Math.round(fakeSpaces); while (fakeSpaces--) { textChunk.str.push(' '); } } else if (fakeSpaces > SPACE_FACTOR) { textChunk.str.push(' '); } } } } bidiTexts.push(runBidi(textChunk)); break; case OPS.showText: bidiTexts.push(runBidi(buildTextGeometry(args[0]))); break; case OPS.nextLineShowText: textState.carriageReturn(); bidiTexts.push(runBidi(buildTextGeometry(args[0]))); break; case OPS.nextLineSetSpacingShowText: textState.wordSpacing = args[0]; textState.charSpacing = args[1]; textState.carriageReturn(); bidiTexts.push(runBidi(buildTextGeometry(args[2]))); break; case OPS.paintXObject: if (args[0].code) { break; } if (!xobjs) { xobjs = (resources.get('XObject') || Dict.empty); } var name = args[0].name; if (xobjsCache.key === name) { if (xobjsCache.texts) { Util.appendToArray(bidiTexts, xobjsCache.texts.items); Util.extendObj(textContent.styles, xobjsCache.texts.styles); } break; } var xobj = xobjs.get(name); if (!xobj) { break; } assert(isStream(xobj), 'XObject should be a stream'); var type = xobj.dict.get('Subtype'); assert(isName(type), 'XObject should have a Name subtype'); if ('Form' !== type.name) { xobjsCache.key = name; xobjsCache.texts = null; break; } stateManager.save(); var matrix = xobj.dict.get('Matrix'); if (isArray(matrix) && matrix.length === 6) { stateManager.transform(matrix); } return self.getTextContent(xobj, xobj.dict.get('Resources') || resources, stateManager). then(function (formTextContent) { Util.appendToArray(bidiTexts, formTextContent.items); Util.extendObj(textContent.styles, formTextContent.styles); stateManager.restore(); xobjsCache.key = name; xobjsCache.texts = formTextContent; next(resolve, reject); }, reject); case OPS.setGState: var dictName = args[0]; var extGState = resources.get('ExtGState'); if (!isDict(extGState) || !extGState.has(dictName.name)) { break; } var gsStateMap = extGState.get(dictName.name); var gsStateFont = null; for (var key in gsStateMap) { if (key === 'Font') { assert(!gsStateFont); gsStateFont = gsStateMap[key]; } } if (gsStateFont) { textState.fontSize = gsStateFont[1]; return handleSetFont(gsStateFont[0]).then(function() { next(resolve, reject); }, reject); } break; } // switch } // while if (stop) { deferred.then(function () { next(resolve, reject); }); return; } resolve(textContent); }); }, extractDataStructures: function partialEvaluatorExtractDataStructures(dict, baseDict, xref, properties) { // 9.10.2 var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode')); if (toUnicode) { properties.toUnicode = this.readToUnicode(toUnicode); } if (properties.composite) { // CIDSystemInfo helps to match CID to glyphs var cidSystemInfo = dict.get('CIDSystemInfo'); if (isDict(cidSystemInfo)) { properties.cidSystemInfo = { registry: cidSystemInfo.get('Registry'), ordering: cidSystemInfo.get('Ordering'), supplement: cidSystemInfo.get('Supplement') }; } var cidToGidMap = dict.get('CIDToGIDMap'); if (isStream(cidToGidMap)) { properties.cidToGidMap = this.readCidToGidMap(cidToGidMap); } } // Based on 9.6.6 of the spec the encoding can come from multiple places // and depends on the font type. The base encoding and differences are // read here, but the encoding that is actually used is chosen during // glyph mapping in the font. // TODO: Loading the built in encoding in the font would allow the // differences to be merged in here not require us to hold on to it. var differences = []; var baseEncodingName = null; var encoding; if (dict.has('Encoding')) { encoding = dict.get('Encoding'); if (isDict(encoding)) { baseEncodingName = encoding.get('BaseEncoding'); baseEncodingName = (isName(baseEncodingName) ? baseEncodingName.name : null); // Load the differences between the base and original if (encoding.has('Differences')) { var diffEncoding = encoding.get('Differences'); var index = 0; for (var j = 0, jj = diffEncoding.length; j < jj; j++) { var data = diffEncoding[j]; if (isNum(data)) { index = data; } else { differences[index++] = data.name; } } } } else if (isName(encoding)) { baseEncodingName = encoding.name; } else { error('Encoding is not a Name nor a Dict'); } // According to table 114 if the encoding is a named encoding it must be // one of these predefined encodings. if ((baseEncodingName !== 'MacRomanEncoding' && baseEncodingName !== 'MacExpertEncoding' && baseEncodingName !== 'WinAnsiEncoding')) { baseEncodingName = null; } } if (baseEncodingName) { properties.defaultEncoding = Encodings[baseEncodingName].slice(); } else { encoding = (properties.type === 'TrueType' ? Encodings.WinAnsiEncoding : Encodings.StandardEncoding); // The Symbolic attribute can be misused for regular fonts // Heuristic: we have to check if the font is a standard one also if (!!(properties.flags & FontFlags.Symbolic)) { encoding = Encodings.MacRomanEncoding; if (!properties.file) { if (/Symbol/i.test(properties.name)) { encoding = Encodings.SymbolSetEncoding; } else if (/Dingbats/i.test(properties.name)) { encoding = Encodings.ZapfDingbatsEncoding; } } } properties.defaultEncoding = encoding; } properties.differences = differences; properties.baseEncodingName = baseEncodingName; properties.dict = dict; }, readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) { var cmap, cmapObj = toUnicode; if (isName(cmapObj)) { cmap = CMapFactory.create(cmapObj, { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null); if (cmap instanceof IdentityCMap) { return new IdentityToUnicodeMap(0, 0xFFFF); } return new ToUnicodeMap(cmap.getMap()); } else if (isStream(cmapObj)) { cmap = CMapFactory.create(cmapObj, { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null); if (cmap instanceof IdentityCMap) { return new IdentityToUnicodeMap(0, 0xFFFF); } cmap = cmap.getMap(); // Convert UTF-16BE // NOTE: cmap can be a sparse array, so use forEach instead of for(;;) // to iterate over all keys. cmap.forEach(function(token, i) { var str = []; for (var k = 0; k < token.length; k += 2) { var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1); if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF str.push(w1); continue; } k += 2; var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1); str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000); } cmap[i] = String.fromCharCode.apply(String, str); }); return new ToUnicodeMap(cmap); } return null; }, readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) { // Extract the encoding from the CIDToGIDMap var glyphsData = cidToGidStream.getBytes(); // Set encoding 0 to later verify the font has an encoding var result = []; for (var j = 0, jj = glyphsData.length; j < jj; j++) { var glyphID = (glyphsData[j++] << 8) | glyphsData[j]; if (glyphID === 0) { continue; } var code = j >> 1; result[code] = glyphID; } return result; }, extractWidths: function PartialEvaluator_extractWidths(dict, xref, descriptor, properties) { var glyphsWidths = []; var defaultWidth = 0; var glyphsVMetrics = []; var defaultVMetrics; var i, ii, j, jj, start, code, widths; if (properties.composite) { defaultWidth = dict.get('DW') || 1000; widths = dict.get('W'); if (widths) { for (i = 0, ii = widths.length; i < ii; i++) { start = widths[i++]; code = xref.fetchIfRef(widths[i]); if (isArray(code)) { for (j = 0, jj = code.length; j < jj; j++) { glyphsWidths[start++] = code[j]; } } else { var width = widths[++i]; for (j = start; j <= code; j++) { glyphsWidths[j] = width; } } } } if (properties.vertical) { var vmetrics = (dict.get('DW2') || [880, -1000]); defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]]; vmetrics = dict.get('W2'); if (vmetrics) { for (i = 0, ii = vmetrics.length; i < ii; i++) { start = vmetrics[i++]; code = xref.fetchIfRef(vmetrics[i]); if (isArray(code)) { for (j = 0, jj = code.length; j < jj; j++) { glyphsVMetrics[start++] = [code[j++], code[j++], code[j]]; } } else { var vmetric = [vmetrics[++i], vmetrics[++i], vmetrics[++i]]; for (j = start; j <= code; j++) { glyphsVMetrics[j] = vmetric; } } } } } } else { var firstChar = properties.firstChar; widths = dict.get('Widths'); if (widths) { j = firstChar; for (i = 0, ii = widths.length; i < ii; i++) { glyphsWidths[j++] = widths[i]; } defaultWidth = (parseFloat(descriptor.get('MissingWidth')) || 0); } else { // Trying get the BaseFont metrics (see comment above). var baseFontName = dict.get('BaseFont'); if (isName(baseFontName)) { var metrics = this.getBaseFontMetrics(baseFontName.name); glyphsWidths = this.buildCharCodeToWidth(metrics.widths, properties); defaultWidth = metrics.defaultWidth; } } } // Heuristic: detection of monospace font by checking all non-zero widths var isMonospace = true; var firstWidth = defaultWidth; for (var glyph in glyphsWidths) { var glyphWidth = glyphsWidths[glyph]; if (!glyphWidth) { continue; } if (!firstWidth) { firstWidth = glyphWidth; continue; } if (firstWidth !== glyphWidth) { isMonospace = false; break; } } if (isMonospace) { properties.flags |= FontFlags.FixedPitch; } properties.defaultWidth = defaultWidth; properties.widths = glyphsWidths; properties.defaultVMetrics = defaultVMetrics; properties.vmetrics = glyphsVMetrics; }, isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) { // Simulating descriptor flags attribute var fontNameWoStyle = baseFontName.split('-')[0]; return (fontNameWoStyle in serifFonts) || (fontNameWoStyle.search(/serif/gi) !== -1); }, getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) { var defaultWidth = 0; var widths = []; var monospace = false; var lookupName = (stdFontMap[name] || name); if (!(lookupName in Metrics)) { // Use default fonts for looking up font metrics if the passed // font is not a base font if (this.isSerifFont(name)) { lookupName = 'Times-Roman'; } else { lookupName = 'Helvetica'; } } var glyphWidths = Metrics[lookupName]; if (isNum(glyphWidths)) { defaultWidth = glyphWidths; monospace = true; } else { widths = glyphWidths; } return { defaultWidth: defaultWidth, monospace: monospace, widths: widths }; }, buildCharCodeToWidth: function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName, properties) { var widths = Object.create(null); var differences = properties.differences; var encoding = properties.defaultEncoding; for (var charCode = 0; charCode < 256; charCode++) { if (charCode in differences && widthsByGlyphName[differences[charCode]]) { widths[charCode] = widthsByGlyphName[differences[charCode]]; continue; } if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) { widths[charCode] = widthsByGlyphName[encoding[charCode]]; continue; } } return widths; }, preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict, xref) { var baseDict = dict; var type = dict.get('Subtype'); assert(isName(type), 'invalid font Subtype'); var composite = false; var uint8array; if (type.name === 'Type0') { // If font is a composite // - get the descendant font // - set the type according to the descendant font // - get the FontDescriptor from the descendant font var df = dict.get('DescendantFonts'); if (!df) { error('Descendant fonts are not specified'); } dict = (isArray(df) ? xref.fetchIfRef(df[0]) : df); type = dict.get('Subtype'); assert(isName(type), 'invalid font Subtype'); composite = true; } var descriptor = dict.get('FontDescriptor'); if (descriptor) { var hash = new MurmurHash3_64(); var encoding = baseDict.getRaw('Encoding'); if (isName(encoding)) { hash.update(encoding.name); } else if (isRef(encoding)) { hash.update(encoding.num + '_' + encoding.gen); } else if (isDict(encoding)) { var keys = encoding.getKeys(); for (var i = 0, ii = keys.length; i < ii; i++) { var entry = encoding.getRaw(keys[i]); if (isName(entry)) { hash.update(entry.name); } else if (isRef(entry)) { hash.update(entry.num + '_' + entry.gen); } else if (isArray(entry)) { // 'Differences' entry. // Ideally we should check the contents of the array, but to avoid // parsing it here and then again in |extractDataStructures|, // we only use the array length for now (fixes bug1157493.pdf). hash.update(entry.length.toString()); } } } var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode'); if (isStream(toUnicode)) { var stream = toUnicode.str || toUnicode; uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start); hash.update(uint8array); } else if (isName(toUnicode)) { hash.update(toUnicode.name); } var widths = dict.get('Widths') || baseDict.get('Widths'); if (widths) { uint8array = new Uint8Array(new Uint32Array(widths).buffer); hash.update(uint8array); } } return { descriptor: descriptor, dict: dict, baseDict: baseDict, composite: composite, type: type.name, hash: hash ? hash.hexdigest() : '' }; }, translateFont: function PartialEvaluator_translateFont(preEvaluatedFont, xref) { var baseDict = preEvaluatedFont.baseDict; var dict = preEvaluatedFont.dict; var composite = preEvaluatedFont.composite; var descriptor = preEvaluatedFont.descriptor; var type = preEvaluatedFont.type; var maxCharIndex = (composite ? 0xFFFF : 0xFF); var properties; if (!descriptor) { if (type === 'Type3') { // FontDescriptor is only required for Type3 fonts when the document // is a tagged pdf. Create a barbebones one to get by. descriptor = new Dict(null); descriptor.set('FontName', Name.get(type)); } else { // Before PDF 1.5 if the font was one of the base 14 fonts, having a // FontDescriptor was not required. // This case is here for compatibility. var baseFontName = dict.get('BaseFont'); if (!isName(baseFontName)) { error('Base font is not specified'); } // Using base font name as a font name. baseFontName = baseFontName.name.replace(/[,_]/g, '-'); var metrics = this.getBaseFontMetrics(baseFontName); // Simulating descriptor flags attribute var fontNameWoStyle = baseFontName.split('-')[0]; var flags = (this.isSerifFont(fontNameWoStyle) ? FontFlags.Serif : 0) | (metrics.monospace ? FontFlags.FixedPitch : 0) | (symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic : FontFlags.Nonsymbolic); properties = { type: type, name: baseFontName, widths: metrics.widths, defaultWidth: metrics.defaultWidth, flags: flags, firstChar: 0, lastChar: maxCharIndex }; this.extractDataStructures(dict, dict, xref, properties); properties.widths = this.buildCharCodeToWidth(metrics.widths, properties); return new Font(baseFontName, null, properties); } } // According to the spec if 'FontDescriptor' is declared, 'FirstChar', // 'LastChar' and 'Widths' should exist too, but some PDF encoders seem // to ignore this rule when a variant of a standart font is used. // TODO Fill the width array depending on which of the base font this is // a variant. var firstChar = (dict.get('FirstChar') || 0); var lastChar = (dict.get('LastChar') || maxCharIndex); var fontName = descriptor.get('FontName'); var baseFont = dict.get('BaseFont'); // Some bad PDFs have a string as the font name. if (isString(fontName)) { fontName = Name.get(fontName); } if (isString(baseFont)) { baseFont = Name.get(baseFont); } if (type !== 'Type3') { var fontNameStr = fontName && fontName.name; var baseFontStr = baseFont && baseFont.name; if (fontNameStr !== baseFontStr) { info('The FontDescriptor\'s FontName is "' + fontNameStr + '" but should be the same as the Font\'s BaseFont "' + baseFontStr + '"'); // Workaround for cases where e.g. fontNameStr = 'Arial' and // baseFontStr = 'Arial,Bold' (needed when no font file is embedded). if (fontNameStr && baseFontStr && baseFontStr.indexOf(fontNameStr) === 0) { fontName = baseFont; } } } fontName = (fontName || baseFont); assert(isName(fontName), 'invalid font name'); var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3'); if (fontFile) { if (fontFile.dict) { var subtype = fontFile.dict.get('Subtype'); if (subtype) { subtype = subtype.name; } var length1 = fontFile.dict.get('Length1'); var length2 = fontFile.dict.get('Length2'); } } properties = { type: type, name: fontName.name, subtype: subtype, file: fontFile, length1: length1, length2: length2, loadedName: baseDict.loadedName, composite: composite, wideChars: composite, fixedPitch: false, fontMatrix: (dict.get('FontMatrix') || FONT_IDENTITY_MATRIX), firstChar: firstChar || 0, lastChar: (lastChar || maxCharIndex), bbox: descriptor.get('FontBBox'), ascent: descriptor.get('Ascent'), descent: descriptor.get('Descent'), xHeight: descriptor.get('XHeight'), capHeight: descriptor.get('CapHeight'), flags: descriptor.get('Flags'), italicAngle: descriptor.get('ItalicAngle'), coded: false }; if (composite) { var cidEncoding = baseDict.get('Encoding'); if (isName(cidEncoding)) { properties.cidEncoding = cidEncoding.name; } properties.cMap = CMapFactory.create(cidEncoding, { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null); properties.vertical = properties.cMap.vertical; } this.extractDataStructures(dict, baseDict, xref, properties); this.extractWidths(dict, xref, descriptor, properties); if (type === 'Type3') { properties.isType3Font = true; } return new Font(fontName.name, fontFile, properties); } }; return PartialEvaluator; })(); var TranslatedFont = (function TranslatedFontClosure() { function TranslatedFont(loadedName, font, dict) { this.loadedName = loadedName; this.font = font; this.dict = dict; this.type3Loaded = null; this.sent = false; } TranslatedFont.prototype = { send: function (handler) { if (this.sent) { return; } var fontData = this.font.exportData(); handler.send('commonobj', [ this.loadedName, 'Font', fontData ]); this.sent = true; }, loadType3Data: function (evaluator, resources, parentOperatorList) { assert(this.font.isType3Font); if (this.type3Loaded) { return this.type3Loaded; } var translatedFont = this.font; var loadCharProcsPromise = Promise.resolve(); var charProcs = this.dict.get('CharProcs').getAll(); var fontResources = this.dict.get('Resources') || resources; var charProcKeys = Object.keys(charProcs); var charProcOperatorList = {}; for (var i = 0, n = charProcKeys.length; i < n; ++i) { loadCharProcsPromise = loadCharProcsPromise.then(function (key) { var glyphStream = charProcs[key]; var operatorList = new OperatorList(); return evaluator.getOperatorList(glyphStream, fontResources, operatorList).then(function () { charProcOperatorList[key] = operatorList.getIR(); // Add the dependencies to the parent operator list so they are // resolved before sub operator list is executed synchronously. parentOperatorList.addDependencies(operatorList.dependencies); }, function (reason) { warn('Type3 font resource \"' + key + '\" is not available'); var operatorList = new OperatorList(); charProcOperatorList[key] = operatorList.getIR(); }); }.bind(this, charProcKeys[i])); } this.type3Loaded = loadCharProcsPromise.then(function () { translatedFont.charProcOperatorList = charProcOperatorList; }); return this.type3Loaded; } }; return TranslatedFont; })(); var OperatorList = (function OperatorListClosure() { var CHUNK_SIZE = 1000; var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5; // close to chunk size function getTransfers(queue) { var transfers = []; var fnArray = queue.fnArray, argsArray = queue.argsArray; for (var i = 0, ii = queue.length; i < ii; i++) { switch (fnArray[i]) { case OPS.paintInlineImageXObject: case OPS.paintInlineImageXObjectGroup: case OPS.paintImageMaskXObject: var arg = argsArray[i][0]; // first param in imgData if (!arg.cached) { transfers.push(arg.data.buffer); } break; } } return transfers; } function OperatorList(intent, messageHandler, pageIndex) { this.messageHandler = messageHandler; this.fnArray = []; this.argsArray = []; this.dependencies = {}; this.pageIndex = pageIndex; this.intent = intent; } OperatorList.prototype = { get length() { return this.argsArray.length; }, addOp: function(fn, args) { this.fnArray.push(fn); this.argsArray.push(args); if (this.messageHandler) { if (this.fnArray.length >= CHUNK_SIZE) { this.flush(); } else if (this.fnArray.length >= CHUNK_SIZE_ABOUT && (fn === OPS.restore || fn === OPS.endText)) { // heuristic to flush on boundary of restore or endText this.flush(); } } }, addDependency: function(dependency) { if (dependency in this.dependencies) { return; } this.dependencies[dependency] = true; this.addOp(OPS.dependency, [dependency]); }, addDependencies: function(dependencies) { for (var key in dependencies) { this.addDependency(key); } }, addOpList: function(opList) { Util.extendObj(this.dependencies, opList.dependencies); for (var i = 0, ii = opList.length; i < ii; i++) { this.addOp(opList.fnArray[i], opList.argsArray[i]); } }, getIR: function() { return { fnArray: this.fnArray, argsArray: this.argsArray, length: this.length }; }, flush: function(lastChunk) { if (this.intent !== 'oplist') { new QueueOptimizer().optimize(this); } var transfers = getTransfers(this); this.messageHandler.send('RenderPageChunk', { operatorList: { fnArray: this.fnArray, argsArray: this.argsArray, lastChunk: lastChunk, length: this.length }, pageIndex: this.pageIndex, intent: this.intent }, transfers); this.dependencies = {}; this.fnArray.length = 0; this.argsArray.length = 0; } }; return OperatorList; })(); var StateManager = (function StateManagerClosure() { function StateManager(initialState) { this.state = initialState; this.stateStack = []; } StateManager.prototype = { save: function () { var old = this.state; this.stateStack.push(this.state); this.state = old.clone(); }, restore: function () { var prev = this.stateStack.pop(); if (prev) { this.state = prev; } }, transform: function (args) { this.state.ctm = Util.transform(this.state.ctm, args); } }; return StateManager; })(); var TextState = (function TextStateClosure() { function TextState() { this.ctm = new Float32Array(IDENTITY_MATRIX); this.fontSize = 0; this.font = null; this.fontMatrix = FONT_IDENTITY_MATRIX; this.textMatrix = IDENTITY_MATRIX.slice(); this.textLineMatrix = IDENTITY_MATRIX.slice(); this.charSpacing = 0; this.wordSpacing = 0; this.leading = 0; this.textHScale = 1; this.textRise = 0; } TextState.prototype = { setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) { var m = this.textMatrix; m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f; }, setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) { var m = this.textLineMatrix; m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f; }, translateTextMatrix: function TextState_translateTextMatrix(x, y) { var m = this.textMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; }, translateTextLineMatrix: function TextState_translateTextMatrix(x, y) { var m = this.textLineMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; }, calcRenderMatrix: function TextState_calcRendeMatrix(ctm) { // 9.4.4 Text Space Details var tsm = [this.fontSize * this.textHScale, 0, 0, this.fontSize, 0, this.textRise]; return Util.transform(ctm, Util.transform(this.textMatrix, tsm)); }, carriageReturn: function TextState_carriageReturn() { this.translateTextLineMatrix(0, -this.leading); this.textMatrix = this.textLineMatrix.slice(); }, clone: function TextState_clone() { var clone = Object.create(this); clone.textMatrix = this.textMatrix.slice(); clone.textLineMatrix = this.textLineMatrix.slice(); clone.fontMatrix = this.fontMatrix.slice(); return clone; } }; return TextState; })(); var EvalState = (function EvalStateClosure() { function EvalState() { this.ctm = new Float32Array(IDENTITY_MATRIX); this.font = null; this.textRenderingMode = TextRenderingMode.FILL; this.fillColorSpace = ColorSpace.singletons.gray; this.strokeColorSpace = ColorSpace.singletons.gray; } EvalState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, }; return EvalState; })(); var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() { // Specifies properties for each command // // If variableArgs === true: [0, `numArgs`] expected // If variableArgs === false: exactly `numArgs` expected var OP_MAP = { // Graphic state w: { id: OPS.setLineWidth, numArgs: 1, variableArgs: false }, J: { id: OPS.setLineCap, numArgs: 1, variableArgs: false }, j: { id: OPS.setLineJoin, numArgs: 1, variableArgs: false }, M: { id: OPS.setMiterLimit, numArgs: 1, variableArgs: false }, d: { id: OPS.setDash, numArgs: 2, variableArgs: false }, ri: { id: OPS.setRenderingIntent, numArgs: 1, variableArgs: false }, i: { id: OPS.setFlatness, numArgs: 1, variableArgs: false }, gs: { id: OPS.setGState, numArgs: 1, variableArgs: false }, q: { id: OPS.save, numArgs: 0, variableArgs: false }, Q: { id: OPS.restore, numArgs: 0, variableArgs: false }, cm: { id: OPS.transform, numArgs: 6, variableArgs: false }, // Path m: { id: OPS.moveTo, numArgs: 2, variableArgs: false }, l: { id: OPS.lineTo, numArgs: 2, variableArgs: false }, c: { id: OPS.curveTo, numArgs: 6, variableArgs: false }, v: { id: OPS.curveTo2, numArgs: 4, variableArgs: false }, y: { id: OPS.curveTo3, numArgs: 4, variableArgs: false }, h: { id: OPS.closePath, numArgs: 0, variableArgs: false }, re: { id: OPS.rectangle, numArgs: 4, variableArgs: false }, S: { id: OPS.stroke, numArgs: 0, variableArgs: false }, s: { id: OPS.closeStroke, numArgs: 0, variableArgs: false }, f: { id: OPS.fill, numArgs: 0, variableArgs: false }, F: { id: OPS.fill, numArgs: 0, variableArgs: false }, 'f*': { id: OPS.eoFill, numArgs: 0, variableArgs: false }, B: { id: OPS.fillStroke, numArgs: 0, variableArgs: false }, 'B*': { id: OPS.eoFillStroke, numArgs: 0, variableArgs: false }, b: { id: OPS.closeFillStroke, numArgs: 0, variableArgs: false }, 'b*': { id: OPS.closeEOFillStroke, numArgs: 0, variableArgs: false }, n: { id: OPS.endPath, numArgs: 0, variableArgs: false }, // Clipping W: { id: OPS.clip, numArgs: 0, variableArgs: false }, 'W*': { id: OPS.eoClip, numArgs: 0, variableArgs: false }, // Text BT: { id: OPS.beginText, numArgs: 0, variableArgs: false }, ET: { id: OPS.endText, numArgs: 0, variableArgs: false }, Tc: { id: OPS.setCharSpacing, numArgs: 1, variableArgs: false }, Tw: { id: OPS.setWordSpacing, numArgs: 1, variableArgs: false }, Tz: { id: OPS.setHScale, numArgs: 1, variableArgs: false }, TL: { id: OPS.setLeading, numArgs: 1, variableArgs: false }, Tf: { id: OPS.setFont, numArgs: 2, variableArgs: false }, Tr: { id: OPS.setTextRenderingMode, numArgs: 1, variableArgs: false }, Ts: { id: OPS.setTextRise, numArgs: 1, variableArgs: false }, Td: { id: OPS.moveText, numArgs: 2, variableArgs: false }, TD: { id: OPS.setLeadingMoveText, numArgs: 2, variableArgs: false }, Tm: { id: OPS.setTextMatrix, numArgs: 6, variableArgs: false }, 'T*': { id: OPS.nextLine, numArgs: 0, variableArgs: false }, Tj: { id: OPS.showText, numArgs: 1, variableArgs: false }, TJ: { id: OPS.showSpacedText, numArgs: 1, variableArgs: false }, '\'': { id: OPS.nextLineShowText, numArgs: 1, variableArgs: false }, '"': { id: OPS.nextLineSetSpacingShowText, numArgs: 3, variableArgs: false }, // Type3 fonts d0: { id: OPS.setCharWidth, numArgs: 2, variableArgs: false }, d1: { id: OPS.setCharWidthAndBounds, numArgs: 6, variableArgs: false }, // Color CS: { id: OPS.setStrokeColorSpace, numArgs: 1, variableArgs: false }, cs: { id: OPS.setFillColorSpace, numArgs: 1, variableArgs: false }, SC: { id: OPS.setStrokeColor, numArgs: 4, variableArgs: true }, SCN: { id: OPS.setStrokeColorN, numArgs: 33, variableArgs: true }, sc: { id: OPS.setFillColor, numArgs: 4, variableArgs: true }, scn: { id: OPS.setFillColorN, numArgs: 33, variableArgs: true }, G: { id: OPS.setStrokeGray, numArgs: 1, variableArgs: false }, g: { id: OPS.setFillGray, numArgs: 1, variableArgs: false }, RG: { id: OPS.setStrokeRGBColor, numArgs: 3, variableArgs: false }, rg: { id: OPS.setFillRGBColor, numArgs: 3, variableArgs: false }, K: { id: OPS.setStrokeCMYKColor, numArgs: 4, variableArgs: false }, k: { id: OPS.setFillCMYKColor, numArgs: 4, variableArgs: false }, // Shading sh: { id: OPS.shadingFill, numArgs: 1, variableArgs: false }, // Images BI: { id: OPS.beginInlineImage, numArgs: 0, variableArgs: false }, ID: { id: OPS.beginImageData, numArgs: 0, variableArgs: false }, EI: { id: OPS.endInlineImage, numArgs: 1, variableArgs: false }, // XObjects Do: { id: OPS.paintXObject, numArgs: 1, variableArgs: false }, MP: { id: OPS.markPoint, numArgs: 1, variableArgs: false }, DP: { id: OPS.markPointProps, numArgs: 2, variableArgs: false }, BMC: { id: OPS.beginMarkedContent, numArgs: 1, variableArgs: false }, BDC: { id: OPS.beginMarkedContentProps, numArgs: 2, variableArgs: false }, EMC: { id: OPS.endMarkedContent, numArgs: 0, variableArgs: false }, // Compatibility BX: { id: OPS.beginCompat, numArgs: 0, variableArgs: false }, EX: { id: OPS.endCompat, numArgs: 0, variableArgs: false }, // (reserved partial commands for the lexer) BM: null, BD: null, 'true': null, fa: null, fal: null, fals: null, 'false': null, nu: null, nul: null, 'null': null }; function EvaluatorPreprocessor(stream, xref, stateManager) { // TODO(mduan): pass array of knownCommands rather than OP_MAP // dictionary this.parser = new Parser(new Lexer(stream, OP_MAP), false, xref); this.stateManager = stateManager; this.nonProcessedArgs = []; } EvaluatorPreprocessor.prototype = { get savedStatesDepth() { return this.stateManager.stateStack.length; }, // |operation| is an object with two fields: // // - |fn| is an out param. // // - |args| is an inout param. On entry, it should have one of two values. // // - An empty array. This indicates that the caller is providing the // array in which the args will be stored in. The caller should use // this value if it can reuse a single array for each call to read(). // // - |null|. This indicates that the caller needs this function to create // the array in which any args are stored in. If there are zero args, // this function will leave |operation.args| as |null| (thus avoiding // allocations that would occur if we used an empty array to represent // zero arguments). Otherwise, it will replace |null| with a new array // containing the arguments. The caller should use this value if it // cannot reuse an array for each call to read(). // // These two modes are present because this function is very hot and so // avoiding allocations where possible is worthwhile. // read: function EvaluatorPreprocessor_read(operation) { var args = operation.args; while (true) { var obj = this.parser.getObj(); if (isCmd(obj)) { var cmd = obj.cmd; // Check that the command is valid var opSpec = OP_MAP[cmd]; if (!opSpec) { warn('Unknown command "' + cmd + '"'); continue; } var fn = opSpec.id; var numArgs = opSpec.numArgs; var argsLength = args !== null ? args.length : 0; if (!opSpec.variableArgs) { // Postscript commands can be nested, e.g. /F2 /GS2 gs 5.711 Tf if (argsLength !== numArgs) { var nonProcessedArgs = this.nonProcessedArgs; while (argsLength > numArgs) { nonProcessedArgs.push(args.shift()); argsLength--; } while (argsLength < numArgs && nonProcessedArgs.length !== 0) { if (!args) { args = []; } args.unshift(nonProcessedArgs.pop()); argsLength++; } } if (argsLength < numArgs) { // If we receive too few args, it's not possible to possible // to execute the command, so skip the command info('Command ' + fn + ': because expected ' + numArgs + ' args, but received ' + argsLength + ' args; skipping'); args = null; continue; } } else if (argsLength > numArgs) { info('Command ' + fn + ': expected [0,' + numArgs + '] args, but received ' + argsLength + ' args'); } // TODO figure out how to type-check vararg functions this.preprocessCommand(fn, args); operation.fn = fn; operation.args = args; return true; } else { if (isEOF(obj)) { return false; // no more commands } // argument if (obj !== null) { if (!args) { args = []; } args.push((obj instanceof Dict ? obj.getAll() : obj)); assert(args.length <= 33, 'Too many arguments'); } } } }, preprocessCommand: function EvaluatorPreprocessor_preprocessCommand(fn, args) { switch (fn | 0) { case OPS.save: this.stateManager.save(); break; case OPS.restore: this.stateManager.restore(); break; case OPS.transform: this.stateManager.transform(args); break; } } }; return EvaluatorPreprocessor; })(); var QueueOptimizer = (function QueueOptimizerClosure() { function addState(parentState, pattern, fn) { var state = parentState; for (var i = 0, ii = pattern.length - 1; i < ii; i++) { var item = pattern[i]; state = (state[item] || (state[item] = [])); } state[pattern[pattern.length - 1]] = fn; } function handlePaintSolidColorImageMask(iFirstSave, count, fnArray, argsArray) { // Handles special case of mainly LaTeX documents which use image masks to // draw lines with the current fill style. // 'count' groups of (save, transform, paintImageMaskXObject, restore)+ // have been found at iFirstSave. var iFirstPIMXO = iFirstSave + 2; for (var i = 0; i < count; i++) { var arg = argsArray[iFirstPIMXO + 4 * i]; var imageMask = arg.length === 1 && arg[0]; if (imageMask && imageMask.width === 1 && imageMask.height === 1 && (!imageMask.data.length || (imageMask.data.length === 1 && imageMask.data[0] === 0))) { fnArray[iFirstPIMXO + 4 * i] = OPS.paintSolidColorImageMask; continue; } break; } return count - i; } var InitialState = []; // This replaces (save, transform, paintInlineImageXObject, restore)+ // sequences with one |paintInlineImageXObjectGroup| operation. addState(InitialState, [OPS.save, OPS.transform, OPS.paintInlineImageXObject, OPS.restore], function foundInlineImageGroup(context) { var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10; var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200; var MAX_WIDTH = 1000; var IMAGE_PADDING = 1; var fnArray = context.fnArray, argsArray = context.argsArray; var curr = context.iCurr; var iFirstSave = curr - 3; var iFirstTransform = curr - 2; var iFirstPIIXO = curr - 1; // Look for the quartets. var i = iFirstSave + 4; var ii = fnArray.length; while (i + 3 < ii) { if (fnArray[i] !== OPS.save || fnArray[i + 1] !== OPS.transform || fnArray[i + 2] !== OPS.paintInlineImageXObject || fnArray[i + 3] !== OPS.restore) { break; // ops don't match } i += 4; } // At this point, i is the index of the first op past the last valid // quartet. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_INLINE_IMAGES_BLOCK); if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) { return i; } // assuming that heights of those image is too small (~1 pixel) // packing as much as possible by lines var maxX = 0; var map = [], maxLineHeight = 0; var currentX = IMAGE_PADDING, currentY = IMAGE_PADDING; var q; for (q = 0; q < count; q++) { var transform = argsArray[iFirstTransform + (q << 2)]; var img = argsArray[iFirstPIIXO + (q << 2)][0]; if (currentX + img.width > MAX_WIDTH) { // starting new line maxX = Math.max(maxX, currentX); currentY += maxLineHeight + 2 * IMAGE_PADDING; currentX = 0; maxLineHeight = 0; } map.push({ transform: transform, x: currentX, y: currentY, w: img.width, h: img.height }); currentX += img.width + 2 * IMAGE_PADDING; maxLineHeight = Math.max(maxLineHeight, img.height); } var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING; var imgHeight = currentY + maxLineHeight + IMAGE_PADDING; var imgData = new Uint8Array(imgWidth * imgHeight * 4); var imgRowSize = imgWidth << 2; for (q = 0; q < count; q++) { var data = argsArray[iFirstPIIXO + (q << 2)][0].data; // Copy image by lines and extends pixels into padding. var rowSize = map[q].w << 2; var dataOffset = 0; var offset = (map[q].x + map[q].y * imgWidth) << 2; imgData.set(data.subarray(0, rowSize), offset - imgRowSize); for (var k = 0, kk = map[q].h; k < kk; k++) { imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset); dataOffset += rowSize; offset += imgRowSize; } imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset); while (offset >= 0) { data[offset - 4] = data[offset]; data[offset - 3] = data[offset + 1]; data[offset - 2] = data[offset + 2]; data[offset - 1] = data[offset + 3]; data[offset + rowSize] = data[offset + rowSize - 4]; data[offset + rowSize + 1] = data[offset + rowSize - 3]; data[offset + rowSize + 2] = data[offset + rowSize - 2]; data[offset + rowSize + 3] = data[offset + rowSize - 1]; offset -= imgRowSize; } } // Replace queue items. fnArray.splice(iFirstSave, count * 4, OPS.paintInlineImageXObjectGroup); argsArray.splice(iFirstSave, count * 4, [{ width: imgWidth, height: imgHeight, kind: ImageKind.RGBA_32BPP, data: imgData }, map]); return iFirstSave + 1; }); // This replaces (save, transform, paintImageMaskXObject, restore)+ // sequences with one |paintImageMaskXObjectGroup| or one // |paintImageMaskXObjectRepeat| operation. addState(InitialState, [OPS.save, OPS.transform, OPS.paintImageMaskXObject, OPS.restore], function foundImageMaskGroup(context) { var MIN_IMAGES_IN_MASKS_BLOCK = 10; var MAX_IMAGES_IN_MASKS_BLOCK = 100; var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000; var fnArray = context.fnArray, argsArray = context.argsArray; var curr = context.iCurr; var iFirstSave = curr - 3; var iFirstTransform = curr - 2; var iFirstPIMXO = curr - 1; // Look for the quartets. var i = iFirstSave + 4; var ii = fnArray.length; while (i + 3 < ii) { if (fnArray[i] !== OPS.save || fnArray[i + 1] !== OPS.transform || fnArray[i + 2] !== OPS.paintImageMaskXObject || fnArray[i + 3] !== OPS.restore) { break; // ops don't match } i += 4; } // At this point, i is the index of the first op past the last valid // quartet. var count = (i - iFirstSave) / 4; count = handlePaintSolidColorImageMask(iFirstSave, count, fnArray, argsArray); if (count < MIN_IMAGES_IN_MASKS_BLOCK) { return i; } var q; var isSameImage = false; var iTransform, transformArgs; var firstPIMXOArg0 = argsArray[iFirstPIMXO][0]; if (argsArray[iFirstTransform][1] === 0 && argsArray[iFirstTransform][2] === 0) { isSameImage = true; var firstTransformArg0 = argsArray[iFirstTransform][0]; var firstTransformArg3 = argsArray[iFirstTransform][3]; iTransform = iFirstTransform + 4; var iPIMXO = iFirstPIMXO + 4; for (q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) { transformArgs = argsArray[iTransform]; if (argsArray[iPIMXO][0] !== firstPIMXOArg0 || transformArgs[0] !== firstTransformArg0 || transformArgs[1] !== 0 || transformArgs[2] !== 0 || transformArgs[3] !== firstTransformArg3) { if (q < MIN_IMAGES_IN_MASKS_BLOCK) { isSameImage = false; } else { count = q; } break; // different image or transform } } } if (isSameImage) { count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK); var positions = new Float32Array(count * 2); iTransform = iFirstTransform; for (q = 0; q < count; q++, iTransform += 4) { transformArgs = argsArray[iTransform]; positions[(q << 1)] = transformArgs[4]; positions[(q << 1) + 1] = transformArgs[5]; } // Replace queue items. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectRepeat); argsArray.splice(iFirstSave, count * 4, [firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]); } else { count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK); var images = []; for (q = 0; q < count; q++) { transformArgs = argsArray[iFirstTransform + (q << 2)]; var maskParams = argsArray[iFirstPIMXO + (q << 2)][0]; images.push({ data: maskParams.data, width: maskParams.width, height: maskParams.height, transform: transformArgs }); } // Replace queue items. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectGroup); argsArray.splice(iFirstSave, count * 4, [images]); } return iFirstSave + 1; }); // This replaces (save, transform, paintImageXObject, restore)+ sequences // with one paintImageXObjectRepeat operation, if the |transform| and // |paintImageXObjectRepeat| ops are appropriate. addState(InitialState, [OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore], function (context) { var MIN_IMAGES_IN_BLOCK = 3; var MAX_IMAGES_IN_BLOCK = 1000; var fnArray = context.fnArray, argsArray = context.argsArray; var curr = context.iCurr; var iFirstSave = curr - 3; var iFirstTransform = curr - 2; var iFirstPIXO = curr - 1; var iFirstRestore = curr; if (argsArray[iFirstTransform][1] !== 0 || argsArray[iFirstTransform][2] !== 0) { return iFirstRestore + 1; // transform has the wrong form } // Look for the quartets. var firstPIXOArg0 = argsArray[iFirstPIXO][0]; var firstTransformArg0 = argsArray[iFirstTransform][0]; var firstTransformArg3 = argsArray[iFirstTransform][3]; var i = iFirstSave + 4; var ii = fnArray.length; while (i + 3 < ii) { if (fnArray[i] !== OPS.save || fnArray[i + 1] !== OPS.transform || fnArray[i + 2] !== OPS.paintImageXObject || fnArray[i + 3] !== OPS.restore) { break; // ops don't match } if (argsArray[i + 1][0] !== firstTransformArg0 || argsArray[i + 1][1] !== 0 || argsArray[i + 1][2] !== 0 || argsArray[i + 1][3] !== firstTransformArg3) { break; // transforms don't match } if (argsArray[i + 2][0] !== firstPIXOArg0) { break; // images don't match } i += 4; } // At this point, i is the index of the first op past the last valid // quartet. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_BLOCK); if (count < MIN_IMAGES_IN_BLOCK) { return i; } // Extract the (x,y) positions from all of the matching transforms. var positions = new Float32Array(count * 2); var iTransform = iFirstTransform; for (var q = 0; q < count; q++, iTransform += 4) { var transformArgs = argsArray[iTransform]; positions[(q << 1)] = transformArgs[4]; positions[(q << 1) + 1] = transformArgs[5]; } // Replace queue items. var args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3, positions]; fnArray.splice(iFirstSave, count * 4, OPS.paintImageXObjectRepeat); argsArray.splice(iFirstSave, count * 4, args); return iFirstSave + 1; }); // This replaces (beginText, setFont, setTextMatrix, showText, endText)+ // sequences with (beginText, setFont, (setTextMatrix, showText)+, endText)+ // sequences, if the font for each one is the same. addState(InitialState, [OPS.beginText, OPS.setFont, OPS.setTextMatrix, OPS.showText, OPS.endText], function (context) { var MIN_CHARS_IN_BLOCK = 3; var MAX_CHARS_IN_BLOCK = 1000; var fnArray = context.fnArray, argsArray = context.argsArray; var curr = context.iCurr; var iFirstBeginText = curr - 4; var iFirstSetFont = curr - 3; var iFirstSetTextMatrix = curr - 2; var iFirstShowText = curr - 1; var iFirstEndText = curr; // Look for the quintets. var firstSetFontArg0 = argsArray[iFirstSetFont][0]; var firstSetFontArg1 = argsArray[iFirstSetFont][1]; var i = iFirstBeginText + 5; var ii = fnArray.length; while (i + 4 < ii) { if (fnArray[i] !== OPS.beginText || fnArray[i + 1] !== OPS.setFont || fnArray[i + 2] !== OPS.setTextMatrix || fnArray[i + 3] !== OPS.showText || fnArray[i + 4] !== OPS.endText) { break; // ops don't match } if (argsArray[i + 1][0] !== firstSetFontArg0 || argsArray[i + 1][1] !== firstSetFontArg1) { break; // fonts don't match } i += 5; } // At this point, i is the index of the first op past the last valid // quintet. var count = Math.min(((i - iFirstBeginText) / 5), MAX_CHARS_IN_BLOCK); if (count < MIN_CHARS_IN_BLOCK) { return i; } // If the preceding quintet is (<something>, setFont, setTextMatrix, // showText, endText), include that as well. (E.g. <something> might be // |dependency|.) var iFirst = iFirstBeginText; if (iFirstBeginText >= 4 && fnArray[iFirstBeginText - 4] === fnArray[iFirstSetFont] && fnArray[iFirstBeginText - 3] === fnArray[iFirstSetTextMatrix] && fnArray[iFirstBeginText - 2] === fnArray[iFirstShowText] && fnArray[iFirstBeginText - 1] === fnArray[iFirstEndText] && argsArray[iFirstBeginText - 4][0] === firstSetFontArg0 && argsArray[iFirstBeginText - 4][1] === firstSetFontArg1) { count++; iFirst -= 5; } // Remove (endText, beginText, setFont) trios. var iEndText = iFirst + 4; for (var q = 1; q < count; q++) { fnArray.splice(iEndText, 3); argsArray.splice(iEndText, 3); iEndText += 2; } return iEndText + 1; }); function QueueOptimizer() {} QueueOptimizer.prototype = { optimize: function QueueOptimizer_optimize(queue) { var fnArray = queue.fnArray, argsArray = queue.argsArray; var context = { iCurr: 0, fnArray: fnArray, argsArray: argsArray }; var state; var i = 0, ii = fnArray.length; while (i < ii) { state = (state || InitialState)[fnArray[i]]; if (typeof state === 'function') { // we found some handler context.iCurr = i; // state() returns the index of the first non-matching op (if we // didn't match) or the first op past the modified ops (if we did // match and replace). i = state(context); state = undefined; // reset the state machine ii = context.fnArray.length; } else { i++; } } } }; return QueueOptimizer; })();
gpl-3.0
isghe/cjdns
node_build/dependencies/libuv/build/gyp/test/mac/gyptest-action-envvars.py
1073
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that env vars work with actions, with relative directory paths. """ import TestGyp import sys if sys.platform == 'darwin': test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode']) # The xcode-ninja generator handles gypfiles which are not at the # project root incorrectly. # cf. https://code.google.com/p/gyp/issues/detail?id=460 if test.format == 'xcode-ninja': test.skip_test() CHDIR = 'action-envvars' test.run_gyp('action/action.gyp', chdir=CHDIR) test.build('action/action.gyp', 'action', chdir=CHDIR, SYMROOT='../build') result_file = test.built_file_path('result', chdir=CHDIR) test.must_exist(result_file) test.must_contain(result_file, 'Test output') other_result_file = test.built_file_path('other_result', chdir=CHDIR) test.must_exist(other_result_file) test.must_contain(other_result_file, 'Other output') test.pass_test()
gpl-3.0
realfake/kubernetes
pkg/registry/extensions/replicaset/storage/storage.go
6477
/* Copyright 2016 The Kubernetes 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. */ // If you make changes to this file, you should also make the corresponding change in ReplicationController. package storage import ( "fmt" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" genericapirequest "k8s.io/apiserver/pkg/endpoints/request" "k8s.io/apiserver/pkg/registry/generic" genericregistry "k8s.io/apiserver/pkg/registry/generic/registry" "k8s.io/apiserver/pkg/registry/rest" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/extensions" extvalidation "k8s.io/kubernetes/pkg/apis/extensions/validation" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/extensions/replicaset" ) // ReplicaSetStorage includes dummy storage for ReplicaSets and for Scale subresource. type ReplicaSetStorage struct { ReplicaSet *REST Status *StatusREST Scale *ScaleREST } func NewStorage(optsGetter generic.RESTOptionsGetter) ReplicaSetStorage { replicaSetRest, replicaSetStatusRest := NewREST(optsGetter) replicaSetRegistry := replicaset.NewRegistry(replicaSetRest) return ReplicaSetStorage{ ReplicaSet: replicaSetRest, Status: replicaSetStatusRest, Scale: &ScaleREST{registry: replicaSetRegistry}, } } type REST struct { *genericregistry.Store } // NewREST returns a RESTStorage object that will work against ReplicaSet. func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST) { store := &genericregistry.Store{ Copier: api.Scheme, NewFunc: func() runtime.Object { return &extensions.ReplicaSet{} }, NewListFunc: func() runtime.Object { return &extensions.ReplicaSetList{} }, ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*extensions.ReplicaSet).Name, nil }, PredicateFunc: replicaset.MatchReplicaSet, QualifiedResource: extensions.Resource("replicasets"), WatchCacheSize: cachesize.GetWatchCacheSizeByResource("replicasets"), CreateStrategy: replicaset.Strategy, UpdateStrategy: replicaset.Strategy, DeleteStrategy: replicaset.Strategy, } options := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: replicaset.GetAttrs} if err := store.CompleteWithOptions(options); err != nil { panic(err) // TODO: Propagate error up } statusStore := *store statusStore.UpdateStrategy = replicaset.StatusStrategy return &REST{store}, &StatusREST{store: &statusStore} } // Implement ShortNamesProvider var _ rest.ShortNamesProvider = &REST{} // ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource. func (r *REST) ShortNames() []string { return []string{"rs"} } // StatusREST implements the REST endpoint for changing the status of a ReplicaSet type StatusREST struct { store *genericregistry.Store } func (r *StatusREST) New() runtime.Object { return &extensions.ReplicaSet{} } // Get retrieves the object from the storage. It is required to support Patch. func (r *StatusREST) Get(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) { return r.store.Get(ctx, name, options) } // Update alters the status subset of an object. func (r *StatusREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) { return r.store.Update(ctx, name, objInfo) } type ScaleREST struct { registry replicaset.Registry } // ScaleREST implements Patcher var _ = rest.Patcher(&ScaleREST{}) // New creates a new Scale object func (r *ScaleREST) New() runtime.Object { return &extensions.Scale{} } func (r *ScaleREST) Get(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) { rs, err := r.registry.GetReplicaSet(ctx, name, options) if err != nil { return nil, errors.NewNotFound(extensions.Resource("replicasets/scale"), name) } scale, err := scaleFromReplicaSet(rs) if err != nil { return nil, errors.NewBadRequest(fmt.Sprintf("%v", err)) } return scale, err } func (r *ScaleREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) { rs, err := r.registry.GetReplicaSet(ctx, name, &metav1.GetOptions{}) if err != nil { return nil, false, errors.NewNotFound(extensions.Resource("replicasets/scale"), name) } oldScale, err := scaleFromReplicaSet(rs) if err != nil { return nil, false, err } obj, err := objInfo.UpdatedObject(ctx, oldScale) if err != nil { return nil, false, err } if obj == nil { return nil, false, errors.NewBadRequest(fmt.Sprintf("nil update passed to Scale")) } scale, ok := obj.(*extensions.Scale) if !ok { return nil, false, errors.NewBadRequest(fmt.Sprintf("wrong object passed to Scale update: %v", obj)) } if errs := extvalidation.ValidateScale(scale); len(errs) > 0 { return nil, false, errors.NewInvalid(extensions.Kind("Scale"), scale.Name, errs) } rs.Spec.Replicas = scale.Spec.Replicas rs.ResourceVersion = scale.ResourceVersion rs, err = r.registry.UpdateReplicaSet(ctx, rs) if err != nil { return nil, false, err } newScale, err := scaleFromReplicaSet(rs) if err != nil { return nil, false, errors.NewBadRequest(fmt.Sprintf("%v", err)) } return newScale, false, err } // scaleFromReplicaSet returns a scale subresource for a replica set. func scaleFromReplicaSet(rs *extensions.ReplicaSet) (*extensions.Scale, error) { return &extensions.Scale{ // TODO: Create a variant of ObjectMeta type that only contains the fields below. ObjectMeta: metav1.ObjectMeta{ Name: rs.Name, Namespace: rs.Namespace, UID: rs.UID, ResourceVersion: rs.ResourceVersion, CreationTimestamp: rs.CreationTimestamp, }, Spec: extensions.ScaleSpec{ Replicas: rs.Spec.Replicas, }, Status: extensions.ScaleStatus{ Replicas: rs.Status.Replicas, Selector: rs.Spec.Selector, }, }, nil }
apache-2.0
wangxing1517/kubernetes
vendor/google.golang.org/grpc/transport/handler_server.go
12580
/* * * Copyright 2016 gRPC 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. * */ // This file is the implementation of a gRPC server using HTTP/2 which // uses the standard Go http2 Server implementation (via the // http.Handler interface), rather than speaking low-level HTTP/2 // frames itself. It is the implementation of *grpc.Server.ServeHTTP. package transport import ( "errors" "fmt" "io" "net" "net/http" "strings" "sync" "time" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "golang.org/x/net/http2" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) // NewServerHandlerTransport returns a ServerTransport handling gRPC // from inside an http.Handler. It requires that the http Server // supports HTTP/2. func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats stats.Handler) (ServerTransport, error) { if r.ProtoMajor != 2 { return nil, errors.New("gRPC requires HTTP/2") } if r.Method != "POST" { return nil, errors.New("invalid gRPC request method") } contentType := r.Header.Get("Content-Type") // TODO: do we assume contentType is lowercase? we did before contentSubtype, validContentType := contentSubtype(contentType) if !validContentType { return nil, errors.New("invalid gRPC request content-type") } if _, ok := w.(http.Flusher); !ok { return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher") } if _, ok := w.(http.CloseNotifier); !ok { return nil, errors.New("gRPC requires a ResponseWriter supporting http.CloseNotifier") } st := &serverHandlerTransport{ rw: w, req: r, closedCh: make(chan struct{}), writes: make(chan func()), contentType: contentType, contentSubtype: contentSubtype, stats: stats, } if v := r.Header.Get("grpc-timeout"); v != "" { to, err := decodeTimeout(v) if err != nil { return nil, streamErrorf(codes.Internal, "malformed time-out: %v", err) } st.timeoutSet = true st.timeout = to } metakv := []string{"content-type", contentType} if r.Host != "" { metakv = append(metakv, ":authority", r.Host) } for k, vv := range r.Header { k = strings.ToLower(k) if isReservedHeader(k) && !isWhitelistedHeader(k) { continue } for _, v := range vv { v, err := decodeMetadataHeader(k, v) if err != nil { return nil, streamErrorf(codes.Internal, "malformed binary metadata: %v", err) } metakv = append(metakv, k, v) } } st.headerMD = metadata.Pairs(metakv...) return st, nil } // serverHandlerTransport is an implementation of ServerTransport // which replies to exactly one gRPC request (exactly one HTTP request), // using the net/http.Handler interface. This http.Handler is guaranteed // at this point to be speaking over HTTP/2, so it's able to speak valid // gRPC. type serverHandlerTransport struct { rw http.ResponseWriter req *http.Request timeoutSet bool timeout time.Duration didCommonHeaders bool headerMD metadata.MD closeOnce sync.Once closedCh chan struct{} // closed on Close // writes is a channel of code to run serialized in the // ServeHTTP (HandleStreams) goroutine. The channel is closed // when WriteStatus is called. writes chan func() // block concurrent WriteStatus calls // e.g. grpc/(*serverStream).SendMsg/RecvMsg writeStatusMu sync.Mutex // we just mirror the request content-type contentType string // we store both contentType and contentSubtype so we don't keep recreating them // TODO make sure this is consistent across handler_server and http2_server contentSubtype string stats stats.Handler } func (ht *serverHandlerTransport) Close() error { ht.closeOnce.Do(ht.closeCloseChanOnce) return nil } func (ht *serverHandlerTransport) closeCloseChanOnce() { close(ht.closedCh) } func (ht *serverHandlerTransport) RemoteAddr() net.Addr { return strAddr(ht.req.RemoteAddr) } // strAddr is a net.Addr backed by either a TCP "ip:port" string, or // the empty string if unknown. type strAddr string func (a strAddr) Network() string { if a != "" { // Per the documentation on net/http.Request.RemoteAddr, if this is // set, it's set to the IP:port of the peer (hence, TCP): // https://golang.org/pkg/net/http/#Request // // If we want to support Unix sockets later, we can // add our own grpc-specific convention within the // grpc codebase to set RemoteAddr to a different // format, or probably better: we can attach it to the // context and use that from serverHandlerTransport.RemoteAddr. return "tcp" } return "" } func (a strAddr) String() string { return string(a) } // do runs fn in the ServeHTTP goroutine. func (ht *serverHandlerTransport) do(fn func()) error { // Avoid a panic writing to closed channel. Imperfect but maybe good enough. select { case <-ht.closedCh: return ErrConnClosing default: select { case ht.writes <- fn: return nil case <-ht.closedCh: return ErrConnClosing } } } func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) error { ht.writeStatusMu.Lock() defer ht.writeStatusMu.Unlock() err := ht.do(func() { ht.writeCommonHeaders(s) // And flush, in case no header or body has been sent yet. // This forces a separation of headers and trailers if this is the // first call (for example, in end2end tests's TestNoService). ht.rw.(http.Flusher).Flush() h := ht.rw.Header() h.Set("Grpc-Status", fmt.Sprintf("%d", st.Code())) if m := st.Message(); m != "" { h.Set("Grpc-Message", encodeGrpcMessage(m)) } if p := st.Proto(); p != nil && len(p.Details) > 0 { stBytes, err := proto.Marshal(p) if err != nil { // TODO: return error instead, when callers are able to handle it. panic(err) } h.Set("Grpc-Status-Details-Bin", encodeBinHeader(stBytes)) } if md := s.Trailer(); len(md) > 0 { for k, vv := range md { // Clients don't tolerate reading restricted headers after some non restricted ones were sent. if isReservedHeader(k) { continue } for _, v := range vv { // http2 ResponseWriter mechanism to send undeclared Trailers after // the headers have possibly been written. h.Add(http2.TrailerPrefix+k, encodeMetadataHeader(k, v)) } } } }) if err == nil { // transport has not been closed if ht.stats != nil { ht.stats.HandleRPC(s.Context(), &stats.OutTrailer{}) } ht.Close() close(ht.writes) } return err } // writeCommonHeaders sets common headers on the first write // call (Write, WriteHeader, or WriteStatus). func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) { if ht.didCommonHeaders { return } ht.didCommonHeaders = true h := ht.rw.Header() h["Date"] = nil // suppress Date to make tests happy; TODO: restore h.Set("Content-Type", ht.contentType) // Predeclare trailers we'll set later in WriteStatus (after the body). // This is a SHOULD in the HTTP RFC, and the way you add (known) // Trailers per the net/http.ResponseWriter contract. // See https://golang.org/pkg/net/http/#ResponseWriter // and https://golang.org/pkg/net/http/#example_ResponseWriter_trailers h.Add("Trailer", "Grpc-Status") h.Add("Trailer", "Grpc-Message") h.Add("Trailer", "Grpc-Status-Details-Bin") if s.sendCompress != "" { h.Set("Grpc-Encoding", s.sendCompress) } } func (ht *serverHandlerTransport) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { return ht.do(func() { ht.writeCommonHeaders(s) ht.rw.Write(hdr) ht.rw.Write(data) if !opts.Delay { ht.rw.(http.Flusher).Flush() } }) } func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error { err := ht.do(func() { ht.writeCommonHeaders(s) h := ht.rw.Header() for k, vv := range md { // Clients don't tolerate reading restricted headers after some non restricted ones were sent. if isReservedHeader(k) { continue } for _, v := range vv { v = encodeMetadataHeader(k, v) h.Add(k, v) } } ht.rw.WriteHeader(200) ht.rw.(http.Flusher).Flush() }) if err == nil { if ht.stats != nil { ht.stats.HandleRPC(s.Context(), &stats.OutHeader{}) } } return err } func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) { // With this transport type there will be exactly 1 stream: this HTTP request. ctx := contextFromRequest(ht.req) var cancel context.CancelFunc if ht.timeoutSet { ctx, cancel = context.WithTimeout(ctx, ht.timeout) } else { ctx, cancel = context.WithCancel(ctx) } // requestOver is closed when either the request's context is done // or the status has been written via WriteStatus. requestOver := make(chan struct{}) // clientGone receives a single value if peer is gone, either // because the underlying connection is dead or because the // peer sends an http2 RST_STREAM. clientGone := ht.rw.(http.CloseNotifier).CloseNotify() go func() { select { case <-requestOver: return case <-ht.closedCh: case <-clientGone: } cancel() }() req := ht.req s := &Stream{ id: 0, // irrelevant requestRead: func(int) {}, cancel: cancel, buf: newRecvBuffer(), st: ht, method: req.URL.Path, recvCompress: req.Header.Get("grpc-encoding"), contentSubtype: ht.contentSubtype, } pr := &peer.Peer{ Addr: ht.RemoteAddr(), } if req.TLS != nil { pr.AuthInfo = credentials.TLSInfo{State: *req.TLS} } ctx = metadata.NewIncomingContext(ctx, ht.headerMD) s.ctx = peer.NewContext(ctx, pr) if ht.stats != nil { s.ctx = ht.stats.TagRPC(s.ctx, &stats.RPCTagInfo{FullMethodName: s.method}) inHeader := &stats.InHeader{ FullMethod: s.method, RemoteAddr: ht.RemoteAddr(), Compression: s.recvCompress, } ht.stats.HandleRPC(s.ctx, inHeader) } s.trReader = &transportReader{ reader: &recvBufferReader{ctx: s.ctx, ctxDone: s.ctx.Done(), recv: s.buf}, windowHandler: func(int) {}, } // readerDone is closed when the Body.Read-ing goroutine exits. readerDone := make(chan struct{}) go func() { defer close(readerDone) // TODO: minimize garbage, optimize recvBuffer code/ownership const readSize = 8196 for buf := make([]byte, readSize); ; { n, err := req.Body.Read(buf) if n > 0 { s.buf.put(recvMsg{data: buf[:n:n]}) buf = buf[n:] } if err != nil { s.buf.put(recvMsg{err: mapRecvMsgError(err)}) return } if len(buf) == 0 { buf = make([]byte, readSize) } } }() // startStream is provided by the *grpc.Server's serveStreams. // It starts a goroutine serving s and exits immediately. // The goroutine that is started is the one that then calls // into ht, calling WriteHeader, Write, WriteStatus, Close, etc. startStream(s) ht.runStream() close(requestOver) // Wait for reading goroutine to finish. req.Body.Close() <-readerDone } func (ht *serverHandlerTransport) runStream() { for { select { case fn, ok := <-ht.writes: if !ok { return } fn() case <-ht.closedCh: return } } } func (ht *serverHandlerTransport) IncrMsgSent() {} func (ht *serverHandlerTransport) IncrMsgRecv() {} func (ht *serverHandlerTransport) Drain() { panic("Drain() is not implemented") } // mapRecvMsgError returns the non-nil err into the appropriate // error value as expected by callers of *grpc.parser.recvMsg. // In particular, in can only be: // * io.EOF // * io.ErrUnexpectedEOF // * of type transport.ConnectionError // * of type transport.StreamError func mapRecvMsgError(err error) error { if err == io.EOF || err == io.ErrUnexpectedEOF { return err } if se, ok := err.(http2.StreamError); ok { if code, ok := http2ErrConvTab[se.Code]; ok { return StreamError{ Code: code, Desc: se.Error(), } } } return connectionErrorf(true, err, err.Error()) }
apache-2.0
slawosz/rubinius
spec/ruby/core/symbol/case_compare_spec.rb
287
require File.expand_path('../../../spec_helper', __FILE__) describe "Symbol#===" do it "returns true when the argument is a Symbol" do (Symbol === :ruby).should == true end it "returns false when the argument is a String" do (Symbol === 'ruby').should == false end end
bsd-3-clause
HugoMontes/si_maestras
assets/filemanager/scripts/zeroclipboard/src/js/core/private.js
49597
/** * The underlying implementation of `ZeroClipboard.config`. * @private */ var _config = function(options) { /*jshint maxdepth:6 */ if (typeof options === "object" && options !== null) { for (var prop in options) { if (_hasOwn.call(options, prop)) { // These configuration values CAN be modified while a SWF is actively embedded. if (/^(?:forceHandCursor|title|zIndex|bubbleEvents)$/.test(prop)) { _globalConfig[prop] = options[prop]; } // All other configuration values CANNOT be modified while a SWF is actively embedded. else if (_flashState.bridge == null) { if (prop === "containerId" || prop === "swfObjectId") { // Validate values against the HTML4 spec for `ID` and `Name` tokens if (_isValidHtml4Id(options[prop])) { _globalConfig[prop] = options[prop]; } else { throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID"); } } else { _globalConfig[prop] = options[prop]; } } } } } if (typeof options === "string" && options) { if (_hasOwn.call(_globalConfig, options)) { // TODO: MAYBE do a `_deepCopy` of this as well? It is convenient to NOT // do a `_deepCopy` if we want to allow consumers to, for example, be // able to update the `trustedDomains` array on their own terms rather // than having to send in a whole new array. return _globalConfig[options]; } // else `return undefined;` return; } return _deepCopy(_globalConfig); }; /** * The underlying implementation of `ZeroClipboard.state`. * @private */ var _state = function() { return { browser: _pick(_navigator, ["userAgent", "platform", "appName"]), flash: _omit(_flashState, ["bridge"]), zeroclipboard: { version: ZeroClipboard.version, config: ZeroClipboard.config() } }; }; /** * The underlying implementation of `ZeroClipboard.isFlashUnusable`. * @private */ var _isFlashUnusable = function() { return !!( _flashState.disabled || _flashState.outdated || _flashState.unavailable || _flashState.deactivated ); }; /** * The underlying implementation of `ZeroClipboard.on`. * @private */ var _on = function(eventType, listener) { var i, len, events, added = {}; if (typeof eventType === "string" && eventType) { events = eventType.toLowerCase().split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.on(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].replace(/^on/, ""); added[eventType] = true; if (!_handlers[eventType]) { _handlers[eventType] = []; } _handlers[eventType].push(listener); } // The following events must be memorized and fired immediately if relevant as they only occur // once per Flash object load. // If the SWF was already loaded, we're à gogo! if (added.ready && _flashState.ready) { ZeroClipboard.emit({ type: "ready" }); } if (added.error) { var errorTypes = ["disabled", "outdated", "unavailable", "deactivated", "overdue"]; for (i = 0, len = errorTypes.length; i < len; i++) { if (_flashState[errorTypes[i]] === true) { ZeroClipboard.emit({ type: "error", name: "flash-" + errorTypes[i] }); break; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.off`. * @private */ var _off = function(eventType, listener) { var i, len, foundIndex, events, perEventHandlers; if (arguments.length === 0) { // Remove ALL of the _handlers for ALL event types events = _keys(_handlers); } else if (typeof eventType === "string" && eventType) { events = eventType.split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.off(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].toLowerCase().replace(/^on/, ""); perEventHandlers = _handlers[eventType]; if (perEventHandlers && perEventHandlers.length) { if (listener) { foundIndex = perEventHandlers.indexOf(listener); while (foundIndex !== -1) { perEventHandlers.splice(foundIndex, 1); foundIndex = perEventHandlers.indexOf(listener, foundIndex); } } else { // If no `listener` was provided, remove ALL of the handlers for this event type perEventHandlers.length = 0; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.handlers`. * @private */ var _listeners = function(eventType) { var copy; if (typeof eventType === "string" && eventType) { copy = _deepCopy(_handlers[eventType]) || null; } else { copy = _deepCopy(_handlers); } return copy; }; /** * The underlying implementation of `ZeroClipboard.emit`. * @private */ var _emit = function(event) { var eventCopy, returnVal, tmp; // Create an event object for this event type event = _createEvent(event); if (!event) { return; } // Preprocess any special behaviors, reactions, or state changes after receiving this event if (_preprocessEvent(event)) { return; } // If this was a Flash "ready" event that was overdue, bail out and fire an "error" event instead if (event.type === "ready" && _flashState.overdue === true) { return ZeroClipboard.emit({ "type": "error", "name": "flash-overdue" }); } // Trigger any and all registered event handlers eventCopy = _extend({}, event); _dispatchCallbacks.call(this, eventCopy); // For the `copy` event, be sure to return the `_clipData` to Flash to be injected into the clipboard if (event.type === "copy") { tmp = _mapClipDataToFlash(_clipData); returnVal = tmp.data; _clipDataFormatMap = tmp.formatMap; } return returnVal; }; /** * The underlying implementation of `ZeroClipboard.create`. * @private */ var _create = function() { // Setup the Flash <-> JavaScript bridge if (typeof _flashState.ready !== "boolean") { _flashState.ready = false; } if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) { var maxWait = _globalConfig.flashLoadTimeout; if (typeof maxWait === "number" && maxWait >= 0) { _setTimeout(function() { // If it took longer than `_globalConfig.flashLoadTimeout` milliseconds to receive // a `ready` event, so consider Flash "deactivated". if (typeof _flashState.deactivated !== "boolean") { _flashState.deactivated = true; } if (_flashState.deactivated === true) { ZeroClipboard.emit({ "type": "error", "name": "flash-deactivated" }); } }, maxWait); } // If attempting a fresh SWF embedding, it is safe to ignore the `overdue` status _flashState.overdue = false; // Embed the SWF _embedSwf(); } }; /** * The underlying implementation of `ZeroClipboard.destroy`. * @private */ var _destroy = function() { // Clear any pending clipboard data ZeroClipboard.clearData(); // Deactivate during self-destruct, even if `_globalConfig.autoActivate` !== `true` ZeroClipboard.blur(); // Emit a special [synchronously handled] event so that Clients may listen // for it and destroy themselves ZeroClipboard.emit("destroy"); // Un-embed the SWF _unembedSwf(); // Remove all event handlers ZeroClipboard.off(); }; /** * The underlying implementation of `ZeroClipboard.setData`. * @private */ var _setData = function(format, data) { var dataObj; if (typeof format === "object" && format && typeof data === "undefined") { dataObj = format; // Clear out existing pending data if an object is provided ZeroClipboard.clearData(); } else if (typeof format === "string" && format) { dataObj = {}; dataObj[format] = data; } else { return; } // Copy over owned properties with non-empty string values for (var dataFormat in dataObj) { if ( typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat] ) { _clipData[dataFormat] = dataObj[dataFormat]; } } }; /** * The underlying implementation of `ZeroClipboard.clearData`. * @private */ var _clearData = function(format) { // If no format is passed, delete all of the pending data if (typeof format === "undefined") { _deleteOwnProperties(_clipData); _clipDataFormatMap = null; } // Otherwise, delete only the pending data of the specified format else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { delete _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.getData`. * @private */ var _getData = function(format) { // If no format is passed, get a copy of ALL of the pending data if (typeof format === "undefined") { return _deepCopy(_clipData); } // Otherwise, get only the pending data of the specified format else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { return _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.focus`/`ZeroClipboard.activate`. * @private */ var _focus = function(element) { if (!(element && element.nodeType === 1)) { return; } // "Ignore" the currently active element if (_currentElement) { _removeClass(_currentElement, _globalConfig.activeClass); if (_currentElement !== element) { _removeClass(_currentElement, _globalConfig.hoverClass); } } // Mark the element as currently activated _currentElement = element; _addClass(element, _globalConfig.hoverClass); // If the element has a title, mimic it var newTitle = element.getAttribute("title") || _globalConfig.title; if (typeof newTitle === "string" && newTitle) { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.setAttribute("title", newTitle); } } // If the element has a pointer style, set to hand cursor var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer"; // Update the hand cursor state without updating the `forceHandCursor` option _setHandCursor(useHandCursor); // Move the Flash object over the newly activated element _reposition(); }; /** * The underlying implementation of `ZeroClipboard.blur`/`ZeroClipboard.deactivate`. * @private */ var _blur = function() { // Hide the Flash object off-screen var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.removeAttribute("title"); htmlBridge.style.left = "0px"; htmlBridge.style.top = "-9999px"; htmlBridge.style.width = "1px"; htmlBridge.style.top = "1px"; } // "Ignore" the currently active element if (_currentElement) { _removeClass(_currentElement, _globalConfig.hoverClass); _removeClass(_currentElement, _globalConfig.activeClass); _currentElement = null; } }; /** * The underlying implementation of `ZeroClipboard.activeElement`. * @private */ var _activeElement = function() { return _currentElement || null; }; // // Helper functions // /** * Check if a value is a valid HTML4 `ID` or `Name` token. * @private */ var _isValidHtml4Id = function(id) { return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id); }; /** * Create or update an `event` object, based on the `eventType`. * @private */ var _createEvent = function(event) { /*jshint maxstatements:30 */ var eventType; if (typeof event === "string" && event) { eventType = event; event = {}; } else if (typeof event === "object" && event && typeof event.type === "string" && event.type) { eventType = event.type; } // Bail if we don't have an event type if (!eventType) { return; } // Sanitize the event type and set the `target` and `relatedTarget` properties if not already set if (!event.target && /^(copy|aftercopy|_click)$/.test(eventType.toLowerCase())) { event.target = _copyTarget; } _extend(event, { type: eventType.toLowerCase(), target: event.target || _currentElement || null, relatedTarget: event.relatedTarget || null, currentTarget: (_flashState && _flashState.bridge) || null, timeStamp: event.timeStamp || _now() || null }); var msg = _eventMessages[event.type]; if (event.type === "error" && event.name && msg) { msg = msg[event.name]; } if (msg) { event.message = msg; } if (event.type === "ready") { _extend(event, { target: null, version: _flashState.version }); } if (event.type === "error") { if (/^flash-(disabled|outdated|unavailable|deactivated|overdue)$/.test(event.name)) { _extend(event, { target: null, minimumVersion: _minimumFlashVersion }); } if (/^flash-(outdated|unavailable|deactivated|overdue)$/.test(event.name)) { _extend(event, { version: _flashState.version }); } } // Add all of the special properties and methods for a `copy` event if (event.type === "copy") { event.clipboardData = { setData: ZeroClipboard.setData, clearData: ZeroClipboard.clearData }; } if (event.type === "aftercopy") { event = _mapClipResultsFromFlash(event, _clipDataFormatMap); } if (event.target && !event.relatedTarget) { event.relatedTarget = _getRelatedTarget(event.target); } event = _addMouseData(event); return event; }; /** * Get a relatedTarget from the target's `data-clipboard-target` attribute * @private */ var _getRelatedTarget = function(targetEl) { var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target"); return relatedTargetId ? _document.getElementById(relatedTargetId) : null; }; /** * Add element and position data to `MouseEvent` instances * @private */ var _addMouseData = function(event) { if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) { // Element data var srcElement = event.target; var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined; var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined; // Calculate positional data var pos = _getDOMObjectPosition(srcElement); var screenLeft = _window.screenLeft || _window.screenX || 0; var screenTop = _window.screenTop || _window.screenY || 0; var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft; var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop; var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0); var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0); var clientX = pageX - scrollLeft; var clientY = pageY - scrollTop; var screenX = screenLeft + clientX; var screenY = screenTop + clientY; var moveX = typeof event.movementX === "number" ? event.movementX : 0; var moveY = typeof event.movementY === "number" ? event.movementY : 0; // Remove these transient properties, if present delete event._stageX; delete event._stageY; // Update the appropriate properties of `event`, mostly with position data. // Good notes: // http://www.jacklmoore.com/notes/mouse-position/ _extend(event, { srcElement: srcElement, fromElement: fromElement, toElement: toElement, screenX: screenX, // screenLeft + clientX screenY: screenY, // screenTop + clientY pageX: pageX, // scrollLeft + clientX pageY: pageY, // scrollTop + clientY clientX: clientX, // pageX - scrollLeft clientY: clientY, // pageY - scrollTop x: clientX, // clientX y: clientY, // clientY movementX: moveX, // movementX movementY: moveY, // movementY offsetX: 0, // Unworthy of calculation offsetY: 0, // Unworthy of calculation layerX: 0, // Unworthy of calculation layerY: 0 // Unworthy of calculation }); } return event; }; /** * Determine if an event's registered handlers should be execute synchronously or asynchronously. * * @returns {boolean} * @private */ var _shouldPerformAsync = function(event) { var eventType = (event && typeof event.type === "string" && event.type) || ""; // Determine if the event handlers for this event can be performed asynchronously. // - `beforecopy`: This event's callback cannot be performed asynchronously because the // subsequent `copy` event cannot. // - `copy`: This event's callback cannot be performed asynchronously as it would prevent the // user from being able to call `.setText` successfully before the pending clipboard // injection associated with this event fires. // - `destroy`: This event's callback cannot be performed asynchronously as it is necessary // to allow any downstream clients the chance to destroy themselves as well // as well before the final destruction of the SWF object and removal of all // registered event handlers. // - The handlers for all other event types should be performed asynchronously. return !/^(?:(?:before)?copy|destroy)$/.test(eventType); }; /** * Control if a callback should be executed asynchronously or not. * * @returns `undefined` * @private */ var _dispatchCallback = function(func, context, args, async) { if (async) { _setTimeout(function() { func.apply(context, args); }, 0); } else { func.apply(context, args); } }; /** * Handle the actual dispatching of events to client instances. * * @returns `undefined` * @private */ var _dispatchCallbacks = function(event) { if (!(typeof event === "object" && event && event.type)) { return; } var async = _shouldPerformAsync(event); // User defined handlers for events var wildcardTypeHandlers = _handlers["*"] || []; var specificTypeHandlers = _handlers[event.type] || []; // Execute wildcard handlers before type-specific handlers var handlers = wildcardTypeHandlers.concat(specificTypeHandlers); if (handlers && handlers.length) { var i, len, func, context, eventCopy, originalContext = this; for (i = 0, len = handlers.length; i < len; i++) { func = handlers[i]; context = originalContext; // If the user provided a string for their callback, grab that function if (typeof func === "string" && typeof _window[func] === "function") { func = _window[func]; } if (typeof func === "object" && func && typeof func.handleEvent === "function") { context = func; func = func.handleEvent; } if (typeof func === "function") { eventCopy = _extend({}, event); _dispatchCallback(func, context, [eventCopy], async); } } } return this; }; /** * Preprocess any special behaviors, reactions, or state changes after receiving this event. * Executes only once per event emitted, NOT once per client. * @private */ var _preprocessEvent = function(event) { var element = event.target || _currentElement || null; var sourceIsSwf = event._source === "swf"; delete event._source; var flashErrorNames = [ "flash-disabled", "flash-outdated", "flash-unavailable", "flash-deactivated", "flash-overdue" ]; switch (event.type) { case "error": if (flashErrorNames.indexOf(event.name) !== -1) { _extend(_flashState, { disabled: event.name === "flash-disabled", outdated: event.name === "flash-outdated", unavailable: event.name === "flash-unavailable", deactivated: event.name === "flash-deactivated", overdue: event.name === "flash-overdue", ready: false }); } break; case "ready": var wasDeactivated = _flashState.deactivated === true; _extend(_flashState, { disabled: false, outdated: false, unavailable: false, deactivated: false, overdue: wasDeactivated, ready: !wasDeactivated }); break; case "beforecopy": _copyTarget = element; break; case "copy": var textContent, htmlContent, targetEl = event.relatedTarget; if ( !(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText) ) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); if (htmlContent !== textContent) { event.clipboardData.setData("text/html", htmlContent); } } else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); } break; case "aftercopy": // If the copy has [or should have] occurred, clear out all of the data ZeroClipboard.clearData(); // Focus the context back on the trigger element (blur the Flash element) if (element && element !== _safeActiveElement() && element.focus) { element.focus(); } break; case "_mouseover": // Set this as the new currently active element ZeroClipboard.focus(element); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { if ( element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element) ) { _fireMouseEvent( _extend({}, event, { type: "mouseenter", bubbles: false, cancelable: false }) ); } _fireMouseEvent( _extend({}, event, { type: "mouseover" }) ); } break; case "_mouseout": // If the mouse is moving to any other element, deactivate and... ZeroClipboard.blur(); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { if ( element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element) ) { _fireMouseEvent( _extend({}, event, { type: "mouseleave", bubbles: false, cancelable: false }) ); } _fireMouseEvent( _extend({}, event, { type: "mouseout" }) ); } break; case "_mousedown": _addClass(element, _globalConfig.activeClass); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_mouseup": _removeClass(element, _globalConfig.activeClass); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_click": _copyTarget = null; if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_mousemove": if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; } // end `switch` // Return a flag to indicate that this event should stop being processed if (/^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) { return true; } }; /** * Dispatch a synthetic MouseEvent. * * @returns `undefined` * @private */ var _fireMouseEvent = function(event) { if (!(event && typeof event.type === "string" && event)) { return; } var e, target = event.target || null, doc = (target && target.ownerDocument) || _document, defaults = { view: doc.defaultView || _window, canBubble: true, cancelable: true, detail: event.type === "click" ? 1 : 0, button: typeof event.which === "number" ? (event.which - 1) : ( typeof event.button === "number" ? event.button : (doc.createEvent ? 0 : 1) ) }, // Update the Event data to its final state args = _extend(defaults, event); if (!target) { return; } // Create and fire the MouseEvent if (doc.createEvent && target.dispatchEvent) { args = [ args.type, args.canBubble, args.cancelable, args.view, args.detail, args.screenX, args.screenY, args.clientX, args.clientY, args.ctrlKey, args.altKey, args.shiftKey, args.metaKey, args.button, args.relatedTarget ]; e = doc.createEvent("MouseEvents"); if (e.initMouseEvent) { e.initMouseEvent.apply(e, args); e._source = "js"; target.dispatchEvent(e); } } }; /** * Create the HTML bridge element to embed the Flash object into. * @private */ var _createHtmlBridge = function() { var container = _document.createElement("div"); container.id = _globalConfig.containerId; container.className = _globalConfig.containerClass; container.style.position = "absolute"; container.style.left = "0px"; container.style.top = "-9999px"; container.style.width = "1px"; container.style.height = "1px"; container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex); return container; }; /** * Get the HTML element container that wraps the Flash bridge object/element. * @private */ var _getHtmlBridge = function(flashBridge) { var htmlBridge = flashBridge && flashBridge.parentNode; while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) { htmlBridge = htmlBridge.parentNode; } return htmlBridge || null; }; /** * Create the SWF object. * * @returns The SWF object reference. * @private */ var _embedSwf = function() { var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge); if (!flashBridge) { // Set `allowScriptAccess`/`allowNetworking` based on `trustedDomains` and `window.location.host` vs. `swfPath` var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig); var allowNetworking = allowScriptAccess === "never" ? "none" : "all"; // Prepare the FlashVars and cache-busting query param var flashvars = _vars(_globalConfig); var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig); // Create the outer container container = _createHtmlBridge(); // Create a to-be-replaced child node var divToBeReplaced = _document.createElement("div"); container.appendChild(divToBeReplaced); // Add this outer container (and its to-be-replaced child node) to the DOM in advance in order // to avoid Flash quirks in various browsers, e.g. https://github.com/zeroclipboard/zeroclipboard/issues/204 _document.body.appendChild(container); // Create the actual Flash object's shell var tmpDiv = _document.createElement("div"); // The object element plus its movie source URL both MUST be created together. // Other attributes and child nodes can techncially be added afterward. // Hybrid of Flash Satay markup is from Ambience: // - Flash Satay version: http://alistapart.com/article/flashsatay // - Ambience version: http://www.ambience.sk/flash-valid.htm var oldIE = _flashState.pluginType === "activex"; /*jshint quotmark:single */ tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (oldIE ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + '>' + (oldIE ? '<param name="movie" value="' + swfUrl + '"/>' : '') + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + '</object>'; /*jshint quotmark:double */ flashBridge = tmpDiv.firstChild; tmpDiv = null; // Store a reference to the `ZeroClipboard` object as a DOM property // on the ZeroClipboard-owned "object" element. This will help us // easily avoid issues with AMD/CommonJS loaders that don't have // a global `ZeroClipboard` reliably available. _unwrap(flashBridge).ZeroClipboard = ZeroClipboard; // NOTE: Using `replaceChild` is very important! // - https://github.com/swfobject/swfobject/blob/562fe358216edbb36445aa62f817c1a56252950c/swfobject/src/swfobject.js // - http://pipwerks.com/2011/05/30/using-the-object-element-to-dynamically-embed-flash-swfs-in-internet-explorer/ container.replaceChild(flashBridge, divToBeReplaced); } if (!flashBridge) { flashBridge = _document[_globalConfig.swfObjectId]; if (flashBridge && (len = flashBridge.length)) { flashBridge = flashBridge[len - 1]; } if (!flashBridge && container) { flashBridge = container.firstChild; } } _flashState.bridge = flashBridge || null; return flashBridge; }; /** * Destroy the SWF object. * @private */ var _unembedSwf = function() { // Remove the Flash bridge var flashBridge = _flashState.bridge; if (flashBridge) { var htmlBridge = _getHtmlBridge(flashBridge); if (htmlBridge) { // Some extra caution is necessary to prevent Flash from causing memory leaks in oldIE // NOTE: Removing the SWF in IE may not be completed synchronously if (_flashState.pluginType === "activex" && "readyState" in flashBridge) { flashBridge.style.display = "none"; (function removeSwfFromIE() { if (flashBridge.readyState === 4) { // This step prevents memory leaks in oldIE for (var prop in flashBridge) { if (typeof flashBridge[prop] === "function") { flashBridge[prop] = null; } } if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } else { _setTimeout(removeSwfFromIE, 10); } })(); } else { if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } } _flashState.ready = null; _flashState.bridge = null; // Reset the `deactivated` status in case the user wants to "try again", e.g. after receiving // an `overdueFlash` event _flashState.deactivated = null; } }; /** * Map the data format names of the "clipData" to Flash-friendly names. * * @returns A new transformed object. * @private */ var _mapClipDataToFlash = function(clipData) { var newClipData = {}, formatMap = {}; if (!(typeof clipData === "object" && clipData)) { return; } for (var dataFormat in clipData) { if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) { // Standardize the allowed clipboard segment names to reduce complexity on the Flash side switch (dataFormat.toLowerCase()) { case "text/plain": case "text": case "air:text": case "flash:text": newClipData.text = clipData[dataFormat]; formatMap.text = dataFormat; break; case "text/html": case "html": case "air:html": case "flash:html": newClipData.html = clipData[dataFormat]; formatMap.html = dataFormat; break; case "application/rtf": case "text/rtf": case "rtf": case "richtext": case "air:rtf": case "flash:rtf": newClipData.rtf = clipData[dataFormat]; formatMap.rtf = dataFormat; break; default: // Just ignore it: the Flash clipboard cannot handle any other formats break; } } } return { data: newClipData, formatMap: formatMap }; }; /** * Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping). * * @returns A new transformed object. * @private */ var _mapClipResultsFromFlash = function(clipResults, formatMap) { if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) { return clipResults; } var newResults = {}; for (var prop in clipResults) { if (_hasOwn.call(clipResults, prop)) { if (prop !== "success" && prop !== "data") { newResults[prop] = clipResults[prop]; continue; } newResults[prop] = {}; // Standardize the allowed clipboard segment names to reduce complexity on the Flash side var tmpHash = clipResults[prop]; for (var dataFormat in tmpHash) { if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) { newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat]; } } } } return newResults; }; /** * Will look at a path, and will create a "?noCache={time}" or "&noCache={time}" * query param string to return. Does NOT append that string to the original path. * This is useful because ExternalInterface often breaks when a Flash SWF is cached. * * @returns The `noCache` query param with necessary "?"/"&" prefix. * @private */ var _cacheBust = function(path, options) { var cacheBust = options == null || (options && options.cacheBust === true); if (cacheBust) { return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now(); } else { return ""; } }; /** * Creates a query string for the FlashVars param. * Does NOT include the cache-busting query param. * * @returns FlashVars query string * @private */ var _vars = function(options) { var i, len, domain, domains, str = "", trustedOriginsExpanded = []; if (options.trustedDomains) { if (typeof options.trustedDomains === "string") { domains = [options.trustedDomains]; } else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) { domains = options.trustedDomains; } } if (domains && domains.length) { for (i = 0, len = domains.length; i < len; i++) { if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") { domain = _extractDomain(domains[i]); if (!domain) { continue; } // If we encounter a wildcard, ignore everything else as they are irrelevant if (domain === "*") { trustedOriginsExpanded.length = 0; trustedOriginsExpanded.push(domain); break; } // Add the domain, relative protocol + domain, and absolute protocol + domain ("origin") // because Flash Player seems to handle these inconsistently (perhaps in different versions) trustedOriginsExpanded.push.apply( trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ] ); } } } if (trustedOriginsExpanded.length) { str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(",")); } if (options.forceEnhancedClipboard === true) { str += (str ? "&" : "") + "forceEnhancedClipboard=true"; } if (typeof options.swfObjectId === "string" && options.swfObjectId) { str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId); } return str; }; /** * Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or * URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/"). * * @returns the domain * @private */ var _extractDomain = function(originOrUrl) { if (originOrUrl == null || originOrUrl === "") { return null; } // Trim originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, ""); if (originOrUrl === "") { return null; } // Strip the protocol, if any was provided var protocolIndex = originOrUrl.indexOf("//"); originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2); // Strip the path, if any was provided var pathIndex = originOrUrl.indexOf("/"); originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex); if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") { return null; } return originOrUrl || null; }; /** * Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`. * * @returns The appropriate script access level. * @private */ var _determineScriptAccess = (function() { var _extractAllDomains = function(origins) { var i, len, tmp, resultsArray = []; if (typeof origins === "string") { origins = [origins]; } if (!(typeof origins === "object" && origins && typeof origins.length === "number")) { return resultsArray; } for (i = 0, len = origins.length; i < len; i++) { if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) { if (tmp === "*") { resultsArray.length = 0; resultsArray.push("*"); break; } if (resultsArray.indexOf(tmp) === -1) { resultsArray.push(tmp); } } } return resultsArray; }; return function(currentDomain, configOptions) { // Get SWF domain var swfDomain = _extractDomain(configOptions.swfPath); if (swfDomain === null) { swfDomain = currentDomain; } // Get all trusted domains var trustedDomains = _extractAllDomains(configOptions.trustedDomains); var len = trustedDomains.length; if (len > 0) { if (len === 1 && trustedDomains[0] === "*") { return "always"; } if (trustedDomains.indexOf(currentDomain) !== -1) { if (len === 1 && currentDomain === swfDomain) { return "sameDomain"; } return "always"; } } return "never"; }; })(); /** * Get the currently active/focused DOM element. * * @returns the currently active/focused element, or `null` * @private */ var _safeActiveElement = function() { try { return _document.activeElement; } catch (err) { return null; } }; /** * Add a class to an element, if it doesn't already have it. * * @returns The element, with its new class added. * @private */ var _addClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } // If the element has `classList` if (element.classList) { if (!element.classList.contains(value)) { element.classList.add(value); } return element; } if (value && typeof value === "string") { var classNames = (value || "").split(/\s+/); if (element.nodeType === 1) { if (!element.className) { element.className = value; } else { var className = " " + element.className + " ", setClass = element.className; for (var c = 0, cl = classNames.length; c < cl; c++) { if (className.indexOf(" " + classNames[c] + " ") < 0) { setClass += " " + classNames[c]; } } // jank trim element.className = setClass.replace(/^\s+|\s+$/g, ""); } } } return element; }; /** * Remove a class from an element, if it has it. * * @returns The element, with its class removed. * @private */ var _removeClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } // If the element has `classList` if (element.classList) { if (element.classList.contains(value)) { element.classList.remove(value); } return element; } if (typeof value === "string" && value) { var classNames = value.split(/\s+/); if (element.nodeType === 1 && element.className) { var className = (" " + element.className + " ").replace(/[\n\t]/g, " "); for (var c = 0, cl = classNames.length; c < cl; c++) { className = className.replace(" " + classNames[c] + " ", " "); } // jank trim element.className = className.replace(/^\s+|\s+$/g, ""); } } return element; }; /** * Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`, * then we assume that it should be a hand ("pointer") cursor if the element * is an anchor element ("a" tag). * * @returns The computed style property. * @private */ var _getStyle = function(el, prop) { var value = _window.getComputedStyle(el, null).getPropertyValue(prop); if (prop === "cursor") { if (!value || value === "auto") { if (el.nodeName === "A") { return "pointer"; } } } return value; }; /** * Get the zoom factor of the browser. Always returns `1.0`, except at * non-default zoom levels in IE<8 and some older versions of WebKit. * * @returns Floating unit percentage of the zoom factor (e.g. 150% = `1.5`). * @private */ var _getZoomFactor = function() { var rect, physicalWidth, logicalWidth, zoomFactor = 1; if (typeof _document.body.getBoundingClientRect === "function") { // rect is only in physical pixels in IE<8 rect = _document.body.getBoundingClientRect(); physicalWidth = rect.right - rect.left; logicalWidth = _document.body.offsetWidth; zoomFactor = _round((physicalWidth / logicalWidth) * 100) / 100; } return zoomFactor; }; /** * Get the DOM positioning info of an element. * * @returns Object containing the element's position, width, and height. * @private */ var _getDOMObjectPosition = function(obj) { // get absolute coordinates for dom element var info = { left: 0, top: 0, width: 0, height: 0 }; // Use getBoundingClientRect where available (almost everywhere). // See: http://www.quirksmode.org/dom/w3c_cssom.html if (obj.getBoundingClientRect) { // compute left / top offset (works for `position:fixed`, too!) var rect = obj.getBoundingClientRect(); var pageXOffset, pageYOffset, zoomFactor; // IE<9 doesn't support `pageXOffset`/`pageXOffset` if ("pageXOffset" in _window && "pageYOffset" in _window) { pageXOffset = _window.pageXOffset; pageYOffset = _window.pageYOffset; } else { zoomFactor = _getZoomFactor(); pageXOffset = _round(_document.documentElement.scrollLeft / zoomFactor); pageYOffset = _round(_document.documentElement.scrollTop / zoomFactor); } // `clientLeft`/`clientTop` are to fix IE's 2px offset in standards mode var leftBorderWidth = _document.documentElement.clientLeft || 0; var topBorderWidth = _document.documentElement.clientTop || 0; info.left = rect.left + pageXOffset - leftBorderWidth; info.top = rect.top + pageYOffset - topBorderWidth; info.width = "width" in rect ? rect.width : rect.right - rect.left; info.height = "height" in rect ? rect.height : rect.bottom - rect.top; } return info; }; /** * Reposition the Flash object to cover the currently activated element. * * @returns `undefined` * @private */ var _reposition = function() { var htmlBridge; // If there is no `_currentElement`, skip it if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) { var pos = _getDOMObjectPosition(_currentElement); _extend(htmlBridge.style, { width: pos.width + "px", height: pos.height + "px", top: pos.top + "px", left: pos.left + "px", zIndex: "" + _getSafeZIndex(_globalConfig.zIndex) }); } }; /** * Sends a signal to the Flash object to display the hand cursor if `true`. * * @returns `undefined` * @private */ var _setHandCursor = function(enabled) { if (_flashState.ready === true) { if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") { _flashState.bridge.setHandCursor(enabled); } else { _flashState.ready = false; } } }; /** * Get a safe value for `zIndex` * * @returns an integer, or "auto" * @private */ var _getSafeZIndex = function(val) { if (/^(?:auto|inherit)$/.test(val)) { return val; } var zIndex; if (typeof val === "number" && !_isNaN(val)) { zIndex = val; } else if (typeof val === "string") { zIndex = _getSafeZIndex(_parseInt(val, 10)); } return typeof zIndex === "number" ? zIndex : "auto"; }; /** * Detect the Flash Player status, version, and plugin type. * * @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code} * @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript} * * @returns `undefined` * @private */ var _detectFlashSupport = function(ActiveXObject) { var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = ""; /** * Derived from Apple's suggested sniffer. * @param {String} desc e.g. "Shockwave Flash 7.0 r61" * @returns {String} "7.0.61" * @private */ function parseFlashVersion(desc) { var matches = desc.match(/[\d]+/g); matches.length = 3; // To standardize IE vs FF return matches.join("."); } function isPepperFlash(flashPlayerFileName) { return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && ( /^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin" ); } function inspectPlugin(plugin) { if (plugin) { hasFlash = true; if (plugin.version) { flashVersion = parseFlashVersion(plugin.version); } if (!flashVersion && plugin.description) { flashVersion = parseFlashVersion(plugin.description); } if (plugin.filename) { isPPAPI = isPepperFlash(plugin.filename); } } } if (_navigator.plugins && _navigator.plugins.length) { plugin = _navigator.plugins["Shockwave Flash"]; inspectPlugin(plugin); if (_navigator.plugins["Shockwave Flash 2.0"]) { hasFlash = true; flashVersion = "2.0.0.11"; } } else if (_navigator.mimeTypes && _navigator.mimeTypes.length) { mimeType = _navigator.mimeTypes["application/x-shockwave-flash"]; plugin = mimeType && mimeType.enabledPlugin; inspectPlugin(plugin); } else if (typeof ActiveXObject !== "undefined") { // // Using IE < 11 // isActiveX = true; try { // Try 7 first, since we know we can use GetVariable with it ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e1) { // Try 6 next, some versions are known to crash with GetVariable calls try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); hasFlash = true; flashVersion = "6.0.21"; // First public version of Flash 6 } catch (e2) { try { // Try the default ActiveX ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e3) { // No flash isActiveX = false; } } } } _flashState.disabled = hasFlash !== true; _flashState.outdated = flashVersion && (_parseFloat(flashVersion) < _parseFloat(_minimumFlashVersion)); _flashState.version = flashVersion || "0.0.0"; _flashState.pluginType = isPPAPI ? "pepper" : (isActiveX ? "activex" : (hasFlash ? "netscape" : "unknown")); }; /** * Invoke the Flash detection algorithms immediately upon inclusion so we're not waiting later. */ _detectFlashSupport(_ActiveXObject);
mit
FKS-Tecnologia/agendeAIRestfull
vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Debug/TraceableEventDispatcher.php
3537
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\Debug; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher as BaseTraceableEventDispatcher; use Symfony\Component\HttpKernel\Profiler\Profiler; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\EventDispatcher\Event; /** * Collects some data about event listeners. * * This event dispatcher delegates the dispatching to another one. * * @author Fabien Potencier <fabien@symfony.com> */ class TraceableEventDispatcher extends BaseTraceableEventDispatcher { /** * Sets the profiler. * * The traceable event dispatcher does not use the profiler anymore. * The job is now done directly by the Profiler listener and the * data collectors themselves. * * @param Profiler|null $profiler A Profiler instance * * @deprecated Deprecated since version 2.4, to be removed in 3.0. */ public function setProfiler(Profiler $profiler = null) { } /** * {@inheritdoc} */ protected function preDispatch($eventName, Event $event) { switch ($eventName) { case KernelEvents::REQUEST: $this->stopwatch->openSection(); break; case KernelEvents::VIEW: case KernelEvents::RESPONSE: // stop only if a controller has been executed if ($this->stopwatch->isStarted('controller')) { $this->stopwatch->stop('controller'); } break; case KernelEvents::TERMINATE: $token = $event->getResponse()->headers->get('X-Debug-Token'); // There is a very special case when using built-in AppCache class as kernel wrapper, in the case // of an ESI request leading to a `stale` response [B] inside a `fresh` cached response [A]. // In this case, `$token` contains the [B] debug token, but the open `stopwatch` section ID // is equal to the [A] debug token. Trying to reopen section with the [B] token throws an exception // which must be caught. try { $this->stopwatch->openSection($token); } catch (\LogicException $e) { } break; } } /** * {@inheritdoc} */ protected function postDispatch($eventName, Event $event) { switch ($eventName) { case KernelEvents::CONTROLLER: $this->stopwatch->start('controller', 'section'); break; case KernelEvents::RESPONSE: $token = $event->getResponse()->headers->get('X-Debug-Token'); $this->stopwatch->stopSection($token); break; case KernelEvents::TERMINATE: // In the special case described in the `preDispatch` method above, the `$token` section // does not exist, then closing it throws an exception which must be caught. $token = $event->getResponse()->headers->get('X-Debug-Token'); try { $this->stopwatch->stopSection($token); } catch (\LogicException $e) { } break; } } }
mit
siscia/jsdelivr
files/canjs/1.1.4/can.observe.attributes.js
3777
/*! * CanJS - 1.1.4 (2013-02-05) * http://canjs.us/ * Copyright (c) 2013 Bitovi * Licensed MIT */ (function (can, window, undefined) { // ## can/observe/attributes/attributes.js can.each([can.Observe, can.Model], function (clss) { // in some cases model might not be defined quite yet. if (clss === undefined) { return; } can.extend(clss, { attributes: {}, convert: { "date": function (str) { var type = typeof str; if (type === "string") { return isNaN(Date.parse(str)) ? null : Date.parse(str) } else if (type === 'number') { return new Date(str) } else { return str } }, "number": function (val) { return parseFloat(val); }, "boolean": function (val) { if (val === 'false' || val === '0' || !val) { return false; } return true; }, "default": function (val, oldVal, error, type) { var construct = can.getObject(type), context = window, realType; // if type has a . we need to look it up if (type.indexOf(".") >= 0) { // get everything before the last . realType = type.substring(0, type.lastIndexOf(".")); // get the object before the last . context = can.getObject(realType); } return typeof construct == "function" ? construct.call(context, val, oldVal) : val; } }, serialize: { "default": function (val, type) { return isObject(val) && val.serialize ? val.serialize() : val; }, "date": function (val) { return val && val.getTime() } } }); // overwrite setup to do this stuff var oldSetup = clss.setup; clss.setup = function (superClass, stat, proto) { var self = this; oldSetup.call(self, superClass, stat, proto); can.each(["attributes"], function (name) { if (!self[name] || superClass[name] === self[name]) { self[name] = {}; } }); can.each(["convert", "serialize"], function (name) { if (superClass[name] != self[name]) { self[name] = can.extend({}, superClass[name], self[name]); } }); }; }); var oldSetup = can.Observe.prototype.setup; can.Observe.prototype.setup = function (obj) { var diff = {}; oldSetup.call(this, obj); can.each(this.constructor.defaults, function (value, key) { if (!this.hasOwnProperty(key)) { diff[key] = value; } }, this); this._init = 1; this.attr(diff); delete this._init; }; can.Observe.prototype.__convert = function (prop, value) { // check if there is a var Class = this.constructor, oldVal = this.attr(prop), type, converter; if (Class.attributes) { // the type of the attribute type = Class.attributes[prop]; converter = Class.convert[type] || Class.convert['default']; } return value === null || !type ? // just use the value value : // otherwise, pass to the converter converter.call(Class, value, oldVal, function () {}, type); }; can.Observe.prototype.serialize = function (attrName) { var where = {}, Class = this.constructor, attrs = {}; if (attrName != undefined) { attrs[attrName] = this[attrName]; } else { attrs = this.__get(); } can.each(attrs, function (val, name) { var type, converter; type = Class.attributes ? Class.attributes[name] : 0; converter = Class.serialize ? Class.serialize[type] : 0; // if the value is an object, and has a attrs or serialize function where[name] = val && typeof val.serialize == 'function' ? // call attrs or serialize to get the original data back val.serialize() : // otherwise if we have a converter converter ? // use the converter converter(val, type) : // or return the val val }); return attrName != undefined ? where[attrName] : where; }; })(can, this);
mit
Third9/jsdelivr
files/ckeditor/4.3.0/plugins/undo/lang/bg.js
280
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'undo', 'bg', { redo: 'Връщане на предишен статус', undo: 'Възтанови' });
mit
tim-mc/quill
node_modules/end-of-stream/test.js
1553
var assert = require('assert'); var eos = require('./index'); var expected = 8; var fs = require('fs'); var cp = require('child_process'); var net = require('net'); var ws = fs.createWriteStream('/dev/null'); eos(ws, function(err) { expected--; assert(!!err); if (!expected) process.exit(0); }); ws.close(); var rs = fs.createReadStream('/dev/random'); eos(rs, function(err) { expected--; assert(!!err); if (!expected) process.exit(0); }); rs.close(); var rs = fs.createReadStream(__filename); eos(rs, function(err) { expected--; assert(!err); if (!expected) process.exit(0); }); rs.pipe(fs.createWriteStream('/dev/null')); var rs = fs.createReadStream(__filename); eos(rs, function(err) { throw new Error('no go') })(); rs.pipe(fs.createWriteStream('/dev/null')); var exec = cp.exec('echo hello world'); eos(exec, function(err) { expected--; assert(!err); if (!expected) process.exit(0); }); var spawn = cp.spawn('echo', ['hello world']); eos(spawn, function(err) { expected--; assert(!err); if (!expected) process.exit(0); }); var socket = net.connect(50000); eos(socket, function(err) { expected--; assert(!!err); if (!expected) process.exit(0); }); var server = net.createServer(function(socket) { eos(socket, function() { expected--; if (!expected) process.exit(0); }); socket.destroy(); }).listen(30000, function() { var socket = net.connect(30000); eos(socket, function() { expected--; if (!expected) process.exit(0); }); }); setTimeout(function() { assert(expected === 0); process.exit(0); }, 1000);
bsd-3-clause
tmckayus/oshinko-cli
vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.deepcopy.go
3542
// +build !ignore_autogenerated /* Copyright 2017 The Kubernetes 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. */ // This file was autogenerated by deepcopy-gen. Do not edit it manually! package internalversion import ( conversion "k8s.io/apimachinery/pkg/conversion" runtime "k8s.io/apimachinery/pkg/runtime" reflect "reflect" ) // GetGeneratedDeepCopyFuncs returns the generated funcs, since we aren't registering them. // // Deprecated: deepcopy registration will go away when static deepcopy is fully implemented. func GetGeneratedDeepCopyFuncs() []conversion.GeneratedDeepCopyFunc { return []conversion.GeneratedDeepCopyFunc{ {Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error { in.(*List).DeepCopyInto(out.(*List)) return nil }, InType: reflect.TypeOf(&List{})}, {Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error { in.(*ListOptions).DeepCopyInto(out.(*ListOptions)) return nil }, InType: reflect.TypeOf(&ListOptions{})}, } } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *List) DeepCopyInto(out *List) { *out = *in out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]runtime.Object, len(*in)) for i := range *in { if (*in)[i] == nil { (*out)[i] = nil } else { (*out)[i] = (*in)[i].DeepCopyObject() } } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new List. func (in *List) DeepCopy() *List { if in == nil { return nil } out := new(List) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *List) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } else { return nil } } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ListOptions) DeepCopyInto(out *ListOptions) { *out = *in out.TypeMeta = in.TypeMeta if in.LabelSelector == nil { out.LabelSelector = nil } else { out.LabelSelector = in.LabelSelector.DeepCopySelector() } if in.FieldSelector == nil { out.FieldSelector = nil } else { out.FieldSelector = in.FieldSelector.DeepCopySelector() } if in.TimeoutSeconds != nil { in, out := &in.TimeoutSeconds, &out.TimeoutSeconds if *in == nil { *out = nil } else { *out = new(int64) **out = **in } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ListOptions. func (in *ListOptions) DeepCopy() *ListOptions { if in == nil { return nil } out := new(ListOptions) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *ListOptions) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } else { return nil } }
apache-2.0
gitromand/phantomjs
src/qt/qtbase/src/gui/doc/snippets/plaintextlayout/window.cpp
4257
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Digia Plc and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include <math.h> #include "window.h" Window::Window(QWidget *parent) : QWidget(parent) { text = QString("Support for text rendering and layout in Qt 4 has been " "redesigned around a system that allows textual content to " "be represented in a more flexible way than was possible " "with Qt 3. Qt 4 also provides a more convenient " "programming interface for editing documents. These " "improvements are made available through a reimplementation " "of the existing text rendering engine, and the " "introduction of several new classes. " "See the relevant module overview for a detailed discussion " "of this framework. The following sections provide a brief " "overview of the main concepts behind Scribe."); setWindowTitle(tr("Plain Text Layout")); } void Window::paintEvent(QPaintEvent *event) { //! [0] QTextLayout textLayout(text, font); qreal margin = 10; qreal radius = qMin(width()/2.0, height()/2.0) - margin; QFontMetrics fm(font); qreal lineHeight = fm.height(); qreal y = 0; textLayout.beginLayout(); while (1) { // create a new line QTextLine line = textLayout.createLine(); if (!line.isValid()) break; qreal x1 = qMax(0.0, pow(pow(radius,2)-pow(radius-y,2), 0.5)); qreal x2 = qMax(0.0, pow(pow(radius,2)-pow(radius-(y+lineHeight),2), 0.5)); qreal x = qMax(x1, x2) + margin; qreal lineWidth = (width() - margin) - x; line.setLineWidth(lineWidth); line.setPosition(QPointF(x, margin+y)); y += line.height(); } textLayout.endLayout(); QPainter painter; painter.begin(this); painter.setRenderHint(QPainter::Antialiasing); painter.fillRect(rect(), Qt::white); painter.setBrush(QBrush(Qt::black)); painter.setPen(QPen(Qt::black)); textLayout.draw(&painter, QPoint(0,0)); painter.setBrush(QBrush(QColor("#a6ce39"))); painter.setPen(QPen(Qt::black)); painter.drawEllipse(QRectF(-radius, margin, 2*radius, 2*radius)); painter.end(); //! [0] }
bsd-3-clause
hqstevenson/camel
components/camel-jclouds/src/test/java/org/apache/camel/component/jclouds/JcloudsSpringComputeTest.java
14088
/** * 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.camel.component.jclouds; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class JcloudsSpringComputeTest extends CamelSpringTestSupport { @EndpointInject(uri = "mock:result") protected MockEndpoint result; @EndpointInject(uri = "mock:resultlist") protected MockEndpoint resultlist; @After public void tearDown() throws Exception { template.sendBodyAndHeaders("direct:start", null, destroyHeaders(null, null)); } @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("classpath:compute-test.xml"); } @Test public void testListImages() throws InterruptedException { result.expectedMessageCount(1); template.sendBodyAndHeader("direct:start", null, JcloudsConstants.OPERATION, JcloudsConstants.LIST_IMAGES); result.assertIsSatisfied(); List<Exchange> exchanges = result.getExchanges(); if (exchanges != null && !exchanges.isEmpty()) { for (Exchange exchange : exchanges) { Set<?> images = exchange.getIn().getBody(Set.class); assertTrue(images.size() > 0); for (Object obj : images) { assertTrue(obj instanceof Image); } } } } @Test public void testListHardware() throws InterruptedException { result.expectedMessageCount(1); template.sendBodyAndHeader("direct:start", null, JcloudsConstants.OPERATION, JcloudsConstants.LIST_HARDWARE); result.assertIsSatisfied(); List<Exchange> exchanges = result.getExchanges(); if (exchanges != null && !exchanges.isEmpty()) { for (Exchange exchange : exchanges) { Set<?> hardwares = exchange.getIn().getBody(Set.class); assertTrue(hardwares.size() > 0); for (Object obj : hardwares) { assertTrue(obj instanceof Hardware); } } } } @Test public void testListNodes() throws InterruptedException { result.expectedMessageCount(1); template.sendBodyAndHeader("direct:start", null, JcloudsConstants.OPERATION, JcloudsConstants.LIST_NODES); result.assertIsSatisfied(); List<Exchange> exchanges = result.getExchanges(); if (exchanges != null && !exchanges.isEmpty()) { for (Exchange exchange : exchanges) { Set<?> nodeMetadatas = exchange.getIn().getBody(Set.class); assertEquals("Nodes should be 0", 0, nodeMetadatas.size()); } } } @Test public void testCreateAndListNodes() throws InterruptedException { result.expectedMessageCount(2); template.sendBodyAndHeaders("direct:start", null, createHeaders("1", "default")); template.sendBodyAndHeader("direct:start", null, JcloudsConstants.OPERATION, JcloudsConstants.LIST_NODES); result.assertIsSatisfied(); List<Exchange> exchanges = result.getExchanges(); if (exchanges != null && !exchanges.isEmpty()) { for (Exchange exchange : exchanges) { Set<?> nodeMetadatas = exchange.getIn().getBody(Set.class); assertEquals("Nodes should be 1", 1, nodeMetadatas.size()); } } } @Test public void testCreateAndListWithPredicates() throws InterruptedException { result.expectedMessageCount(6); //Create a node for the default group template.sendBodyAndHeaders("direct:start", null, createHeaders("1", "default")); //Create a node for the group 'other' template.sendBodyAndHeaders("direct:start", null, createHeaders("1", "other")); template.sendBodyAndHeaders("direct:start", null, createHeaders("2", "other")); template.sendBodyAndHeaders("direct:start", null, listNodeHeaders(null, "other", null)); template.sendBodyAndHeaders("direct:start", null, listNodeHeaders("3", "other", null)); template.sendBodyAndHeaders("direct:start", null, listNodeHeaders("3", "other", "RUNNING")); result.assertIsSatisfied(); } @Test public void testCreateAndDestroyNode() throws InterruptedException { result.expectedMessageCount(1); template.sendBodyAndHeaders("direct:start", null, createHeaders("1", "default")); result.assertIsSatisfied(); List<Exchange> exchanges = result.getExchanges(); if (exchanges != null && !exchanges.isEmpty()) { for (Exchange exchange : exchanges) { Set<?> nodeMetadatas = exchange.getIn().getBody(Set.class); assertEquals("There should be no node running", 1, nodeMetadatas.size()); for (Object obj : nodeMetadatas) { NodeMetadata nodeMetadata = (NodeMetadata) obj; template.sendBodyAndHeaders("direct:start", null, destroyHeaders(nodeMetadata.getId(), null)); } } } } @Test public void testCreateAndRebootNode() throws InterruptedException { result.expectedMessageCount(1); template.sendBodyAndHeaders("direct:start", null, createHeaders("1", "default")); result.assertIsSatisfied(); List<Exchange> exchanges = result.getExchanges(); if (exchanges != null && !exchanges.isEmpty()) { for (Exchange exchange : exchanges) { Set<?> nodeMetadatas = exchange.getIn().getBody(Set.class); assertEquals("There should be one node running", 1, nodeMetadatas.size()); for (Object obj : nodeMetadatas) { NodeMetadata nodeMetadata = (NodeMetadata) obj; template.sendBodyAndHeaders("direct:start", null, rebootHeaders(nodeMetadata.getId(), null)); } } } } @Test public void testCreateAndSuspendNode() throws InterruptedException { result.expectedMessageCount(1); template.sendBodyAndHeaders("direct:start", null, createHeaders("1", "default")); result.assertIsSatisfied(); List<Exchange> exchanges = result.getExchanges(); if (exchanges != null && !exchanges.isEmpty()) { for (Exchange exchange : exchanges) { Set<?> nodeMetadatas = exchange.getIn().getBody(Set.class); assertEquals("There should be one node running", 1, nodeMetadatas.size()); for (Object obj : nodeMetadatas) { NodeMetadata nodeMetadata = (NodeMetadata) obj; template.sendBodyAndHeaders("direct:start", null, suspendHeaders(nodeMetadata.getId(), null)); } } } } @Test public void testCreateSuspendAndResumeNode() throws InterruptedException { result.expectedMessageCount(1); template.sendBodyAndHeaders("direct:start", null, createHeaders("1", "default")); result.assertIsSatisfied(); List<Exchange> exchanges = result.getExchanges(); if (exchanges != null && !exchanges.isEmpty()) { for (Exchange exchange : exchanges) { Set<?> nodeMetadatas = exchange.getIn().getBody(Set.class); assertEquals("There should be one node running", 1, nodeMetadatas.size()); for (Object obj : nodeMetadatas) { NodeMetadata nodeMetadata = (NodeMetadata) obj; template.sendBodyAndHeaders("direct:start", null, resumeHeaders(nodeMetadata.getId(), null)); } } } } @SuppressWarnings("unchecked") @Ignore("For now not possible to combine stub provider with ssh module, required for runScript") @Test public void testRunScript() throws InterruptedException { Map<String, Object> runScriptHeaders = new HashMap<String, Object>(); runScriptHeaders.put(JcloudsConstants.OPERATION, JcloudsConstants.RUN_SCRIPT); Set<? extends NodeMetadata> nodeMetadatas = (Set<? extends NodeMetadata>) template.requestBodyAndHeaders("direct:in-out", null, createHeaders("1", "default")); assertEquals("There should be a node running", 1, nodeMetadatas.size()); for (NodeMetadata nodeMetadata : nodeMetadatas) { runScriptHeaders.put(JcloudsConstants.NODE_ID, nodeMetadata.getId()); template.requestBodyAndHeaders("direct:in-out", null, runScriptHeaders); template.sendBodyAndHeaders("direct:in-out", null, destroyHeaders(nodeMetadata.getId(), null)); } } /** * Returns a {@Map} with the create headers. * * @param imageId The imageId to use for creating the node. * @param group The group to be assigned to the node. */ protected Map<String, Object> createHeaders(String imageId, String group) { Map<String, Object> createHeaders = new HashMap<String, Object>(); createHeaders.put(JcloudsConstants.OPERATION, JcloudsConstants.CREATE_NODE); createHeaders.put(JcloudsConstants.IMAGE_ID, imageId); createHeaders.put(JcloudsConstants.GROUP, group); return createHeaders; } /** * Returns a {@Map} with the destroy headers. * * @param nodeId The id of the node to destroy. * @param group The group of the node to destroy. */ protected Map<String, Object> destroyHeaders(String nodeId, String group) { Map<String, Object> destroyHeaders = new HashMap<String, Object>(); destroyHeaders.put(JcloudsConstants.OPERATION, JcloudsConstants.DESTROY_NODE); if (nodeId != null) { destroyHeaders.put(JcloudsConstants.NODE_ID, nodeId); } if (group != null) { destroyHeaders.put(JcloudsConstants.GROUP, group); } return destroyHeaders; } /** * Returns a {@Map} with the destroy headers. * * @param nodeId The id of the node to destroy. * @param group The group of the node to destroy. */ protected Map<String, Object> listNodeHeaders(String nodeId, String group, Object state) { Map<String, Object> listHeaders = new HashMap<String, Object>(); listHeaders.put(JcloudsConstants.OPERATION, JcloudsConstants.LIST_NODES); if (nodeId != null) { listHeaders.put(JcloudsConstants.NODE_ID, nodeId); } if (group != null) { listHeaders.put(JcloudsConstants.GROUP, group); } if (state != null) { listHeaders.put(JcloudsConstants.NODE_STATE, state); } return listHeaders; } /** * Returns a {@Map} with the reboot headers. * * @param nodeId The id of the node to reboot. * @param group The group of the node to reboot. */ protected Map<String, Object> rebootHeaders(String nodeId, String group) { Map<String, Object> rebootHeaders = new HashMap<String, Object>(); rebootHeaders.put(JcloudsConstants.OPERATION, JcloudsConstants.REBOOT_NODE); if (nodeId != null) { rebootHeaders.put(JcloudsConstants.NODE_ID, nodeId); } if (group != null) { rebootHeaders.put(JcloudsConstants.GROUP, group); } return rebootHeaders; } /** * Returns a {@Map} with the suspend headers. * * @param nodeId The id of the node to suspend. * @param group The group of the node to suspend. */ protected Map<String, Object> suspendHeaders(String nodeId, String group) { Map<String, Object> rebootHeaders = new HashMap<String, Object>(); rebootHeaders.put(JcloudsConstants.OPERATION, JcloudsConstants.SUSPEND_NODE); if (nodeId != null) { rebootHeaders.put(JcloudsConstants.NODE_ID, nodeId); } if (group != null) { rebootHeaders.put(JcloudsConstants.GROUP, group); } return rebootHeaders; } /** * Returns a {@Map} with the suspend headers. * * @param nodeId The id of the node to resume. * @param group The group of the node to resume. */ protected Map<String, Object> resumeHeaders(String nodeId, String group) { Map<String, Object> rebootHeaders = new HashMap<String, Object>(); rebootHeaders.put(JcloudsConstants.OPERATION, JcloudsConstants.RESUME_NODE); if (nodeId != null) { rebootHeaders.put(JcloudsConstants.NODE_ID, nodeId); } if (group != null) { rebootHeaders.put(JcloudsConstants.GROUP, group); } return rebootHeaders; } }
apache-2.0
macfisher/magento1.9-sandbox
tests/vendor/symfony/console/Tests/Input/ArrayInputTest.php
7159
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Console\Tests\Input; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; class ArrayInputTest extends TestCase { public function testGetFirstArgument() { $input = new ArrayInput(array()); $this->assertNull($input->getFirstArgument(), '->getFirstArgument() returns null if no argument were passed'); $input = new ArrayInput(array('name' => 'Fabien')); $this->assertEquals('Fabien', $input->getFirstArgument(), '->getFirstArgument() returns the first passed argument'); $input = new ArrayInput(array('--foo' => 'bar', 'name' => 'Fabien')); $this->assertEquals('Fabien', $input->getFirstArgument(), '->getFirstArgument() returns the first passed argument'); } public function testHasParameterOption() { $input = new ArrayInput(array('name' => 'Fabien', '--foo' => 'bar')); $this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if an option is present in the passed parameters'); $this->assertFalse($input->hasParameterOption('--bar'), '->hasParameterOption() returns false if an option is not present in the passed parameters'); $input = new ArrayInput(array('--foo')); $this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if an option is present in the passed parameters'); $input = new ArrayInput(array('--foo', '--', '--bar')); $this->assertTrue($input->hasParameterOption('--bar'), '->hasParameterOption() returns true if an option is present in the passed parameters'); $this->assertFalse($input->hasParameterOption('--bar', true), '->hasParameterOption() returns false if an option is present in the passed parameters after an end of options signal'); } public function testGetParameterOption() { $input = new ArrayInput(array('name' => 'Fabien', '--foo' => 'bar')); $this->assertEquals('bar', $input->getParameterOption('--foo'), '->getParameterOption() returns the option of specified name'); $this->assertFalse($input->getParameterOption('--bar'), '->getParameterOption() returns the default if an option is not present in the passed parameters'); $input = new ArrayInput(array('Fabien', '--foo' => 'bar')); $this->assertEquals('bar', $input->getParameterOption('--foo'), '->getParameterOption() returns the option of specified name'); $input = new ArrayInput(array('--foo', '--', '--bar' => 'woop')); $this->assertEquals('woop', $input->getParameterOption('--bar'), '->getParameterOption() returns the correct value if an option is present in the passed parameters'); $this->assertFalse($input->getParameterOption('--bar', false, true), '->getParameterOption() returns false if an option is present in the passed parameters after an end of options signal'); } public function testParseArguments() { $input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name')))); $this->assertEquals(array('name' => 'foo'), $input->getArguments(), '->parse() parses required arguments'); } /** * @dataProvider provideOptions */ public function testParseOptions($input, $options, $expectedOptions, $message) { $input = new ArrayInput($input, new InputDefinition($options)); $this->assertEquals($expectedOptions, $input->getOptions(), $message); } public function provideOptions() { return array( array( array('--foo' => 'bar'), array(new InputOption('foo')), array('foo' => 'bar'), '->parse() parses long options', ), array( array('--foo' => 'bar'), array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')), array('foo' => 'bar'), '->parse() parses long options with a default value', ), array( array('--foo' => null), array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')), array('foo' => 'default'), '->parse() parses long options with a default value', ), array( array('-f' => 'bar'), array(new InputOption('foo', 'f')), array('foo' => 'bar'), '->parse() parses short options', ), array( array('--' => null, '-f' => 'bar'), array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')), array('foo' => 'default'), '->parse() does not parse opts after an end of options signal', ), array( array('--' => null), array(), array(), '->parse() does not choke on end of options signal', ), ); } /** * @dataProvider provideInvalidInput */ public function testParseInvalidInput($parameters, $definition, $expectedExceptionMessage) { if (method_exists($this, 'expectException')) { $this->expectException('InvalidArgumentException'); $this->expectExceptionMessage($expectedExceptionMessage); } else { $this->setExpectedException('InvalidArgumentException', $expectedExceptionMessage); } new ArrayInput($parameters, $definition); } public function provideInvalidInput() { return array( array( array('foo' => 'foo'), new InputDefinition(array(new InputArgument('name'))), 'The "foo" argument does not exist.', ), array( array('--foo' => null), new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))), 'The "--foo" option requires a value.', ), array( array('--foo' => 'foo'), new InputDefinition(), 'The "--foo" option does not exist.', ), array( array('-o' => 'foo'), new InputDefinition(), 'The "-o" option does not exist.', ), ); } public function testToString() { $input = new ArrayInput(array('-f' => null, '-b' => 'bar', '--foo' => 'b a z', '--lala' => null, 'test' => 'Foo', 'test2' => "A\nB'C")); $this->assertEquals('-f -b=bar --foo='.escapeshellarg('b a z').' --lala Foo '.escapeshellarg("A\nB'C"), (string) $input); } }
mit
abhinay100/openerm_app
phpmyadmin/libraries/navigation/Nodes/Node_Procedure_Container.class.php
1778
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Functionality for the navigation tree * * @package PhpMyAdmin-Navigation */ if (! defined('PHPMYADMIN')) { exit; } /** * Represents a container for procedure nodes in the navigation tree * * @package PhpMyAdmin-Navigation */ class Node_Procedure_Container extends Node { /** * Initialises the class * * @return Node_Procedure_Container */ public function __construct() { parent::__construct(__('Procedures'), Node::CONTAINER); $this->icon = PMA_Util::getImage('b_routines.png', __('Procedures')); $this->links = array( 'text' => 'db_routines.php?server=' . $GLOBALS['server'] . '&amp;db=%1$s&amp;token=' . $GLOBALS['token'] . '&amp;type=PROCEDURE', 'icon' => 'db_routines.php?server=' . $GLOBALS['server'] . '&amp;db=%1$s&amp;token=' . $GLOBALS['token'] . '&amp;type=PROCEDURE', ); $this->real_name = 'procedures'; $new_label = _pgettext('Create new procedure', 'New'); $new = PMA_NodeFactory::getInstance('Node', $new_label); $new->isNew = true; $new->icon = PMA_Util::getImage('b_routine_add.png', $new_label); $new->links = array( 'text' => 'db_routines.php?server=' . $GLOBALS['server'] . '&amp;db=%2$s&amp;token=' . $GLOBALS['token'] . '&add_item=1', 'icon' => 'db_routines.php?server=' . $GLOBALS['server'] . '&amp;db=%2$s&amp;token=' . $GLOBALS['token'] . '&add_item=1', ); $new->classes = 'new_procedure italics'; $this->addChild($new); } } ?>
gpl-3.0
Adriqun/Assassin-s-Genesis
3rd-party/boost/boost/graph/detail/list_base.hpp
5593
//======================================================================= // Copyright 2002 Indiana University. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef BOOST_LIST_BASE_HPP #define BOOST_LIST_BASE_HPP #include <boost/iterator_adaptors.hpp> // Perhaps this should go through formal review, and move to <boost/>. /* An alternate interface idea: Extend the std::list functionality by creating remove/insert functions that do not require the container object! */ namespace boost { namespace detail { //========================================================================= // Linked-List Generic Implementation Functions template <class Node, class Next> inline Node slist_insert_after(Node pos, Node x, Next next) { next(x) = next(pos); next(pos) = x; return x; } // return next(pos) or next(next(pos)) ? template <class Node, class Next> inline Node slist_remove_after(Node pos, Next next) { Node n = next(pos); next(pos) = next(n); return n; } template <class Node, class Next> inline Node slist_remove_range(Node before_first, Node last, Next next) { next(before_first) = last; return last; } template <class Node, class Next> inline Node slist_previous(Node head, Node x, Node empty, Next next) { while (head != empty && next(head) != x) head = next(head); return head; } template<class Node, class Next> inline void slist_splice_after(Node pos, Node before_first, Node before_last, Next next) { if (pos != before_first && pos != before_last) { Node first = next(before_first); Node after = next(pos); next(before_first) = next(before_last); next(pos) = first; next(before_last) = after; } } template <class Node, class Next> inline Node slist_reverse(Node node, Node empty, Next next) { Node result = node; node = next(node); next(result) = empty; while(node) { Node next = next(node); next(node) = result; result = node; node = next; } return result; } template <class Node, class Next> inline std::size_t slist_size(Node head, Node empty, Next next) { std::size_t s = 0; for ( ; head != empty; head = next(head)) ++s; return s; } template <class Next, class Data> class slist_iterator_policies { public: explicit slist_iterator_policies(const Next& n, const Data& d) : m_next(n), m_data(d) { } template <class Reference, class Node> Reference dereference(type<Reference>, const Node& x) const { return m_data(x); } template <class Node> void increment(Node& x) const { x = m_next(x); } template <class Node> bool equal(Node& x, Node& y) const { return x == y; } protected: Next m_next; Data m_data; }; //=========================================================================== // Doubly-Linked List Generic Implementation Functions template <class Node, class Next, class Prev> inline void dlist_insert_before(Node pos, Node x, Next next, Prev prev) { next(x) = pos; prev(x) = prev(pos); next(prev(pos)) = x; prev(pos) = x; } template <class Node, class Next, class Prev> void dlist_remove(Node pos, Next next, Prev prev) { Node next_node = next(pos); Node prev_node = prev(pos); next(prev_node) = next_node; prev(next_node) = prev_node; } // This deletes every node in the list except the // sentinel node. template <class Node, class Delete> inline void dlist_clear(Node sentinel, Delete del) { Node i, tmp; i = next(sentinel); while (i != sentinel) { tmp = i; i = next(i); del(tmp); } } template <class Node> inline bool dlist_empty(Node dummy) { return next(dummy) == dummy; } template <class Node, class Next, class Prev> void dlist_transfer(Node pos, Node first, Node last, Next next, Prev prev) { if (pos != last) { // Remove [first,last) from its old position next(prev(last)) = pos; next(prev(first)) = last; next(prev(pos)) = first; // Splice [first,last) into its new position Node tmp = prev(pos); prev(pos) = prev(last); prev(last) = prev(first); prev(first) = tmp; } } template <class Next, class Prev, class Data> class dlist_iterator_policies : public slist_iterator_policies<Next, Data> { typedef slist_iterator_policies<Next, Data> Base; public: template <class Node> void decrement(Node& x) const { x = m_prev(x); } dlist_iterator_policies(Next n, Prev p, Data d) : Base(n,d), m_prev(p) { } protected: Prev m_prev; }; } // namespace detail } // namespace boost #endif // BOOST_LIST_BASE_HPP
gpl-3.0
littlebroken/forem
spec/lib/generators/forem/dummy/templates/config/application.rb
356
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require require "forem" # Need to load Devise manually at this point so that the autoload hooks are loaded # Otherwise it will bomb out because it cannot find Devise::SessionsController require "devise" require "devise/rails" require 'jquery-rails' <%= application_definition %>
mit
caesarxuchao/kubernetes
pkg/client/listers/imagepolicy/v1alpha1/expansion_generated.go
778
/* Copyright 2017 The Kubernetes 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. */ // This file was automatically generated by lister-gen package v1alpha1 // ImageReviewListerExpansion allows custom methods to be added to // ImageReviewLister. type ImageReviewListerExpansion interface{}
apache-2.0
goette/wordpress-starter
wp-content/plugins/wordpress-seo/admin/class-taxonomy.php
9797
<?php /** * @package Admin */ if ( ! defined( 'WPSEO_VERSION' ) ) { header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit(); } if ( ! class_exists( 'WPSEO_Taxonomy' ) ) { /** * Class that handles the edit boxes on taxonomy edit pages. */ class WPSEO_Taxonomy { /** * @var array Options array for the no-index options, including translated labels */ public $no_index_options = array(); /** * @var array Options array for the sitemap_include options, including translated labels */ public $sitemap_include_options = array(); /** * Class constructor */ function __construct() { $options = WPSEO_Options::get_all(); if ( is_admin() && ( isset( $_GET['taxonomy'] ) && $_GET['taxonomy'] !== '' ) && ( ! isset( $options['hideeditbox-tax-' . $_GET['taxonomy']] ) || $options['hideeditbox-tax-' . $_GET['taxonomy']] === false ) ) add_action( sanitize_text_field( $_GET['taxonomy'] ) . '_edit_form', array( $this, 'term_seo_form' ), 10, 1 ); add_action( 'edit_term', array( $this, 'update_term' ), 99, 3 ); add_action( 'init', array( $this, 'custom_category_descriptions_allow_html' ) ); add_filter( 'category_description', array( $this, 'custom_category_descriptions_add_shortcode_support' ) ); add_action( 'admin_init', array( $this, 'translate_meta_options' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) ); } /** * Translate options text strings for use in the select fields * * @internal IMPORTANT: if you want to add a new string (option) somewhere, make sure you add * that array key to the main options definition array in the class WPSEO_Taxonomy_Meta() as well!!!! */ public function translate_meta_options() { $this->no_index_options = WPSEO_Taxonomy_Meta::$no_index_options; $this->sitemap_include_options = WPSEO_Taxonomy_Meta::$sitemap_include_options; $this->no_index_options['default'] = __( 'Use %s default (Currently: %s)', 'wordpress-seo' ); $this->no_index_options['index'] = __( 'Always index', 'wordpress-seo' ); $this->no_index_options['noindex'] = __( 'Always noindex', 'wordpress-seo' ); $this->sitemap_include_options['-'] = __( 'Auto detect', 'wordpress-seo' ); $this->sitemap_include_options['always'] = __( 'Always include', 'wordpress-seo' ); $this->sitemap_include_options['never'] = __( 'Never include', 'wordpress-seo' ); } /** * Test whether we are on a public taxonomy - no metabox actions needed if we are not * Unfortunately we have to hook most everything in before the point where all taxonomies are registered and * we know which taxonomy is being requested, so we need to use this check in nearly every hooked in function. * * @since 1.5.0 */ function tax_is_public() { // Don't make static as taxonomies may still be added during the run $taxonomies = get_taxonomies( array( 'public' => true ), 'names' ); return ( isset( $_GET['taxonomy'] ) && in_array( $_GET['taxonomy'], $taxonomies ) ); } /** * Add our admin css file */ function admin_enqueue_scripts() { global $pagenow; if ( $pagenow === 'edit-tags.php' && ( isset( $_GET['action'] ) && $_GET['action'] === 'edit' ) ) { wp_enqueue_style( 'yoast-taxonomy-css', plugins_url( 'css/taxonomy-meta' . WPSEO_CSSJS_SUFFIX . '.css', WPSEO_FILE ), array(), WPSEO_VERSION ); } } /** * Create a row in the form table. * * @param string $var Variable the row controls. * @param string $label Label for the variable. * @param string $desc Description of the use of the variable. * @param array $tax_meta Taxonomy meta value. * @param string $type Type of form row to create. * @param array $options Options to use when form row is a select box. */ function form_row( $var, $label, $desc, $tax_meta, $type = 'text', $options = array() ) { $val = ''; if ( isset( $tax_meta[$var] ) && $tax_meta[$var] !== '' ) { $val = $tax_meta[$var]; } $esc_var = esc_attr( $var ); $field = ''; if ( $type == 'text' ) { $field .= ' <input name="' . $esc_var . '" id="' . $esc_var . '" type="text" value="' . esc_attr( $val ) . '" size="40"/>'; if ( is_string( $desc ) && $desc !== '' ) { $field .= ' <p class="description">' . esc_html( $desc ) . '</p>'; } } elseif ( $type == 'checkbox' ) { $field .= ' <input name="' . $esc_var . '" id="' . $esc_var . '" type="checkbox" ' . checked( $val ) . '/>'; } elseif ( $type == 'select' ) { if ( is_array( $options ) && $options !== array() ) { $field .= ' <select name="' . $esc_var . '" id="' . $esc_var . '">'; foreach ( $options as $option => $option_label ) { $selected = selected( $option, $val, false ); $field .= ' <option ' . $selected . ' value="' . esc_attr( $option ) . '">' . esc_html( $option_label ) . '</option>'; } $field .= ' </select>'; } } echo ' <tr class="form-field"> <th scope="row"><label for="' . $esc_var . '">' . esc_html( $label ) . ':</label></th> <td>' . $field . '</td> </tr>'; } /** * Show the SEO inputs for term. * * @param object $term Term to show the edit boxes for. */ function term_seo_form( $term ) { if ( $this->tax_is_public() === false ) return; $tax_meta = WPSEO_Taxonomy_Meta::get_term_meta( (int) $term->term_id, $term->taxonomy ); $options = WPSEO_Options::get_all(); echo '<h2>' . __( 'Yoast WordPress SEO Settings', 'wordpress-seo' ) . '</h2>'; echo '<table class="form-table wpseo-taxonomy-form">'; $this->form_row( 'wpseo_title', __( 'SEO Title', 'wordpress-seo' ), __( 'The SEO title is used on the archive page for this term.', 'wordpress-seo' ), $tax_meta ); $this->form_row( 'wpseo_desc', __( 'SEO Description', 'wordpress-seo' ), __( 'The SEO description is used for the meta description on the archive page for this term.', 'wordpress-seo' ), $tax_meta ); if ( $options['usemetakeywords'] === true ) { $this->form_row( 'wpseo_metakey', __( 'Meta Keywords', 'wordpress-seo' ), __( 'Meta keywords used on the archive page for this term.', 'wordpress-seo' ), $tax_meta ); } $this->form_row( 'wpseo_canonical', __( 'Canonical', 'wordpress-seo' ), __( 'The canonical link is shown on the archive page for this term.', 'wordpress-seo' ), $tax_meta ); if ( $options['breadcrumbs-enable'] === true ) { $this->form_row( 'wpseo_bctitle', __( 'Breadcrumbs Title', 'wordpress-seo' ), sprintf( __( 'The Breadcrumbs title is used in the breadcrumbs where this %s appears.', 'wordpress-seo' ), $term->taxonomy ), $tax_meta ); } /* Don't show the robots index field if it's overruled by a blog-wide option */ if ( '0' != get_option( 'blog_public' ) ) { $current = 'index'; if ( isset( $options['noindex-tax-' . $term->taxonomy] ) && $options['noindex-tax-' . $term->taxonomy] === true ) { $current = 'noindex'; } $noindex_options = $this->no_index_options; $noindex_options['default'] = sprintf( $noindex_options['default'], $term->taxonomy, $current ); $this->form_row( 'wpseo_noindex', sprintf( __( 'Noindex this %s', 'wordpress-seo' ), $term->taxonomy ), sprintf( __( 'This %s follows the indexation rules set under Metas and Titles, you can override it here.', 'wordpress-seo' ), $term->taxonomy ), $tax_meta, 'select', $noindex_options ); } $this->form_row( 'wpseo_sitemap_include', __( 'Include in sitemap?', 'wordpress-seo' ), '', $tax_meta, 'select', $this->sitemap_include_options ); echo '</table>'; } /** * Update the taxonomy meta data on save. * * @param int $term_id ID of the term to save data for * @param int $tt_id The taxonomy_term_id for the term. * @param string $taxonomy The taxonomy the term belongs to. */ function update_term( $term_id, $tt_id, $taxonomy ) { $tax_meta = get_option( 'wpseo_taxonomy_meta' ); /* Create post array with only our values */ $new_meta_data = array(); foreach ( WPSEO_Taxonomy_Meta::$defaults_per_term as $key => $default ) { if ( isset( $_POST[$key] ) ) { $new_meta_data[$key] = $_POST[$key]; } } /* Validate the post values */ $old = WPSEO_Taxonomy_Meta::get_term_meta( $term_id, $taxonomy ); $clean = WPSEO_Taxonomy_Meta::validate_term_meta_data( $new_meta_data, $old ); /* Add/remove the result to/from the original option value */ if ( $clean !== array() ) { $tax_meta[$taxonomy][$term_id] = $clean; } else { unset( $tax_meta[$taxonomy][$term_id] ); if ( isset( $tax_meta[$taxonomy] ) && $tax_meta[$taxonomy] === array() ) { unset( $tax_meta[$taxonomy] ); } } // Prevent complete array validation $tax_meta['wpseo_already_validated'] = true; update_option( 'wpseo_taxonomy_meta', $tax_meta ); } /** * Allows HTML in descriptions */ function custom_category_descriptions_allow_html() { $filters = array( 'pre_term_description', 'pre_link_description', 'pre_link_notes', 'pre_user_description', ); foreach ( $filters as $filter ) { remove_filter( $filter, 'wp_filter_kses' ); } remove_filter( 'term_description', 'wp_kses_data' ); } /** * Adds shortcode support to category descriptions. * * @param string $desc String to add shortcodes in. * @return string */ function custom_category_descriptions_add_shortcode_support( $desc ) { // Wrap in output buffering to prevent shortcodes that echo stuff instead of return from breaking things. ob_start(); $desc = do_shortcode( $desc ); ob_end_clean(); return $desc; } } /* End of class */ } /* End of class-exists wrapper */
gpl-2.0
ducktyper/bfnz
vendor/cache/ruby/2.3.0/gems/bootstrap-sass-3.3.5/test/node_mincer_test.rb
1025
require 'test_helper' require 'json' class NodeMincerTest < Minitest::Test DUMMY_PATH = 'test/dummy_node_mincer' def test_font_helper_without_suffix assert_match %r(url\(['"]?/assets/.*eot['"]?\)), @css end def test_font_helper_with_suffix_sharp assert_match %r(url\(['"]?/assets/.*svg#.+['"]?\)), @css end def test_font_helper_with_suffix_question assert_match %r(url\(['"]?/assets/.*eot\?.*['"]?\)), @css end def test_image_helper assert_match %r(url\(['"]?/assets/apple-touch-icon-144-precomposed.*png['"]?\)), @css end def setup tmp_dir = File.join GEM_PATH, 'tmp/node-mincer' command = "node manifest.js #{tmp_dir}" success = Dir.chdir DUMMY_PATH do silence_stdout_if !ENV['VERBOSE'] do system(command) end end assert success, 'Node.js Mincer compilation failed' manifest = JSON.parse(File.read("#{tmp_dir}/manifest.json")) css_name = manifest["assets"]["application.css"] @css = File.read("#{tmp_dir}/#{css_name}") end end
mit
HereSinceres/TypeScript
tests/cases/conformance/parser/ecmascript5/parserSbp_7.9_A9_T3.ts
343
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * Check Do-While Statement for automatic semicolon insertion * * @path bestPractice/Sbp_7.9_A9_T3.js * @description Execute do { \n ; \n }while(false) true */ //CHECK#1 do { ; } while (false) true
apache-2.0
wangfakang/go-1
test/nosplit.go
8999
// +build !nacl // run // Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "fmt" "io/ioutil" "log" "os" "os/exec" "path/filepath" "regexp" "runtime" "strconv" "strings" ) var tests = ` # These are test cases for the linker analysis that detects chains of # nosplit functions that would cause a stack overflow. # # Lines beginning with # are comments. # # Each test case describes a sequence of functions, one per line. # Each function definition is the function name, then the frame size, # then optionally the keyword 'nosplit', then the body of the function. # The body is assembly code, with some shorthands. # The shorthand 'call x' stands for CALL x(SB). # The shorthand 'callind' stands for 'CALL R0', where R0 is a register. # Each test case must define a function named main, and it must be first. # That is, a line beginning "main " indicates the start of a new test case. # Within a stanza, ; can be used instead of \n to separate lines. # # After the function definition, the test case ends with an optional # REJECT line, specifying the architectures on which the case should # be rejected. "REJECT" without any architectures means reject on all architectures. # The linker should accept the test case on systems not explicitly rejected. # # 64-bit systems do not attempt to execute test cases with frame sizes # that are only 32-bit aligned. # Ordinary function should work main 0 # Large frame marked nosplit is always wrong. main 10000 nosplit REJECT # Calling a large frame is okay. main 0 call big big 10000 # But not if the frame is nosplit. main 0 call big big 10000 nosplit REJECT # Recursion is okay. main 0 call main # Recursive nosplit runs out of space. main 0 nosplit call main REJECT # Chains of ordinary functions okay. main 0 call f1 f1 80 call f2 f2 80 # Chains of nosplit must fit in the stack limit, 128 bytes. main 0 call f1 f1 80 nosplit call f2 f2 80 nosplit REJECT # Larger chains. main 0 call f1 f1 16 call f2 f2 16 call f3 f3 16 call f4 f4 16 call f5 f5 16 call f6 f6 16 call f7 f7 16 call f8 f8 16 call end end 1000 main 0 call f1 f1 16 nosplit call f2 f2 16 nosplit call f3 f3 16 nosplit call f4 f4 16 nosplit call f5 f5 16 nosplit call f6 f6 16 nosplit call f7 f7 16 nosplit call f8 f8 16 nosplit call end end 1000 REJECT # Test cases near the 128-byte limit. # Ordinary stack split frame is always okay. main 112 main 116 main 120 main 124 main 128 main 132 main 136 # A nosplit leaf can use the whole 128-CallSize bytes available on entry. main 112 nosplit main 116 nosplit main 120 nosplit main 124 nosplit main 128 nosplit; REJECT main 132 nosplit; REJECT main 136 nosplit; REJECT # Calling a nosplit function from a nosplit function requires # having room for the saved caller PC and the called frame. # Because ARM doesn't save LR in the leaf, it gets an extra 4 bytes. # Because ppc64 doesn't save LR in the leaf, it gets an extra 8 bytes. main 112 nosplit call f; f 0 nosplit main 116 nosplit call f; f 0 nosplit main 120 nosplit call f; f 0 nosplit; REJECT amd64 main 124 nosplit call f; f 0 nosplit; REJECT amd64 386 main 128 nosplit call f; f 0 nosplit; REJECT main 132 nosplit call f; f 0 nosplit; REJECT main 136 nosplit call f; f 0 nosplit; REJECT # Calling a splitting function from a nosplit function requires # having room for the saved caller PC of the call but also the # saved caller PC for the call to morestack. # Again the ARM and ppc64 work in less space. main 104 nosplit call f; f 0 call f main 108 nosplit call f; f 0 call f main 112 nosplit call f; f 0 call f; REJECT amd64 main 116 nosplit call f; f 0 call f; REJECT amd64 main 120 nosplit call f; f 0 call f; REJECT amd64 386 main 124 nosplit call f; f 0 call f; REJECT amd64 386 main 128 nosplit call f; f 0 call f; REJECT main 132 nosplit call f; f 0 call f; REJECT main 136 nosplit call f; f 0 call f; REJECT # Indirect calls are assumed to be splitting functions. main 104 nosplit callind main 108 nosplit callind main 112 nosplit callind; REJECT amd64 main 116 nosplit callind; REJECT amd64 main 120 nosplit callind; REJECT amd64 386 main 124 nosplit callind; REJECT amd64 386 main 128 nosplit callind; REJECT main 132 nosplit callind; REJECT main 136 nosplit callind; REJECT # Issue 7623 main 0 call f; f 112 main 0 call f; f 116 main 0 call f; f 120 main 0 call f; f 124 main 0 call f; f 128 main 0 call f; f 132 main 0 call f; f 136 ` var ( commentRE = regexp.MustCompile(`(?m)^#.*`) rejectRE = regexp.MustCompile(`(?s)\A(.+?)((\n|; *)REJECT(.*))?\z`) lineRE = regexp.MustCompile(`(\w+) (\d+)( nosplit)?(.*)`) callRE = regexp.MustCompile(`\bcall (\w+)\b`) callindRE = regexp.MustCompile(`\bcallind\b`) ) func main() { goarch := os.Getenv("GOARCH") if goarch == "" { goarch = runtime.GOARCH } version, err := exec.Command("go", "tool", "compile", "-V").Output() if err != nil { bug() fmt.Printf("running go tool compile -V: %v\n", err) return } if strings.Contains(string(version), "framepointer") { // Skip this test if GOEXPERIMENT=framepointer return } dir, err := ioutil.TempDir("", "go-test-nosplit") if err != nil { bug() fmt.Printf("creating temp dir: %v\n", err) return } defer os.RemoveAll(dir) tests = strings.Replace(tests, "\t", " ", -1) tests = commentRE.ReplaceAllString(tests, "") nok := 0 nfail := 0 TestCases: for len(tests) > 0 { var stanza string i := strings.Index(tests, "\nmain ") if i < 0 { stanza, tests = tests, "" } else { stanza, tests = tests[:i], tests[i+1:] } m := rejectRE.FindStringSubmatch(stanza) if m == nil { bug() fmt.Printf("invalid stanza:\n\t%s\n", indent(stanza)) continue } lines := strings.TrimSpace(m[1]) reject := false if m[2] != "" { if strings.TrimSpace(m[4]) == "" { reject = true } else { for _, rej := range strings.Fields(m[4]) { if rej == goarch { reject = true } } } } if lines == "" && !reject { continue } var gobuf bytes.Buffer fmt.Fprintf(&gobuf, "package main\n") var buf bytes.Buffer ptrSize := 4 switch goarch { case "ppc64", "ppc64le": ptrSize = 8 fmt.Fprintf(&buf, "#define CALL BL\n#define REGISTER (CTR)\n") case "arm": fmt.Fprintf(&buf, "#define CALL BL\n#define REGISTER (R0)\n") case "arm64": ptrSize = 8 fmt.Fprintf(&buf, "#define CALL BL\n#define REGISTER (R0)\n") case "amd64": ptrSize = 8 fmt.Fprintf(&buf, "#define REGISTER AX\n") default: fmt.Fprintf(&buf, "#define REGISTER AX\n") } for _, line := range strings.Split(lines, "\n") { line = strings.TrimSpace(line) if line == "" { continue } for i, subline := range strings.Split(line, ";") { subline = strings.TrimSpace(subline) if subline == "" { continue } m := lineRE.FindStringSubmatch(subline) if m == nil { bug() fmt.Printf("invalid function line: %s\n", subline) continue TestCases } name := m[1] size, _ := strconv.Atoi(m[2]) // The limit was originally 128 but is now 512. // Instead of rewriting the test cases above, adjust // the first stack frame to use up the extra bytes. if i == 0 { size += 512 - 128 // Noopt builds have a larger stackguard. // See ../cmd/dist/buildruntime.go:stackGuardMultiplier for _, s := range strings.Split(os.Getenv("GO_GCFLAGS"), " ") { if s == "-N" { size += 640 } } } if size%ptrSize == 4 || goarch == "arm64" && size != 0 && (size+8)%16 != 0 { continue TestCases } nosplit := m[3] body := m[4] if nosplit != "" { nosplit = ",7" } else { nosplit = ",0" } body = callRE.ReplaceAllString(body, "CALL ·$1(SB);") body = callindRE.ReplaceAllString(body, "CALL REGISTER;") fmt.Fprintf(&gobuf, "func %s()\n", name) fmt.Fprintf(&buf, "TEXT ·%s(SB)%s,$%d-0\n\t%s\n\tRET\n\n", name, nosplit, size, body) } } if err := ioutil.WriteFile(filepath.Join(dir, "asm.s"), buf.Bytes(), 0666); err != nil { log.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(dir, "main.go"), gobuf.Bytes(), 0666); err != nil { log.Fatal(err) } cmd := exec.Command("go", "build") cmd.Dir = dir output, err := cmd.CombinedOutput() if err == nil { nok++ if reject { bug() fmt.Printf("accepted incorrectly:\n\t%s\n", indent(strings.TrimSpace(stanza))) } } else { nfail++ if !reject { bug() fmt.Printf("rejected incorrectly:\n\t%s\n", indent(strings.TrimSpace(stanza))) fmt.Printf("\n\tlinker output:\n\t%s\n", indent(string(output))) } } } if !bugged && (nok == 0 || nfail == 0) { bug() fmt.Printf("not enough test cases run\n") } } func indent(s string) string { return strings.Replace(s, "\n", "\n\t", -1) } var bugged = false func bug() { if !bugged { bugged = true fmt.Printf("BUG\n") } }
bsd-3-clause
0x90sled/catapult
third_party/gsutil/third_party/boto/tests/unit/route53/test_zone.py
2548
#!/usr/bin/env python # Copyright (c) 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # from boto.route53.zone import Zone from tests.compat import mock, unittest class TestZone(unittest.TestCase): def test_find_records(self): mock_connection = mock.Mock() zone = Zone(mock_connection, {}) zone.id = None rr_names = ['amazon.com', 'amazon.com', 'aws.amazon.com', 'aws.amazon.com'] mock_rrs = [] # Create some mock resource records. for rr_name in rr_names: mock_rr = mock.Mock() mock_rr.name = rr_name mock_rr.type = 'A' mock_rr.weight = None mock_rr.region = None mock_rrs.append(mock_rr) # Set the last resource record to ``None``. The ``find_records`` loop # should never hit this. mock_rrs[3] = None mock_connection.get_all_rrsets.return_value = mock_rrs mock_connection._make_qualified.return_value = 'amazon.com' # Ensure that the ``None`` type object was not iterated over. try: result_rrs = zone.find_records('amazon.com', 'A', all=True) except AttributeError as e: self.fail("find_records() iterated too far into resource" " record list.") # Determine that the resulting records are correct. self.assertEqual(result_rrs, [mock_rrs[0], mock_rrs[1]]) if __name__ == "__main__": unittest.main()
bsd-3-clause
freewind/DefinitelyTyped
types/jwt-decode/index.d.ts
514
// Type definitions for jwt-decode 2.2 // Project: https://github.com/auth0/jwt-decode // Definitions by: Giedrius Grabauskas <https://github.com/GiedriusGrabauskas>, Mads Madsen <https://github.com/madsmadsen> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace JwtDecode { interface Options { header: boolean; } } declare function JwtDecode<TTokenDto>(token: string, options?: JwtDecode.Options): TTokenDto; export = JwtDecode; export as namespace jwt_decode;
mit
iwdmb/cdnjs
ajax/libs/highcharts/5.0.5/js/modules/funnel.js
1963
/* Highcharts JS v5.0.5 (2016-11-29) Highcharts funnel module (c) 2010-2016 Torstein Honsi License: www.highcharts.com/license */ (function(c){"object"===typeof module&&module.exports?module.exports=c:c(Highcharts)})(function(c){(function(c){var n=c.seriesType,z=c.seriesTypes,F=c.noop,G=c.each;n("funnel","pie",{animation:!1,center:["50%","50%"],width:"90%",neckWidth:"30%",height:"100%",neckHeight:"25%",reversed:!1,size:!0},{animate:F,translate:function(){var b=function(a,b){return/%$/.test(a)?b*parseInt(a,10)/100:parseInt(a,10)},c=0,e=this.chart,d=this.options,r=d.reversed,H=d.ignoreHiddenPoint,t=e.plotWidth,e=e.plotHeight, p=0,n=d.center,f=b(n[0],t),q=b(n[1],e),z=b(d.width,t),h,v,k=b(d.height,e),w=b(d.neckWidth,t),D=b(d.neckHeight,e),x=q-k/2+k-D,b=this.data,A,B,I="left"===d.dataLabels.position?1:0,C,l,E,u,g,y,m;this.getWidthAt=v=function(a){var b=q-k/2;return a>x||k===D?w:w+(z-w)*(1-(a-b)/(k-D))};this.getX=function(a,b){return f+(b?-1:1)*(v(r?2*q-a:a)/2+d.dataLabels.distance)};this.center=[f,q,k];this.centerX=f;G(b,function(a){H&&!1===a.visible||(c+=a.y)});G(b,function(a){m=null;B=c?a.y/c:0;l=q-k/2+p*k;g=l+B*k;h=v(l); C=f-h/2;E=C+h;h=v(g);u=f-h/2;y=u+h;l>x?(C=u=f-w/2,E=y=f+w/2):g>x&&(m=g,h=v(x),u=f-h/2,y=u+h,g=x);r&&(l=2*q-l,g=2*q-g,m=m?2*q-m:null);A=["M",C,l,"L",E,l,y,g];m&&A.push(y,m,u,m);A.push(u,g,"Z");a.shapeType="path";a.shapeArgs={d:A};a.percentage=100*B;a.plotX=f;a.plotY=(l+(m||g))/2;a.tooltipPos=[f,a.plotY];a.slice=F;a.half=I;H&&!1===a.visible||(p+=B)})},drawPoints:z.column.prototype.drawPoints,sortByAngle:function(b){b.sort(function(b,c){return b.plotY-c.plotY})},drawDataLabels:function(){var b=this.data, c=this.options.dataLabels.distance,e,d,r,n=b.length,t,p;for(this.center[2]-=2*c;n--;)r=b[n],d=(e=r.half)?1:-1,p=r.plotY,t=this.getX(p,e),r.labelPos=[0,p,t+(c-5)*d,p,t+c*d,p,e?"right":"left",0];z.pie.prototype.drawDataLabels.call(this)}});n("pyramid","funnel",{neckWidth:"0%",neckHeight:"0%",reversed:!0})})(c)});
mit
tlist/asian-crush-backup
wp-content/plugins/backwpup/vendor/OpenCloud/ObjectStore/Exception/ContainerException.php
327
<?php /** * PHP OpenCloud library. * * @copyright 2014 Rackspace Hosting, Inc. See LICENSE for information. * @license https://www.apache.org/licenses/LICENSE-2.0 * @author Jamie Hannaford <jamie.hannaford@rackspace.com> */ namespace OpenCloud\ObjectStore\Exception; class ContainerException extends \Exception { }
gpl-2.0
topher1kenobe/lockon
wp-content/themes/make/js/libs/cycle2/jquery.cycle2.js
48603
/*! * jQuery Cycle2; version: 2.1.3 build: 20140314 * http://jquery.malsup.com/cycle2/ * Copyright (c) 2014 M. Alsup; Dual licensed: MIT/GPL */ /* Cycle2 core engine */ ;(function($) { "use strict"; var version = '2.1.2'; $.fn.cycle = function( options ) { // fix mistakes with the ready state var o; if ( this.length === 0 && !$.isReady ) { o = { s: this.selector, c: this.context }; $.fn.cycle.log('requeuing slideshow (dom not ready)'); $(function() { $( o.s, o.c ).cycle(options); }); return this; } return this.each(function() { var data, opts, shortName, val; var container = $(this); var log = $.fn.cycle.log; if ( container.data('cycle.opts') ) return; // already initialized if ( container.data('cycle-log') === false || ( options && options.log === false ) || ( opts && opts.log === false) ) { log = $.noop; } log('--c2 init--'); data = container.data(); for (var p in data) { // allow props to be accessed sans 'cycle' prefix and log the overrides if (data.hasOwnProperty(p) && /^cycle[A-Z]+/.test(p) ) { val = data[p]; shortName = p.match(/^cycle(.*)/)[1].replace(/^[A-Z]/, lowerCase); log(shortName+':', val, '('+typeof val +')'); data[shortName] = val; } } opts = $.extend( {}, $.fn.cycle.defaults, data, options || {}); opts.timeoutId = 0; opts.paused = opts.paused || false; // #57 opts.container = container; opts._maxZ = opts.maxZ; opts.API = $.extend ( { _container: container }, $.fn.cycle.API ); opts.API.log = log; opts.API.trigger = function( eventName, args ) { opts.container.trigger( eventName, args ); return opts.API; }; container.data( 'cycle.opts', opts ); container.data( 'cycle.API', opts.API ); // opportunity for plugins to modify opts and API opts.API.trigger('cycle-bootstrap', [ opts, opts.API ]); opts.API.addInitialSlides(); opts.API.preInitSlideshow(); if ( opts.slides.length ) opts.API.initSlideshow(); }); }; $.fn.cycle.API = { opts: function() { return this._container.data( 'cycle.opts' ); }, addInitialSlides: function() { var opts = this.opts(); var slides = opts.slides; opts.slideCount = 0; opts.slides = $(); // empty set // add slides that already exist slides = slides.jquery ? slides : opts.container.find( slides ); if ( opts.random ) { slides.sort(function() {return Math.random() - 0.5;}); } opts.API.add( slides ); }, preInitSlideshow: function() { var opts = this.opts(); opts.API.trigger('cycle-pre-initialize', [ opts ]); var tx = $.fn.cycle.transitions[opts.fx]; if (tx && $.isFunction(tx.preInit)) tx.preInit( opts ); opts._preInitialized = true; }, postInitSlideshow: function() { var opts = this.opts(); opts.API.trigger('cycle-post-initialize', [ opts ]); var tx = $.fn.cycle.transitions[opts.fx]; if (tx && $.isFunction(tx.postInit)) tx.postInit( opts ); }, initSlideshow: function() { var opts = this.opts(); var pauseObj = opts.container; var slideOpts; opts.API.calcFirstSlide(); if ( opts.container.css('position') == 'static' ) opts.container.css('position', 'relative'); $(opts.slides[opts.currSlide]).css({ opacity: 1, display: 'block', visibility: 'visible' }); opts.API.stackSlides( opts.slides[opts.currSlide], opts.slides[opts.nextSlide], !opts.reverse ); if ( opts.pauseOnHover ) { // allow pauseOnHover to specify an element if ( opts.pauseOnHover !== true ) pauseObj = $( opts.pauseOnHover ); pauseObj.hover( function(){ opts.API.pause( true ); }, function(){ opts.API.resume( true ); } ); } // stage initial transition if ( opts.timeout ) { slideOpts = opts.API.getSlideOpts( opts.currSlide ); opts.API.queueTransition( slideOpts, slideOpts.timeout + opts.delay ); } opts._initialized = true; opts.API.updateView( true ); opts.API.trigger('cycle-initialized', [ opts ]); opts.API.postInitSlideshow(); }, pause: function( hover ) { var opts = this.opts(), slideOpts = opts.API.getSlideOpts(), alreadyPaused = opts.hoverPaused || opts.paused; if ( hover ) opts.hoverPaused = true; else opts.paused = true; if ( ! alreadyPaused ) { opts.container.addClass('cycle-paused'); opts.API.trigger('cycle-paused', [ opts ]).log('cycle-paused'); if ( slideOpts.timeout ) { clearTimeout( opts.timeoutId ); opts.timeoutId = 0; // determine how much time is left for the current slide opts._remainingTimeout -= ( $.now() - opts._lastQueue ); if ( opts._remainingTimeout < 0 || isNaN(opts._remainingTimeout) ) opts._remainingTimeout = undefined; } } }, resume: function( hover ) { var opts = this.opts(), alreadyResumed = !opts.hoverPaused && !opts.paused, remaining; if ( hover ) opts.hoverPaused = false; else opts.paused = false; if ( ! alreadyResumed ) { opts.container.removeClass('cycle-paused'); // #gh-230; if an animation is in progress then don't queue a new transition; it will // happen naturally if ( opts.slides.filter(':animated').length === 0 ) opts.API.queueTransition( opts.API.getSlideOpts(), opts._remainingTimeout ); opts.API.trigger('cycle-resumed', [ opts, opts._remainingTimeout ] ).log('cycle-resumed'); } }, add: function( slides, prepend ) { var opts = this.opts(); var oldSlideCount = opts.slideCount; var startSlideshow = false; var len; if ( $.type(slides) == 'string') slides = $.trim( slides ); $( slides ).each(function(i) { var slideOpts; var slide = $(this); if ( prepend ) opts.container.prepend( slide ); else opts.container.append( slide ); opts.slideCount++; slideOpts = opts.API.buildSlideOpts( slide ); if ( prepend ) opts.slides = $( slide ).add( opts.slides ); else opts.slides = opts.slides.add( slide ); opts.API.initSlide( slideOpts, slide, --opts._maxZ ); slide.data('cycle.opts', slideOpts); opts.API.trigger('cycle-slide-added', [ opts, slideOpts, slide ]); }); opts.API.updateView( true ); startSlideshow = opts._preInitialized && (oldSlideCount < 2 && opts.slideCount >= 1); if ( startSlideshow ) { if ( !opts._initialized ) opts.API.initSlideshow(); else if ( opts.timeout ) { len = opts.slides.length; opts.nextSlide = opts.reverse ? len - 1 : 1; if ( !opts.timeoutId ) { opts.API.queueTransition( opts ); } } } }, calcFirstSlide: function() { var opts = this.opts(); var firstSlideIndex; firstSlideIndex = parseInt( opts.startingSlide || 0, 10 ); if (firstSlideIndex >= opts.slides.length || firstSlideIndex < 0) firstSlideIndex = 0; opts.currSlide = firstSlideIndex; if ( opts.reverse ) { opts.nextSlide = firstSlideIndex - 1; if (opts.nextSlide < 0) opts.nextSlide = opts.slides.length - 1; } else { opts.nextSlide = firstSlideIndex + 1; if (opts.nextSlide == opts.slides.length) opts.nextSlide = 0; } }, calcNextSlide: function() { var opts = this.opts(); var roll; if ( opts.reverse ) { roll = (opts.nextSlide - 1) < 0; opts.nextSlide = roll ? opts.slideCount - 1 : opts.nextSlide-1; opts.currSlide = roll ? 0 : opts.nextSlide+1; } else { roll = (opts.nextSlide + 1) == opts.slides.length; opts.nextSlide = roll ? 0 : opts.nextSlide+1; opts.currSlide = roll ? opts.slides.length-1 : opts.nextSlide-1; } }, calcTx: function( slideOpts, manual ) { var opts = slideOpts; var tx; if ( manual && opts.manualFx ) tx = $.fn.cycle.transitions[opts.manualFx]; if ( !tx ) tx = $.fn.cycle.transitions[opts.fx]; if (!tx) { tx = $.fn.cycle.transitions.fade; opts.API.log('Transition "' + opts.fx + '" not found. Using fade.'); } return tx; }, prepareTx: function( manual, fwd ) { var opts = this.opts(); var after, curr, next, slideOpts, tx; if ( opts.slideCount < 2 ) { opts.timeoutId = 0; return; } if ( manual && ( !opts.busy || opts.manualTrump ) ) { opts.API.stopTransition(); opts.busy = false; clearTimeout(opts.timeoutId); opts.timeoutId = 0; } if ( opts.busy ) return; if ( opts.timeoutId === 0 && !manual ) return; curr = opts.slides[opts.currSlide]; next = opts.slides[opts.nextSlide]; slideOpts = opts.API.getSlideOpts( opts.nextSlide ); tx = opts.API.calcTx( slideOpts, manual ); opts._tx = tx; if ( manual && slideOpts.manualSpeed !== undefined ) slideOpts.speed = slideOpts.manualSpeed; // if ( opts.nextSlide === opts.currSlide ) // opts.API.calcNextSlide(); // ensure that: // 1. advancing to a different slide // 2. this is either a manual event (prev/next, pager, cmd) or // a timer event and slideshow is not paused if ( opts.nextSlide != opts.currSlide && (manual || (!opts.paused && !opts.hoverPaused && opts.timeout) )) { // #62 opts.API.trigger('cycle-before', [ slideOpts, curr, next, fwd ]); if ( tx.before ) tx.before( slideOpts, curr, next, fwd ); after = function() { opts.busy = false; // #76; bail if slideshow has been destroyed if (! opts.container.data( 'cycle.opts' ) ) return; if (tx.after) tx.after( slideOpts, curr, next, fwd ); opts.API.trigger('cycle-after', [ slideOpts, curr, next, fwd ]); opts.API.queueTransition( slideOpts); opts.API.updateView( true ); }; opts.busy = true; if (tx.transition) tx.transition(slideOpts, curr, next, fwd, after); else opts.API.doTransition( slideOpts, curr, next, fwd, after); opts.API.calcNextSlide(); opts.API.updateView(); } else { opts.API.queueTransition( slideOpts ); } }, // perform the actual animation doTransition: function( slideOpts, currEl, nextEl, fwd, callback) { var opts = slideOpts; var curr = $(currEl), next = $(nextEl); var fn = function() { // make sure animIn has something so that callback doesn't trigger immediately next.animate(opts.animIn || { opacity: 1}, opts.speed, opts.easeIn || opts.easing, callback); }; next.css(opts.cssBefore || {}); curr.animate(opts.animOut || {}, opts.speed, opts.easeOut || opts.easing, function() { curr.css(opts.cssAfter || {}); if (!opts.sync) { fn(); } }); if (opts.sync) { fn(); } }, queueTransition: function( slideOpts, specificTimeout ) { var opts = this.opts(); var timeout = specificTimeout !== undefined ? specificTimeout : slideOpts.timeout; if (opts.nextSlide === 0 && --opts.loop === 0) { opts.API.log('terminating; loop=0'); opts.timeout = 0; if ( timeout ) { setTimeout(function() { opts.API.trigger('cycle-finished', [ opts ]); }, timeout); } else { opts.API.trigger('cycle-finished', [ opts ]); } // reset nextSlide opts.nextSlide = opts.currSlide; return; } if ( opts.continueAuto !== undefined ) { if ( opts.continueAuto === false || ($.isFunction(opts.continueAuto) && opts.continueAuto() === false )) { opts.API.log('terminating automatic transitions'); opts.timeout = 0; if ( opts.timeoutId ) clearTimeout(opts.timeoutId); return; } } if ( timeout ) { opts._lastQueue = $.now(); if ( specificTimeout === undefined ) opts._remainingTimeout = slideOpts.timeout; if ( !opts.paused && ! opts.hoverPaused ) { opts.timeoutId = setTimeout(function() { opts.API.prepareTx( false, !opts.reverse ); }, timeout ); } } }, stopTransition: function() { var opts = this.opts(); if ( opts.slides.filter(':animated').length ) { opts.slides.stop(false, true); opts.API.trigger('cycle-transition-stopped', [ opts ]); } if ( opts._tx && opts._tx.stopTransition ) opts._tx.stopTransition( opts ); }, // advance slide forward or back advanceSlide: function( val ) { var opts = this.opts(); clearTimeout(opts.timeoutId); opts.timeoutId = 0; opts.nextSlide = opts.currSlide + val; if (opts.nextSlide < 0) opts.nextSlide = opts.slides.length - 1; else if (opts.nextSlide >= opts.slides.length) opts.nextSlide = 0; opts.API.prepareTx( true, val >= 0 ); return false; }, buildSlideOpts: function( slide ) { var opts = this.opts(); var val, shortName; var slideOpts = slide.data() || {}; for (var p in slideOpts) { // allow props to be accessed sans 'cycle' prefix and log the overrides if (slideOpts.hasOwnProperty(p) && /^cycle[A-Z]+/.test(p) ) { val = slideOpts[p]; shortName = p.match(/^cycle(.*)/)[1].replace(/^[A-Z]/, lowerCase); opts.API.log('['+(opts.slideCount-1)+']', shortName+':', val, '('+typeof val +')'); slideOpts[shortName] = val; } } slideOpts = $.extend( {}, $.fn.cycle.defaults, opts, slideOpts ); slideOpts.slideNum = opts.slideCount; try { // these props should always be read from the master state object delete slideOpts.API; delete slideOpts.slideCount; delete slideOpts.currSlide; delete slideOpts.nextSlide; delete slideOpts.slides; } catch(e) { // no op } return slideOpts; }, getSlideOpts: function( index ) { var opts = this.opts(); if ( index === undefined ) index = opts.currSlide; var slide = opts.slides[index]; var slideOpts = $(slide).data('cycle.opts'); return $.extend( {}, opts, slideOpts ); }, initSlide: function( slideOpts, slide, suggestedZindex ) { var opts = this.opts(); slide.css( slideOpts.slideCss || {} ); if ( suggestedZindex > 0 ) slide.css( 'zIndex', suggestedZindex ); // ensure that speed settings are sane if ( isNaN( slideOpts.speed ) ) slideOpts.speed = $.fx.speeds[slideOpts.speed] || $.fx.speeds._default; if ( !slideOpts.sync ) slideOpts.speed = slideOpts.speed / 2; slide.addClass( opts.slideClass ); }, updateView: function( isAfter, isDuring, forceEvent ) { var opts = this.opts(); if ( !opts._initialized ) return; var slideOpts = opts.API.getSlideOpts(); var currSlide = opts.slides[ opts.currSlide ]; if ( ! isAfter && isDuring !== true ) { opts.API.trigger('cycle-update-view-before', [ opts, slideOpts, currSlide ]); if ( opts.updateView < 0 ) return; } if ( opts.slideActiveClass ) { opts.slides.removeClass( opts.slideActiveClass ) .eq( opts.currSlide ).addClass( opts.slideActiveClass ); } if ( isAfter && opts.hideNonActive ) opts.slides.filter( ':not(.' + opts.slideActiveClass + ')' ).css('visibility', 'hidden'); if ( opts.updateView === 0 ) { setTimeout(function() { opts.API.trigger('cycle-update-view', [ opts, slideOpts, currSlide, isAfter ]); }, slideOpts.speed / (opts.sync ? 2 : 1) ); } if ( opts.updateView !== 0 ) opts.API.trigger('cycle-update-view', [ opts, slideOpts, currSlide, isAfter ]); if ( isAfter ) opts.API.trigger('cycle-update-view-after', [ opts, slideOpts, currSlide ]); }, getComponent: function( name ) { var opts = this.opts(); var selector = opts[name]; if (typeof selector === 'string') { // if selector is a child, sibling combinator, adjancent selector then use find, otherwise query full dom return (/^\s*[\>|\+|~]/).test( selector ) ? opts.container.find( selector ) : $( selector ); } if (selector.jquery) return selector; return $(selector); }, stackSlides: function( curr, next, fwd ) { var opts = this.opts(); if ( !curr ) { curr = opts.slides[opts.currSlide]; next = opts.slides[opts.nextSlide]; fwd = !opts.reverse; } // reset the zIndex for the common case: // curr slide on top, next slide beneath, and the rest in order to be shown $(curr).css('zIndex', opts.maxZ); var i; var z = opts.maxZ - 2; var len = opts.slideCount; if (fwd) { for ( i = opts.currSlide + 1; i < len; i++ ) $( opts.slides[i] ).css( 'zIndex', z-- ); for ( i = 0; i < opts.currSlide; i++ ) $( opts.slides[i] ).css( 'zIndex', z-- ); } else { for ( i = opts.currSlide - 1; i >= 0; i-- ) $( opts.slides[i] ).css( 'zIndex', z-- ); for ( i = len - 1; i > opts.currSlide; i-- ) $( opts.slides[i] ).css( 'zIndex', z-- ); } $(next).css('zIndex', opts.maxZ - 1); }, getSlideIndex: function( el ) { return this.opts().slides.index( el ); } }; // API // default logger $.fn.cycle.log = function log() { /*global console:true */ if (window.console && console.log) console.log('[cycle2] ' + Array.prototype.join.call(arguments, ' ') ); }; $.fn.cycle.version = function() { return 'Cycle2: ' + version; }; // helper functions function lowerCase(s) { return (s || '').toLowerCase(); } // expose transition object $.fn.cycle.transitions = { custom: { }, none: { before: function( opts, curr, next, fwd ) { opts.API.stackSlides( next, curr, fwd ); opts.cssBefore = { opacity: 1, visibility: 'visible', display: 'block' }; } }, fade: { before: function( opts, curr, next, fwd ) { var css = opts.API.getSlideOpts( opts.nextSlide ).slideCss || {}; opts.API.stackSlides( curr, next, fwd ); opts.cssBefore = $.extend(css, { opacity: 0, visibility: 'visible', display: 'block' }); opts.animIn = { opacity: 1 }; opts.animOut = { opacity: 0 }; } }, fadeout: { before: function( opts , curr, next, fwd ) { var css = opts.API.getSlideOpts( opts.nextSlide ).slideCss || {}; opts.API.stackSlides( curr, next, fwd ); opts.cssBefore = $.extend(css, { opacity: 1, visibility: 'visible', display: 'block' }); opts.animOut = { opacity: 0 }; } }, scrollHorz: { before: function( opts, curr, next, fwd ) { opts.API.stackSlides( curr, next, fwd ); var w = opts.container.css('overflow','hidden').width(); opts.cssBefore = { left: fwd ? w : - w, top: 0, opacity: 1, visibility: 'visible', display: 'block' }; opts.cssAfter = { zIndex: opts._maxZ - 2, left: 0 }; opts.animIn = { left: 0 }; opts.animOut = { left: fwd ? -w : w }; } } }; // @see: http://jquery.malsup.com/cycle2/api $.fn.cycle.defaults = { allowWrap: true, autoSelector: '.cycle-slideshow[data-cycle-auto-init!=false]', delay: 0, easing: null, fx: 'fade', hideNonActive: true, loop: 0, manualFx: undefined, manualSpeed: undefined, manualTrump: true, maxZ: 100, pauseOnHover: false, reverse: false, slideActiveClass: 'cycle-slide-active', slideClass: 'cycle-slide', slideCss: { position: 'absolute', top: 0, left: 0 }, slides: '> img', speed: 500, startingSlide: 0, sync: true, timeout: 4000, updateView: 0 }; // automatically find and run slideshows $(document).ready(function() { $( $.fn.cycle.defaults.autoSelector ).cycle(); }); })(jQuery); /*! Cycle2 autoheight plugin; Copyright (c) M.Alsup, 2012; version: 20130913 */ (function($) { "use strict"; $.extend($.fn.cycle.defaults, { autoHeight: 0, // setting this option to false disables autoHeight logic autoHeightSpeed: 250, autoHeightEasing: null }); $(document).on( 'cycle-initialized', function( e, opts ) { var autoHeight = opts.autoHeight; var t = $.type( autoHeight ); var resizeThrottle = null; var ratio; if ( t !== 'string' && t !== 'number' ) return; // bind events opts.container.on( 'cycle-slide-added cycle-slide-removed', initAutoHeight ); opts.container.on( 'cycle-destroyed', onDestroy ); if ( autoHeight == 'container' ) { opts.container.on( 'cycle-before', onBefore ); } else if ( t === 'string' && /\d+\:\d+/.test( autoHeight ) ) { // use ratio ratio = autoHeight.match(/(\d+)\:(\d+)/); ratio = ratio[1] / ratio[2]; opts._autoHeightRatio = ratio; } // if autoHeight is a number then we don't need to recalculate the sentinel // index on resize if ( t !== 'number' ) { // bind unique resize handler per slideshow (so it can be 'off-ed' in onDestroy) opts._autoHeightOnResize = function () { clearTimeout( resizeThrottle ); resizeThrottle = setTimeout( onResize, 50 ); }; $(window).on( 'resize orientationchange', opts._autoHeightOnResize ); } setTimeout( onResize, 30 ); function onResize() { initAutoHeight( e, opts ); } }); function initAutoHeight( e, opts ) { var clone, height, sentinelIndex; var autoHeight = opts.autoHeight; if ( autoHeight == 'container' ) { height = $( opts.slides[ opts.currSlide ] ).outerHeight(); opts.container.height( height ); } else if ( opts._autoHeightRatio ) { opts.container.height( opts.container.width() / opts._autoHeightRatio ); } else if ( autoHeight === 'calc' || ( $.type( autoHeight ) == 'number' && autoHeight >= 0 ) ) { if ( autoHeight === 'calc' ) sentinelIndex = calcSentinelIndex( e, opts ); else if ( autoHeight >= opts.slides.length ) sentinelIndex = 0; else sentinelIndex = autoHeight; // only recreate sentinel if index is different if ( sentinelIndex == opts._sentinelIndex ) return; opts._sentinelIndex = sentinelIndex; if ( opts._sentinel ) opts._sentinel.remove(); // clone existing slide as sentinel clone = $( opts.slides[ sentinelIndex ].cloneNode(true) ); // #50; remove special attributes from cloned content clone.removeAttr( 'id name rel' ).find( '[id],[name],[rel]' ).removeAttr( 'id name rel' ); clone.css({ position: 'static', visibility: 'hidden', display: 'block' }).prependTo( opts.container ).addClass('cycle-sentinel cycle-slide').removeClass('cycle-slide-active'); clone.find( '*' ).css( 'visibility', 'hidden' ); opts._sentinel = clone; } } function calcSentinelIndex( e, opts ) { var index = 0, max = -1; // calculate tallest slide index opts.slides.each(function(i) { var h = $(this).height(); if ( h > max ) { max = h; index = i; } }); return index; } function onBefore( e, opts, outgoing, incoming, forward ) { var h = $(incoming).outerHeight(); opts.container.animate( { height: h }, opts.autoHeightSpeed, opts.autoHeightEasing ); } function onDestroy( e, opts ) { if ( opts._autoHeightOnResize ) { $(window).off( 'resize orientationchange', opts._autoHeightOnResize ); opts._autoHeightOnResize = null; } opts.container.off( 'cycle-slide-added cycle-slide-removed', initAutoHeight ); opts.container.off( 'cycle-destroyed', onDestroy ); opts.container.off( 'cycle-before', onBefore ); if ( opts._sentinel ) { opts._sentinel.remove(); opts._sentinel = null; } } })(jQuery); /*! caption plugin for Cycle2; version: 20130306 */ (function($) { "use strict"; $.extend($.fn.cycle.defaults, { caption: '> .cycle-caption', captionTemplate: '{{slideNum}} / {{slideCount}}', overlay: '> .cycle-overlay', overlayTemplate: '<div>{{title}}</div><div>{{desc}}</div>', captionModule: 'caption' }); $(document).on( 'cycle-update-view', function( e, opts, slideOpts, currSlide ) { if ( opts.captionModule !== 'caption' ) return; var el; $.each(['caption','overlay'], function() { var name = this; var template = slideOpts[name+'Template']; var el = opts.API.getComponent( name ); if( el.length && template ) { el.html( opts.API.tmpl( template, slideOpts, opts, currSlide ) ); el.show(); } else { el.hide(); } }); }); $(document).on( 'cycle-destroyed', function( e, opts ) { var el; $.each(['caption','overlay'], function() { var name = this, template = opts[name+'Template']; if ( opts[name] && template ) { el = opts.API.getComponent( 'caption' ); el.empty(); } }); }); })(jQuery); /*! command plugin for Cycle2; version: 20130707 */ (function($) { "use strict"; var c2 = $.fn.cycle; $.fn.cycle = function( options ) { var cmd, cmdFn, opts; var args = $.makeArray( arguments ); if ( $.type( options ) == 'number' ) { return this.cycle( 'goto', options ); } if ( $.type( options ) == 'string' ) { return this.each(function() { var cmdArgs; cmd = options; opts = $(this).data('cycle.opts'); if ( opts === undefined ) { c2.log('slideshow must be initialized before sending commands; "' + cmd + '" ignored'); return; } else { cmd = cmd == 'goto' ? 'jump' : cmd; // issue #3; change 'goto' to 'jump' internally cmdFn = opts.API[ cmd ]; if ( $.isFunction( cmdFn )) { cmdArgs = $.makeArray( args ); cmdArgs.shift(); return cmdFn.apply( opts.API, cmdArgs ); } else { c2.log( 'unknown command: ', cmd ); } } }); } else { return c2.apply( this, arguments ); } }; // copy props $.extend( $.fn.cycle, c2 ); $.extend( c2.API, { next: function() { var opts = this.opts(); if ( opts.busy && ! opts.manualTrump ) return; var count = opts.reverse ? -1 : 1; if ( opts.allowWrap === false && ( opts.currSlide + count ) >= opts.slideCount ) return; opts.API.advanceSlide( count ); opts.API.trigger('cycle-next', [ opts ]).log('cycle-next'); }, prev: function() { var opts = this.opts(); if ( opts.busy && ! opts.manualTrump ) return; var count = opts.reverse ? 1 : -1; if ( opts.allowWrap === false && ( opts.currSlide + count ) < 0 ) return; opts.API.advanceSlide( count ); opts.API.trigger('cycle-prev', [ opts ]).log('cycle-prev'); }, destroy: function() { this.stop(); //#204 var opts = this.opts(); var clean = $.isFunction( $._data ) ? $._data : $.noop; // hack for #184 and #201 clearTimeout(opts.timeoutId); opts.timeoutId = 0; opts.API.stop(); opts.API.trigger( 'cycle-destroyed', [ opts ] ).log('cycle-destroyed'); opts.container.removeData(); clean( opts.container[0], 'parsedAttrs', false ); // #75; remove inline styles if ( ! opts.retainStylesOnDestroy ) { opts.container.removeAttr( 'style' ); opts.slides.removeAttr( 'style' ); opts.slides.removeClass( opts.slideActiveClass ); } opts.slides.each(function() { $(this).removeData(); clean( this, 'parsedAttrs', false ); }); }, jump: function( index ) { // go to the requested slide var fwd; var opts = this.opts(); if ( opts.busy && ! opts.manualTrump ) return; var num = parseInt( index, 10 ); if (isNaN(num) || num < 0 || num >= opts.slides.length) { opts.API.log('goto: invalid slide index: ' + num); return; } if (num == opts.currSlide) { opts.API.log('goto: skipping, already on slide', num); return; } opts.nextSlide = num; clearTimeout(opts.timeoutId); opts.timeoutId = 0; opts.API.log('goto: ', num, ' (zero-index)'); fwd = opts.currSlide < opts.nextSlide; opts.API.prepareTx( true, fwd ); }, stop: function() { var opts = this.opts(); var pauseObj = opts.container; clearTimeout(opts.timeoutId); opts.timeoutId = 0; opts.API.stopTransition(); if ( opts.pauseOnHover ) { if ( opts.pauseOnHover !== true ) pauseObj = $( opts.pauseOnHover ); pauseObj.off('mouseenter mouseleave'); } opts.API.trigger('cycle-stopped', [ opts ]).log('cycle-stopped'); }, reinit: function() { var opts = this.opts(); opts.API.destroy(); opts.container.cycle(); }, remove: function( index ) { var opts = this.opts(); var slide, slideToRemove, slides = [], slideNum = 1; for ( var i=0; i < opts.slides.length; i++ ) { slide = opts.slides[i]; if ( i == index ) { slideToRemove = slide; } else { slides.push( slide ); $( slide ).data('cycle.opts').slideNum = slideNum; slideNum++; } } if ( slideToRemove ) { opts.slides = $( slides ); opts.slideCount--; $( slideToRemove ).remove(); if (index == opts.currSlide) opts.API.advanceSlide( 1 ); else if ( index < opts.currSlide ) opts.currSlide--; else opts.currSlide++; opts.API.trigger('cycle-slide-removed', [ opts, index, slideToRemove ]).log('cycle-slide-removed'); opts.API.updateView(); } } }); // listen for clicks on elements with data-cycle-cmd attribute $(document).on('click.cycle', '[data-cycle-cmd]', function(e) { // issue cycle command e.preventDefault(); var el = $(this); var command = el.data('cycle-cmd'); var context = el.data('cycle-context') || '.cycle-slideshow'; $(context).cycle(command, el.data('cycle-arg')); }); })(jQuery); /*! hash plugin for Cycle2; version: 20130905 */ (function($) { "use strict"; $(document).on( 'cycle-pre-initialize', function( e, opts ) { onHashChange( opts, true ); opts._onHashChange = function() { onHashChange( opts, false ); }; $( window ).on( 'hashchange', opts._onHashChange); }); $(document).on( 'cycle-update-view', function( e, opts, slideOpts ) { if ( slideOpts.hash && ( '#' + slideOpts.hash ) != window.location.hash ) { opts._hashFence = true; window.location.hash = slideOpts.hash; } }); $(document).on( 'cycle-destroyed', function( e, opts) { if ( opts._onHashChange ) { $( window ).off( 'hashchange', opts._onHashChange ); } }); function onHashChange( opts, setStartingSlide ) { var hash; if ( opts._hashFence ) { opts._hashFence = false; return; } hash = window.location.hash.substring(1); opts.slides.each(function(i) { if ( $(this).data( 'cycle-hash' ) == hash ) { if ( setStartingSlide === true ) { opts.startingSlide = i; } else { var fwd = opts.currSlide < i; opts.nextSlide = i; opts.API.prepareTx( true, fwd ); } return false; } }); } })(jQuery); /*! loader plugin for Cycle2; version: 20131121 */ (function($) { "use strict"; $.extend($.fn.cycle.defaults, { loader: false }); $(document).on( 'cycle-bootstrap', function( e, opts ) { var addFn; if ( !opts.loader ) return; // override API.add for this slideshow addFn = opts.API.add; opts.API.add = add; function add( slides, prepend ) { var slideArr = []; if ( $.type( slides ) == 'string' ) slides = $.trim( slides ); else if ( $.type( slides) === 'array' ) { for (var i=0; i < slides.length; i++ ) slides[i] = $(slides[i])[0]; } slides = $( slides ); var slideCount = slides.length; if ( ! slideCount ) return; slides.css('visibility','hidden').appendTo('body').each(function(i) { // appendTo fixes #56 var count = 0; var slide = $(this); var images = slide.is('img') ? slide : slide.find('img'); slide.data('index', i); // allow some images to be marked as unimportant (and filter out images w/o src value) images = images.filter(':not(.cycle-loader-ignore)').filter(':not([src=""])'); if ( ! images.length ) { --slideCount; slideArr.push( slide ); return; } count = images.length; images.each(function() { // add images that are already loaded if ( this.complete ) { imageLoaded(); } else { $(this).load(function() { imageLoaded(); }).on("error", function() { if ( --count === 0 ) { // ignore this slide opts.API.log('slide skipped; img not loaded:', this.src); if ( --slideCount === 0 && opts.loader == 'wait') { addFn.apply( opts.API, [ slideArr, prepend ] ); } } }); } }); function imageLoaded() { if ( --count === 0 ) { --slideCount; addSlide( slide ); } } }); if ( slideCount ) opts.container.addClass('cycle-loading'); function addSlide( slide ) { var curr; if ( opts.loader == 'wait' ) { slideArr.push( slide ); if ( slideCount === 0 ) { // #59; sort slides into original markup order slideArr.sort( sorter ); addFn.apply( opts.API, [ slideArr, prepend ] ); opts.container.removeClass('cycle-loading'); } } else { curr = $(opts.slides[opts.currSlide]); addFn.apply( opts.API, [ slide, prepend ] ); curr.show(); opts.container.removeClass('cycle-loading'); } } function sorter(a, b) { return a.data('index') - b.data('index'); } } }); })(jQuery); /*! pager plugin for Cycle2; version: 20140324 */ (function($) { "use strict"; $.extend($.fn.cycle.defaults, { pager: '> .cycle-pager', pagerActiveClass: 'cycle-pager-active', pagerEvent: 'click.cycle', pagerEventBubble: undefined, pagerTemplate: '<span>&bull;</span>' }); $(document).on( 'cycle-bootstrap', function( e, opts, API ) { // add method to API API.buildPagerLink = buildPagerLink; }); $(document).on( 'cycle-slide-added', function( e, opts, slideOpts, slideAdded ) { if ( opts.pager ) { opts.API.buildPagerLink ( opts, slideOpts, slideAdded ); opts.API.page = page; } }); $(document).on( 'cycle-slide-removed', function( e, opts, index, slideRemoved ) { if ( opts.pager ) { var pagers = opts.API.getComponent( 'pager' ); pagers.each(function() { var pager = $(this); $( pager.children()[index] ).remove(); }); } }); $(document).on( 'cycle-update-view', function( e, opts, slideOpts ) { var pagers; if ( opts.pager ) { pagers = opts.API.getComponent( 'pager' ); pagers.each(function() { $(this).children().removeClass( opts.pagerActiveClass ) .eq( opts.currSlide ).addClass( opts.pagerActiveClass ); }); } }); $(document).on( 'cycle-destroyed', function( e, opts ) { var pager = opts.API.getComponent( 'pager' ); if ( pager ) { pager.children().off( opts.pagerEvent ); // #202 if ( opts.pagerTemplate ) pager.empty(); } }); function buildPagerLink( opts, slideOpts, slide ) { var pagerLink; var pagers = opts.API.getComponent( 'pager' ); pagers.each(function() { var pager = $(this); if ( slideOpts.pagerTemplate ) { var markup = opts.API.tmpl( slideOpts.pagerTemplate, slideOpts, opts, slide[0] ); pagerLink = $( markup ).appendTo( pager ); } else { pagerLink = pager.children().eq( opts.slideCount - 1 ); } pagerLink.on( opts.pagerEvent, function(e) { if ( ! opts.pagerEventBubble ) e.preventDefault(); opts.API.page( pager, e.currentTarget); }); }); } function page( pager, target ) { /*jshint validthis:true */ var opts = this.opts(); if ( opts.busy && ! opts.manualTrump ) return; var index = pager.children().index( target ); var nextSlide = index; var fwd = opts.currSlide < nextSlide; if (opts.currSlide == nextSlide) { return; // no op, clicked pager for the currently displayed slide } opts.nextSlide = nextSlide; opts.API.prepareTx( true, fwd ); opts.API.trigger('cycle-pager-activated', [opts, pager, target ]); } })(jQuery); /*! prevnext plugin for Cycle2; version: 20130709 */ (function($) { "use strict"; $.extend($.fn.cycle.defaults, { next: '> .cycle-next', nextEvent: 'click.cycle', disabledClass: 'disabled', prev: '> .cycle-prev', prevEvent: 'click.cycle', swipe: false }); $(document).on( 'cycle-initialized', function( e, opts ) { opts.API.getComponent( 'next' ).on( opts.nextEvent, function(e) { e.preventDefault(); opts.API.next(); }); opts.API.getComponent( 'prev' ).on( opts.prevEvent, function(e) { e.preventDefault(); opts.API.prev(); }); if ( opts.swipe ) { var nextEvent = opts.swipeVert ? 'swipeUp.cycle' : 'swipeLeft.cycle swipeleft.cycle'; var prevEvent = opts.swipeVert ? 'swipeDown.cycle' : 'swipeRight.cycle swiperight.cycle'; opts.container.on( nextEvent, function(e) { opts.API.next(); }); opts.container.on( prevEvent, function() { opts.API.prev(); }); } }); $(document).on( 'cycle-update-view', function( e, opts, slideOpts, currSlide ) { if ( opts.allowWrap ) return; var cls = opts.disabledClass; var next = opts.API.getComponent( 'next' ); var prev = opts.API.getComponent( 'prev' ); var prevBoundry = opts._prevBoundry || 0; var nextBoundry = (opts._nextBoundry !== undefined)?opts._nextBoundry:opts.slideCount - 1; if ( opts.currSlide == nextBoundry ) next.addClass( cls ).prop( 'disabled', true ); else next.removeClass( cls ).prop( 'disabled', false ); if ( opts.currSlide === prevBoundry ) prev.addClass( cls ).prop( 'disabled', true ); else prev.removeClass( cls ).prop( 'disabled', false ); }); $(document).on( 'cycle-destroyed', function( e, opts ) { opts.API.getComponent( 'prev' ).off( opts.nextEvent ); opts.API.getComponent( 'next' ).off( opts.prevEvent ); opts.container.off( 'swipeleft.cycle swiperight.cycle swipeLeft.cycle swipeRight.cycle swipeUp.cycle swipeDown.cycle' ); }); })(jQuery); /*! progressive loader plugin for Cycle2; version: 20130315 */ (function($) { "use strict"; $.extend($.fn.cycle.defaults, { progressive: false }); $(document).on( 'cycle-pre-initialize', function( e, opts ) { if ( !opts.progressive ) return; var API = opts.API; var nextFn = API.next; var prevFn = API.prev; var prepareTxFn = API.prepareTx; var type = $.type( opts.progressive ); var slides, scriptEl; if ( type == 'array' ) { slides = opts.progressive; } else if ($.isFunction( opts.progressive ) ) { slides = opts.progressive( opts ); } else if ( type == 'string' ) { scriptEl = $( opts.progressive ); slides = $.trim( scriptEl.html() ); if ( !slides ) return; // is it json array? if ( /^(\[)/.test( slides ) ) { try { slides = $.parseJSON( slides ); } catch(err) { API.log( 'error parsing progressive slides', err ); return; } } else { // plain text, split on delimeter slides = slides.split( new RegExp( scriptEl.data('cycle-split') || '\n') ); // #95; look for empty slide if ( ! slides[ slides.length - 1 ] ) slides.pop(); } } if ( prepareTxFn ) { API.prepareTx = function( manual, fwd ) { var index, slide; if ( manual || slides.length === 0 ) { prepareTxFn.apply( opts.API, [ manual, fwd ] ); return; } if ( fwd && opts.currSlide == ( opts.slideCount-1) ) { slide = slides[ 0 ]; slides = slides.slice( 1 ); opts.container.one('cycle-slide-added', function(e, opts ) { setTimeout(function() { opts.API.advanceSlide( 1 ); },50); }); opts.API.add( slide ); } else if ( !fwd && opts.currSlide === 0 ) { index = slides.length-1; slide = slides[ index ]; slides = slides.slice( 0, index ); opts.container.one('cycle-slide-added', function(e, opts ) { setTimeout(function() { opts.currSlide = 1; opts.API.advanceSlide( -1 ); },50); }); opts.API.add( slide, true ); } else { prepareTxFn.apply( opts.API, [ manual, fwd ] ); } }; } if ( nextFn ) { API.next = function() { var opts = this.opts(); if ( slides.length && opts.currSlide == ( opts.slideCount - 1 ) ) { var slide = slides[ 0 ]; slides = slides.slice( 1 ); opts.container.one('cycle-slide-added', function(e, opts ) { nextFn.apply( opts.API ); opts.container.removeClass('cycle-loading'); }); opts.container.addClass('cycle-loading'); opts.API.add( slide ); } else { nextFn.apply( opts.API ); } }; } if ( prevFn ) { API.prev = function() { var opts = this.opts(); if ( slides.length && opts.currSlide === 0 ) { var index = slides.length-1; var slide = slides[ index ]; slides = slides.slice( 0, index ); opts.container.one('cycle-slide-added', function(e, opts ) { opts.currSlide = 1; opts.API.advanceSlide( -1 ); opts.container.removeClass('cycle-loading'); }); opts.container.addClass('cycle-loading'); opts.API.add( slide, true ); } else { prevFn.apply( opts.API ); } }; } }); })(jQuery); /*! tmpl plugin for Cycle2; version: 20121227 */ (function($) { "use strict"; $.extend($.fn.cycle.defaults, { tmplRegex: '{{((.)?.*?)}}' }); $.extend($.fn.cycle.API, { tmpl: function( str, opts /*, ... */) { var regex = new RegExp( opts.tmplRegex || $.fn.cycle.defaults.tmplRegex, 'g' ); var args = $.makeArray( arguments ); args.shift(); return str.replace(regex, function(_, str) { var i, j, obj, prop, names = str.split('.'); for (i=0; i < args.length; i++) { obj = args[i]; if ( ! obj ) continue; if (names.length > 1) { prop = obj; for (j=0; j < names.length; j++) { obj = prop; prop = prop[ names[j] ] || str; } } else { prop = obj[str]; } if ($.isFunction(prop)) return prop.apply(obj, args); if (prop !== undefined && prop !== null && prop != str) return prop; } return str; }); } }); })(jQuery);
gpl-2.0
cunningt/camel
camel-core/src/main/java/org/apache/camel/impl/DefaultRouteStartupOrder.java
2498
/** * 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.camel.impl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.camel.Consumer; import org.apache.camel.Route; import org.apache.camel.Service; import org.apache.camel.spi.RouteStartupOrder; /** * Default implementation of {@link org.apache.camel.spi.RouteStartupOrder}. * * @version */ public class DefaultRouteStartupOrder implements RouteStartupOrder { private final int startupOrder; private final Route route; private final RouteService routeService; public DefaultRouteStartupOrder(int startupOrder, Route route, RouteService routeService) { this.startupOrder = startupOrder; this.route = route; this.routeService = routeService; } public int getStartupOrder() { return startupOrder; } public Route getRoute() { return route; } public List<Consumer> getInputs() { List<Consumer> answer = new ArrayList<Consumer>(); Map<Route, Consumer> inputs = routeService.getInputs(); for (Consumer consumer : inputs.values()) { answer.add(consumer); } return answer; } public List<Service> getServices() { List<Service> answer = new ArrayList<Service>(); Collection<Route> routes = routeService.getRoutes(); for (Route route : routes) { answer.addAll(route.getServices()); } return answer; } public RouteService getRouteService() { return routeService; } @Override public String toString() { return "Route " + route.getId() + " starts in order " + startupOrder; } }
apache-2.0
gvijayarangan/newcasseldev2
vendor/symfony/console/Tests/Style/SymfonyStyleTest.php
2135
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Console\Tests\Style; use PHPUnit_Framework_TestCase; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Console\Tester\CommandTester; class SymfonyStyleTest extends PHPUnit_Framework_TestCase { /** @var Command */ protected $command; /** @var CommandTester */ protected $tester; protected function setUp() { $this->command = new Command('sfstyle'); $this->tester = new CommandTester($this->command); } protected function tearDown() { $this->command = null; $this->tester = null; } /** * @dataProvider inputCommandToOutputFilesProvider */ public function testOutputs($inputCommandFilepath, $outputFilepath) { $code = require $inputCommandFilepath; $this->command->setCode($code); $this->tester->execute(array(), array('interactive' => false, 'decorated' => false)); $this->assertStringEqualsFile($outputFilepath, $this->tester->getDisplay(true)); } public function inputCommandToOutputFilesProvider() { $baseDir = __DIR__.'/../Fixtures/Style/SymfonyStyle'; return array_map(null, glob($baseDir.'/command/command_*.php'), glob($baseDir.'/output/output_*.txt')); } } /** * Use this class in tests to force the line length * and ensure a consistent output for expectations. */ class SymfonyStyleWithForcedLineLength extends SymfonyStyle { public function __construct(InputInterface $input, OutputInterface $output) { parent::__construct($input, $output); $ref = new \ReflectionProperty(get_parent_class($this), 'lineLength'); $ref->setAccessible(true); $ref->setValue($this, 120); } }
mit
akrabat/zf1
library/Zend/Session/Abstract.php
6001
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Session * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ * @since Preview Release 0.2 */ /** * Zend_Session_Abstract * * @category Zend * @package Zend_Session * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Session_Abstract { /** * Whether or not session permits writing (modification of $_SESSION[]) * * @var bool */ protected static $_writable = false; /** * Whether or not session permits reading (reading data in $_SESSION[]) * * @var bool */ protected static $_readable = false; /** * Since expiring data is handled at startup to avoid __destruct difficulties, * the data that will be expiring at end of this request is held here * * @var array */ protected static $_expiringData = array(); /** * Error message thrown when an action requires modification, * but current Zend_Session has been marked as read-only. */ const _THROW_NOT_WRITABLE_MSG = 'Zend_Session is currently marked as read-only.'; /** * Error message thrown when an action requires reading session data, * but current Zend_Session is not marked as readable. */ const _THROW_NOT_READABLE_MSG = 'Zend_Session is not marked as readable.'; /** * namespaceIsset() - check to see if a namespace or a variable within a namespace is set * * @param string $namespace * @param string $name * @return bool */ protected static function _namespaceIsset($namespace, $name = null) { if (self::$_readable === false) { /** * @see Zend_Session_Exception */ require_once 'Zend/Session/Exception.php'; throw new Zend_Session_Exception(self::_THROW_NOT_READABLE_MSG); } if ($name === null) { return ( isset($_SESSION[$namespace]) || isset(self::$_expiringData[$namespace]) ); } else { return ( isset($_SESSION[$namespace][$name]) || isset(self::$_expiringData[$namespace][$name]) ); } } /** * namespaceUnset() - unset a namespace or a variable within a namespace * * @param string $namespace * @param string $name * @throws Zend_Session_Exception * @return void */ protected static function _namespaceUnset($namespace, $name = null) { if (self::$_writable === false) { /** * @see Zend_Session_Exception */ require_once 'Zend/Session/Exception.php'; throw new Zend_Session_Exception(self::_THROW_NOT_WRITABLE_MSG); } $name = (string) $name; // check to see if the api wanted to remove a var from a namespace or a namespace if ($name === '') { unset($_SESSION[$namespace]); unset(self::$_expiringData[$namespace]); } else { unset($_SESSION[$namespace][$name]); unset(self::$_expiringData[$namespace][$name]); } // if we remove the last value, remove namespace. if (empty($_SESSION[$namespace])) { unset($_SESSION[$namespace]); } } /** * namespaceGet() - Get $name variable from $namespace, returning by reference. * * @param string $namespace * @param string $name * @return mixed */ protected static function & _namespaceGet($namespace, $name = null) { if (self::$_readable === false) { /** * @see Zend_Session_Exception */ require_once 'Zend/Session/Exception.php'; throw new Zend_Session_Exception(self::_THROW_NOT_READABLE_MSG); } if ($name === null) { if (isset($_SESSION[$namespace])) { // check session first for data requested return $_SESSION[$namespace]; } elseif (isset(self::$_expiringData[$namespace])) { // check expiring data for data reqeusted return self::$_expiringData[$namespace]; } else { return $_SESSION[$namespace]; // satisfy return by reference } } else { if (isset($_SESSION[$namespace][$name])) { // check session first return $_SESSION[$namespace][$name]; } elseif (isset(self::$_expiringData[$namespace][$name])) { // check expiring data return self::$_expiringData[$namespace][$name]; } else { return $_SESSION[$namespace][$name]; // satisfy return by reference } } } /** * namespaceGetAll() - Get an array containing $namespace, including expiring data. * * @param string $namespace * @param string $name * @return mixed */ protected static function _namespaceGetAll($namespace) { $currentData = (isset($_SESSION[$namespace]) && is_array($_SESSION[$namespace])) ? $_SESSION[$namespace] : array(); $expiringData = (isset(self::$_expiringData[$namespace]) && is_array(self::$_expiringData[$namespace])) ? self::$_expiringData[$namespace] : array(); return array_merge($currentData, $expiringData); } }
bsd-3-clause
getstackd/stackd
vendor/boost-context/tools/build/v2/test/qt4/qtmultimedia.cpp
825
// (c) Copyright Juergen Hunold 2009 // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #define BOOST_TEST_MODULE QtMultimedia #include <QAudioDeviceInfo> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE( defines) { BOOST_CHECK_EQUAL(BOOST_IS_DEFINED(QT_CORE_LIB), true); BOOST_CHECK_EQUAL(BOOST_IS_DEFINED(QT_GUI_LIB), true); BOOST_CHECK_EQUAL(BOOST_IS_DEFINED(QT_MULTIMEDIA_LIB), true); } BOOST_AUTO_TEST_CASE( audiodevices) { QList<QAudioDeviceInfo> devices = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput); for(int i = 0; i < devices.size(); ++i) { BOOST_TEST_MESSAGE(QAudioDeviceInfo(devices.at(i)).deviceName().constData()); } }
mit
ICML14MoMCompare/spectral-learn
code/tensor/cpp/include/boost/preprocessor/iterate.hpp
747
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_ITERATE_HPP # define BOOST_PREPROCESSOR_ITERATE_HPP # # include <boost/preprocessor/iteration/iterate.hpp> # # endif
apache-2.0
MuShiiii/java-design-patterns
event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java
289
package com.iluwatar.event.aggregator; /** * * KingJoffrey observes events from {@link KingsHand}. * */ public class KingJoffrey implements EventObserver { @Override public void onEvent(Event e) { System.out.println("Received event from the King's Hand: " + e.toString()); } }
mit
JosueR1518/DaseDeDatosTarea
vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/PostUpdate.php
1115
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\ORM\Mapping; /** * @Annotation * @Target("METHOD") */ final class PostUpdate implements Annotation { }
mit
joelsmith/kubernetes
test/integration/node/main_test.go
716
/* Copyright 2020 The Kubernetes 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 node import ( "testing" "k8s.io/kubernetes/test/integration/framework" ) func TestMain(m *testing.M) { framework.EtcdMain(m.Run) }
apache-2.0
manuelh9r/camel
components/camel-krati/src/main/java/org/apache/camel/component/krati/serializer/KratiDefaultSerializer.java
3926
/** * 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.camel.component.krati.serializer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.Serializable; import krati.io.SerializationException; import krati.io.Serializer; import org.apache.camel.util.IOHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KratiDefaultSerializer<T extends Serializable> implements Serializer<T> { private static final Logger LOG = LoggerFactory.getLogger(KratiDefaultSerializer.class); /** * Serialize an object into a byte array. * * @param object - an object to be serialized by this Serializer. * @return a byte array which is the raw representation of an object. */ public byte[] serialize(T object) throws SerializationException { byte[] result = null; if (object == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(object); result = baos.toByteArray(); } catch (IOException e) { LOG.warn("Error while serializing object. Null will be used.", e); } finally { IOHelper.close(oos, baos); } return result; } /** * Deserialize an object from its raw bytes generated by {{@link #serialize(Object)}. * * @param binary - the raw bytes from which an object is constructed. * @return an object constructed from the raw bytes. * @throws SerializationException if the object cannot be constructed from the raw bytes. */ @SuppressWarnings("unchecked") public T deserialize(byte[] binary) throws SerializationException { T result = null; ObjectInputStream ois = null; if (binary == null) { return null; } // TODO: should use Camel's ClassResolver for classloading ByteArrayInputStream bais = new ByteArrayInputStream(binary); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { ois = new ObjectInputStream(bais) { @Override public Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { try { return classLoader.loadClass(desc.getName()); } catch (Exception e) { } return super.resolveClass(desc); } }; result = (T) ois.readObject(); } catch (IOException e) { LOG.warn("Error while deserializing object. Null will be used.", e); } catch (ClassNotFoundException e) { LOG.warn("Could not find class while deserializing object. Null will be used.", e); } finally { IOHelper.close(ois, bais); } return result; } }
apache-2.0
todojudo/todojudo
administrator/components/com_users/views/users/tmpl/default_batch.php
1462
<?php /** * @package Joomla.Administrator * @subpackage com_content * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // no direct access defined('_JEXEC') or die; // Create the copy/move options. $options = array( JHtml::_('select.option', 'add', JText::_('COM_USERS_BATCH_ADD')), JHtml::_('select.option', 'del', JText::_('COM_USERS_BATCH_DELETE')), JHtml::_('select.option', 'set', JText::_('COM_USERS_BATCH_SET')) ); ?> <fieldset class="batch"> <legend><?php echo JText::_('COM_USERS_BATCH_OPTIONS');?></legend> <label id="batch-choose-action-lbl" for="batch-choose-action"><?php echo JText::_('COM_USERS_BATCH_GROUP') ?></label> <fieldset id="batch-choose-action" class="combo"> <select name="batch[group_id]" class="inputbox" id="batch-group-id"> <option value=""><?php echo JText::_('JSELECT') ?></option> <?php echo JHtml::_('select.options', JHtml::_('user.groups', JFactory::getUser()->get('isRoot'))); ?> </select> <?php echo JHtml::_('select.radiolist', $options, 'batch[group_action]', '', 'value', 'text', 'add') ?> </fieldset> <button type="submit" onclick="Joomla.submitbutton('user.batch');"> <?php echo JText::_('JGLOBAL_BATCH_PROCESS'); ?> </button> <button type="button" onclick="document.id('batch-group-id').value=''"> <?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?> </button> </fieldset>
gpl-2.0
ssmaciel/PhoneGap
HellowHordPhoneGap/HellowHordPhoneGap/app/platforms/android/CordovaLib/src/com/squareup/okhttp/Connection.java
10405
/* * 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.squareup.okhttp; import com.squareup.okhttp.internal.Platform; import com.squareup.okhttp.internal.http.HttpAuthenticator; import com.squareup.okhttp.internal.http.HttpEngine; import com.squareup.okhttp.internal.http.HttpTransport; import com.squareup.okhttp.internal.http.RawHeaders; import com.squareup.okhttp.internal.http.SpdyTransport; import com.squareup.okhttp.internal.spdy.SpdyConnection; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Proxy; import java.net.Socket; import java.net.URL; import java.util.Arrays; import javax.net.ssl.SSLSocket; import static java.net.HttpURLConnection.HTTP_OK; import static java.net.HttpURLConnection.HTTP_PROXY_AUTH; /** * Holds the sockets and streams of an HTTP, HTTPS, or HTTPS+SPDY connection, * which may be used for multiple HTTP request/response exchanges. Connections * may be direct to the origin server or via a proxy. * * <p>Typically instances of this class are created, connected and exercised * automatically by the HTTP client. Applications may use this class to monitor * HTTP connections as members of a {@link ConnectionPool connection pool}. * * <p>Do not confuse this class with the misnamed {@code HttpURLConnection}, * which isn't so much a connection as a single request/response exchange. * * <h3>Modern TLS</h3> * There are tradeoffs when selecting which options to include when negotiating * a secure connection to a remote host. Newer TLS options are quite useful: * <ul> * <li>Server Name Indication (SNI) enables one IP address to negotiate secure * connections for multiple domain names. * <li>Next Protocol Negotiation (NPN) enables the HTTPS port (443) to be used * for both HTTP and SPDY transports. * </ul> * Unfortunately, older HTTPS servers refuse to connect when such options are * presented. Rather than avoiding these options entirely, this class allows a * connection to be attempted with modern options and then retried without them * should the attempt fail. */ public final class Connection implements Closeable { private static final byte[] NPN_PROTOCOLS = new byte[] { 6, 's', 'p', 'd', 'y', '/', '3', 8, 'h', 't', 't', 'p', '/', '1', '.', '1' }; private static final byte[] SPDY3 = new byte[] { 's', 'p', 'd', 'y', '/', '3' }; private static final byte[] HTTP_11 = new byte[] { 'h', 't', 't', 'p', '/', '1', '.', '1' }; private final Route route; private Socket socket; private InputStream in; private OutputStream out; private boolean connected = false; private SpdyConnection spdyConnection; private int httpMinorVersion = 1; // Assume HTTP/1.1 private long idleStartTimeNs; public Connection(Route route) { this.route = route; } public void connect(int connectTimeout, int readTimeout, TunnelRequest tunnelRequest) throws IOException { if (connected) { throw new IllegalStateException("already connected"); } connected = true; socket = (route.proxy.type() != Proxy.Type.HTTP) ? new Socket(route.proxy) : new Socket(); socket.connect(route.inetSocketAddress, connectTimeout); socket.setSoTimeout(readTimeout); in = socket.getInputStream(); out = socket.getOutputStream(); if (route.address.sslSocketFactory != null) { upgradeToTls(tunnelRequest); } // Use MTU-sized buffers to send fewer packets. int mtu = Platform.get().getMtu(socket); in = new BufferedInputStream(in, mtu); out = new BufferedOutputStream(out, mtu); } /** * Create an {@code SSLSocket} and perform the TLS handshake and certificate * validation. */ private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException { Platform platform = Platform.get(); // Make an SSL Tunnel on the first message pair of each SSL + proxy connection. if (requiresTunnel()) { makeTunnel(tunnelRequest); } // Create the wrapper over connected socket. socket = route.address.sslSocketFactory .createSocket(socket, route.address.uriHost, route.address.uriPort, true /* autoClose */); SSLSocket sslSocket = (SSLSocket) socket; if (route.modernTls) { platform.enableTlsExtensions(sslSocket, route.address.uriHost); } else { platform.supportTlsIntolerantServer(sslSocket); } if (route.modernTls) { platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS); } // Force handshake. This can throw! sslSocket.startHandshake(); // Verify that the socket's certificates are acceptable for the target host. if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) { throw new IOException("Hostname '" + route.address.uriHost + "' was not verified"); } out = sslSocket.getOutputStream(); in = sslSocket.getInputStream(); byte[] selectedProtocol; if (route.modernTls && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) { if (Arrays.equals(selectedProtocol, SPDY3)) { sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream. spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out) .build(); } else if (!Arrays.equals(selectedProtocol, HTTP_11)) { throw new IOException( "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1")); } } } /** Returns true if {@link #connect} has been attempted on this connection. */ public boolean isConnected() { return connected; } @Override public void close() throws IOException { socket.close(); } /** Returns the route used by this connection. */ public Route getRoute() { return route; } /** * Returns the socket that this connection uses, or null if the connection * is not currently connected. */ public Socket getSocket() { return socket; } /** Returns true if this connection is alive. */ public boolean isAlive() { return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown(); } public void resetIdleStartTime() { if (spdyConnection != null) { throw new IllegalStateException("spdyConnection != null"); } this.idleStartTimeNs = System.nanoTime(); } /** Returns true if this connection is idle. */ public boolean isIdle() { return spdyConnection == null || spdyConnection.isIdle(); } /** * Returns true if this connection has been idle for longer than * {@code keepAliveDurationNs}. */ public boolean isExpired(long keepAliveDurationNs) { return isIdle() && System.nanoTime() - getIdleStartTimeNs() > keepAliveDurationNs; } /** * Returns the time in ns when this connection became idle. Undefined if * this connection is not idle. */ public long getIdleStartTimeNs() { return spdyConnection == null ? idleStartTimeNs : spdyConnection.getIdleStartTimeNs(); } /** Returns the transport appropriate for this connection. */ public Object newTransport(HttpEngine httpEngine) throws IOException { return (spdyConnection != null) ? new SpdyTransport(httpEngine, spdyConnection) : new HttpTransport(httpEngine, out, in); } /** * Returns true if this is a SPDY connection. Such connections can be used * in multiple HTTP requests simultaneously. */ public boolean isSpdy() { return spdyConnection != null; } public SpdyConnection getSpdyConnection() { return spdyConnection; } /** * Returns the minor HTTP version that should be used for future requests on * this connection. Either 0 for HTTP/1.0, or 1 for HTTP/1.1. The default * value is 1 for new connections. */ public int getHttpMinorVersion() { return httpMinorVersion; } public void setHttpMinorVersion(int httpMinorVersion) { this.httpMinorVersion = httpMinorVersion; } /** * Returns true if the HTTP connection needs to tunnel one protocol over * another, such as when using HTTPS through an HTTP proxy. When doing so, * we must avoid buffering bytes intended for the higher-level protocol. */ public boolean requiresTunnel() { return route.address.sslSocketFactory != null && route.proxy.type() == Proxy.Type.HTTP; } /** * To make an HTTPS connection over an HTTP proxy, send an unencrypted * CONNECT request to create the proxy connection. This may need to be * retried if the proxy requires authorization. */ private void makeTunnel(TunnelRequest tunnelRequest) throws IOException { RawHeaders requestHeaders = tunnelRequest.getRequestHeaders(); while (true) { out.write(requestHeaders.toBytes()); RawHeaders responseHeaders = RawHeaders.fromBytes(in); switch (responseHeaders.getResponseCode()) { case HTTP_OK: return; case HTTP_PROXY_AUTH: requestHeaders = new RawHeaders(requestHeaders); URL url = new URL("https", tunnelRequest.host, tunnelRequest.port, "/"); boolean credentialsFound = HttpAuthenticator.processAuthHeader(HTTP_PROXY_AUTH, responseHeaders, requestHeaders, route.proxy, url); if (credentialsFound) { continue; } else { throw new IOException("Failed to authenticate with proxy"); } default: throw new IOException( "Unexpected response code for CONNECT: " + responseHeaders.getResponseCode()); } } } }
apache-2.0
danielneis/moodle
blocks/tags/classes/privacy/provider.php
1497
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Privacy Subsystem implementation for block_tags. * * @package block_tags * @copyright 2018 Zig Tan <zig@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace block_tags\privacy; defined('MOODLE_INTERNAL') || die(); /** * Privacy Subsystem for block_tags implementing null_provider. * * @copyright 2018 Zig Tan <zig@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class provider implements \core_privacy\local\metadata\null_provider { /** * Get the language string identifier with the component's language * file to explain why this plugin stores no data. * * @return string */ public static function get_reason() : string { return 'privacy:metadata'; } }
gpl-3.0
ragmani/coreclr
tests/src/JIT/Regression/VS-ia64-JIT/V1.2-M02/b108129/test2.cs
2184
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; namespace JitTest.HFA { public class TestCase { [DllImport("test2", EntryPoint = "GetInt32Const")] public static extern int GetInt32Const(); [DllImport("test2", EntryPoint = "GetInt64Const")] public static extern long GetInt64Const(); [DllImport("test2", EntryPoint = "GetFloatConst")] public static extern float GetFloatConst(); [DllImport("test2", EntryPoint = "GetDoubleConst")] public static extern double GetDoubleConst(); private static int Main() { System.Console.WriteLine("Int32 Const = " + GetInt32Const()); System.Console.WriteLine("Int64 Const = " + GetInt64Const()); System.Console.WriteLine("Float Const = " + GetFloatConst()); System.Console.WriteLine("Double Const = " + GetDoubleConst()); if (GetInt32Const() != 7) { System.Console.WriteLine("FAILED: GetInt32Const()!=7"); System.Console.WriteLine("GetInt32Const() is {0}", GetInt32Const()); return 1; } if (GetInt64Const() != 7) { System.Console.WriteLine("FAILED: GetInt64Const()!=7"); System.Console.WriteLine("GetInt64Const() is {0}", GetInt64Const()); return 1; } if ((GetFloatConst() - 7.777777) > 0.5) { System.Console.WriteLine("FAILED: (GetFloatConst()-7.777777)>0.5"); System.Console.WriteLine("GetFloatConst() is {0}", GetFloatConst()); return 1; } if ((GetDoubleConst() - 7.777777) > 0.5) { System.Console.WriteLine("FAILED: (GetDoubleConst()-7.777777)>0.5"); System.Console.WriteLine("GetDoubleConst() is {0}", GetDoubleConst()); return 1; } return 100; } } }
mit
grshane/monthofmud
web/themes/custom/mom/node_modules/parker/node_modules/minimist/index.js
5504
module.exports = function (args, opts) { if (!opts) opts = {}; var flags = { bools : {}, strings : {} }; [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { flags.bools[key] = true; }); [].concat(opts.string).filter(Boolean).forEach(function (key) { flags.strings[key] = true; }); var aliases = {}; Object.keys(opts.alias || {}).forEach(function (key) { aliases[key] = [].concat(opts.alias[key]); aliases[key].forEach(function (x) { aliases[x] = [key].concat(aliases[key].filter(function (y) { return x !== y; })); }); }); var defaults = opts['default'] || {}; var argv = { _ : [] }; Object.keys(flags.bools).forEach(function (key) { setArg(key, defaults[key] === undefined ? false : defaults[key]); }); var notFlags = []; if (args.indexOf('--') !== -1) { notFlags = args.slice(args.indexOf('--')+1); args = args.slice(0, args.indexOf('--')); } function setArg (key, val) { var value = !flags.strings[key] && isNumber(val) ? Number(val) : val ; setKey(argv, key.split('.'), value); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), value); }); } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (/^--.+=/.test(arg)) { // Using [\s\S] instead of . because js doesn't support the // 'dotall' regex modifier. See: // http://stackoverflow.com/a/1068308/13216 var m = arg.match(/^--([^=]+)=([\s\S]*)$/); setArg(m[1], m[2]); } else if (/^--no-.+/.test(arg)) { var key = arg.match(/^--no-(.+)/)[1]; setArg(key, false); } else if (/^--.+/.test(arg)) { var key = arg.match(/^--(.+)/)[1]; var next = args[i + 1]; if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && (aliases[key] ? !flags.bools[aliases[key]] : true)) { setArg(key, next); i++; } else if (/^(true|false)$/.test(next)) { setArg(key, next === 'true'); i++; } else { setArg(key, true); } } else if (/^-[^-]+/.test(arg)) { var letters = arg.slice(1,-1).split(''); var broken = false; for (var j = 0; j < letters.length; j++) { var next = arg.slice(j+2); if (next === '-') { setArg(letters[j], next) continue; } if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { setArg(letters[j], next); broken = true; break; } if (letters[j+1] && letters[j+1].match(/\W/)) { setArg(letters[j], arg.slice(j+2)); broken = true; break; } else { setArg(letters[j], true); } } var key = arg.slice(-1)[0]; if (!broken && key !== '-') { if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) && !flags.bools[key] && (aliases[key] ? !flags.bools[aliases[key]] : true)) { setArg(key, args[i+1]); i++; } else if (args[i+1] && /true|false/.test(args[i+1])) { setArg(key, args[i+1] === 'true'); i++; } else { setArg(key, true); } } } else { argv._.push( flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) ); } } Object.keys(defaults).forEach(function (key) { if (!hasKey(argv, key.split('.'))) { setKey(argv, key.split('.'), defaults[key]); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), defaults[key]); }); } }); notFlags.forEach(function(key) { argv._.push(key); }); return argv; }; function hasKey (obj, keys) { var o = obj; keys.slice(0,-1).forEach(function (key) { o = (o[key] || {}); }); var key = keys[keys.length - 1]; return key in o; } function setKey (obj, keys, value) { var o = obj; keys.slice(0,-1).forEach(function (key) { if (o[key] === undefined) o[key] = {}; o = o[key]; }); var key = keys[keys.length - 1]; if (o[key] === undefined || typeof o[key] === 'boolean') { o[key] = value; } else if (Array.isArray(o[key])) { o[key].push(value); } else { o[key] = [ o[key], value ]; } } function isNumber (x) { if (typeof x === 'number') return true; if (/^0x[0-9a-f]+$/i.test(x)) return true; return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); } function longest (xs) { return Math.max.apply(null, xs.map(function (x) { return x.length })); }
mit
tillahoffmann/tensorflow
tensorflow/contrib/linear_optimizer/python/ops/sharded_mutable_dense_hashtable_test.py
4456
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for sharded_mutable_dense_hashtable.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.linear_optimizer.python.ops.sharded_mutable_dense_hashtable import ShardedMutableDenseHashTable from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework.test_util import TensorFlowTestCase from tensorflow.python.platform import googletest class ShardedMutableDenseHashTableTest(TensorFlowTestCase): """Tests for the ShardedMutableHashTable class.""" def testShardedMutableHashTable(self): for num_shards in [1, 3, 10]: with self.test_session(): default_val = -1 empty_key = 0 keys = constant_op.constant([11, 12, 13], dtypes.int64) values = constant_op.constant([0, 1, 2], dtypes.int64) table = ShardedMutableDenseHashTable( dtypes.int64, dtypes.int64, default_val, empty_key, num_shards=num_shards) self.assertAllEqual(0, table.size().eval()) table.insert(keys, values).run() self.assertAllEqual(3, table.size().eval()) input_string = constant_op.constant([11, 12, 14], dtypes.int64) output = table.lookup(input_string) self.assertAllEqual([3], output.get_shape()) self.assertAllEqual([0, 1, -1], output.eval()) def testShardedMutableHashTableVectors(self): for num_shards in [1, 3, 10]: with self.test_session(): default_val = [-0.1, 0.2] empty_key = [0, 1] keys = constant_op.constant([[11, 12], [13, 14], [15, 16]], dtypes.int64) values = constant_op.constant([[0.5, 0.6], [1.5, 1.6], [2.5, 2.6]], dtypes.float32) table = ShardedMutableDenseHashTable( dtypes.int64, dtypes.float32, default_val, empty_key, num_shards=num_shards) self.assertAllEqual(0, table.size().eval()) table.insert(keys, values).run() self.assertAllEqual(3, table.size().eval()) input_string = constant_op.constant([[11, 12], [13, 14], [11, 14]], dtypes.int64) output = table.lookup(input_string) self.assertAllEqual([3, 2], output.get_shape()) self.assertAllClose([[0.5, 0.6], [1.5, 1.6], [-0.1, 0.2]], output.eval()) def testExportSharded(self): with self.test_session(): empty_key = -2 default_val = -1 num_shards = 2 keys = constant_op.constant([10, 11, 12], dtypes.int64) values = constant_op.constant([2, 3, 4], dtypes.int64) table = ShardedMutableDenseHashTable( dtypes.int64, dtypes.int64, default_val, empty_key, num_shards=num_shards) self.assertAllEqual(0, table.size().eval()) table.insert(keys, values).run() self.assertAllEqual(3, table.size().eval()) keys_list, values_list = table.export_sharded() self.assertAllEqual(num_shards, len(keys_list)) self.assertAllEqual(num_shards, len(values_list)) # Exported keys include empty key buckets set to the empty_key self.assertAllEqual(set([-2, 10, 12]), set(keys_list[0].eval().flatten())) self.assertAllEqual(set([-2, 11]), set(keys_list[1].eval().flatten())) # Exported values include empty value buckets set to 0 self.assertAllEqual(set([0, 2, 4]), set(values_list[0].eval().flatten())) self.assertAllEqual(set([0, 3]), set(values_list[1].eval().flatten())) if __name__ == '__main__': googletest.main()
apache-2.0
CodeDJ/qt5-hidpi
qt/qtwebkit/Source/WebCore/svg/SVGFontFaceNameElement.cpp
1570
/* * Copyright (C) 2007 Eric Seidel <eric@webkit.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #if ENABLE(SVG_FONTS) #include "SVGFontFaceNameElement.h" #include "CSSFontFaceSrcValue.h" #include "SVGNames.h" namespace WebCore { inline SVGFontFaceNameElement::SVGFontFaceNameElement(const QualifiedName& tagName, Document* document) : SVGElement(tagName, document) { ASSERT(hasTagName(SVGNames::font_face_nameTag)); } PassRefPtr<SVGFontFaceNameElement> SVGFontFaceNameElement::create(const QualifiedName& tagName, Document* document) { return adoptRef(new SVGFontFaceNameElement(tagName, document)); } PassRefPtr<CSSFontFaceSrcValue> SVGFontFaceNameElement::srcValue() const { return CSSFontFaceSrcValue::createLocal(fastGetAttribute(SVGNames::nameAttr)); } } #endif // ENABLE(SVG)
lgpl-2.1
jonobr1/cdnjs
ajax/libs/element-ui/1.2.2/locale/ru-RU.js
3115
(function (global, factory) { if (typeof define === "function" && define.amd) { define('element/locale/ru-RU', ['module', 'exports'], factory); } else if (typeof exports !== "undefined") { factory(module, exports); } else { var mod = { exports: {} }; factory(mod, mod.exports); global.ELEMENT.lang = global.ELEMENT.lang || {}; global.ELEMENT.lang.ruRU = mod.exports; } })(this, function (module, exports) { 'use strict'; exports.__esModule = true; exports.default = { el: { colorpicker: { confirm: 'OK', clear: 'Очистить' }, datepicker: { now: 'Сейчас', today: 'Сегодня', cancel: 'Отмена', clear: 'Очистить', confirm: 'OK', selectDate: 'Выбрать дату', selectTime: 'Выбрать время', startDate: 'Дата начала', startTime: 'Время начала', endDate: 'Дата окончания', endTime: 'Время окончания', year: '', month1: 'Январь', month2: 'Февраль', month3: 'Март', month4: 'Апрель', month5: 'Май', month6: 'Июнь', month7: 'Июль', month8: 'Август', month9: 'Сентябрь', month10: 'Октябрь', month11: 'Ноябрь', month12: 'Декабрь', // week: 'week', weeks: { sun: 'Вс', mon: 'Пн', tue: 'Вт', wed: 'Ср', thu: 'Чт', fri: 'Пт', sat: 'Сб' }, months: { jan: 'Янв', feb: 'Фев', mar: 'Мар', apr: 'Апр', may: 'Май', jun: 'Июн', jul: 'Июл', aug: 'Авг', sep: 'Сен', oct: 'Окт', nov: 'Ноя', dec: 'Дек' } }, select: { loading: 'Загрузка', noMatch: 'Совпадений не найдено', noData: 'Нет данных', placeholder: 'Выбрать' }, cascader: { noMatch: 'Совпадений не найдено', placeholder: 'Выбрать' }, pagination: { goto: 'Перейти', pagesize: '/page', total: 'Всего {total}', pageClassifier: '' }, messagebox: { title: 'Сообщение', confirm: 'OK', cancel: 'Отмена', error: 'Недопустимый ввод данных' }, upload: { delete: 'Удалить', preview: 'Превью', continue: 'Продолжить' }, table: { emptyText: 'Нет данных', confirmFilter: 'Подтвердить', resetFilter: 'Сбросить', clearFilter: 'Все' }, tree: { emptyText: 'Нет данных' } } }; module.exports = exports['default']; });
mit
yizhang82/coreclr
tests/src/GC/Scenarios/SingLinkList/singlinkstay.cs
3782
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************** /*Test case for testing GC with cyclic single linked list leaks /*In every loop. SetLink() to create a SingLink object array whose size /*is iRep, each SingLink Object is a iObj node cyclic single /*linked list. MakeLeak() deletes all the object reference in the array /*to make all the cyclic single linked lists become memory leaks. /******************************************************************/ namespace SingLink { using System; public class SingLinkStay { internal SingLink []Mv_Sing; public static int Main(System.String [] Args) { int iRep = 0; int iObj = 0; Console.WriteLine("Test should return with ExitCode 100 ..."); switch( Args.Length ) { case 1: if (!Int32.TryParse( Args[0], out iRep )) { iRep = 100; } break; case 2: if (!Int32.TryParse( Args[0], out iRep )) { iRep = 100; } if (!Int32.TryParse( Args[1], out iObj )) { iObj = 10; } break; default: iRep = 100; iObj = 10; break; } SingLinkStay Mv_Leak = new SingLinkStay(); if(Mv_Leak.runTest(iRep, iObj )) { Console.WriteLine( "Test Passed" ); return 100; } else { Console.WriteLine( "Test Failed" ); return 1; } } public bool runTest(int iRep, int iObj) { for(int i=0; i<20; i++) { SetLink(iRep, iObj); MakeLeak(iRep); } return true; } public void SetLink(int iRep, int iObj) { Mv_Sing = new SingLink[iRep]; for(int i=0; i<iRep; i++) { Mv_Sing[i] = new SingLink(iObj); } } public void MakeLeak(int iRep) { for(int i=0; i<iRep; i++) { Mv_Sing[i] = null; } } } public class LinkNode { // disabling unused variable warning #pragma warning disable 0414 internal LinkNode Last; internal int[] Size; #pragma warning restore 0414 public static int FinalCount = 0; ~LinkNode() { FinalCount++; } public LinkNode(int SizeNum, LinkNode LastObject) { Last = LastObject; Size = new int[SizeNum * 1024]; } } public class SingLink { internal LinkNode[] Mv_SLink; public SingLink(int Num) { Mv_SLink = new LinkNode[Num]; if (Num == 0) { return; } if (Num == 1) { Mv_SLink[0] = new LinkNode(1, Mv_SLink[0]); } else { Mv_SLink[0] = new LinkNode(1, Mv_SLink[Num - 1]); } for (int i = 1; i < Num - 1; i++) { Mv_SLink[i] = new LinkNode((i + 1), Mv_SLink[i - 1]); } Mv_SLink[Num - 1] = new LinkNode(Num, Mv_SLink[0]); } } }
mit
baptistecosta/apigility
config/autoload/zfconfig.global.php
295
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ return array( 'view_manager' => array( 'strategies' => array( 'ViewJsonStrategy', ), ), );
bsd-3-clause
jonathangizmo/HadoopDistJ
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/AppState.java
1355
/** * 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.hadoop.yarn.server.resourcemanager.webapp.dao; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "appstate") @XmlAccessorType(XmlAccessType.FIELD) public class AppState { String state; public AppState() { } public AppState(String state) { this.state = state; } public void setState(String state) { this.state = state; } public String getState() { return this.state; } }
mit
MavenRain/Windows-universal-samples
Samples/AnimationLibrary/js/js/sample-configuration.js
1930
//// Copyright (c) Microsoft Corporation. All rights reserved (function () { "use strict"; var sampleTitle = "Animation library JS sample"; var scenarios = [ { url: "/html/enterPage.html", title: "Show page" }, { url: "/html/transitionPages.html", title: "Transition between pages" }, { url: "/html/enterContent.html", title: "Show content" }, { url: "/html/transitionContents.html", title: "Transition between content" }, { url: "/html/expandAndCollapse.html", title: "Expand and collapse" }, { url: "/html/pointerFeedback.html", title: "Tap and click feedback" }, { url: "/html/addAndDeleteFromList.html", title: "Add and remove from list" }, { url: "/html/filterSearchList.html", title: "Filter search list" }, { url: "/html/fadeInAndOut.html", title: "Fade in and out" }, { url: "/html/crossfade.html", title: "Crossfade" }, { url: "/html/reposition.html", title: "Reposition" }, { url: "/html/dragAndDrop.html", title: "Drag and drop" }, { url: "/html/dragBetween.html", title: "Drag between to reorder" }, { url: "/html/showPopupUI.html", title: "Show pop-up UI" }, { url: "/html/showEdgeUI.html", title: "Show edge UI" }, { url: "/html/showPanel.html", title: "Show panel" }, { url: "/html/swipeReveal.html", title: "Reveal ability to swipe" }, { url: "/html/swipeSelection.html", title: "Swipe select and deselect" }, { url: "/html/updateBadge.html", title: "Update a badge" }, { url: "/html/updateTile.html", title: "Update a tile" }, { url: "/html/customAnimation.html", title: "Run a custom animation" }, { url: "/html/disableAnimations.html", title: "Disable animations" } ]; WinJS.Namespace.define("SdkSample", { sampleTitle: sampleTitle, scenarios: new WinJS.Binding.List(scenarios) }); })();
mit
ICJIA/icjia-public-website
sitedev/infographic2/node_modules/globule/node_modules/lodash/isObjectLike.js
608
/** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike;
mit
mitchlloyd/guides
source/javascripts/common-old-ie.js
56
//= require vendor/jquery-1.11.2 //= require common-all
mit
emmy41124/cdnjs
ajax/libs/angular-strap/2.0.0-rc.3/modules/date-parser.js
5723
/** * angular-strap * @version v2.0.0-rc.3 - 2014-02-10 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes (olivier@mg-crea.com) * @license MIT License, http://www.opensource.org/licenses/MIT */ 'use strict'; angular.module('mgcrea.ngStrap.helpers.dateParser', []).provider('$dateParser', [ '$localeProvider', function ($localeProvider) { var proto = Date.prototype; function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } var defaults = this.defaults = { format: 'shortDate', strict: false }; this.$get = [ '$locale', function ($locale) { var DateParserFactory = function (config) { var options = angular.extend({}, defaults, config); var $dateParser = {}; var regExpMap = { 'sss': '[0-9]{3}', 'ss': '[0-5][0-9]', 's': options.strict ? '[1-5]?[0-9]' : '[0-5][0-9]', 'mm': '[0-5][0-9]', 'm': options.strict ? '[1-5]?[0-9]' : '[0-5][0-9]', 'HH': '[01][0-9]|2[0-3]', 'H': options.strict ? '[0][1-9]|[1][012]' : '[01][0-9]|2[0-3]', 'hh': '[0][1-9]|[1][012]', 'h': options.strict ? '[1-9]|[1][012]' : '[0]?[1-9]|[1][012]', 'a': 'AM|PM', 'EEEE': $locale.DATETIME_FORMATS.DAY.join('|'), 'EEE': $locale.DATETIME_FORMATS.SHORTDAY.join('|'), 'dd': '[0-2][0-9]{1}|[3][01]{1}', 'd': options.strict ? '[1-2]?[0-9]{1}|[3][01]{1}' : '[0-2][0-9]{1}|[3][01]{1}', 'MMMM': $locale.DATETIME_FORMATS.MONTH.join('|'), 'MMM': $locale.DATETIME_FORMATS.SHORTMONTH.join('|'), 'MM': '[0][1-9]|[1][012]', 'M': options.strict ? '[1-9]|[1][012]' : '[0][1-9]|[1][012]', 'yyyy': '(?:(?:[1]{1}[0-9]{1}[0-9]{1}[0-9]{1})|(?:[2]{1}[0-9]{3}))(?![[0-9]])', 'yy': '(?:(?:[0-9]{1}[0-9]{1}))(?![[0-9]])' }; var setFnMap = { 'sss': proto.setMilliseconds, 'ss': proto.setSeconds, 's': proto.setSeconds, 'mm': proto.setMinutes, 'm': proto.setMinutes, 'HH': proto.setHours, 'H': proto.setHours, 'hh': proto.setHours, 'h': proto.setHours, 'dd': proto.setDate, 'd': proto.setDate, 'a': function (value) { var hours = this.getHours(); return this.setHours(value.match(/pm/i) ? hours + 12 : hours); }, 'MMMM': function (value) { return this.setMonth($locale.DATETIME_FORMATS.MONTH.indexOf(value)); }, 'MMM': function (value) { return this.setMonth($locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value)); }, 'MM': function (value) { return this.setMonth(1 * value - 1); }, 'M': function (value) { return this.setMonth(1 * value - 1); }, 'yyyy': proto.setFullYear, 'yy': function (value) { return this.setFullYear(2000 + 1 * value); }, 'y': proto.setFullYear }; var regex, setMap; $dateParser.init = function () { $dateParser.$format = $locale.DATETIME_FORMATS[options.format] || options.format; regex = regExpForFormat($dateParser.$format); setMap = setMapForFormat($dateParser.$format); }; $dateParser.isValid = function (date) { if (angular.isDate(date)) return !isNaN(date.getTime()); return regex.test(date); }; $dateParser.parse = function (value, baseDate) { if (angular.isDate(value)) return value; var matches = regex.exec(value); if (!matches) return false; var date = baseDate || new Date(0); for (var i = 0; i < matches.length - 1; i++) { setMap[i] && setMap[i].call(date, matches[i + 1]); } return date; }; function setMapForFormat(format) { var keys = Object.keys(setFnMap), i; var map = [], sortedMap = []; var clonedFormat = format; for (i = 0; i < keys.length; i++) { if (format.split(keys[i]).length > 1) { var index = clonedFormat.search(keys[i]); format = format.split(keys[i]).join(''); if (setFnMap[keys[i]]) map[index] = setFnMap[keys[i]]; } } angular.forEach(map, function (v) { sortedMap.push(v); }); return sortedMap; } function escapeReservedSymbols(text) { return text.replace(/\//g, '[\\/]').replace('/-/g', '[-]').replace(/\./g, '[.]').replace(/\\s/g, '[\\s]'); } function regExpForFormat(format) { var keys = Object.keys(regExpMap), i; var re = format; for (i = 0; i < keys.length; i++) { re = re.split(keys[i]).join('${' + i + '}'); } for (i = 0; i < keys.length; i++) { re = re.split('${' + i + '}').join('(' + regExpMap[keys[i]] + ')'); } format = escapeReservedSymbols(format); return new RegExp('^' + re + '$', ['i']); } $dateParser.init(); return $dateParser; }; return DateParserFactory; } ]; } ]);
mit
pshelton-skype/gocd
server/webapp/WEB-INF/rails.new/vendor/bundle/jruby/1.9/gems/arel-4.0.2/test/visitors/test_mssql.rb
2724
require 'helper' module Arel module Visitors describe 'the mssql visitor' do before do @visitor = MSSQL.new Table.engine.connection @table = Arel::Table.new "users" end it 'should not modify query if no offset or limit' do stmt = Nodes::SelectStatement.new sql = @visitor.accept(stmt) sql.must_be_like "SELECT" end it 'should go over table PK if no .order() or .group()' do stmt = Nodes::SelectStatement.new stmt.cores.first.from = @table stmt.limit = Nodes::Limit.new(10) sql = @visitor.accept(stmt) sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY \"users\".\"id\") as _row_num FROM \"users\" ) as _t WHERE _row_num BETWEEN 1 AND 10" end it 'should go over query ORDER BY if .order()' do stmt = Nodes::SelectStatement.new stmt.limit = Nodes::Limit.new(10) stmt.orders << Nodes::SqlLiteral.new('order_by') sql = @visitor.accept(stmt) sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY order_by) as _row_num) as _t WHERE _row_num BETWEEN 1 AND 10" end it 'should go over query GROUP BY if no .order() and there is .group()' do stmt = Nodes::SelectStatement.new stmt.cores.first.groups << Nodes::SqlLiteral.new('group_by') stmt.limit = Nodes::Limit.new(10) sql = @visitor.accept(stmt) sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY group_by) as _row_num GROUP BY group_by) as _t WHERE _row_num BETWEEN 1 AND 10" end it 'should use BETWEEN if both .limit() and .offset' do stmt = Nodes::SelectStatement.new stmt.limit = Nodes::Limit.new(10) stmt.offset = Nodes::Offset.new(20) sql = @visitor.accept(stmt) sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY ) as _row_num) as _t WHERE _row_num BETWEEN 21 AND 30" end it 'should use >= if only .offset' do stmt = Nodes::SelectStatement.new stmt.offset = Nodes::Offset.new(20) sql = @visitor.accept(stmt) sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY ) as _row_num) as _t WHERE _row_num >= 21" end it 'should generate subquery for .count' do stmt = Nodes::SelectStatement.new stmt.limit = Nodes::Limit.new(10) stmt.cores.first.projections << Nodes::Count.new('*') sql = @visitor.accept(stmt) sql.must_be_like "SELECT COUNT(1) as count_id FROM (SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY ) as _row_num) as _t WHERE _row_num BETWEEN 1 AND 10) AS subquery" end end end end
apache-2.0
laurenceHR/cdnjs
ajax/libs/angular-strap/2.0.0-beta.3/angular-strap.js
78460
/** * angular-strap * @version v2.0.0-beta.3 - 2014-01-15 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes <olivier@mg-crea.com> * @license MIT License, http://www.opensource.org/licenses/MIT */ (function (window, document, $, undefined) { 'use strict'; angular.module('mgcrea.ngStrap', [ 'mgcrea.ngStrap.modal', 'mgcrea.ngStrap.aside', 'mgcrea.ngStrap.alert', 'mgcrea.ngStrap.button', 'mgcrea.ngStrap.select', 'mgcrea.ngStrap.navbar', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.popover', 'mgcrea.ngStrap.dropdown', 'mgcrea.ngStrap.typeahead', 'mgcrea.ngStrap.scrollspy', 'mgcrea.ngStrap.affix', 'mgcrea.ngStrap.tab' ]); angular.module('mgcrea.ngStrap.affix', ['mgcrea.ngStrap.helpers.dimensions']).provider('$affix', function () { var defaults = this.defaults = { offsetTop: 'auto' }; this.$get = [ '$window', 'dimensions', function ($window, dimensions) { var windowEl = angular.element($window); var bodyEl = angular.element($window.document.body); function AffixFactory(element, config) { var $affix = {}; var options = angular.extend({}, defaults, config); var reset = 'affix affix-top affix-bottom', initialAffixTop = 0, initialOffsetTop = 0, affixed = null, unpin = null; var parent = element.parent(); if (options.offsetParent) { if (options.offsetParent.match(/^\d+$/)) { for (var i = 0; i < options.offsetParent * 1 - 1; i++) { parent = parent.parent(); } } else { parent = angular.element(options.offsetParent); } } var offsetTop = 0; if (options.offsetTop) { if (options.offsetTop === 'auto') { options.offsetTop = '+0'; } if (options.offsetTop.match(/^[-+]\d+$/)) { initialAffixTop -= options.offsetTop * 1; if (options.offsetParent) { offsetTop = dimensions.offset(parent[0]).top + options.offsetTop * 1; } else { offsetTop = dimensions.offset(element[0]).top - dimensions.css(element[0], 'marginTop', true) + options.offsetTop * 1; } } else { offsetTop = options.offsetTop * 1; } } var offsetBottom = 0; if (options.offsetBottom) { if (options.offsetParent && options.offsetBottom.match(/^[-+]\d+$/)) { offsetBottom = $window.document.body.scrollHeight - (dimensions.offset(parent[0]).top + dimensions.height(parent[0])) + options.offsetBottom * 1 + 1; } else { offsetBottom = options.offsetBottom * 1; } } $affix.init = function () { initialOffsetTop = dimensions.offset(element[0]).top + initialAffixTop; windowEl.on('scroll', this.checkPosition); windowEl.on('click', this.checkPositionWithEventLoop); this.checkPosition(); this.checkPositionWithEventLoop(); }; $affix.destroy = function () { windowEl.off('scroll', this.checkPosition); windowEl.off('click', this.checkPositionWithEventLoop); }; $affix.checkPositionWithEventLoop = function () { setTimeout(this.checkPosition, 1); }; $affix.checkPosition = function () { var scrollTop = $window.pageYOffset; var position = dimensions.offset(element[0]); var elementHeight = dimensions.height(element[0]); var affix = getRequiredAffixClass(unpin, position, elementHeight); if (affixed === affix) return; affixed = affix; element.removeClass(reset).addClass('affix' + (affix !== 'middle' ? '-' + affix : '')); if (affix === 'top') { unpin = null; element.css('position', options.offsetParent ? '' : 'relative'); element.css('top', ''); } else if (affix === 'bottom') { if (options.offsetUnpin) { unpin = -(options.offsetUnpin * 1); } else { unpin = position.top - scrollTop; } element.css('position', options.offsetParent ? '' : 'relative'); element.css('top', options.offsetParent ? '' : bodyEl[0].offsetHeight - offsetBottom - elementHeight - initialOffsetTop + 'px'); } else { unpin = null; element.css('position', 'fixed'); element.css('top', initialAffixTop + 'px'); } }; function getRequiredAffixClass(unpin, position, elementHeight) { var scrollTop = $window.pageYOffset; var scrollHeight = $window.document.body.scrollHeight; if (scrollTop <= offsetTop) { return 'top'; } else if (unpin !== null && scrollTop + unpin <= position.top) { return 'middle'; } else if (offsetBottom !== null && position.top + elementHeight + initialAffixTop >= scrollHeight - offsetBottom) { return 'bottom'; } else { return 'middle'; } } $affix.init(); return $affix; } return AffixFactory; } ]; }).directive('bsAffix', [ '$affix', 'dimensions', function ($affix, dimensions) { return { restrict: 'EAC', link: function postLink(scope, element, attr) { var options = { scope: scope, offsetTop: 'auto' }; angular.forEach([ 'offsetTop', 'offsetBottom', 'offsetParent', 'offsetUnpin' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); var affix = $affix(element, options); scope.$on('$destroy', function () { options = null; affix = null; }); } }; } ]); angular.module('mgcrea.ngStrap.alert', []).run([ '$templateCache', function ($templateCache) { var template = '' + '<div class="alert" tabindex="-1" ng-class="[type ? \'alert-\' + type : null]">' + '<button type="button" class="close" ng-click="$hide()">&times;</button>' + '<strong ng-bind="title"></strong>&nbsp;<span ng-bind-html="content"></span>' + '</div>'; $templateCache.put('$alert', template); } ]).provider('$alert', function () { var defaults = this.defaults = { animation: 'animation-fade', prefixClass: 'alert', placement: null, template: '$alert', container: false, element: null, backdrop: false, keyboard: true, show: true, duration: false }; this.$get = [ '$modal', '$timeout', function ($modal, $timeout) { function AlertFactory(config) { var $alert = {}; var options = angular.extend({}, defaults, config); $alert = $modal(options); if (!options.scope) { angular.forEach(['type'], function (key) { if (options[key]) $alert.$scope[key] = options[key]; }); } var show = $alert.show; if (options.duration) { $alert.show = function () { show(); $timeout(function () { $alert.hide(); }, options.duration * 1000); }; } return $alert; } return AlertFactory; } ]; }).directive('bsAlert', [ '$window', '$location', '$sce', '$alert', function ($window, $location, $sce, $alert) { var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; return { restrict: 'EAC', scope: true, link: function postLink(scope, element, attr, transclusion) { var options = { scope: scope, element: element, show: false }; angular.forEach([ 'template', 'placement', 'keyboard', 'html', 'container', 'animation', 'duration' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); angular.forEach([ 'title', 'content', 'type' ], function (key) { attr[key] && attr.$observe(key, function (newValue, oldValue) { scope[key] = newValue; }); }); attr.bsAlert && scope.$watch(attr.bsAlert, function (newValue, oldValue) { if (angular.isObject(newValue)) { angular.extend(scope, newValue); } else { scope.content = newValue; } }, true); var alert = $alert(options); element.on(attr.trigger || 'click', alert.toggle); scope.$on('$destroy', function () { alert.destroy(); options = null; alert = null; }); } }; } ]); angular.module('mgcrea.ngStrap.aside', ['mgcrea.ngStrap.modal']).run([ '$templateCache', function ($templateCache) { var template = '' + '<div class="aside" tabindex="-1" role="dialog">' + '<div class="aside-dialog">' + '<div class="aside-content">' + '<div class="aside-header" ng-show="title">' + '<button type="button" class="close" ng-click="$hide()">&times;</button>' + '<h4 class="aside-title" ng-bind="title"></h4>' + '</div>' + '<div class="aside-body" ng-show="content" ng-bind="content"></div>' + '<div class="aside-footer">' + '<button type="button" class="btn btn-default" ng-click="$hide()">Close</button>' + '</div>' + '</div>' + '</div>' + '</div>'; $templateCache.put('$aside', template); } ]).provider('$aside', function () { var defaults = this.defaults = { animation: 'animation-fadeAndSlideRight', prefixClass: 'aside', placement: 'right', template: '$aside', container: false, element: null, backdrop: true, keyboard: true, html: false, show: true }; this.$get = [ '$modal', function ($modal) { function AsideFactory(config) { var $aside = {}; var options = angular.extend({}, defaults, config); $aside = $modal(options); return $aside; } return AsideFactory; } ]; }).directive('bsAside', [ '$window', '$location', '$sce', '$aside', function ($window, $location, $sce, $aside) { var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; return { restrict: 'EAC', scope: true, link: function postLink(scope, element, attr, transclusion) { var options = { scope: scope, element: element, show: false }; angular.forEach([ 'template', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); angular.forEach([ 'title', 'content' ], function (key) { attr[key] && attr.$observe(key, function (newValue, oldValue) { scope[key] = newValue; }); }); attr.bsAside && scope.$watch(attr.bsAside, function (newValue, oldValue) { if (angular.isObject(newValue)) { angular.extend(scope, newValue); } else { scope.content = newValue; } }, true); var aside = $aside(options); element.on(attr.trigger || 'click', aside.toggle); scope.$on('$destroy', function () { aside.destroy(); options = null; aside = null; }); } }; } ]); angular.module('mgcrea.ngStrap.button', []).provider('$button', function () { var defaults = this.defaults = { activeClass: 'active', toggleEvent: 'click' }; this.$get = function () { return { defaults: defaults }; }; }).directive('bsCheckboxGroup', function () { return { restrict: 'A', require: 'ngModel', compile: function postLink(element, attr) { element.attr('data-toggle', 'buttons'); element.removeAttr('ng-model'); var children = element[0].querySelectorAll('input[type="checkbox"]'); angular.forEach(children, function (child) { var childEl = angular.element(child); childEl.attr('bs-checkbox', ''); childEl.attr('ng-model', attr.ngModel + '.' + childEl.attr('value')); }); } }; }).directive('bsCheckbox', [ '$button', function ($button) { var defaults = $button.defaults; var constantValueRegExp = /^(true|false|\d+)$/; return { restrict: 'A', require: 'ngModel', link: function postLink(scope, element, attr, controller) { var options = defaults; var isInput = element[0].nodeName === 'INPUT'; var activeElement = isInput ? element.parent() : element; var trueValue = angular.isDefined(attr.trueValue) ? attr.trueValue : true; if (constantValueRegExp.test(attr.trueValue)) { trueValue = scope.$eval(attr.trueValue); } var falseValue = angular.isDefined(attr.falseValue) ? attr.falseValue : false; if (constantValueRegExp.test(attr.falseValue)) { falseValue = scope.$eval(attr.falseValue); } var hasExoticValues = typeof trueValue !== 'boolean' || typeof falseValue !== 'boolean'; if (hasExoticValues) { controller.$parsers.push(function (viewValue) { return viewValue ? trueValue : falseValue; }); scope.$watch(attr.ngModel, function (newValue, oldValue) { controller.$render(); }); } controller.$render = function () { var isActive = angular.equals(controller.$modelValue, trueValue); if (isInput) { element[0].checked = isActive; } activeElement.toggleClass(options.activeClass, isActive); }; element.bind(options.toggleEvent, function () { scope.$apply(function () { if (!isInput) { controller.$setViewValue(!activeElement.hasClass('active')); } if (!hasExoticValues) { controller.$render(); } }); }); } }; } ]).directive('bsRadioGroup', function () { return { restrict: 'A', require: 'ngModel', compile: function postLink(element, attr) { element.attr('data-toggle', 'buttons'); element.removeAttr('ng-model'); var children = element[0].querySelectorAll('input[type="radio"]'); angular.forEach(children, function (child) { angular.element(child).attr('bs-radio', ''); angular.element(child).attr('ng-model', attr.ngModel); }); } }; }).directive('bsRadio', [ '$button', function ($button) { var defaults = $button.defaults; var constantValueRegExp = /^(true|false|\d+)$/; return { restrict: 'A', require: 'ngModel', link: function postLink(scope, element, attr, controller) { var options = defaults; var isInput = element[0].nodeName === 'INPUT'; var activeElement = isInput ? element.parent() : element; var value = constantValueRegExp.test(attr.value) ? scope.$eval(attr.value) : attr.value; controller.$render = function () { var isActive = angular.equals(controller.$modelValue, value); if (isInput) { element[0].checked = isActive; } activeElement.toggleClass(options.activeClass, isActive); }; element.bind(options.toggleEvent, function () { scope.$apply(function () { controller.$setViewValue(value); controller.$render(); }); }); } }; } ]); angular.module('mgcrea.ngStrap.dropdown', ['mgcrea.ngStrap.tooltip']).run([ '$templateCache', function ($templateCache) { var template = '' + '<ul tabindex="-1" class="dropdown-menu" role="menu">' + '<li role="presentation" ng-class="{divider: item.divider}" ng-repeat="item in content" >' + '<a role="menuitem" tabindex="-1" href="{{item.href}}" ng-if="!item.divider" ng-click="$eval(item.click);$hide()" ng-bind="item.text"></a>' + '</li>' + '</ul>'; $templateCache.put('$dropdown', template); } ]).provider('$dropdown', function () { var defaults = this.defaults = { animation: 'animation-fade', prefixClass: 'dropdown', placement: 'bottom-left', template: '$dropdown', trigger: 'click', container: false, keyboard: true, html: false, delay: 0 }; this.$get = [ '$window', '$tooltip', function ($window, $tooltip) { var bodyEl = angular.element($window.document.body); var matchesSelector = Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector; function DropdownFactory(element, config) { var $dropdown = {}; var options = angular.extend({}, defaults, config); $dropdown = $tooltip(element, options); $dropdown.$onKeyDown = function (evt) { if (!/(38|40)/.test(evt.keyCode)) return; evt.preventDefault(); evt.stopPropagation(); var items = angular.element($dropdown.$element[0].querySelectorAll('li:not(.divider) a')); if (!items.length) return; var index; angular.forEach(items, function (el, i) { if (matchesSelector && matchesSelector.call(el, ':focus')) index = i; }); if (evt.keyCode === 38 && index > 0) index--; else if (evt.keyCode === 40 && index < items.length - 1) index++; else if (angular.isUndefined(index)) index = 0; items.eq(index)[0].focus(); }; var show = $dropdown.show; $dropdown.show = function () { show(); setTimeout(function () { options.keyboard && $dropdown.$element.on('keydown', $dropdown.$onKeyDown); bodyEl.on('click', onBodyClick); }); }; var hide = $dropdown.hide; $dropdown.hide = function () { options.keyboard && $dropdown.$element.off('keydown', $dropdown.$onKeyDown); bodyEl.off('click', onBodyClick); hide(); }; function onBodyClick(evt) { if (evt.target === element[0]) return; return evt.target !== element[0] && $dropdown.hide(); } return $dropdown; } return DropdownFactory; } ]; }).directive('bsDropdown', [ '$window', '$location', '$sce', '$dropdown', function ($window, $location, $sce, $dropdown) { return { restrict: 'EAC', scope: true, link: function postLink(scope, element, attr, transclusion) { var options = { scope: scope }; angular.forEach([ 'placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); attr.bsDropdown && scope.$watch(attr.bsDropdown, function (newValue, oldValue) { scope.content = newValue; }, true); var dropdown = $dropdown(element, options); scope.$on('$destroy', function () { dropdown.destroy(); options = null; dropdown = null; }); } }; } ]); angular.module('mgcrea.ngStrap.helpers.debounce', []).constant('debounce', function (func, wait, immediate) { var timeout, args, context, timestamp, result; return function () { context = this; args = arguments; timestamp = new Date(); var later = function () { var last = new Date() - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) result = func.apply(context, args); return result; }; }).constant('throttle', function (func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function () { previous = options.leading === false ? 0 : new Date(); timeout = null; result = func.apply(context, args); }; return function () { var now = new Date(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }); angular.module('mgcrea.ngStrap.helpers.dimensions', []).factory('dimensions', [ '$document', '$window', function ($document, $window) { var jqLite = angular.element; var fn = {}; var nodeName = fn.nodeName = function (element, name) { return element.nodeName && element.nodeName.toLowerCase() === name.toLowerCase(); }; fn.css = function (element, prop, extra) { var value; if (element.currentStyle) { value = element.currentStyle[prop]; } else if (window.getComputedStyle) { value = window.getComputedStyle(element)[prop]; } else { value = element.style[prop]; } return extra === true ? parseFloat(value) || 0 : value; }; fn.offset = function (element) { var boxRect = element.getBoundingClientRect(); var docElement = element.ownerDocument; return { width: element.offsetWidth, height: element.offsetHeight, top: boxRect.top + (window.pageYOffset || docElement.documentElement.scrollTop) - (docElement.documentElement.clientTop || 0), left: boxRect.left + (window.pageXOffset || docElement.documentElement.scrollLeft) - (docElement.documentElement.clientLeft || 0) }; }; fn.position = function (element) { var offsetParentRect = { top: 0, left: 0 }, offsetParentElement, offset; if (fn.css(element, 'position') === 'fixed') { offset = element.getBoundingClientRect(); } else { offsetParentElement = offsetParent(element); offset = fn.offset(element); offset = fn.offset(element); if (!nodeName(offsetParentElement, 'html')) { offsetParentRect = fn.offset(offsetParentElement); } offsetParentRect.top += fn.css(offsetParentElement, 'borderTopWidth', true); offsetParentRect.left += fn.css(offsetParentElement, 'borderLeftWidth', true); } return { width: element.offsetWidth, height: element.offsetHeight, top: offset.top - offsetParentRect.top - fn.css(element, 'marginTop', true), left: offset.left - offsetParentRect.left - fn.css(element, 'marginLeft', true) }; }; var offsetParent = function offsetParentElement(element) { var docElement = element.ownerDocument; var offsetParent = element.offsetParent || docElement; if (nodeName(offsetParent, '#document')) return docElement.documentElement; while (offsetParent && !nodeName(offsetParent, 'html') && fn.css(offsetParent, 'position') === 'static') { offsetParent = offsetParent.offsetParent; } return offsetParent || docElement.documentElement; }; fn.height = function (element, outer) { var value = element.offsetHeight; if (outer) { value += fn.css(element, 'marginTop', true) + fn.css(element, 'marginBottom', true); } else { value -= fn.css(element, 'paddingTop', true) + fn.css(element, 'paddingBottom', true) + fn.css(element, 'borderTopWidth', true) + fn.css(element, 'borderBottomWidth', true); } return value; }; fn.width = function (element, outer) { var value = element.offsetWidth; if (outer) { value += fn.css(element, 'marginLeft', true) + fn.css(element, 'marginRight', true); } else { value -= fn.css(element, 'paddingLeft', true) + fn.css(element, 'paddingRight', true) + fn.css(element, 'borderLeftWidth', true) + fn.css(element, 'borderRightWidth', true); } return value; }; return fn; } ]); angular.module('mgcrea.ngStrap.helpers.parseOptions', []).provider('$parseOptions', function () { var defaults = this.defaults = { regexp: /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/ }; this.$get = [ '$parse', '$q', function ($parse, $q) { function ParseOptionsFactory(attr, config) { var $parseOptions = {}; var options = angular.extend({}, defaults, config); $parseOptions.$values = []; var match, displayFn, valueName, keyName, groupByFn, valueFn, valuesFn; $parseOptions.init = function () { $parseOptions.$match = match = attr.match(options.regexp); displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]); }; $parseOptions.valuesFn = function (scope, controller) { return $q.when(valuesFn(scope, controller)).then(function (values) { $parseOptions.$values = parseValues(values); return $parseOptions.$values; }); }; function parseValues(values) { return values.map(function (match) { var locals = {}, label, value; locals[valueName] = match; label = displayFn(locals); value = valueFn(locals); if (angular.isObject(value)) value = label; return { label: label, value: value }; }); } $parseOptions.init(); return $parseOptions; } return ParseOptionsFactory; } ]; }); angular.module('mgcrea.ngStrap.modal', ['mgcrea.ngStrap.helpers.dimensions']).run([ '$templateCache', '$modal', function ($templateCache, $modal) { var template = '' + '<div class="modal" tabindex="-1" role="dialog">' + '<div class="modal-dialog">' + '<div class="modal-content">' + '<div class="modal-header" ng-show="title">' + '<button type="button" class="close" ng-click="$hide()">&times;</button>' + '<h4 class="modal-title" ng-bind="title"></h4>' + '</div>' + '<div class="modal-body" ng-show="content" ng-bind="content"></div>' + '<div class="modal-footer">' + '<button type="button" class="btn btn-default" ng-click="$hide()">Close</button>' + '</div>' + '</div>' + '</div>' + '</div>'; $templateCache.put('$modal', template); } ]).provider('$modal', function () { var defaults = this.defaults = { animation: 'animation-fade', prefixClass: 'modal', placement: 'top', template: '$modal', container: false, element: null, backdrop: true, keyboard: true, html: false, show: true }; this.$get = [ '$window', '$rootScope', '$compile', '$q', '$templateCache', '$http', '$animate', '$timeout', 'dimensions', function ($window, $rootScope, $compile, $q, $templateCache, $http, $animate, $timeout, dimensions) { var forEach = angular.forEach; var jqLite = angular.element; var trim = String.prototype.trim; var bodyElement = jqLite($window.document.body); var htmlReplaceRegExp = /ng-bind="/gi; var findElement = function (query, element) { return jqLite((element || document).querySelectorAll(query)); }; function ModalFactory(config) { var $modal = {}; var options = angular.extend({}, defaults, config); $modal.$promise = $q.when($templateCache.get(options.template) || $http.get(options.template)); var scope = $modal.$scope = options.scope && options.scope.$new() || $rootScope.$new(); if (!options.element && !options.container) { options.container = 'body'; } if (!options.scope) { forEach([ 'title', 'content' ], function (key) { if (options[key]) scope[key] = options[key]; }); } scope.$hide = function () { scope.$$postDigest(function () { $modal.hide(); }); }; scope.$show = function () { scope.$$postDigest(function () { $modal.show(); }); }; scope.$toggle = function () { scope.$$postDigest(function () { $modal.toggle(); }); }; var modalLinker, modalElement; var backdropElement = jqLite('<div class="' + options.prefixClass + '-backdrop"/>'); $modal.$promise.then(function (template) { if (angular.isObject(template)) template = template.data; if (options.html) template = template.replace(htmlReplaceRegExp, 'ng-bind-html="'); template = trim.apply(template); modalLinker = $compile(template); $modal.init(); }); $modal.init = function () { if (options.show) { scope.$$postDigest(function () { $modal.show(); }); } }; $modal.destroy = function () { if (modalElement) { modalElement.remove(); modalElement = null; } if (backdropElement) { backdropElement.remove(); backdropElement = null; } scope.$destroy(); }; $modal.show = function () { var parent = options.container ? findElement(options.container) : null; var after = options.container ? null : options.element; modalElement = $modal.$element = modalLinker(scope, function (clonedElement, scope) { }); modalElement.css({ display: 'block' }).addClass(options.placement); if (options.animation) { if (options.backdrop) { backdropElement.addClass('animation-fade'); } modalElement.addClass(options.animation); } if (options.backdrop) { $animate.enter(backdropElement, bodyElement, null, function () { }); } $animate.enter(modalElement, parent, after, function () { }); scope.$isShown = true; scope.$$phase || scope.$digest(); $modal.focus(); bodyElement.addClass(options.prefixClass + '-open'); if (options.backdrop) { modalElement.on('click', hideOnBackdropClick); } if (options.keyboard) { modalElement.on('keyup', $modal.$onKeyUp); } }; $modal.hide = function () { $animate.leave(modalElement, function () { bodyElement.removeClass(options.prefixClass + '-open'); }); if (options.backdrop) { $animate.leave(backdropElement, function () { }); } scope.$$phase || scope.$digest(); scope.$isShown = false; if (options.backdrop) { modalElement.off('click', hideOnBackdropClick); } if (options.keyboard) { modalElement.off('keyup', $modal.$onKeyUp); } }; $modal.toggle = function () { scope.$isShown ? $modal.hide() : $modal.show(); }; $modal.focus = function () { modalElement[0].focus(); }; $modal.$onKeyUp = function (evt) { evt.which === 27 && $modal.hide(); }; function hideOnBackdropClick(evt) { if (evt.target !== evt.currentTarget) return; options.backdrop === 'static' ? $modal.focus() : $modal.hide(); } return $modal; } return ModalFactory; } ]; }).directive('bsModal', [ '$window', '$location', '$sce', '$modal', function ($window, $location, $sce, $modal) { return { restrict: 'EAC', scope: true, link: function postLink(scope, element, attr, transclusion) { var options = { scope: scope, element: element, show: false }; angular.forEach([ 'template', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); angular.forEach([ 'title', 'content' ], function (key) { attr[key] && attr.$observe(key, function (newValue, oldValue) { scope[key] = newValue; }); }); attr.bsModal && scope.$watch(attr.bsModal, function (newValue, oldValue) { if (angular.isObject(newValue)) { angular.extend(scope, newValue); } else { scope.content = newValue; } }, true); var modal = $modal(options); element.on(attr.trigger || 'click', modal.toggle); scope.$on('$destroy', function () { modal.destroy(); options = null; modal = null; }); } }; } ]); angular.module('mgcrea.ngStrap.navbar', []).provider('$navbar', function () { var defaults = this.defaults = { activeClass: 'active', routeAttr: 'data-match-route' }; this.$get = function () { return { defaults: defaults }; }; }).directive('bsNavbar', [ '$window', '$location', '$navbar', function ($window, $location, $navbar) { var defaults = $navbar.defaults; return { restrict: 'A', link: function postLink(scope, element, attr, controller) { var options = defaults; angular.forEach(Object.keys(defaults), function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); scope.$watch(function () { return $location.path(); }, function (newValue, oldValue) { var liElements = element[0].querySelectorAll('li[' + options.routeAttr + ']'); angular.forEach(liElements, function (li) { var liElement = angular.element(li); var pattern = liElement.attr(options.routeAttr); var regexp = new RegExp('^' + pattern.replace('/', '\\/') + '$', ['i']); if (regexp.test(newValue)) { liElement.addClass(options.activeClass); } else { liElement.removeClass(options.activeClass); } }); }); } }; } ]); angular.module('mgcrea.ngStrap.popover', ['mgcrea.ngStrap.tooltip']).run([ '$templateCache', function ($templateCache) { var template = '' + '<div class="popover" tabindex="-1" ng-show="content" ng-class="{\'in\': $visible}">' + '<div class="arrow"></div>' + '<h3 class="popover-title" ng-bind="title" ng-show="title"></h3>' + '<div class="popover-content" ng-bind="content"></div>' + '</div>'; $templateCache.put('$popover', template); } ]).provider('$popover', function () { var defaults = this.defaults = { animation: 'animation-fade', placement: 'right', template: '$popover', trigger: 'click', keyboard: true, html: false, title: '', content: '', delay: 0, container: false }; this.$get = [ '$tooltip', function ($tooltip) { function PopoverFactory(element, config) { var options = angular.extend({}, defaults, config); return $tooltip(element, options); } return PopoverFactory; } ]; }).directive('bsPopover', [ '$window', '$location', '$sce', '$popover', function ($window, $location, $sce, $popover) { var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; return { restrict: 'EAC', scope: true, link: function postLink(scope, element, attr) { var options = { scope: scope }; angular.forEach([ 'placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); angular.forEach([ 'title', 'content' ], function (key) { attr[key] && attr.$observe(key, function (newValue, oldValue) { scope[key] = newValue; angular.isDefined(oldValue) && requestAnimationFrame(function () { popover && popover.$applyPlacement(); }); }); }); attr.bsPopover && scope.$watch(attr.bsPopover, function (newValue, oldValue) { if (angular.isObject(newValue)) { angular.extend(scope, newValue); } else { scope.content = newValue; } angular.isDefined(oldValue) && requestAnimationFrame(function () { popover && popover.$applyPlacement(); }); }, true); var popover = $popover(element, options); scope.$on('$destroy', function () { popover.destroy(); options = null; popover = null; }); } }; } ]); angular.module('mgcrea.ngStrap.scrollspy', [ 'mgcrea.ngStrap.helpers.debounce', 'mgcrea.ngStrap.helpers.dimensions' ]).provider('$scrollspy', function () { var spies = this.$$spies = {}; var defaults = this.defaults = { debounce: 150, throttle: 100, offset: 100 }; this.$get = [ '$window', '$document', '$rootScope', 'dimensions', 'debounce', 'throttle', function ($window, $document, $rootScope, dimensions, debounce, throttle) { var windowEl = angular.element($window); var docEl = angular.element($document.prop('documentElement')); var bodyEl = angular.element($window.document.body); function nodeName(element, name) { return element[0].nodeName && element[0].nodeName.toLowerCase() === name.toLowerCase(); } function ScrollSpyFactory(config) { var options = angular.extend({}, defaults, config); if (!options.element) options.element = bodyEl; var isWindowSpy = nodeName(options.element, 'body'); var scrollEl = isWindowSpy ? windowEl : options.element; var scrollId = isWindowSpy ? 'window' : options.id; if (spies[scrollId]) { spies[scrollId].$$count++; return spies[scrollId]; } var $scrollspy = {}; var trackedElements = $scrollspy.$trackedElements = []; var sortedElements = []; var activeTarget; var debouncedCheckPosition; var throttledCheckPosition; var debouncedCheckOffsets; var viewportHeight; var scrollTop; $scrollspy.init = function () { this.$$count = 1; debouncedCheckPosition = debounce(this.checkPosition, options.debounce); throttledCheckPosition = throttle(this.checkPosition, options.throttle); scrollEl.on('click', this.checkPositionWithEventLoop); windowEl.on('resize', debouncedCheckPosition); scrollEl.on('scroll', throttledCheckPosition); debouncedCheckOffsets = debounce(this.checkOffsets, options.debounce); $rootScope.$on('$viewContentLoaded', debouncedCheckOffsets); $rootScope.$on('$includeContentLoaded', debouncedCheckOffsets); debouncedCheckOffsets(); if (scrollId) { spies[scrollId] = $scrollspy; } }; $scrollspy.destroy = function () { this.$$count--; if (this.$$count > 0) { return; } scrollEl.off('click', this.checkPositionWithEventLoop); windowEl.off('resize', debouncedCheckPosition); scrollEl.off('scroll', debouncedCheckPosition); $rootScope.$off('$viewContentLoaded', debouncedCheckOffsets); $rootScope.$off('$includeContentLoaded', debouncedCheckOffsets); }; $scrollspy.checkPosition = function () { if (!sortedElements.length) return; scrollTop = (isWindowSpy ? $window.pageYOffset : scrollEl.prop('scrollTop')) || 0; viewportHeight = Math.max($window.innerHeight, docEl.prop('clientHeight')); if (scrollTop < sortedElements[0].offsetTop && activeTarget !== sortedElements[0].target) { return $scrollspy.$activateElement(sortedElements[0]); } for (var i = sortedElements.length; i--;) { if (angular.isUndefined(sortedElements[i].offsetTop) || sortedElements[i].offsetTop === null) continue; if (activeTarget === sortedElements[i].target) continue; if (scrollTop < sortedElements[i].offsetTop) continue; if (sortedElements[i + 1] && scrollTop > sortedElements[i + 1].offsetTop) continue; return $scrollspy.$activateElement(sortedElements[i]); } }; $scrollspy.checkPositionWithEventLoop = function () { setTimeout(this.checkPosition, 1); }; $scrollspy.$activateElement = function (element) { if (activeTarget) { var activeElement = $scrollspy.$getTrackedElement(activeTarget); if (activeElement) { activeElement.source.removeClass('active'); if (nodeName(activeElement.source, 'li') && nodeName(activeElement.source.parent().parent(), 'li')) { activeElement.source.parent().parent().removeClass('active'); } } } activeTarget = element.target; element.source.addClass('active'); if (nodeName(element.source, 'li') && nodeName(element.source.parent().parent(), 'li')) { element.source.parent().parent().addClass('active'); } }; $scrollspy.$getTrackedElement = function (target) { return trackedElements.filter(function (obj) { return obj.target === target; })[0]; }; $scrollspy.checkOffsets = function () { angular.forEach(trackedElements, function (trackedElement) { var targetElement = document.querySelector(trackedElement.target); trackedElement.offsetTop = targetElement ? dimensions.offset(targetElement).top : null; if (options.offset && trackedElement.offsetTop !== null) trackedElement.offsetTop -= options.offset * 1; }); sortedElements = trackedElements.filter(function (el) { return el.offsetTop !== null; }).sort(function (a, b) { return a.offsetTop - b.offsetTop; }); debouncedCheckPosition(); }; $scrollspy.trackElement = function (target, source) { trackedElements.push({ target: target, source: source }); }; $scrollspy.untrackElement = function (target, source) { var toDelete; for (var i = trackedElements.length; i--;) { if (trackedElements[i].target === target && trackedElements[i].source === source) { toDelete = i; break; } } trackedElements = trackedElements.splice(toDelete, 1); }; $scrollspy.activate = function (i) { trackedElements[i].addClass('active'); }; $scrollspy.init(); return $scrollspy; } return ScrollSpyFactory; } ]; }).directive('bsScrollspy', [ '$rootScope', 'debounce', 'dimensions', '$scrollspy', function ($rootScope, debounce, dimensions, $scrollspy) { return { restrict: 'EAC', link: function postLink(scope, element, attr) { var options = { scope: scope }; angular.forEach([ 'offset', 'target' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); var scrollspy = $scrollspy(options); scrollspy.trackElement(options.target, element); scope.$on('$destroy', function () { scrollspy.untrackElement(options.target, element); scrollspy.destroy(); options = null; scrollspy = null; }); } }; } ]).directive('bsScrollspyList', [ '$rootScope', 'debounce', 'dimensions', '$scrollspy', function ($rootScope, debounce, dimensions, $scrollspy) { return { restrict: 'A', compile: function postLink(element, attr) { var children = element[0].querySelectorAll('li > a[href]'); angular.forEach(children, function (child) { var childEl = angular.element(child); childEl.parent().attr('bs-scrollspy', '').attr('data-target', childEl.attr('href')); }); } }; } ]); angular.module('mgcrea.ngStrap.select', [ 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions' ]).run([ '$templateCache', function ($templateCache) { var template = '' + '<ul tabindex="-1" class="select dropdown-menu" ng-show="$isVisible()" role="select">' + '<li role="presentation" ng-repeat="match in $matches" ng-class="{active: $isActive($index)}">' + '<a role="menuitem" tabindex="-1" ng-click="$select($index, $event)" ng-bind="match.label"></a>' + '<i class="glyphicon glyphicon-ok" ng-if="$isMultiple"></i>' + '</li>' + '</ul>'; $templateCache.put('$select', template); } ]).provider('$select', function () { var defaults = this.defaults = { animation: 'animation-fade', prefixClass: 'select', placement: 'bottom-left', template: '$select', trigger: 'focus', container: false, keyboard: true, html: false, delay: 0, multiple: false, sort: true, caretHtml: '&nbsp;<span class="caret"></span>', placeholder: 'Choose among the following...' }; var isTouch = 'ontouchstart' in window; this.$get = [ '$window', '$document', '$rootScope', '$tooltip', function ($window, $document, $rootScope, $tooltip) { var bodyEl = angular.element($window.document.body); function SelectFactory(element, config) { var $select = {}; var options = angular.extend({}, defaults, config); var controller = options.controller; if (!controller) throw 'ngModelController required'; $select = $tooltip(element, options); var parentScope = config.scope; var scope = $select.$scope; scope.$matches = []; scope.$activeIndex = 0; scope.$isMultiple = options.multiple; scope.$activate = function (index) { scope.$$postDigest(function () { $select.activate(index); }); }; scope.$select = function (index, evt) { scope.$$postDigest(function () { $select.select(index); }); }; scope.$isVisible = function () { return $select.$isVisible(); }; scope.$isActive = function (index) { return $select.$isActive(index); }; $select.update = function (matches) { scope.$matches = matches; if (controller.$modelValue && matches.length) { if (options.multiple && angular.isArray(controller.$modelValue)) { scope.$activeIndex = controller.$modelValue.map(function (value) { return $select.$getIndex(value); }); } else { scope.$activeIndex = $select.$getIndex(controller.$modelValue); } } else if (scope.$activeIndex >= matches.length) { scope.$activeIndex = options.multiple ? [] : 0; } }; $select.activate = function (index) { if (options.multiple) { scope.$activeIndex.sort(); $select.$isActive(index) ? scope.$activeIndex.splice(scope.$activeIndex.indexOf(index), 1) : scope.$activeIndex.push(index); if (options.sort) scope.$activeIndex.sort(); } else { scope.$activeIndex = index; } return scope.$activeIndex; }; $select.select = function (index) { var value = scope.$matches[index].value; $select.activate(index); if (options.multiple) { controller.$setViewValue(scope.$activeIndex.map(function (index) { return scope.$matches[index].value; })); } else { controller.$setViewValue(value); } controller.$render(); if (parentScope) parentScope.$digest(); if (!options.multiple) { if (options.trigger === 'focus') element[0].blur(); else if ($select.$isShown) $select.hide(); } scope.$emit('$select.select', value, index); }; $select.$isVisible = function () { if (!options.minLength || !controller) { return scope.$matches.length; } return scope.$matches.length && controller.$viewValue.length >= options.minLength; }; $select.$isActive = function (index) { if (options.multiple) { return scope.$activeIndex.indexOf(index) !== -1; } else { return scope.$activeIndex === index; } }; $select.$getIndex = function (value) { var l = scope.$matches.length, i = l; if (!l) return; for (i = l; i--;) { if (scope.$matches[i].value === value) break; } if (i < 0) return; return i; }; $select.$onElementMouseDown = function (evt) { if ($window.document.activeElement === element[0]) { element[0].blur(); evt.preventDefault(); evt.stopPropagation(); } }; $select.$onClick = function (evt) { if (isTouch) { element[0].focus(); } }; $select.$onMouseDown = function (evt) { evt.preventDefault(); evt.stopPropagation(); if (isTouch) { var targetEl = angular.element(evt.target); targetEl.triggerHandler('click'); } }; $select.$onKeyDown = function (evt) { if (!/(38|40|13)/.test(evt.keyCode)) return; evt.preventDefault(); evt.stopPropagation(); if (evt.keyCode === 13) { return $select.select(scope.$activeIndex); } if (evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; else if (evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; else if (angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; scope.$digest(); }; var _init = $select.init; $select.init = function () { _init(); element.on('click', $select.$onClick); }; var _destroy = $select.destroy; $select.destroy = function () { _destroy(); element.off('click', $select.$onClick); }; var _show = $select.show; $select.show = function () { _show(); if (options.multiple) { $select.$element.addClass('select-multiple'); } setTimeout(function () { element.on(isTouch ? 'touchstart' : 'mousedown', $select.$onElementMouseDown); $select.$element.on(isTouch ? 'touchstart' : 'mousedown', $select.$onMouseDown); if (options.keyboard) { element.on('keydown', $select.$onKeyDown); } }); }; var _hide = $select.hide; $select.hide = function () { element.off(isTouch ? 'touchstart' : 'mousedown', $select.$onElementMouseDown); $select.$element.off(isTouch ? 'touchstart' : 'mousedown', $select.$onMouseDown); if (options.keyboard) { element.off('keydown', $select.$onKeyDown); } _hide(); }; return $select; } SelectFactory.defaults = defaults; return SelectFactory; } ]; }).directive('bsSelect', [ '$window', '$parse', '$q', '$select', '$parseOptions', function ($window, $parse, $q, $select, $parseOptions) { var defaults = $select.defaults; return { restrict: 'EAC', require: 'ngModel', link: function postLink(scope, element, attr, controller) { var options = { scope: scope, controller: controller }; angular.forEach([ 'placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'multiple' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); var parsedOptions = $parseOptions(attr.ngOptions); var select = $select(element, options); scope.$watch(parsedOptions.$match[7], function (newValue, oldValue) { parsedOptions.valuesFn(scope, controller).then(function (values) { select.update(values); controller.$render(); }); }); controller.$render = function () { var selected, index; if (options.multiple && angular.isArray(controller.$modelValue)) { selected = controller.$modelValue.map(function (value) { index = select.$getIndex(value); return angular.isDefined(index) ? select.$scope.$matches[index].label : false; }).filter(angular.isDefined).join(', '); } else { index = select.$getIndex(controller.$modelValue); selected = angular.isDefined(index) ? select.$scope.$matches[index].label : false; } element.html((selected ? selected : attr.placeholder || defaults.placeholder) + defaults.caretHtml); }; scope.$on('$destroy', function () { select.destroy(); options = null; select = null; }); } }; } ]); angular.module('mgcrea.ngStrap.tab', []).run([ '$templateCache', function ($templateCache) { $templateCache.put('$pane', '{{pane.content}}'); var template = '<ul class="nav nav-tabs">' + '<li ng-repeat="pane in panes" ng-class="{active:$index==active}">' + '<a data-toggle="tab" ng-click="setActive($index, $event)" data-index="{{$index}}">{{pane.title}}</a>' + '</li>' + '</ul>' + '<div class="tab-content">' + '<div ng-repeat="pane in panes" class="tab-pane" ng-class="[$index==active?\'active\':\'\']" ng-include="pane.template || \'$pane\'"></div>' + '</div>'; $templateCache.put('$tabs', template); } ]).provider('$tab', function () { var defaults = this.defaults = { animation: 'animation-fade', template: '$tabs' }; this.$get = function () { return { defaults: defaults }; }; }).directive('bsTabs', [ '$window', '$animate', '$tab', function ($window, $animate, $tab) { var defaults = $tab.defaults; return { restrict: 'EAC', scope: true, require: '?ngModel', templateUrl: function (element, attr) { return attr.template || defaults.template; }, link: function postLink(scope, element, attr, controller) { var options = defaults; angular.forEach(['animation'], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); attr.bsTabs && scope.$watch(attr.bsTabs, function (newValue, oldValue) { scope.panes = newValue; }, true); element.addClass('tabs'); if (options.animation) { element.addClass(options.animation); } scope.active = scope.activePane = 0; scope.setActive = function (index, ev) { scope.active = index; if (controller) { controller.$setViewValue(index); } }; if (controller) { controller.$render = function () { scope.active = controller.$modelValue * 1; }; } } }; } ]); angular.module('mgcrea.ngStrap.tooltip', ['mgcrea.ngStrap.helpers.dimensions']).run([ '$templateCache', function ($templateCache) { var template = '' + '<div class="tooltip" ng-show="title">' + '<div class="tooltip-arrow"></div>' + '<div class="tooltip-inner" ng-bind="title"></div>' + '</div>'; $templateCache.put('$tooltip', template); } ]).provider('$tooltip', function () { var defaults = this.defaults = { animation: 'animation-fade', prefixClass: 'tooltip', container: false, placement: 'top', template: '$tooltip', trigger: 'hover focus', keyboard: false, html: false, show: false, title: '', type: '', delay: 0 }; this.$get = [ '$window', '$rootScope', '$compile', '$q', '$templateCache', '$http', '$animate', '$timeout', 'dimensions', function ($window, $rootScope, $compile, $q, $templateCache, $http, $animate, $timeout, dimensions) { var trim = String.prototype.trim; var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; var htmlReplaceRegExp = /ng-bind="/gi; var findElement = function (query, element) { return angular.element((element || document).querySelectorAll(query)); }; function TooltipFactory(element, config) { var $tooltip = {}; var options = angular.extend({}, defaults, config); $tooltip.$promise = $q.when($templateCache.get(options.template) || $http.get(options.template)); var scope = $tooltip.$scope = options.scope && options.scope.$new() || $rootScope.$new(); if (options.delay && angular.isString(options.delay)) { options.delay = parseFloat(options.delay); } scope.$hide = function () { scope.$$postDigest(function () { $tooltip.hide(); }); }; scope.$show = function () { scope.$$postDigest(function () { $tooltip.show(); }); }; scope.$toggle = function () { scope.$$postDigest(function () { $tooltip.toggle(); }); }; $tooltip.$isShown = false; var timeout, hoverState; var tipLinker, tipElement, tipTemplate; $tooltip.$promise.then(function (template) { if (angular.isObject(template)) template = template.data; if (options.html) template = template.replace(htmlReplaceRegExp, 'ng-bind-html="'); template = trim.apply(template); tipTemplate = template; tipLinker = $compile(template); $tooltip.init(); }); $tooltip.init = function () { if (options.delay && angular.isNumber(options.delay)) { options.delay = { show: options.delay, hide: options.delay }; } var triggers = options.trigger.split(' '); for (var i = triggers.length; i--;) { var trigger = triggers[i]; if (trigger === 'click') { element.on('click', $tooltip.toggle); } else if (trigger !== 'manual') { element.on(trigger === 'hover' ? 'mouseenter' : 'focus', $tooltip.enter); element.on(trigger === 'hover' ? 'mouseleave' : 'blur', $tooltip.leave); } } if (options.show) { scope.$$postDigest(function () { $tooltip.show(); }); } }; $tooltip.destroy = function () { var triggers = options.trigger.split(' '); for (var i = triggers.length; i--;) { var trigger = triggers[i]; if (trigger === 'click') { element.off('click', $tooltip.toggle); } else if (trigger !== 'manual') { element.off(trigger === 'hover' ? 'mouseenter' : 'focus', $tooltip.enter); element.off(trigger === 'hover' ? 'mouseleave' : 'blur', $tooltip.leave); } } if (tipElement) { tipElement.remove(); tipElement = null; } scope.$destroy(); }; $tooltip.enter = function () { clearTimeout(timeout); hoverState = 'in'; if (!options.delay || !options.delay.show) { return $tooltip.show(); } timeout = setTimeout(function () { if (hoverState === 'in') $tooltip.show(); }, options.delay.show); }; $tooltip.show = function () { var parent = options.container ? findElement(options.container) : null; var after = options.container ? null : element; tipElement = $tooltip.$element = tipLinker(scope, function (clonedElement, scope) { }); tipElement.css({ top: '0px', left: '0px', display: 'block' }).addClass(options.placement); if (options.animation) tipElement.addClass(options.animation); if (options.type) tipElement.addClass(options.prefixClass + '-' + options.type); $animate.enter(tipElement, parent, after, function () { }); $tooltip.$isShown = true; scope.$$phase || scope.$digest(); requestAnimationFrame($tooltip.$applyPlacement); if (options.keyboard) { if (options.trigger !== 'focus') { $tooltip.focus(); tipElement.on('keyup', $tooltip.$onKeyUp); } else { element.on('keyup', $tooltip.$onFocusKeyUp); } } }; $tooltip.leave = function () { clearTimeout(timeout); hoverState = 'out'; if (!options.delay || !options.delay.hide) { return $tooltip.hide(); } timeout = setTimeout(function () { if (hoverState === 'out') { $tooltip.hide(); } }, options.delay.hide); }; $tooltip.hide = function () { $animate.leave(tipElement, function () { }); scope.$$phase || scope.$digest(); $tooltip.$isShown = false; if (options.keyboard) { tipElement.off('keyup', $tooltip.$onKeyUp); } }; $tooltip.toggle = function () { $tooltip.$isShown ? $tooltip.leave() : $tooltip.enter(); }; $tooltip.focus = function () { tipElement[0].focus(); }; $tooltip.$applyPlacement = function () { if (!tipElement) return; var elementPosition = getPosition(); var tipWidth = tipElement.prop('offsetWidth'), tipHeight = tipElement.prop('offsetHeight'); var tipPosition = getCalculatedOffset(options.placement, elementPosition, tipWidth, tipHeight); tipPosition.top += 'px'; tipPosition.left += 'px'; tipElement.css(tipPosition); }; $tooltip.$onKeyUp = function (evt) { evt.which === 27 && $tooltip.hide(); }; $tooltip.$onFocusKeyUp = function (evt) { evt.which === 27 && element[0].blur(); }; function getPosition() { if (options.container === 'body') { return dimensions.offset(element[0]); } else { return dimensions.position(element[0]); } } function getCalculatedOffset(placement, position, actualWidth, actualHeight) { var offset; var split = placement.split('-'); switch (split[0]) { case 'right': offset = { top: position.top + position.height / 2 - actualHeight / 2, left: position.left + position.width }; break; case 'bottom': offset = { top: position.top + position.height, left: position.left + position.width / 2 - actualWidth / 2 }; break; case 'left': offset = { top: position.top + position.height / 2 - actualHeight / 2, left: position.left - actualWidth }; break; default: offset = { top: position.top - actualHeight, left: position.left + position.width / 2 - actualWidth / 2 }; break; } if (!split[1]) { return offset; } if (split[0] === 'top' || split[0] === 'bottom') { switch (split[1]) { case 'left': offset.left = position.left; break; case 'right': offset.left = position.left + position.width - actualWidth; } } else if (split[0] === 'left' || split[0] === 'right') { switch (split[1]) { case 'top': offset.top = position.top - actualHeight; break; case 'bottom': offset.top = position.top + position.height; } } return offset; } return $tooltip; } return TooltipFactory; } ]; }).directive('bsTooltip', [ '$window', '$location', '$sce', '$tooltip', function ($window, $location, $sce, $tooltip) { var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; return { restrict: 'EAC', scope: true, link: function postLink(scope, element, attr, transclusion) { var options = { scope: scope }; angular.forEach([ 'placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'type', 'template' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); angular.forEach(['title'], function (key) { attr[key] && attr.$observe(key, function (newValue, oldValue) { scope[key] = newValue; angular.isDefined(oldValue) && requestAnimationFrame(function () { tooltip && tooltip.$applyPlacement(); }); }); }); attr.bsTooltip && scope.$watch(attr.bsTooltip, function (newValue, oldValue) { if (angular.isObject(newValue)) { angular.extend(scope, newValue); } else { scope.content = newValue; } angular.isDefined(oldValue) && requestAnimationFrame(function () { tooltip && tooltip.$applyPlacement(); }); }, true); var tooltip = $tooltip(element, options); scope.$on('$destroy', function () { tooltip.destroy(); options = null; tooltip = null; }); } }; } ]); angular.module('mgcrea.ngStrap.typeahead', [ 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions' ]).run([ '$templateCache', function ($templateCache) { var template = '' + '<ul tabindex="-1" class="typeahead dropdown-menu" ng-show="$isVisible()" role="select">' + '<li role="presentation" ng-repeat="match in $matches" ng-class="{active: $index == $activeIndex}">' + '<a role="menuitem" tabindex="-1" ng-click="$select($index, $event)" ng-bind="match.label"></a>' + '</li>' + '</ul>'; $templateCache.put('$typeahead', template); } ]).provider('$typeahead', function () { var defaults = this.defaults = { animation: 'animation-fade', prefixClass: 'typeahead', placement: 'bottom-left', template: '$typeahead', trigger: 'focus', container: false, keyboard: true, html: false, delay: 0, minLength: 1, limit: 6 }; this.$get = [ '$window', '$rootScope', '$tooltip', function ($window, $rootScope, $tooltip) { var bodyEl = angular.element($window.document.body); function TypeaheadFactory(element, config) { var $typeahead = {}; var options = angular.extend({}, defaults, config); var controller = options.controller; $typeahead = $tooltip(element, options); var parentScope = config.scope; var scope = $typeahead.$scope; scope.$matches = []; scope.$activeIndex = 0; scope.$activate = function (index) { scope.$$postDigest(function () { $typeahead.activate(index); }); }; scope.$select = function (index, evt) { scope.$$postDigest(function () { $typeahead.select(index); }); }; scope.$isVisible = function () { return $typeahead.$isVisible(); }; $typeahead.update = function (matches) { scope.$matches = matches; if (scope.$activeIndex >= matches.length) { scope.$activeIndex = 0; } }; $typeahead.activate = function (index) { scope.$activeIndex = index; }; $typeahead.select = function (index) { var value = scope.$matches[index].value; if (controller) { controller.$setViewValue(value); controller.$render(); if (parentScope) parentScope.$digest(); } if (options.trigger === 'focus') element[0].blur(); else if ($typeahead.$isShown) $typeahead.hide(); scope.$activeIndex = 0; scope.$emit('$typeahead.select', value, index); }; $typeahead.$isVisible = function () { if (!options.minLength || !controller) { return !!scope.$matches.length; } return scope.$matches.length && controller.$viewValue.length >= options.minLength; }; $typeahead.$onMouseDown = function (evt) { evt.preventDefault(); evt.stopPropagation(); }; $typeahead.$onKeyDown = function (evt) { if (!/(38|40|13)/.test(evt.keyCode)) return; evt.preventDefault(); evt.stopPropagation(); if (evt.keyCode === 13) { return $typeahead.select(scope.$activeIndex); } if (evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; else if (evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; else if (angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; scope.$digest(); }; var show = $typeahead.show; $typeahead.show = function () { show(); setTimeout(function () { $typeahead.$element.on('mousedown', $typeahead.$onMouseDown); if (options.keyboard) { element.on('keydown', $typeahead.$onKeyDown); } }); }; var hide = $typeahead.hide; $typeahead.hide = function () { $typeahead.$element.off('mousedown', $typeahead.$onMouseDown); if (options.keyboard) { element.off('keydown', $typeahead.$onKeyDown); } hide(); }; return $typeahead; } TypeaheadFactory.defaults = defaults; return TypeaheadFactory; } ]; }).directive('bsTypeahead', [ '$window', '$parse', '$q', '$typeahead', '$parseOptions', function ($window, $parse, $q, $typeahead, $parseOptions) { var defaults = $typeahead.defaults; return { restrict: 'EAC', require: 'ngModel', link: function postLink(scope, element, attr, controller) { var options = { scope: scope, controller: controller }; angular.forEach([ 'placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'limit', 'minLength' ], function (key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); var limit = options.limit || defaults.limit; var parsedOptions = $parseOptions(attr.ngOptions + ' | filter:$viewValue |\xa0limitTo:' + limit); var typeahead = $typeahead(element, options); scope.$watch(attr.ngModel, function (newValue, oldValue) { parsedOptions.valuesFn(scope, controller).then(function (values) { if (values.length > limit) values = values.slice(0, limit); typeahead.update(values); }); }); scope.$on('$destroy', function () { typeahead.destroy(); options = null; typeahead = null; }); } }; } ]); }(window, document, window.jQuery));
mit
seogi1004/cdnjs
ajax/libs/react-virtualized/6.1.2/react-virtualized.js
127214
!function(root, factory) { "object" == typeof exports && "object" == typeof module ? module.exports = factory(require("react"), require("react-dom")) : "function" == typeof define && define.amd ? define([ "react", "react-dom" ], factory) : "object" == typeof exports ? exports.ReactVirtualized = factory(require("react"), require("react-dom")) : root.ReactVirtualized = factory(root.React, root.ReactDOM); }(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_26__) { /******/ return function(modules) { /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if (installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: !1 }; /******/ /******/ // Return the exports of the module /******/ /******/ /******/ // Execute the module function /******/ /******/ /******/ // Flag the module as loaded /******/ return modules[moduleId].call(module.exports, module, module.exports, __webpack_require__), module.loaded = !0, module.exports; } // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // Load entry module and return exports /******/ /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ /******/ /******/ // expose the module cache /******/ /******/ /******/ // __webpack_public_path__ /******/ return __webpack_require__.m = modules, __webpack_require__.c = installedModules, __webpack_require__.p = "", __webpack_require__(0); }([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var _ArrowKeyStepper = __webpack_require__(1); Object.defineProperty(exports, "ArrowKeyStepper", { enumerable: !0, get: function() { return _ArrowKeyStepper.ArrowKeyStepper; } }); var _AutoSizer = __webpack_require__(7); Object.defineProperty(exports, "AutoSizer", { enumerable: !0, get: function() { return _AutoSizer.AutoSizer; } }); var _ColumnSizer = __webpack_require__(10); Object.defineProperty(exports, "ColumnSizer", { enumerable: !0, get: function() { return _ColumnSizer.ColumnSizer; } }); var _FlexTable = __webpack_require__(21); Object.defineProperty(exports, "FlexTable", { enumerable: !0, get: function() { return _FlexTable.FlexTable; } }), Object.defineProperty(exports, "FlexColumn", { enumerable: !0, get: function() { return _FlexTable.FlexColumn; } }), Object.defineProperty(exports, "SortDirection", { enumerable: !0, get: function() { return _FlexTable.SortDirection; } }), Object.defineProperty(exports, "SortIndicator", { enumerable: !0, get: function() { return _FlexTable.SortIndicator; } }); var _Grid = __webpack_require__(12); Object.defineProperty(exports, "Grid", { enumerable: !0, get: function() { return _Grid.Grid; } }); var _InfiniteLoader = __webpack_require__(27); Object.defineProperty(exports, "InfiniteLoader", { enumerable: !0, get: function() { return _InfiniteLoader.InfiniteLoader; } }); var _ScrollSync = __webpack_require__(29); Object.defineProperty(exports, "ScrollSync", { enumerable: !0, get: function() { return _ScrollSync.ScrollSync; } }); var _VirtualScroll = __webpack_require__(31); Object.defineProperty(exports, "VirtualScroll", { enumerable: !0, get: function() { return _VirtualScroll.VirtualScroll; } }); }, /* 1 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ArrowKeyStepper = exports["default"] = void 0; var _ArrowKeyStepper2 = __webpack_require__(2), _ArrowKeyStepper3 = _interopRequireDefault(_ArrowKeyStepper2); exports["default"] = _ArrowKeyStepper3["default"], exports.ArrowKeyStepper = _ArrowKeyStepper3["default"]; }, /* 2 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _jsx = function() { var REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103; return function(type, props, key, children) { var defaultProps = type && type.defaultProps, childrenLength = arguments.length - 3; if (props || 0 === childrenLength || (props = {}), props && defaultProps) for (var propName in defaultProps) void 0 === props[propName] && (props[propName] = defaultProps[propName]); else props || (props = defaultProps || {}); if (1 === childrenLength) props.children = children; else if (childrenLength > 1) { for (var childArray = Array(childrenLength), i = 0; childrenLength > i; i++) childArray[i] = arguments[i + 3]; props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: void 0 === key ? null : "" + key, ref: null, props: props, _owner: null }; }; }(), _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _reactAddonsShallowCompare = (_interopRequireDefault(_react), __webpack_require__(4)), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ArrowKeyStepper = function(_Component) { function ArrowKeyStepper(props, context) { _classCallCheck(this, ArrowKeyStepper); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ArrowKeyStepper).call(this, props, context)); return _this.state = { scrollToColumn: 0, scrollToRow: 0 }, _this._columnStartIndex = 0, _this._columnStopIndex = 0, _this._rowStartIndex = 0, _this._rowStopIndex = 0, _this._onKeyDown = _this._onKeyDown.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this), _this; } return _inherits(ArrowKeyStepper, _Component), _createClass(ArrowKeyStepper, [ { key: "render", value: function() { var _props = this.props, className = _props.className, children = _props.children, _state = this.state, scrollToColumn = _state.scrollToColumn, scrollToRow = _state.scrollToRow; return _jsx("div", { className: className, onKeyDown: this._onKeyDown }, void 0, children({ onSectionRendered: this._onSectionRendered, scrollToColumn: scrollToColumn, scrollToRow: scrollToRow })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onKeyDown", value: function(event) { var _props2 = this.props, columnsCount = _props2.columnsCount, rowsCount = _props2.rowsCount; switch (event.key) { case "ArrowDown": event.preventDefault(), this.setState({ scrollToRow: Math.min(this._rowStopIndex + 1, rowsCount - 1) }); break; case "ArrowLeft": event.preventDefault(), this.setState({ scrollToColumn: Math.max(this._columnStartIndex - 1, 0) }); break; case "ArrowRight": event.preventDefault(), this.setState({ scrollToColumn: Math.min(this._columnStopIndex + 1, columnsCount - 1) }); break; case "ArrowUp": event.preventDefault(), this.setState({ scrollToRow: Math.max(this._rowStartIndex - 1, 0) }); } } }, { key: "_onSectionRendered", value: function(_ref) { var columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex; this._columnStartIndex = columnStartIndex, this._columnStopIndex = columnStopIndex, this._rowStartIndex = rowStartIndex, this._rowStopIndex = rowStopIndex; } } ]), ArrowKeyStepper; }(_react.Component); ArrowKeyStepper.propTypes = { children: _react.PropTypes.func.isRequired, className: _react.PropTypes.string, columnsCount: _react.PropTypes.number.isRequired, rowsCount: _react.PropTypes.number.isRequired }, exports["default"] = ArrowKeyStepper; }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; }, /* 4 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(5); }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowCompare */ "use strict"; /** * Does a shallow comparison for props and state. * See ReactComponentWithPureRenderMixin */ function shallowCompare(instance, nextProps, nextState) { return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState); } var shallowEqual = __webpack_require__(6); module.exports = shallowCompare; }, /* 6 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual * @typechecks * */ "use strict"; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (objA === objB) return !0; if ("object" != typeof objA || null === objA || "object" != typeof objB || null === objB) return !1; var keysA = Object.keys(objA), keysB = Object.keys(objB); if (keysA.length !== keysB.length) return !1; for (var bHasOwnProperty = hasOwnProperty.bind(objB), i = 0; i < keysA.length; i++) if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) return !1; return !0; } var hasOwnProperty = Object.prototype.hasOwnProperty; module.exports = shallowEqual; }, /* 7 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.AutoSizer = exports["default"] = void 0; var _AutoSizer2 = __webpack_require__(8), _AutoSizer3 = _interopRequireDefault(_AutoSizer2); exports["default"] = _AutoSizer3["default"], exports.AutoSizer = _AutoSizer3["default"]; }, /* 8 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), AutoSizer = function(_Component) { function AutoSizer(props) { _classCallCheck(this, AutoSizer); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(AutoSizer).call(this, props)); return _this.state = { height: 0, width: 0 }, _this._onResize = _this._onResize.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._setRef = _this._setRef.bind(_this), _this; } return _inherits(AutoSizer, _Component), _createClass(AutoSizer, [ { key: "componentDidMount", value: function() { this._detectElementResize = __webpack_require__(9), this._detectElementResize.addResizeListener(this._parentNode, this._onResize), this._onResize(); } }, { key: "componentWillUnmount", value: function() { this._detectElementResize.removeResizeListener(this._parentNode, this._onResize); } }, { key: "render", value: function() { var _props = this.props, children = _props.children, disableHeight = _props.disableHeight, disableWidth = _props.disableWidth, _state = this.state, height = _state.height, width = _state.width, outerStyle = { overflow: "visible" }; return disableHeight || (outerStyle.height = 0), disableWidth || (outerStyle.width = 0), _react2["default"].createElement("div", { ref: this._setRef, onScroll: this._onScroll, style: outerStyle }, children({ height: height, width: width })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onResize", value: function() { var onResize = this.props.onResize, _parentNode$getBoundi = this._parentNode.getBoundingClientRect(), height = _parentNode$getBoundi.height, width = _parentNode$getBoundi.width, style = getComputedStyle(this._parentNode), paddingLeft = parseInt(style.paddingLeft, 10), paddingRight = parseInt(style.paddingRight, 10), paddingTop = parseInt(style.paddingTop, 10), paddingBottom = parseInt(style.paddingBottom, 10); this.setState({ height: height - paddingTop - paddingBottom, width: width - paddingLeft - paddingRight }), onResize({ height: height, width: width }); } }, { key: "_onScroll", value: function(event) { event.stopPropagation(); } }, { key: "_setRef", value: function(autoSizer) { this._parentNode = autoSizer && autoSizer.parentNode; } } ]), AutoSizer; }(_react.Component); AutoSizer.propTypes = { children: _react.PropTypes.func.isRequired, disableHeight: _react.PropTypes.bool, disableWidth: _react.PropTypes.bool, onResize: _react.PropTypes.func.isRequired }, AutoSizer.defaultProps = { onResize: function() {} }, exports["default"] = AutoSizer; }, /* 9 */ /***/ function(module, exports) { "use strict"; var _window; _window = "undefined" != typeof window ? window : "undefined" != typeof self ? self : void 0; var attachEvent = "undefined" != typeof document && document.attachEvent, stylesCreated = !1; if (!attachEvent) { var requestFrame = function() { var raf = _window.requestAnimationFrame || _window.mozRequestAnimationFrame || _window.webkitRequestAnimationFrame || function(fn) { return _window.setTimeout(fn, 20); }; return function(fn) { return raf(fn); }; }(), cancelFrame = function() { var cancel = _window.cancelAnimationFrame || _window.mozCancelAnimationFrame || _window.webkitCancelAnimationFrame || _window.clearTimeout; return function(id) { return cancel(id); }; }(), resetTriggers = function(element) { var triggers = element.__resizeTriggers__, expand = triggers.firstElementChild, contract = triggers.lastElementChild, expandChild = expand.firstElementChild; contract.scrollLeft = contract.scrollWidth, contract.scrollTop = contract.scrollHeight, expandChild.style.width = expand.offsetWidth + 1 + "px", expandChild.style.height = expand.offsetHeight + 1 + "px", expand.scrollLeft = expand.scrollWidth, expand.scrollTop = expand.scrollHeight; }, checkTriggers = function(element) { return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height; }, scrollListener = function(e) { var element = this; resetTriggers(this), this.__resizeRAF__ && cancelFrame(this.__resizeRAF__), this.__resizeRAF__ = requestFrame(function() { checkTriggers(element) && (element.__resizeLast__.width = element.offsetWidth, element.__resizeLast__.height = element.offsetHeight, element.__resizeListeners__.forEach(function(fn) { fn.call(element, e); })); }); }, animation = !1, animationstring = "animation", keyframeprefix = "", animationstartevent = "animationstart", domPrefixes = "Webkit Moz O ms".split(" "), startEvents = "webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "), pfx = "", elm = document.createElement("fakeelement"); if (void 0 !== elm.style.animationName && (animation = !0), animation === !1) for (var i = 0; i < domPrefixes.length; i++) if (void 0 !== elm.style[domPrefixes[i] + "AnimationName"]) { pfx = domPrefixes[i], animationstring = pfx + "Animation", keyframeprefix = "-" + pfx.toLowerCase() + "-", animationstartevent = startEvents[i], animation = !0; break; } var animationName = "resizeanim", animationKeyframes = "@" + keyframeprefix + "keyframes " + animationName + " { from { opacity: 0; } to { opacity: 0; } } ", animationStyle = keyframeprefix + "animation: 1ms " + animationName + "; "; } var createStyles = function() { if (!stylesCreated) { var css = (animationKeyframes ? animationKeyframes : "") + ".resize-triggers { " + (animationStyle ? animationStyle : "") + 'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }', head = document.head || document.getElementsByTagName("head")[0], style = document.createElement("style"); style.type = "text/css", style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)), head.appendChild(style), stylesCreated = !0; } }, addResizeListener = function(element, fn) { attachEvent ? element.attachEvent("onresize", fn) : (element.__resizeTriggers__ || ("static" == getComputedStyle(element).position && (element.style.position = "relative"), createStyles(), element.__resizeLast__ = {}, element.__resizeListeners__ = [], (element.__resizeTriggers__ = document.createElement("div")).className = "resize-triggers", element.__resizeTriggers__.innerHTML = '<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>', element.appendChild(element.__resizeTriggers__), resetTriggers(element), element.addEventListener("scroll", scrollListener, !0), animationstartevent && element.__resizeTriggers__.addEventListener(animationstartevent, function(e) { e.animationName == animationName && resetTriggers(element); })), element.__resizeListeners__.push(fn)); }, removeResizeListener = function(element, fn) { attachEvent ? element.detachEvent("onresize", fn) : (element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1), element.__resizeListeners__.length || (element.removeEventListener("scroll", scrollListener), element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__))); }; module.exports = { addResizeListener: addResizeListener, removeResizeListener: removeResizeListener }; }, /* 10 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ColumnSizer = exports["default"] = void 0; var _ColumnSizer2 = __webpack_require__(11), _ColumnSizer3 = _interopRequireDefault(_ColumnSizer2); exports["default"] = _ColumnSizer3["default"], exports.ColumnSizer = _ColumnSizer3["default"]; }, /* 11 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(12), _Grid2 = _interopRequireDefault(_Grid), ColumnSizer = function(_Component) { function ColumnSizer(props, context) { _classCallCheck(this, ColumnSizer); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ColumnSizer).call(this, props, context)); return _this._registerChild = _this._registerChild.bind(_this), _this; } return _inherits(ColumnSizer, _Component), _createClass(ColumnSizer, [ { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props = this.props, columnMaxWidth = _props.columnMaxWidth, columnMinWidth = _props.columnMinWidth, columnsCount = _props.columnsCount, width = _props.width; columnMaxWidth === prevProps.columnMaxWidth && columnMinWidth === prevProps.columnMinWidth && columnsCount === prevProps.columnsCount && width === prevProps.width || this._registeredChild && this._registeredChild.recomputeGridSize(); } }, { key: "render", value: function() { var _props2 = this.props, children = _props2.children, columnMaxWidth = _props2.columnMaxWidth, columnMinWidth = _props2.columnMinWidth, columnsCount = _props2.columnsCount, width = _props2.width, safeColumnMinWidth = columnMinWidth || 1, safeColumnMaxWidth = columnMaxWidth ? Math.min(columnMaxWidth, width) : width, columnWidth = width / columnsCount; columnWidth = Math.max(safeColumnMinWidth, columnWidth), columnWidth = Math.min(safeColumnMaxWidth, columnWidth), columnWidth = Math.floor(columnWidth); var adjustedWidth = Math.min(width, columnWidth * columnsCount); return children({ adjustedWidth: adjustedWidth, getColumnWidth: function() { return columnWidth; }, registerChild: this._registerChild }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_registerChild", value: function(child) { if (null !== child && !(child instanceof _Grid2["default"])) throw Error("Unexpected child type registered; only Grid children are supported."); this._registeredChild = child, this._registeredChild && this._registeredChild.recomputeGridSize(); } } ]), ColumnSizer; }(_react.Component); ColumnSizer.propTypes = { children: _react.PropTypes.func.isRequired, columnMaxWidth: _react.PropTypes.number, columnMinWidth: _react.PropTypes.number, columnsCount: _react.PropTypes.number.isRequired, width: _react.PropTypes.number.isRequired }, exports["default"] = ColumnSizer; }, /* 12 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.Grid = exports["default"] = void 0; var _Grid2 = __webpack_require__(13), _Grid3 = _interopRequireDefault(_Grid2); exports["default"] = _Grid3["default"], exports.Grid = _Grid3["default"]; }, /* 13 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function defaultRenderCellRanges(_ref4) { for (var columnMetadata = _ref4.columnMetadata, columnStartIndex = _ref4.columnStartIndex, columnStopIndex = _ref4.columnStopIndex, renderCell = _ref4.renderCell, rowMetadata = _ref4.rowMetadata, rowStartIndex = _ref4.rowStartIndex, rowStopIndex = _ref4.rowStopIndex, renderedCells = [], rowIndex = rowStartIndex; rowStopIndex >= rowIndex; rowIndex++) for (var rowDatum = rowMetadata[rowIndex], columnIndex = columnStartIndex; columnStopIndex >= columnIndex; columnIndex++) { var columnDatum = columnMetadata[columnIndex], renderedCell = renderCell({ columnIndex: columnIndex, rowIndex: rowIndex }), key = rowIndex + "-" + columnIndex; if (null != renderedCell && renderedCell !== !1) { var child = _jsx("div", { className: "Grid__cell", style: { height: rowDatum.size, left: columnDatum.offset, top: rowDatum.offset, width: columnDatum.size } }, key, renderedCell); renderedCells.push(child); } } return renderedCells; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _jsx = function() { var REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103; return function(type, props, key, children) { var defaultProps = type && type.defaultProps, childrenLength = arguments.length - 3; if (props || 0 === childrenLength || (props = {}), props && defaultProps) for (var propName in defaultProps) void 0 === props[propName] && (props[propName] = defaultProps[propName]); else props || (props = defaultProps || {}); if (1 === childrenLength) props.children = children; else if (childrenLength > 1) { for (var childArray = Array(childrenLength), i = 0; childrenLength > i; i++) childArray[i] = arguments[i + 3]; props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: void 0 === key ? null : "" + key, ref: null, props: props, _owner: null }; }; }(), _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _GridUtils = __webpack_require__(14), _classnames = __webpack_require__(15), _classnames2 = _interopRequireDefault(_classnames), _raf = __webpack_require__(16), _raf2 = _interopRequireDefault(_raf), _scrollbarSize = __webpack_require__(19), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), IS_SCROLLING_TIMEOUT = 150, SCROLL_POSITION_CHANGE_REASONS = { OBSERVED: "observed", REQUESTED: "requested" }, Grid = function(_Component) { function Grid(props, context) { _classCallCheck(this, Grid); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Grid).call(this, props, context)); return _this.state = { computeGridMetadataOnNextUpdate: !1, isScrolling: !1, scrollLeft: 0, scrollTop: 0 }, _this._onGridRenderedMemoizer = (0, _GridUtils.createCallbackMemoizer)(), _this._onScrollMemoizer = (0, _GridUtils.createCallbackMemoizer)(!1), _this._computeColumnMetadata = _this._computeColumnMetadata.bind(_this), _this._computeRowMetadata = _this._computeRowMetadata.bind(_this), _this._invokeOnGridRenderedHelper = _this._invokeOnGridRenderedHelper.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._updateScrollLeftForScrollToColumn = _this._updateScrollLeftForScrollToColumn.bind(_this), _this._updateScrollTopForScrollToRow = _this._updateScrollTopForScrollToRow.bind(_this), _this; } return _inherits(Grid, _Component), _createClass(Grid, [ { key: "recomputeGridSize", value: function() { this.setState({ computeGridMetadataOnNextUpdate: !0 }); } }, { key: "componentDidMount", value: function() { var _props = this.props, scrollLeft = _props.scrollLeft, scrollToColumn = _props.scrollToColumn, scrollTop = _props.scrollTop, scrollToRow = _props.scrollToRow; this._scrollbarSize = (0, _scrollbarSize2["default"])(), (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({ scrollLeft: scrollLeft, scrollTop: scrollTop }), (scrollToColumn >= 0 || scrollToRow >= 0) && (this._updateScrollLeftForScrollToColumn(), this._updateScrollTopForScrollToRow()), this._invokeOnGridRenderedHelper(), this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft || 0, scrollTop: scrollTop || 0, totalColumnsWidth: this._getTotalColumnsWidth(), totalRowsHeight: this._getTotalRowsHeight() }); } }, { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props2 = this.props, columnsCount = _props2.columnsCount, columnWidth = _props2.columnWidth, height = _props2.height, rowHeight = _props2.rowHeight, rowsCount = _props2.rowsCount, scrollToColumn = _props2.scrollToColumn, scrollToRow = _props2.scrollToRow, width = _props2.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollTop = _state.scrollTop; scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this.refs.scrollingContainer.scrollLeft && (this.refs.scrollingContainer.scrollLeft = scrollLeft), scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this.refs.scrollingContainer.scrollTop && (this.refs.scrollingContainer.scrollTop = scrollTop)), (0, _GridUtils.updateScrollIndexHelper)({ cellsCount: columnsCount, cellMetadata: this._columnMetadata, cellSize: columnWidth, previousCellsCount: prevProps.columnsCount, previousCellSize: prevProps.columnWidth, previousScrollToIndex: prevProps.scrollToColumn, previousSize: prevProps.width, scrollOffset: scrollLeft, scrollToIndex: scrollToColumn, size: width, updateScrollIndexCallback: this._updateScrollLeftForScrollToColumn }), (0, _GridUtils.updateScrollIndexHelper)({ cellsCount: rowsCount, cellMetadata: this._rowMetadata, cellSize: rowHeight, previousCellsCount: prevProps.rowsCount, previousCellSize: prevProps.rowHeight, previousScrollToIndex: prevProps.scrollToRow, previousSize: prevProps.height, scrollOffset: scrollTop, scrollToIndex: scrollToRow, size: height, updateScrollIndexCallback: this._updateScrollTopForScrollToRow }), this._invokeOnGridRenderedHelper(); } }, { key: "componentWillMount", value: function() { this._computeColumnMetadata(this.props), this._computeRowMetadata(this.props); } }, { key: "componentWillUnmount", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { 0 === nextProps.columnsCount && 0 !== nextState.scrollLeft || 0 === nextProps.rowsCount && 0 !== nextState.scrollTop ? this._setScrollPosition({ scrollLeft: 0, scrollTop: 0 }) : nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({ scrollLeft: nextProps.scrollLeft, scrollTop: nextProps.scrollTop }), (0, _GridUtils.computeCellMetadataAndUpdateScrollOffsetHelper)({ cellsCount: this.props.columnsCount, cellSize: this.props.columnWidth, computeMetadataCallback: this._computeColumnMetadata, computeMetadataCallbackProps: nextProps, computeMetadataOnNextUpdate: nextState.computeGridMetadataOnNextUpdate, nextCellsCount: nextProps.columnsCount, nextCellSize: nextProps.columnWidth, nextScrollToIndex: nextProps.scrollToColumn, scrollToIndex: this.props.scrollToColumn, updateScrollOffsetForScrollToIndex: this._updateScrollLeftForScrollToColumn }), (0, _GridUtils.computeCellMetadataAndUpdateScrollOffsetHelper)({ cellsCount: this.props.rowsCount, cellSize: this.props.rowHeight, computeMetadataCallback: this._computeRowMetadata, computeMetadataCallbackProps: nextProps, computeMetadataOnNextUpdate: nextState.computeGridMetadataOnNextUpdate, nextCellsCount: nextProps.rowsCount, nextCellSize: nextProps.rowHeight, nextScrollToIndex: nextProps.scrollToRow, scrollToIndex: this.props.scrollToRow, updateScrollOffsetForScrollToIndex: this._updateScrollTopForScrollToRow }), this.setState({ computeGridMetadataOnNextUpdate: !1 }); } }, { key: "render", value: function() { var _props3 = this.props, className = _props3.className, columnsCount = _props3.columnsCount, height = _props3.height, noContentRenderer = _props3.noContentRenderer, overscanColumnsCount = _props3.overscanColumnsCount, overscanRowsCount = _props3.overscanRowsCount, renderCell = _props3.renderCell, renderCellRanges = _props3.renderCellRanges, rowsCount = _props3.rowsCount, width = _props3.width, _state2 = this.state, isScrolling = _state2.isScrolling, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop, childrenToDisplay = []; if (height > 0 && width > 0) { var visibleColumnIndices = (0, _GridUtils.getVisibleCellIndices)({ cellsCount: columnsCount, cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft }), visibleRowIndices = (0, _GridUtils.getVisibleCellIndices)({ cellsCount: rowsCount, cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop }); this._renderedColumnStartIndex = visibleColumnIndices.start, this._renderedColumnStopIndex = visibleColumnIndices.stop, this._renderedRowStartIndex = visibleRowIndices.start, this._renderedRowStopIndex = visibleRowIndices.stop; var overscanColumnIndices = (0, _GridUtils.getOverscanIndices)({ cellsCount: columnsCount, overscanCellsCount: overscanColumnsCount, startIndex: this._renderedColumnStartIndex, stopIndex: this._renderedColumnStopIndex }), overscanRowIndices = (0, _GridUtils.getOverscanIndices)({ cellsCount: rowsCount, overscanCellsCount: overscanRowsCount, startIndex: this._renderedRowStartIndex, stopIndex: this._renderedRowStopIndex }); this._columnStartIndex = overscanColumnIndices.overscanStartIndex, this._columnStopIndex = overscanColumnIndices.overscanStopIndex, this._rowStartIndex = overscanRowIndices.overscanStartIndex, this._rowStopIndex = overscanRowIndices.overscanStopIndex, childrenToDisplay = renderCellRanges({ columnMetadata: this._columnMetadata, columnStartIndex: this._columnStartIndex, columnStopIndex: this._columnStopIndex, renderCell: renderCell, rowMetadata: this._rowMetadata, rowStartIndex: this._rowStartIndex, rowStopIndex: this._rowStopIndex }); } var gridStyle = { height: height, width: width }, totalColumnsWidth = this._getTotalColumnsWidth(), totalRowsHeight = this._getTotalRowsHeight(); return width >= totalColumnsWidth && (gridStyle.overflowX = "hidden"), height >= totalRowsHeight && (gridStyle.overflowY = "hidden"), _react2["default"].createElement("div", { ref: "scrollingContainer", "aria-label": this.props["aria-label"], className: (0, _classnames2["default"])("Grid", className), onScroll: this._onScroll, role: "grid", style: gridStyle, tabIndex: 0 }, childrenToDisplay.length > 0 && _jsx("div", { className: "Grid__innerScrollContainer", style: { width: totalColumnsWidth, height: totalRowsHeight, maxWidth: totalColumnsWidth, maxHeight: totalRowsHeight, pointerEvents: isScrolling ? "none" : "auto" } }, void 0, childrenToDisplay), 0 === childrenToDisplay.length && noContentRenderer()); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_computeColumnMetadata", value: function(props) { var columnsCount = props.columnsCount, columnWidth = props.columnWidth; this._columnMetadata = (0, _GridUtils.initCellMetadata)({ cellsCount: columnsCount, size: columnWidth }); } }, { key: "_computeRowMetadata", value: function(props) { var rowHeight = props.rowHeight, rowsCount = props.rowsCount; this._rowMetadata = (0, _GridUtils.initCellMetadata)({ cellsCount: rowsCount, size: rowHeight }); } }, { key: "_enablePointerEventsAfterDelay", value: function() { var _this2 = this; this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._disablePointerEventsTimeoutId = setTimeout(function() { _this2._disablePointerEventsTimeoutId = null, _this2.setState({ isScrolling: !1 }); }, IS_SCROLLING_TIMEOUT); } }, { key: "_getTotalColumnsWidth", value: function() { if (0 === this._columnMetadata.length) return 0; var datum = this._columnMetadata[this._columnMetadata.length - 1]; return datum.offset + datum.size; } }, { key: "_getTotalRowsHeight", value: function() { if (0 === this._rowMetadata.length) return 0; var datum = this._rowMetadata[this._rowMetadata.length - 1]; return datum.offset + datum.size; } }, { key: "_invokeOnGridRenderedHelper", value: function() { var onSectionRendered = this.props.onSectionRendered; this._onGridRenderedMemoizer({ callback: onSectionRendered, indices: { columnOverscanStartIndex: this._columnStartIndex, columnOverscanStopIndex: this._columnStopIndex, columnStartIndex: this._renderedColumnStartIndex, columnStopIndex: this._renderedColumnStopIndex, rowOverscanStartIndex: this._rowStartIndex, rowOverscanStopIndex: this._rowStopIndex, rowStartIndex: this._renderedRowStartIndex, rowStopIndex: this._renderedRowStopIndex } }); } }, { key: "_invokeOnScrollMemoizer", value: function(_ref) { var scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, totalColumnsWidth = _ref.totalColumnsWidth, totalRowsHeight = _ref.totalRowsHeight, _props4 = this.props, height = _props4.height, onScroll = _props4.onScroll, width = _props4.width; this._onScrollMemoizer({ callback: function(_ref2) { var scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop; onScroll({ clientHeight: height, clientWidth: width, scrollHeight: totalRowsHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: totalColumnsWidth }); }, indices: { scrollLeft: scrollLeft, scrollTop: scrollTop } }); } }, { key: "_setNextState", value: function(state) { var _this3 = this; this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId), this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() { _this3._setNextStateAnimationFrameId = null, _this3.setState(state); }); } }, { key: "_setScrollPosition", value: function(_ref3) { var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, newState = { scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED }; scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop), (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState); } }, { key: "_updateScrollLeftForScrollToColumn", value: function(scrollToColumnOverride) { var scrollToColumn = null != scrollToColumnOverride ? scrollToColumnOverride : this.props.scrollToColumn, width = this.props.width, scrollLeft = this.state.scrollLeft; if (scrollToColumn >= 0) { var calculatedScrollLeft = (0, _GridUtils.getUpdatedOffsetForIndex)({ cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft, targetIndex: scrollToColumn }); scrollLeft !== calculatedScrollLeft && this._setScrollPosition({ scrollLeft: calculatedScrollLeft }); } } }, { key: "_updateScrollTopForScrollToRow", value: function(scrollToRowOverride) { var scrollToRow = null != scrollToRowOverride ? scrollToRowOverride : this.props.scrollToRow, height = this.props.height, scrollTop = this.state.scrollTop; if (scrollToRow >= 0) { var calculatedScrollTop = (0, _GridUtils.getUpdatedOffsetForIndex)({ cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop, targetIndex: scrollToRow }); scrollTop !== calculatedScrollTop && this._setScrollPosition({ scrollTop: calculatedScrollTop }); } } }, { key: "_onScroll", value: function(event) { if (event.target === this.refs.scrollingContainer) { this._enablePointerEventsAfterDelay(); var _props5 = this.props, height = _props5.height, width = _props5.width, scrollbarSize = this._scrollbarSize, totalRowsHeight = this._getTotalRowsHeight(), totalColumnsWidth = this._getTotalColumnsWidth(), scrollLeft = Math.min(totalColumnsWidth - width + scrollbarSize, event.target.scrollLeft), scrollTop = Math.min(totalRowsHeight - height + scrollbarSize, event.target.scrollTop); if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED; this.state.isScrolling || this.setState({ isScrolling: !0 }), this._setNextState({ isScrolling: !0, scrollLeft: scrollLeft, scrollPositionChangeReason: scrollPositionChangeReason, scrollTop: scrollTop }); } this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft, scrollTop: scrollTop, totalColumnsWidth: totalColumnsWidth, totalRowsHeight: totalRowsHeight }); } } } ]), Grid; }(_react.Component); Grid.propTypes = { "aria-label": _react.PropTypes.string, className: _react.PropTypes.string, columnsCount: _react.PropTypes.number.isRequired, columnWidth: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, height: _react.PropTypes.number.isRequired, noContentRenderer: _react.PropTypes.func.isRequired, onScroll: _react.PropTypes.func.isRequired, onSectionRendered: _react.PropTypes.func.isRequired, overscanColumnsCount: _react.PropTypes.number.isRequired, overscanRowsCount: _react.PropTypes.number.isRequired, renderCell: _react.PropTypes.func.isRequired, renderCellRanges: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowsCount: _react.PropTypes.number.isRequired, scrollLeft: _react.PropTypes.number, scrollToColumn: _react.PropTypes.number, scrollTop: _react.PropTypes.number, scrollToRow: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, Grid.defaultProps = { "aria-label": "grid", noContentRenderer: function() { return null; }, onScroll: function() { return null; }, onSectionRendered: function() { return null; }, overscanColumnsCount: 0, overscanRowsCount: 10, renderCellRanges: defaultRenderCellRanges }, exports["default"] = Grid; }, /* 14 */ /***/ function(module, exports) { "use strict"; function computeCellMetadataAndUpdateScrollOffsetHelper(_ref) { var cellsCount = _ref.cellsCount, cellSize = _ref.cellSize, computeMetadataCallback = _ref.computeMetadataCallback, computeMetadataCallbackProps = _ref.computeMetadataCallbackProps, computeMetadataOnNextUpdate = _ref.computeMetadataOnNextUpdate, nextCellsCount = _ref.nextCellsCount, nextCellSize = _ref.nextCellSize, nextScrollToIndex = _ref.nextScrollToIndex, scrollToIndex = _ref.scrollToIndex, updateScrollOffsetForScrollToIndex = _ref.updateScrollOffsetForScrollToIndex; (computeMetadataOnNextUpdate || cellsCount !== nextCellsCount || ("number" == typeof cellSize || "number" == typeof nextCellSize) && cellSize !== nextCellSize) && (computeMetadataCallback(computeMetadataCallbackProps), scrollToIndex >= 0 && scrollToIndex === nextScrollToIndex && updateScrollOffsetForScrollToIndex()); } function createCallbackMemoizer() { var requireAllKeys = arguments.length <= 0 || void 0 === arguments[0] ? !0 : arguments[0], cachedIndices = {}; return function(_ref2) { var callback = _ref2.callback, indices = _ref2.indices, keys = Object.keys(indices), allInitialized = !requireAllKeys || keys.every(function(key) { return indices[key] >= 0; }), indexChanged = keys.some(function(key) { return cachedIndices[key] !== indices[key]; }); cachedIndices = indices, allInitialized && indexChanged && callback(indices); }; } function findNearestCell(_ref3) { for (var cellMetadata = _ref3.cellMetadata, mode = _ref3.mode, offset = _ref3.offset, high = cellMetadata.length - 1, low = 0, middle = void 0, currentOffset = void 0; high >= low; ) { if (middle = low + Math.floor((high - low) / 2), currentOffset = cellMetadata[middle].offset, currentOffset === offset) return middle; offset > currentOffset ? low = middle + 1 : currentOffset > offset && (high = middle - 1); } return mode === findNearestCell.EQUAL_OR_LOWER && low > 0 ? low - 1 : mode === findNearestCell.EQUAL_OR_HIGHER && high < cellMetadata.length - 1 ? high + 1 : void 0; } function getOverscanIndices(_ref4) { var cellsCount = _ref4.cellsCount, overscanCellsCount = _ref4.overscanCellsCount, startIndex = _ref4.startIndex, stopIndex = _ref4.stopIndex; return { overscanStartIndex: Math.max(0, startIndex - overscanCellsCount), overscanStopIndex: Math.min(cellsCount - 1, stopIndex + overscanCellsCount) }; } function getUpdatedOffsetForIndex(_ref5) { var cellMetadata = _ref5.cellMetadata, containerSize = _ref5.containerSize, currentOffset = _ref5.currentOffset, targetIndex = _ref5.targetIndex; if (0 === cellMetadata.length) return 0; targetIndex = Math.max(0, Math.min(cellMetadata.length - 1, targetIndex)); var datum = cellMetadata[targetIndex], maxOffset = datum.offset, minOffset = maxOffset - containerSize + datum.size, newOffset = Math.max(minOffset, Math.min(maxOffset, currentOffset)); return newOffset; } function getVisibleCellIndices(_ref6) { var cellsCount = _ref6.cellsCount, cellMetadata = _ref6.cellMetadata, containerSize = _ref6.containerSize, currentOffset = _ref6.currentOffset; if (0 === cellsCount) return {}; var lastDatum = cellMetadata[cellMetadata.length - 1], totalCellSize = lastDatum.offset + lastDatum.size; currentOffset = Math.max(0, Math.min(totalCellSize - containerSize, currentOffset)); var maxOffset = Math.min(totalCellSize, currentOffset + containerSize), start = findNearestCell({ cellMetadata: cellMetadata, mode: findNearestCell.EQUAL_OR_LOWER, offset: currentOffset }), datum = cellMetadata[start]; currentOffset = datum.offset + datum.size; for (var stop = start; maxOffset > currentOffset && cellsCount - 1 > stop; ) stop++, currentOffset += cellMetadata[stop].size; return { start: start, stop: stop }; } function initCellMetadata(_ref7) { for (var cellsCount = _ref7.cellsCount, size = _ref7.size, sizeGetter = size instanceof Function ? size : function(index) { return size; }, cellMetadata = [], offset = 0, i = 0; cellsCount > i; i++) { var _size = sizeGetter(i); if (null == _size || isNaN(_size)) throw Error("Invalid size returned for cell " + i + " of value " + _size); cellMetadata[i] = { size: _size, offset: offset }, offset += _size; } return cellMetadata; } function updateScrollIndexHelper(_ref8) { var cellMetadata = _ref8.cellMetadata, cellsCount = _ref8.cellsCount, cellSize = _ref8.cellSize, previousCellsCount = _ref8.previousCellsCount, previousCellSize = _ref8.previousCellSize, previousScrollToIndex = _ref8.previousScrollToIndex, previousSize = _ref8.previousSize, scrollOffset = _ref8.scrollOffset, scrollToIndex = _ref8.scrollToIndex, size = _ref8.size, updateScrollIndexCallback = _ref8.updateScrollIndexCallback, hasScrollToIndex = scrollToIndex >= 0 && cellsCount > scrollToIndex, sizeHasChanged = size !== previousSize || !previousCellSize || "number" == typeof cellSize && cellSize !== previousCellSize; if (hasScrollToIndex && (sizeHasChanged || scrollToIndex !== previousScrollToIndex)) updateScrollIndexCallback(); else if (!hasScrollToIndex && (previousSize > size || previousCellsCount > cellsCount)) { var calculatedScrollOffset = getUpdatedOffsetForIndex({ cellMetadata: cellMetadata, containerSize: size, currentOffset: scrollOffset, targetIndex: cellsCount - 1 }); scrollOffset > calculatedScrollOffset && updateScrollIndexCallback(cellsCount - 1); } } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.computeCellMetadataAndUpdateScrollOffsetHelper = computeCellMetadataAndUpdateScrollOffsetHelper, exports.createCallbackMemoizer = createCallbackMemoizer, exports.findNearestCell = findNearestCell, exports.getOverscanIndices = getOverscanIndices, exports.getUpdatedOffsetForIndex = getUpdatedOffsetForIndex, exports.getVisibleCellIndices = getVisibleCellIndices, exports.initCellMetadata = initCellMetadata, exports.updateScrollIndexHelper = updateScrollIndexHelper, findNearestCell.EQUAL_OR_LOWER = 1, findNearestCell.EQUAL_OR_HIGHER = 2; }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ !function() { "use strict"; function classNames() { for (var classes = [], i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { var argType = typeof arg; if ("string" === argType || "number" === argType) classes.push(arg); else if (Array.isArray(arg)) classes.push(classNames.apply(null, arg)); else if ("object" === argType) for (var key in arg) hasOwn.call(arg, key) && arg[key] && classes.push(key); } } return classes.join(" "); } var hasOwn = {}.hasOwnProperty; "undefined" != typeof module && module.exports ? module.exports = classNames : (__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), !(void 0 !== __WEBPACK_AMD_DEFINE_RESULT__ && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))); }(); }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(global) { for (var now = __webpack_require__(17), root = "undefined" == typeof window ? global : window, vendors = [ "moz", "webkit" ], suffix = "AnimationFrame", raf = root["request" + suffix], caf = root["cancel" + suffix] || root["cancelRequest" + suffix], i = 0; !raf && i < vendors.length; i++) raf = root[vendors[i] + "Request" + suffix], caf = root[vendors[i] + "Cancel" + suffix] || root[vendors[i] + "CancelRequest" + suffix]; // Some versions of FF have rAF but not cAF if (!raf || !caf) { var last = 0, id = 0, queue = [], frameDuration = 1e3 / 60; raf = function(callback) { if (0 === queue.length) { var _now = now(), next = Math.max(0, frameDuration - (_now - last)); last = next + _now, setTimeout(function() { var cp = queue.slice(0); // Clear queue here to prevent // callbacks from appending listeners // to the current frame's queue queue.length = 0; for (var i = 0; i < cp.length; i++) if (!cp[i].cancelled) try { cp[i].callback(last); } catch (e) { setTimeout(function() { throw e; }, 0); } }, Math.round(next)); } return queue.push({ handle: ++id, callback: callback, cancelled: !1 }), id; }, caf = function(handle) { for (var i = 0; i < queue.length; i++) queue[i].handle === handle && (queue[i].cancelled = !0); }; } module.exports = function(fn) { // Wrap in a new function to prevent // `cancel` potentially being assigned // to the native rAF function return raf.call(root, fn); }, module.exports.cancel = function() { caf.apply(root, arguments); }, module.exports.polyfill = function() { root.requestAnimationFrame = raf, root.cancelAnimationFrame = caf; }; }).call(exports, function() { return this; }()); }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { // Generated by CoffeeScript 1.7.1 (function() { var getNanoSeconds, hrtime, loadTime; "undefined" != typeof performance && null !== performance && performance.now ? module.exports = function() { return performance.now(); } : "undefined" != typeof process && null !== process && process.hrtime ? (module.exports = function() { return (getNanoSeconds() - loadTime) / 1e6; }, hrtime = process.hrtime, getNanoSeconds = function() { var hr; return hr = hrtime(), 1e9 * hr[0] + hr[1]; }, loadTime = getNanoSeconds()) : Date.now ? (module.exports = function() { return Date.now() - loadTime; }, loadTime = Date.now()) : (module.exports = function() { return new Date().getTime() - loadTime; }, loadTime = new Date().getTime()); }).call(this); }).call(exports, __webpack_require__(18)); }, /* 18 */ /***/ function(module, exports) { function cleanUpNextTick() { draining = !1, currentQueue.length ? queue = currentQueue.concat(queue) : queueIndex = -1, queue.length && drainQueue(); } function drainQueue() { if (!draining) { var timeout = setTimeout(cleanUpNextTick); draining = !0; for (var len = queue.length; len; ) { for (currentQueue = queue, queue = []; ++queueIndex < len; ) currentQueue && currentQueue[queueIndex].run(); queueIndex = -1, len = queue.length; } currentQueue = null, draining = !1, clearTimeout(timeout); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun, this.array = array; } function noop() {} // shim for using process in browser var currentQueue, process = module.exports = {}, queue = [], draining = !1, queueIndex = -1; process.nextTick = function(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i]; queue.push(new Item(fun, args)), 1 !== queue.length || draining || setTimeout(drainQueue, 0); }, Item.prototype.run = function() { this.fun.apply(null, this.array); }, process.title = "browser", process.browser = !0, process.env = {}, process.argv = [], process.version = "", // empty string to avoid regexp issues process.versions = {}, process.on = noop, process.addListener = noop, process.once = noop, process.off = noop, process.removeListener = noop, process.removeAllListeners = noop, process.emit = noop, process.binding = function(name) { throw new Error("process.binding is not supported"); }, process.cwd = function() { return "/"; }, process.chdir = function(dir) { throw new Error("process.chdir is not supported"); }, process.umask = function() { return 0; }; }, /* 19 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var size, canUseDOM = __webpack_require__(20); module.exports = function(recalc) { if ((!size || recalc) && canUseDOM) { var scrollDiv = document.createElement("div"); scrollDiv.style.position = "absolute", scrollDiv.style.top = "-9999px", scrollDiv.style.width = "50px", scrollDiv.style.height = "50px", scrollDiv.style.overflow = "scroll", document.body.appendChild(scrollDiv), size = scrollDiv.offsetWidth - scrollDiv.clientWidth, document.body.removeChild(scrollDiv); } return size; }; }, /* 20 */ /***/ function(module, exports) { "use strict"; module.exports = !("undefined" == typeof window || !window.document || !window.document.createElement); }, /* 21 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.SortIndicator = exports.SortDirection = exports.FlexColumn = exports.FlexTable = exports["default"] = void 0; var _FlexTable2 = __webpack_require__(22), _FlexTable3 = _interopRequireDefault(_FlexTable2), _FlexColumn2 = __webpack_require__(23), _FlexColumn3 = _interopRequireDefault(_FlexColumn2), _SortDirection2 = __webpack_require__(25), _SortDirection3 = _interopRequireDefault(_SortDirection2), _SortIndicator2 = __webpack_require__(24), _SortIndicator3 = _interopRequireDefault(_SortIndicator2); exports["default"] = _FlexTable3["default"], exports.FlexTable = _FlexTable3["default"], exports.FlexColumn = _FlexColumn3["default"], exports.SortDirection = _SortDirection3["default"], exports.SortIndicator = _SortIndicator3["default"]; }, /* 22 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _jsx = function() { var REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103; return function(type, props, key, children) { var defaultProps = type && type.defaultProps, childrenLength = arguments.length - 3; if (props || 0 === childrenLength || (props = {}), props && defaultProps) for (var propName in defaultProps) void 0 === props[propName] && (props[propName] = defaultProps[propName]); else props || (props = defaultProps || {}); if (1 === childrenLength) props.children = children; else if (childrenLength > 1) { for (var childArray = Array(childrenLength), i = 0; childrenLength > i; i++) childArray[i] = arguments[i + 3]; props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: void 0 === key ? null : "" + key, ref: null, props: props, _owner: null }; }; }(), _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _classnames = __webpack_require__(15), _classnames2 = _interopRequireDefault(_classnames), _FlexColumn = __webpack_require__(23), _FlexColumn2 = _interopRequireDefault(_FlexColumn), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(26), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(12), _Grid2 = _interopRequireDefault(_Grid), _SortDirection = __webpack_require__(25), _SortDirection2 = _interopRequireDefault(_SortDirection), FlexTable = function(_Component) { function FlexTable(props) { _classCallCheck(this, FlexTable); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(FlexTable).call(this, props)); return _this.state = { scrollbarWidth: 0 }, _this._createRow = _this._createRow.bind(_this), _this; } return _inherits(FlexTable, _Component), _createClass(FlexTable, [ { key: "recomputeRowHeights", value: function() { this.refs.Grid.recomputeGridSize(); } }, { key: "componentDidMount", value: function() { this._setScrollbarWidth(); } }, { key: "componentDidUpdate", value: function() { this._setScrollbarWidth(); } }, { key: "render", value: function() { var _this2 = this, _props = this.props, className = _props.className, disableHeader = _props.disableHeader, headerHeight = _props.headerHeight, height = _props.height, noRowsRenderer = _props.noRowsRenderer, onRowsRendered = _props.onRowsRendered, _onScroll = _props.onScroll, overscanRowsCount = _props.overscanRowsCount, rowClassName = _props.rowClassName, rowHeight = _props.rowHeight, rowsCount = _props.rowsCount, scrollToIndex = _props.scrollToIndex, scrollTop = _props.scrollTop, width = _props.width, scrollbarWidth = this.state.scrollbarWidth, availableRowsHeight = height - headerHeight, rowRenderer = function(index) { return _this2._createRow(index); }, rowClass = rowClassName instanceof Function ? rowClassName(-1) : rowClassName; return _jsx("div", { className: (0, _classnames2["default"])("FlexTable", className) }, void 0, !disableHeader && _jsx("div", { className: (0, _classnames2["default"])("FlexTable__headerRow", rowClass), style: { height: headerHeight, paddingRight: scrollbarWidth, width: width } }, void 0, this._getRenderedHeaderRow()), _react2["default"].createElement(_Grid2["default"], { "aria-label": this.props["aria-label"], ref: "Grid", className: "FlexTable__Grid", columnWidth: width, columnsCount: 1, height: availableRowsHeight, noContentRenderer: noRowsRenderer, onScroll: function(_ref) { var clientHeight = _ref.clientHeight, scrollHeight = _ref.scrollHeight, scrollTop = _ref.scrollTop; return _onScroll({ clientHeight: clientHeight, scrollHeight: scrollHeight, scrollTop: scrollTop }); }, onSectionRendered: function(_ref2) { var rowOverscanStartIndex = _ref2.rowOverscanStartIndex, rowOverscanStopIndex = _ref2.rowOverscanStopIndex, rowStartIndex = _ref2.rowStartIndex, rowStopIndex = _ref2.rowStopIndex; return onRowsRendered({ overscanStartIndex: rowOverscanStartIndex, overscanStopIndex: rowOverscanStopIndex, startIndex: rowStartIndex, stopIndex: rowStopIndex }); }, overscanRowsCount: overscanRowsCount, renderCell: function(_ref3) { var rowIndex = (_ref3.columnIndex, _ref3.rowIndex); return rowRenderer(rowIndex); }, rowHeight: rowHeight, rowsCount: rowsCount, scrollToRow: scrollToIndex, scrollTop: scrollTop, width: width })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_createColumn", value: function(column, columnIndex, rowData, rowIndex) { var _column$props = column.props, cellClassName = _column$props.cellClassName, cellDataGetter = _column$props.cellDataGetter, columnData = _column$props.columnData, dataKey = _column$props.dataKey, cellRenderer = _column$props.cellRenderer, cellData = cellDataGetter(dataKey, rowData, columnData), renderedCell = cellRenderer(cellData, dataKey, rowData, rowIndex, columnData), style = this._getFlexStyleForColumn(column), title = "string" == typeof renderedCell ? renderedCell : null; return _jsx("div", { className: (0, _classnames2["default"])("FlexTable__rowColumn", cellClassName), style: style }, "Row" + rowIndex + "-Col" + columnIndex, _jsx("div", { className: "FlexTable__truncatedColumnText", title: title }, void 0, renderedCell)); } }, { key: "_createHeader", value: function(column, columnIndex) { var _props2 = this.props, headerClassName = _props2.headerClassName, onHeaderClick = _props2.onHeaderClick, sort = _props2.sort, sortBy = _props2.sortBy, sortDirection = _props2.sortDirection, _column$props2 = column.props, dataKey = _column$props2.dataKey, disableSort = _column$props2.disableSort, headerRenderer = _column$props2.headerRenderer, label = _column$props2.label, columnData = _column$props2.columnData, sortEnabled = !disableSort && sort, classNames = (0, _classnames2["default"])("FlexTable__headerColumn", headerClassName, column.props.headerClassName, { FlexTable__sortableHeaderColumn: sortEnabled }), style = this._getFlexStyleForColumn(column), renderedHeader = headerRenderer({ columnData: columnData, dataKey: dataKey, disableSort: disableSort, label: label, sortBy: sortBy, sortDirection: sortDirection }), a11yProps = {}; return (sortEnabled || onHeaderClick) && !function() { var newSortDirection = sortBy !== dataKey || sortDirection === _SortDirection2["default"].DESC ? _SortDirection2["default"].ASC : _SortDirection2["default"].DESC, onClick = function() { sortEnabled && sort(dataKey, newSortDirection), onHeaderClick && onHeaderClick(dataKey, columnData); }, onKeyDown = function(event) { "Enter" !== event.key && " " !== event.key || onClick(); }; a11yProps["aria-label"] = column.props["aria-label"] || label || dataKey, a11yProps.role = "rowheader", a11yProps.tabIndex = 0, a11yProps.onClick = onClick, a11yProps.onKeyDown = onKeyDown; }(), _react2["default"].createElement("div", _extends({}, a11yProps, { key: "Header-Col" + columnIndex, className: classNames, style: style }), renderedHeader); } }, { key: "_createRow", value: function(rowIndex) { var _this3 = this, _props3 = this.props, children = _props3.children, onRowClick = _props3.onRowClick, rowClassName = _props3.rowClassName, rowGetter = _props3.rowGetter, scrollbarWidth = this.state.scrollbarWidth, rowClass = rowClassName instanceof Function ? rowClassName(rowIndex) : rowClassName, rowData = rowGetter(rowIndex), renderedRow = _react2["default"].Children.map(children, function(column, columnIndex) { return _this3._createColumn(column, columnIndex, rowData, rowIndex); }), a11yProps = {}; return onRowClick && (a11yProps["aria-label"] = "row", a11yProps.role = "row", a11yProps.tabIndex = 0, a11yProps.onClick = function() { return onRowClick(rowIndex); }), _react2["default"].createElement("div", _extends({}, a11yProps, { key: rowIndex, className: (0, _classnames2["default"])("FlexTable__row", rowClass), style: { height: this._getRowHeight(rowIndex), paddingRight: scrollbarWidth } }), renderedRow); } }, { key: "_getFlexStyleForColumn", value: function(column) { var flexValue = column.props.flexGrow + " " + column.props.flexShrink + " " + column.props.width + "px", style = { flex: flexValue, msFlex: flexValue, WebkitFlex: flexValue }; return column.props.maxWidth && (style.maxWidth = column.props.maxWidth), column.props.minWidth && (style.minWidth = column.props.minWidth), style; } }, { key: "_getRenderedHeaderRow", value: function() { var _this4 = this, _props4 = this.props, children = _props4.children, disableHeader = _props4.disableHeader, items = disableHeader ? [] : children; return _react2["default"].Children.map(items, function(column, index) { return _this4._createHeader(column, index); }); } }, { key: "_getRowHeight", value: function(rowIndex) { var rowHeight = this.props.rowHeight; return rowHeight instanceof Function ? rowHeight(rowIndex) : rowHeight; } }, { key: "_setScrollbarWidth", value: function() { var Grid = (0, _reactDom.findDOMNode)(this.refs.Grid), clientWidth = Grid.clientWidth || 0, offsetWidth = Grid.offsetWidth || 0, scrollbarWidth = offsetWidth - clientWidth; this.setState({ scrollbarWidth: scrollbarWidth }); } } ]), FlexTable; }(_react.Component); FlexTable.propTypes = { "aria-label": _react.PropTypes.string, children: function children(props, propName, componentName) { for (var children = _react2["default"].Children.toArray(props.children), i = 0; i < children.length; i++) if (children[i].type !== _FlexColumn2["default"]) return new Error("FlexTable only accepts children of type FlexColumn"); }, className: _react.PropTypes.string, disableHeader: _react.PropTypes.bool, headerClassName: _react.PropTypes.string, headerHeight: _react.PropTypes.number.isRequired, height: _react.PropTypes.number.isRequired, noRowsRenderer: _react.PropTypes.func, onHeaderClick: _react.PropTypes.func, onRowClick: _react.PropTypes.func, onRowsRendered: _react.PropTypes.func, onScroll: _react.PropTypes.func.isRequired, overscanRowsCount: _react.PropTypes.number.isRequired, rowClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), rowGetter: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowsCount: _react.PropTypes.number.isRequired, scrollToIndex: _react.PropTypes.number, scrollTop: _react.PropTypes.number, sort: _react.PropTypes.func, sortBy: _react.PropTypes.string, sortDirection: _react.PropTypes.oneOf([ _SortDirection2["default"].ASC, _SortDirection2["default"].DESC ]), width: _react.PropTypes.number.isRequired }, FlexTable.defaultProps = { disableHeader: !1, headerHeight: 0, noRowsRenderer: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; }, overscanRowsCount: 10 }, exports["default"] = FlexTable; }, /* 23 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function defaultCellRenderer(cellData, cellDataKey, rowData, rowIndex, columnData) { return null === cellData || void 0 === cellData ? "" : String(cellData); } function defaultCellDataGetter(dataKey, rowData, columnData) { return rowData.get instanceof Function ? rowData.get(dataKey) : rowData[dataKey]; } function defaultHeaderRenderer(_ref) { var dataKey = (_ref.columnData, _ref.dataKey), label = (_ref.disableSort, _ref.label), sortBy = _ref.sortBy, sortDirection = _ref.sortDirection, showSortIndicator = sortBy === dataKey, children = [ _jsx("div", { className: "FlexTable__headerTruncatedText", title: label }, "label", label) ]; return showSortIndicator && children.push(_jsx(_SortIndicator2["default"], { sortDirection: sortDirection }, "SortIndicator")), children; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _jsx = function() { var REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103; return function(type, props, key, children) { var defaultProps = type && type.defaultProps, childrenLength = arguments.length - 3; if (props || 0 === childrenLength || (props = {}), props && defaultProps) for (var propName in defaultProps) void 0 === props[propName] && (props[propName] = defaultProps[propName]); else props || (props = defaultProps || {}); if (1 === childrenLength) props.children = children; else if (childrenLength > 1) { for (var childArray = Array(childrenLength), i = 0; childrenLength > i; i++) childArray[i] = arguments[i + 3]; props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: void 0 === key ? null : "" + key, ref: null, props: props, _owner: null }; }; }(); exports.defaultCellRenderer = defaultCellRenderer, exports.defaultCellDataGetter = defaultCellDataGetter, exports.defaultHeaderRenderer = defaultHeaderRenderer; var _react = __webpack_require__(3), _SortIndicator = (_interopRequireDefault(_react), __webpack_require__(24)), _SortIndicator2 = _interopRequireDefault(_SortIndicator), Column = function(_Component) { function Column() { return _classCallCheck(this, Column), _possibleConstructorReturn(this, Object.getPrototypeOf(Column).apply(this, arguments)); } return _inherits(Column, _Component), Column; }(_react.Component); Column.defaultProps = { cellDataGetter: defaultCellDataGetter, cellRenderer: defaultCellRenderer, flexGrow: 0, flexShrink: 1, headerRenderer: defaultHeaderRenderer }, Column.propTypes = { "aria-label": _react.PropTypes.string, cellClassName: _react.PropTypes.string, cellDataGetter: _react.PropTypes.func, cellRenderer: _react.PropTypes.func, columnData: _react.PropTypes.object, dataKey: _react.PropTypes.any.isRequired, disableSort: _react.PropTypes.bool, flexGrow: _react.PropTypes.number, flexShrink: _react.PropTypes.number, headerClassName: _react.PropTypes.string, headerRenderer: _react.PropTypes.func.isRequired, label: _react.PropTypes.string, maxWidth: _react.PropTypes.number, minWidth: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, exports["default"] = Column; }, /* 24 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function SortIndicator(_ref) { var sortDirection = _ref.sortDirection, classNames = (0, _classnames2["default"])("FlexTable__sortableHeaderIcon", { "FlexTable__sortableHeaderIcon--ASC": sortDirection === _SortDirection2["default"].ASC, "FlexTable__sortableHeaderIcon--DESC": sortDirection === _SortDirection2["default"].DESC }); return _jsx("svg", { className: classNames, width: 18, height: 18, viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg" }, void 0, sortDirection === _SortDirection2["default"].ASC ? _jsx("path", { d: "M7 14l5-5 5 5z" }) : _jsx("path", { d: "M7 10l5 5 5-5z" }), _jsx("path", { d: "M0 0h24v24H0z", fill: "none" })); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _jsx = function() { var REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103; return function(type, props, key, children) { var defaultProps = type && type.defaultProps, childrenLength = arguments.length - 3; if (props || 0 === childrenLength || (props = {}), props && defaultProps) for (var propName in defaultProps) void 0 === props[propName] && (props[propName] = defaultProps[propName]); else props || (props = defaultProps || {}); if (1 === childrenLength) props.children = children; else if (childrenLength > 1) { for (var childArray = Array(childrenLength), i = 0; childrenLength > i; i++) childArray[i] = arguments[i + 3]; props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: void 0 === key ? null : "" + key, ref: null, props: props, _owner: null }; }; }(); exports["default"] = SortIndicator; var _react = __webpack_require__(3), _classnames = (_interopRequireDefault(_react), __webpack_require__(15)), _classnames2 = _interopRequireDefault(_classnames), _SortDirection = __webpack_require__(25), _SortDirection2 = _interopRequireDefault(_SortDirection); SortIndicator.propTypes = { sortDirection: _react.PropTypes.oneOf([ _SortDirection2["default"].ASC, _SortDirection2["default"].DESC ]) }; }, /* 25 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var SortDirection = { ASC: "ASC", DESC: "DESC" }; exports["default"] = SortDirection; }, /* 26 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_26__; }, /* 27 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.InfiniteLoader = exports["default"] = void 0; var _InfiniteLoader2 = __webpack_require__(28), _InfiniteLoader3 = _interopRequireDefault(_InfiniteLoader2); exports["default"] = _InfiniteLoader3["default"], exports.InfiniteLoader = _InfiniteLoader3["default"]; }, /* 28 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function isRangeVisible(_ref2) { var lastRenderedStartIndex = _ref2.lastRenderedStartIndex, lastRenderedStopIndex = _ref2.lastRenderedStopIndex, startIndex = _ref2.startIndex, stopIndex = _ref2.stopIndex; return !(startIndex > lastRenderedStopIndex || lastRenderedStartIndex > stopIndex); } function scanForUnloadedRanges(_ref3) { for (var isRowLoaded = _ref3.isRowLoaded, startIndex = _ref3.startIndex, stopIndex = _ref3.stopIndex, unloadedRanges = [], rangeStartIndex = null, rangeStopIndex = null, i = startIndex; stopIndex >= i; i++) { var loaded = isRowLoaded(i); loaded ? null !== rangeStopIndex && (unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }), rangeStartIndex = rangeStopIndex = null) : (rangeStopIndex = i, null === rangeStartIndex && (rangeStartIndex = i)); } return null !== rangeStopIndex && unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }), unloadedRanges; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(); exports.isRangeVisible = isRangeVisible, exports.scanForUnloadedRanges = scanForUnloadedRanges; var _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), InfiniteLoader = function(_Component) { function InfiniteLoader(props, context) { _classCallCheck(this, InfiniteLoader); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(InfiniteLoader).call(this, props, context)); return _this._onRowsRendered = _this._onRowsRendered.bind(_this), _this._registerChild = _this._registerChild.bind(_this), _this; } return _inherits(InfiniteLoader, _Component), _createClass(InfiniteLoader, [ { key: "render", value: function() { var children = this.props.children; return children({ onRowsRendered: this._onRowsRendered, registerChild: this._registerChild }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onRowsRendered", value: function(_ref) { var _this2 = this, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex, _props = this.props, isRowLoaded = _props.isRowLoaded, loadMoreRows = _props.loadMoreRows, rowsCount = _props.rowsCount, threshold = _props.threshold; this._lastRenderedStartIndex = startIndex, this._lastRenderedStopIndex = stopIndex; var unloadedRanges = scanForUnloadedRanges({ isRowLoaded: isRowLoaded, startIndex: Math.max(0, startIndex - threshold), stopIndex: Math.min(rowsCount, stopIndex + threshold) }); unloadedRanges.forEach(function(unloadedRange) { var promise = loadMoreRows(unloadedRange); promise && promise.then(function() { isRangeVisible({ lastRenderedStartIndex: _this2._lastRenderedStartIndex, lastRenderedStopIndex: _this2._lastRenderedStopIndex, startIndex: unloadedRange.startIndex, stopIndex: unloadedRange.stopIndex }) && _this2._registeredChild && _this2._registeredChild.forceUpdate(); }); }); } }, { key: "_registerChild", value: function(registeredChild) { this._registeredChild = registeredChild; } } ]), InfiniteLoader; }(_react.Component); InfiniteLoader.propTypes = { children: _react.PropTypes.func.isRequired, isRowLoaded: _react.PropTypes.func.isRequired, loadMoreRows: _react.PropTypes.func.isRequired, rowsCount: _react.PropTypes.number.isRequired, threshold: _react.PropTypes.number.isRequired }, InfiniteLoader.defaultProps = { rowsCount: 0, threshold: 15 }, exports["default"] = InfiniteLoader; }, /* 29 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ScrollSync = exports["default"] = void 0; var _ScrollSync2 = __webpack_require__(30), _ScrollSync3 = _interopRequireDefault(_ScrollSync2); exports["default"] = _ScrollSync3["default"], exports.ScrollSync = _ScrollSync3["default"]; }, /* 30 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ScrollSync = function(_Component) { function ScrollSync(props, context) { _classCallCheck(this, ScrollSync); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ScrollSync).call(this, props, context)); return _this.state = { clientHeight: 0, clientWidth: 0, scrollHeight: 0, scrollLeft: 0, scrollTop: 0, scrollWidth: 0 }, _this._onScroll = _this._onScroll.bind(_this), _this; } return _inherits(ScrollSync, _Component), _createClass(ScrollSync, [ { key: "render", value: function() { var children = this.props.children, _state = this.state, clientHeight = _state.clientHeight, clientWidth = _state.clientWidth, scrollHeight = _state.scrollHeight, scrollLeft = _state.scrollLeft, scrollTop = _state.scrollTop, scrollWidth = _state.scrollWidth; return children({ clientHeight: clientHeight, clientWidth: clientWidth, onScroll: this._onScroll, scrollHeight: scrollHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: scrollWidth }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onScroll", value: function(_ref) { var clientHeight = _ref.clientHeight, clientWidth = _ref.clientWidth, scrollHeight = _ref.scrollHeight, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, scrollWidth = _ref.scrollWidth; this.setState({ clientHeight: clientHeight, clientWidth: clientWidth, scrollHeight: scrollHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: scrollWidth }); } } ]), ScrollSync; }(_react.Component); ScrollSync.propTypes = { children: _react.PropTypes.func.isRequired }, exports["default"] = ScrollSync; }, /* 31 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.VirtualScroll = exports["default"] = void 0; var _VirtualScroll2 = __webpack_require__(32), _VirtualScroll3 = _interopRequireDefault(_VirtualScroll2); exports["default"] = _VirtualScroll3["default"], exports.VirtualScroll = _VirtualScroll3["default"]; }, /* 32 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _Grid = __webpack_require__(12), _Grid2 = _interopRequireDefault(_Grid), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(15), _classnames2 = _interopRequireDefault(_classnames), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), VirtualScroll = function(_Component) { function VirtualScroll() { return _classCallCheck(this, VirtualScroll), _possibleConstructorReturn(this, Object.getPrototypeOf(VirtualScroll).apply(this, arguments)); } return _inherits(VirtualScroll, _Component), _createClass(VirtualScroll, [ { key: "recomputeRowHeights", value: function() { this.refs.Grid.recomputeGridSize(); } }, { key: "render", value: function() { var _props = this.props, className = _props.className, height = _props.height, noRowsRenderer = _props.noRowsRenderer, onRowsRendered = _props.onRowsRendered, _onScroll = _props.onScroll, rowHeight = _props.rowHeight, rowRenderer = _props.rowRenderer, overscanRowsCount = _props.overscanRowsCount, rowsCount = _props.rowsCount, scrollToIndex = _props.scrollToIndex, scrollTop = _props.scrollTop, width = _props.width, classNames = (0, _classnames2["default"])("VirtualScroll", className); return _react2["default"].createElement(_Grid2["default"], { ref: "Grid", "aria-label": this.props["aria-label"], className: classNames, columnWidth: width, columnsCount: 1, height: height, noContentRenderer: noRowsRenderer, onScroll: function(_ref) { var clientHeight = _ref.clientHeight, scrollHeight = _ref.scrollHeight, scrollTop = _ref.scrollTop; return _onScroll({ clientHeight: clientHeight, scrollHeight: scrollHeight, scrollTop: scrollTop }); }, onSectionRendered: function(_ref2) { var rowOverscanStartIndex = _ref2.rowOverscanStartIndex, rowOverscanStopIndex = _ref2.rowOverscanStopIndex, rowStartIndex = _ref2.rowStartIndex, rowStopIndex = _ref2.rowStopIndex; return onRowsRendered({ overscanStartIndex: rowOverscanStartIndex, overscanStopIndex: rowOverscanStopIndex, startIndex: rowStartIndex, stopIndex: rowStopIndex }); }, overscanRowsCount: overscanRowsCount, renderCell: function(_ref3) { var rowIndex = (_ref3.columnIndex, _ref3.rowIndex); return rowRenderer(rowIndex); }, rowHeight: rowHeight, rowsCount: rowsCount, scrollToRow: scrollToIndex, scrollTop: scrollTop, width: width }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } } ]), VirtualScroll; }(_react.Component); VirtualScroll.propTypes = { "aria-label": _react.PropTypes.string, className: _react.PropTypes.string, height: _react.PropTypes.number.isRequired, noRowsRenderer: _react.PropTypes.func.isRequired, onRowsRendered: _react.PropTypes.func.isRequired, overscanRowsCount: _react.PropTypes.number.isRequired, onScroll: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowRenderer: _react.PropTypes.func.isRequired, rowsCount: _react.PropTypes.number.isRequired, scrollToIndex: _react.PropTypes.number, scrollTop: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, VirtualScroll.defaultProps = { noRowsRenderer: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; }, overscanRowsCount: 10 }, exports["default"] = VirtualScroll; } ]); }); //# sourceMappingURL=react-virtualized.js.map
mit
aexeagmbh/dockerfiles
es-tools/HQ/js/lib/ace/src-noconflict/snippets/coffee.js
2460
ace.define('ace/snippets/coffee', ['require', 'exports', 'module' ], function(require, exports, module) { exports.snippetText = "# Closure loop\n\ snippet forindo\n\ for ${1:name} in ${2:array}\n\ do ($1) ->\n\ ${3:// body}\n\ # Array comprehension\n\ snippet fora\n\ for ${1:name} in ${2:array}\n\ ${3:// body...}\n\ # Object comprehension\n\ snippet foro\n\ for ${1:key}, ${2:value} of ${3:object}\n\ ${4:// body...}\n\ # Range comprehension (inclusive)\n\ snippet forr\n\ for ${1:name} in [${2:start}..${3:finish}]\n\ ${4:// body...}\n\ snippet forrb\n\ for ${1:name} in [${2:start}..${3:finish}] by ${4:step}\n\ ${5:// body...}\n\ # Range comprehension (exclusive)\n\ snippet forrex\n\ for ${1:name} in [${2:start}...${3:finish}]\n\ ${4:// body...}\n\ snippet forrexb\n\ for ${1:name} in [${2:start}...${3:finish}] by ${4:step}\n\ ${5:// body...}\n\ # Function\n\ snippet fun\n\ (${1:args}) ->\n\ ${2:// body...}\n\ # Function (bound)\n\ snippet bfun\n\ (${1:args}) =>\n\ ${2:// body...}\n\ # Class\n\ snippet cla class ..\n\ class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\ ${2}\n\ snippet cla class .. constructor: ..\n\ class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\ constructor: (${2:args}) ->\n\ ${3}\n\ \n\ ${4}\n\ snippet cla class .. extends ..\n\ class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} extends ${2:ParentClass}\n\ ${3}\n\ snippet cla class .. extends .. constructor: ..\n\ class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} extends ${2:ParentClass}\n\ constructor: (${3:args}) ->\n\ ${4}\n\ \n\ ${5}\n\ # If\n\ snippet if\n\ if ${1:condition}\n\ ${2:// body...}\n\ # If __ Else\n\ snippet ife\n\ if ${1:condition}\n\ ${2:// body...}\n\ else\n\ ${3:// body...}\n\ # Else if\n\ snippet elif\n\ else if ${1:condition}\n\ ${2:// body...}\n\ # Ternary If\n\ snippet ifte\n\ if ${1:condition} then ${2:value} else ${3:other}\n\ # Unless\n\ snippet unl\n\ ${1:action} unless ${2:condition}\n\ # Switch\n\ snippet swi\n\ switch ${1:object}\n\ when ${2:value}\n\ ${3:// body...}\n\ \n\ # Log\n\ snippet log\n\ console.log ${1}\n\ # Try __ Catch\n\ snippet try\n\ try\n\ ${1}\n\ catch ${2:error}\n\ ${3}\n\ # Require\n\ snippet req\n\ ${2:$1} = require '${1:sys}'${3}\n\ # Export\n\ snippet exp\n\ ${1:root} = exports ? this\n\ "; exports.scope = "coffee"; });
mit
akhlaq-kiwi/secom
wp-admin/options-head.php
589
<?php /** * WordPress Options Header. * * Resets variables: 'action', 'standalone', and 'option_group_id'. Displays * updated message, if updated variable is part of the URL query. * * @package WordPress * @subpackage Administration */ wp_reset_vars(array('action', 'standalone', 'option_group_id')); if ( isset( $_GET['updated'] ) && isset( $_GET['page'] ) ) { // For backwards compat with plugins that don't use the Settings API and just set updated=1 in the redirect add_settings_error('general', 'settings_updated', __('Settings saved.'), 'updated'); } settings_errors();
gpl-2.0
brycefrees/nddLive
wp-content/themes/ndd/post-formats/format-link.php
2973
<article id="post-<?php the_ID(); ?>" <?php post_class('cf'); ?> role="article" itemscope itemtype="http://schema.org/BlogPosting"> <header class="article-header"> <h1 class="entry-title single-title" itemprop="headline"><?php the_title(); ?></h1> <p class="byline vcard"> <?php printf( __( 'Posted', 'bonestheme' ).' %1$s %2$s', /* the time the post was published */ '<time class="updated entry-time" datetime="' . get_the_time('Y-m-d') . '" itemprop="datePublished">' . get_the_time(get_option('date_format')) . '</time>', /* the author of the post */ '<span class="by">'.__( 'by', 'bonestheme' ).'</span> <span class="entry-author author" itemprop="author" itemscope itemptype="http://schema.org/Person">' . get_the_author_link( get_the_author_meta( 'ID' ) ) . '</span>' ); ?> </p> </header> <?php // end article header ?> <section class="entry-content cf" itemprop="articleBody"> <?php // the content (pretty self explanatory huh) the_content(); /* * Link Pages is used in case you have posts that are set to break into * multiple pages. You can remove this if you don't plan on doing that. * * Also, breaking content up into multiple pages is a horrible experience, * so don't do it. While there are SOME edge cases where this is useful, it's * mostly used for people to get more ad views. It's up to you but if you want * to do it, you're wrong and I hate you. (Ok, I still love you but just not as much) * * http://gizmodo.com/5841121/google-wants-to-help-you-avoid-stupid-annoying-multiple-page-articles * */ wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'bonestheme' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>', ) ); ?> </section> <?php // end article section ?> <footer class="article-footer"> <?php printf( __( 'Filed under: %1$s', 'bonestheme' ), get_the_category_list(', ') ); ?> <?php the_tags( '<p class="tags"><span class="tags-title">' . __( 'Tags:', 'bonestheme' ) . '</span> ', ', ', '</p>' ); ?> </footer> <?php // end article footer ?> <?php //comments_template(); ?> </article> <?php // end article ?>
gpl-2.0
vilyever/iosched
third_party/glide/library/src/main/java/com/bumptech/glide/load/engine/bitmap_recycle/LruPoolStrategy.java
412
package com.bumptech.glide.load.engine.bitmap_recycle; import android.graphics.Bitmap; interface LruPoolStrategy { public void put(Bitmap bitmap); public Bitmap get(int width, int height, Bitmap.Config config); public Bitmap removeLast(); public String logBitmap(Bitmap bitmap); public String logBitmap(int width, int height, Bitmap.Config config); public int getSize(Bitmap bitmap); }
apache-2.0
stephguac/isbx-loopback-cms
vendor/ace-builds/src-min-noconflict/snippets/eiffel.js
135
ace.define("ace/snippets/eiffel",["require","exports","module"],function(e,t,n){"use strict";t.snippetText=undefined,t.scope="eiffel"})
mit
freedesktop-unofficial-mirror/gstreamer-sdk__gcc
libjava/classpath/gnu/javax/net/ssl/provider/DelegatedTask.java
2864
/* DelegatedTask.java -- Copyright (C) 2006 Free Software Foundation, Inc. This file is a part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.javax.net.ssl.provider; import gnu.classpath.debug.Component; import gnu.classpath.debug.SystemLogger; /** * @author Casey Marshall (csm@gnu.org) */ public abstract class DelegatedTask implements Runnable { private static final SystemLogger logger = SystemLogger.SYSTEM; private boolean hasRun; protected Throwable thrown; protected DelegatedTask() { hasRun = false; } public final void run() { if (hasRun) throw new IllegalStateException("task already ran"); try { if (Debug.DEBUG) logger.logv(Component.SSL_DELEGATED_TASK, "running delegated task {0} in {1}", this, Thread.currentThread()); implRun(); } catch (Throwable t) { if (Debug.DEBUG) logger.log(Component.SSL_DELEGATED_TASK, "task threw exception", t); thrown = t; } finally { hasRun = true; } } public final boolean hasRun() { return hasRun; } public final Throwable thrown() { return thrown; } protected abstract void implRun() throws Throwable; }
gpl-2.0
puppeh/gcc-6502
libjava/classpath/gnu/javax/print/ipp/attribute/job/AttributesNaturalLanguage.java
3182
/* AttributesNaturalLanguage.java -- Copyright (C) 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.javax.print.ipp.attribute.job; import gnu.javax.print.ipp.attribute.NaturalLanguageSyntax; import javax.print.attribute.Attribute; /** * AttributesNaturalLanguage attribute as described in RFC 2911 chapter * 3.1.4 Character Set and Natural Language Operation Attributes. * <p> * This operation attribute identifies the natural language used * by any text and name attribute supplied by the client in the request. * The printer object should use this natural language for the response * to this request. * </p> * * @author Wolfgang Baer (WBaer@gmx.de) */ public final class AttributesNaturalLanguage extends NaturalLanguageSyntax implements Attribute { /** Defines the default language EN */ public static final AttributesNaturalLanguage EN = new AttributesNaturalLanguage("en"); /** * Creates a <code>AttributesNaturalLanguage</code> object. * * @param value the language string value. */ public AttributesNaturalLanguage(String value) { super(value); } /** * Returns category of this class. * * @return The class <code>AttributesNaturalLanguage</code> itself. */ public Class<? extends Attribute> getCategory() { return AttributesNaturalLanguage.class; } /** * Returns the name of this attribute. * * @return The name "attributes-natural-language". */ public String getName() { return "attributes-natural-language"; } }
gpl-2.0
davidsainty/ZoneMinder
web/api/lib/Cake/Test/test_app/Plugin/TestPlugin/Controller/Component/TestPluginOtherComponent.php
940
<?php /** * Short description for file. * * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests * @package Cake.Test.TestApp.Plugin.TestPlugin.Controller.Component * @since CakePHP(tm) v 1.2.0.4206 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ /** * Class TestPluginOtherComponent * * @package Cake.Test.TestApp.Plugin.TestPlugin.Controller.Component */ class TestPluginOtherComponent extends Component { }
gpl-2.0
SokolovArtur/tochka
frontend/node_modules/rxjs/scheduler/queue.d.ts
1903
import { QueueScheduler } from './QueueScheduler'; /** * * Queue Scheduler * * <span class="informal">Put every next task on a queue, instead of executing it immediately</span> * * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler. * * When used without delay, it schedules given task synchronously - executes it right when * it is scheduled. However when called recursively, that is when inside the scheduled task, * another task is scheduled with queue scheduler, instead of executing immediately as well, * that task will be put on a queue and wait for current one to finish. * * This means that when you execute task with `queue` scheduler, you are sure it will end * before any other task scheduled with that scheduler will start. * * @examples <caption>Schedule recursively first, then do something</caption> * * Rx.Scheduler.queue.schedule(() => { * Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue * * console.log('first'); * }); * * // Logs: * // "first" * // "second" * * * @example <caption>Reschedule itself recursively</caption> * * Rx.Scheduler.queue.schedule(function(state) { * if (state !== 0) { * console.log('before', state); * this.schedule(state - 1); // `this` references currently executing Action, * // which we reschedule with new state * console.log('after', state); * } * }, 0, 3); * * // In scheduler that runs recursively, you would expect: * // "before", 3 * // "before", 2 * // "before", 1 * // "after", 1 * // "after", 2 * // "after", 3 * * // But with queue it logs: * // "before", 3 * // "after", 3 * // "before", 2 * // "after", 2 * // "before", 1 * // "after", 1 * * * @static true * @name queue * @owner Scheduler */ export declare const queue: QueueScheduler;
mit
tpounds/kubernetes
vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go
1321
package leafnodes import ( "github.com/onsi/ginkgo/internal/failer" "github.com/onsi/ginkgo/types" "time" ) type SetupNode struct { runner *runner } func (node *SetupNode) Run() (outcome types.SpecState, failure types.SpecFailure) { return node.runner.run() } func (node *SetupNode) Type() types.SpecComponentType { return node.runner.nodeType } func (node *SetupNode) CodeLocation() types.CodeLocation { return node.runner.codeLocation } func NewBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { return &SetupNode{ runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeBeforeEach, componentIndex), } } func NewAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { return &SetupNode{ runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeAfterEach, componentIndex), } } func NewJustBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { return &SetupNode{ runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeJustBeforeEach, componentIndex), } }
apache-2.0
jjo/kubeless
vendor/github.com/mailru/easyjson/opt/gotemplate_Int.go
1685
// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Int struct { V int Defined bool } // Creates an optional type with a given value. func OInt(v int) Int { return Int{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Int) Get(deflt int) int { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Int) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Int(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Int) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Int{} } else { v.V = l.Int() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v *Int) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // MarshalJSON implements a standard json marshaler interface. func (v *Int) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Int) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Int) String() string { if !v.Defined { return "<undefined>" } return fmt.Sprint(v.V) }
apache-2.0
josejithinps/coursera-android
Examples/BcastRecCompOrdBcastWithResRec/src/course/examples/broadcastreceiver/compoundorderedbroadcast/CompoundOrderedBroadcastWithResultReceiver.java
1482
package course.examples.broadcastreceiver.compoundorderedbroadcast; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class CompoundOrderedBroadcastWithResultReceiver extends Activity { static final String CUSTOM_INTENT = "course.examples.BroadcastReceiver.show_toast"; private final Receiver1 mReceiver1 = new Receiver1(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); IntentFilter intentFilter = new IntentFilter(CUSTOM_INTENT); intentFilter.setPriority(3); registerReceiver(mReceiver1, intentFilter); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { sendOrderedBroadcast(new Intent(CUSTOM_INTENT), null, new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Final Result is " + getResultData(), Toast.LENGTH_LONG).show(); } }, null, 0, null, null); } }); } @Override protected void onDestroy() { unregisterReceiver(mReceiver1); super.onDestroy(); } }
mit
Risyandi/discourse
lib/auth/default_current_user_provider.rb
3463
require_dependency "auth/current_user_provider" class Auth::DefaultCurrentUserProvider CURRENT_USER_KEY ||= "_DISCOURSE_CURRENT_USER".freeze API_KEY ||= "api_key".freeze API_KEY_ENV ||= "_DISCOURSE_API".freeze TOKEN_COOKIE ||= "_t".freeze PATH_INFO ||= "PATH_INFO".freeze # do all current user initialization here def initialize(env) @env = env @request = Rack::Request.new(env) end # our current user, return nil if none is found def current_user return @env[CURRENT_USER_KEY] if @env.key?(CURRENT_USER_KEY) # bypass if we have the shared session header if shared_key = @env['HTTP_X_SHARED_SESSION_KEY'] uid = $redis.get("shared_session_key_#{shared_key}") user = nil if uid user = User.find_by(id: uid.to_i) end @env[CURRENT_USER_KEY] = user return user end request = @request auth_token = request.cookies[TOKEN_COOKIE] current_user = nil if auth_token && auth_token.length == 32 current_user = User.find_by(auth_token: auth_token) end if current_user && (current_user.suspended? || !current_user.active) current_user = nil end if current_user && should_update_last_seen? u = current_user Scheduler::Defer.later "Updating Last Seen" do u.update_last_seen! u.update_ip_address!(request.ip) end end # possible we have an api call, impersonate if api_key = request[API_KEY] current_user = lookup_api_user(api_key, request) raise Discourse::InvalidAccess unless current_user @env[API_KEY_ENV] = true end @env[CURRENT_USER_KEY] = current_user end def log_on_user(user, session, cookies) unless user.auth_token && user.auth_token.length == 32 user.auth_token = SecureRandom.hex(16) user.save! end cookies.permanent[TOKEN_COOKIE] = { value: user.auth_token, httponly: true } make_developer_admin(user) @env[CURRENT_USER_KEY] = user end def make_developer_admin(user) if user.active? && !user.admin && Rails.configuration.respond_to?(:developer_emails) && Rails.configuration.developer_emails.include?(user.email) user.admin = true user.save end end def log_off_user(session, cookies) if SiteSetting.log_out_strict && (user = current_user) user.auth_token = nil user.save! MessageBus.publish "/logout", user.id, user_ids: [user.id] end cookies[TOKEN_COOKIE] = nil end # api has special rights return true if api was detected def is_api? current_user @env[API_KEY_ENV] end def has_auth_cookie? cookie = @request.cookies[TOKEN_COOKIE] !cookie.nil? && cookie.length == 32 end def should_update_last_seen? !(@request.path =~ /^\/message-bus\//) end protected def lookup_api_user(api_key_value, request) api_key = ApiKey.where(key: api_key_value).includes(:user).first if api_key api_username = request["api_username"] if api_key.allowed_ips.present? && !api_key.allowed_ips.any?{|ip| ip.include?(request.ip)} Rails.logger.warn("Unauthorized API access: #{api_username} ip address: #{request.ip}") return nil end if api_key.user api_key.user if !api_username || (api_key.user.username_lower == api_username.downcase) elsif api_username User.find_by(username_lower: api_username.downcase) end end end end
gpl-2.0
3manuek/kubernetes
third_party/ui/bower_components/modernizr/feature-detects/forms-validation.js
2054
// This implementation only tests support for interactive form validation. // To check validation for a specific type or a specific other constraint, // the test can be combined: // - Modernizr.inputtypes.numer && Modernizr.formvalidation (browser supports rangeOverflow, typeMismatch etc. for type=number) // - Modernizr.input.required && Modernizr.formvalidation (browser supports valueMissing) // (function(document, Modernizr){ Modernizr.formvalidationapi = false; Modernizr.formvalidationmessage = false; Modernizr.addTest('formvalidation', function() { var form = document.createElement('form'); if ( !('checkValidity' in form) || !('addEventListener' in form) ) { return false; } if ('reportValidity' in form) { return true; } var invalidFired = false; var input; Modernizr.formvalidationapi = true; // Prevent form from being submitted form.addEventListener('submit', function(e) { //Opera does not validate form, if submit is prevented if ( !window.opera ) { e.preventDefault(); } e.stopPropagation(); }, false); // Calling form.submit() doesn't trigger interactive validation, // use a submit button instead //older opera browsers need a name attribute form.innerHTML = '<input name="modTest" required><button></button>'; Modernizr.testStyles('#modernizr form{position:absolute;top:-99999em}', function( node ) { node.appendChild(form); input = form.getElementsByTagName('input')[0]; // Record whether "invalid" event is fired input.addEventListener('invalid', function(e) { invalidFired = true; e.preventDefault(); e.stopPropagation(); }, false); //Opera does not fully support the validationMessage property Modernizr.formvalidationmessage = !!input.validationMessage; // Submit form by clicking submit button form.getElementsByTagName('button')[0].click(); }); return invalidFired; }); })(document, window.Modernizr);
apache-2.0
SzymonCierniewski/CasparCG-headless
dependencies64/boost/boost/log/keywords/time_based_rotation.hpp
1017
/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file keywords/time_based_rotation.hpp * \author Andrey Semashev * \date 14.03.2009 * * The header contains the \c time_based_rotation keyword declaration. */ #ifndef BOOST_LOG_KEYWORDS_TIME_BASED_ROTATION_HPP_INCLUDED_ #define BOOST_LOG_KEYWORDS_TIME_BASED_ROTATION_HPP_INCLUDED_ #include <boost/parameter/keyword.hpp> #include <boost/log/detail/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace keywords { //! The keyword allows to pass time-based file rotation predicate to the file sink backend BOOST_PARAMETER_KEYWORD(tag, time_based_rotation) } // namespace keywords BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #endif // BOOST_LOG_KEYWORDS_TIME_BASED_ROTATION_HPP_INCLUDED_
gpl-3.0
tdaajames/kubernetes
pkg/credentialprovider/azure/azure_credentials_test.go
2374
/* Copyright 2016 The Kubernetes 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 azure import ( "bytes" "testing" "github.com/Azure/azure-sdk-for-go/arm/containerregistry" "github.com/Azure/go-autorest/autorest/to" ) type fakeClient struct { results containerregistry.RegistryListResult } func (f *fakeClient) List() (containerregistry.RegistryListResult, error) { return f.results, nil } func Test(t *testing.T) { configStr := ` { "aadClientId": "foo", "aadClientSecret": "bar" }` result := containerregistry.RegistryListResult{ Value: &[]containerregistry.Registry{ { Name: to.StringPtr("foo"), RegistryProperties: &containerregistry.RegistryProperties{ LoginServer: to.StringPtr("foo-microsoft.azurecr.io"), }, }, { Name: to.StringPtr("bar"), RegistryProperties: &containerregistry.RegistryProperties{ LoginServer: to.StringPtr("bar-microsoft.azurecr.io"), }, }, { Name: to.StringPtr("baz"), RegistryProperties: &containerregistry.RegistryProperties{ LoginServer: to.StringPtr("baz-microsoft.azurecr.io"), }, }, }, } fakeClient := &fakeClient{ results: result, } provider := &acrProvider{ registryClient: fakeClient, } provider.loadConfig(bytes.NewBufferString(configStr)) creds := provider.Provide() if len(creds) != len(*result.Value) { t.Errorf("Unexpected list: %v, expected length %d", creds, len(*result.Value)) } for _, cred := range creds { if cred.Username != "foo" { t.Errorf("expected 'foo' for username, saw: %v", cred.Username) } if cred.Password != "bar" { t.Errorf("expected 'bar' for password, saw: %v", cred.Username) } } for _, val := range *result.Value { registryName := getLoginServer(val) if _, found := creds[registryName]; !found { t.Errorf("Missing expected registry: %s", registryName) } } }
apache-2.0
cripure/openpne3
lib/vendor/Zend/Validate/InArray.php
3191
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: InArray.php 8064 2008-02-16 10:58:39Z thomas $ */ /** * @see Zend_Validate_Abstract */ require_once 'Zend/Validate/Abstract.php'; /** * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Validate_InArray extends Zend_Validate_Abstract { const NOT_IN_ARRAY = 'notInArray'; /** * @var array */ protected $_messageTemplates = array( self::NOT_IN_ARRAY => "'%value%' was not found in the haystack" ); /** * Haystack of possible values * * @var array */ protected $_haystack; /** * Whether a strict in_array() invocation is used * * @var boolean */ protected $_strict; /** * Sets validator options * * @param array $haystack * @param boolean $strict * @return void */ public function __construct(array $haystack, $strict = false) { $this->setHaystack($haystack) ->setStrict($strict); } /** * Returns the haystack option * * @return mixed */ public function getHaystack() { return $this->_haystack; } /** * Sets the haystack option * * @param mixed $haystack * @return Zend_Validate_InArray Provides a fluent interface */ public function setHaystack(array $haystack) { $this->_haystack = $haystack; return $this; } /** * Returns the strict option * * @return boolean */ public function getStrict() { return $this->_strict; } /** * Sets the strict option * * @param boolean $strict * @return Zend_Validate_InArray Provides a fluent interface */ public function setStrict($strict) { $this->_strict = $strict; return $this; } /** * Defined by Zend_Validate_Interface * * Returns true if and only if $value is contained in the haystack option. If the strict * option is true, then the type of $value is also checked. * * @param mixed $value * @return boolean */ public function isValid($value) { $this->_setValue($value); if (!in_array($value, $this->_haystack, $this->_strict)) { $this->_error(); return false; } return true; } }
apache-2.0
xiaozhou322/dubbo-master
dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/support/jcache/JCacheFactory.java
1027
/* * Copyright 1999-2012 Alibaba 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. */ package com.alibaba.dubbo.cache.support.jcache; import com.alibaba.dubbo.cache.Cache; import com.alibaba.dubbo.cache.support.AbstractCacheFactory; import com.alibaba.dubbo.common.URL; /** * JCacheFactory * * @author william.liangf */ public class JCacheFactory extends AbstractCacheFactory { protected Cache createCache(URL url) { return new JCache(url); } }
apache-2.0
iains/darwin-gcc-5
libjava/classpath/java/security/SecurityPermission.java
7571
/* SecurityPermission.java -- Class for named security permissions Copyright (C) 1998, 2002 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.security; /** * This class provides a mechanism for specified named permissions * related to the Java security framework. These permissions have no * associated actions list. They are either granted or not granted. * * <p>The list of valid permission names is:<br> * <table border=1> * <tr><th>Permission Name</th><th>Permission Allows</th><th>Risks</th</tr> * <tr> * <td><code>createAccessControlContext</code></td> * <td>Allows creation of an AccessControlContext</td> * <td>The new control context can have a rogue DomainCombiner, leading * to a privacy leak</td></tr> * <tr> * <td><code>getDomainCombiner</code></td> * <td>Get a DomainCombiner from an AccessControlContext</td> * <td>Access to a DomainCombiner can lead to a privacy leak</td></tr> * <tr> * <td><code>getPolicy</code></td> * <td>Allows retrieval of the system security policy</td> * <td>Malicious code can use information from the policy to better plan * an attack</td></tr> * <tr> * <td><code>setPolicy</code></td> * <td>Allows the security policy to be changed</td> * <td>Malicious code can give itself any permission it wants</td></tr> * <tr> * <td><code>getProperty.</code><em>key</em></td> * <td>Retrieve the property specified by the key</td> * <td>Malicious code can use information from the property to better plan * an attack</td></tr> * <tr> * <td><code>setProperty.</code><em>key</em></td> * <td>Allows changing of the value of all properties implied by key</td> * <td>Malicious code can insert rogue classes to steal keys or recreate * the security policy with whatever permissions it desires</td></tr> * <tr> * <td><code>insertProvider.</code><em>key</em></td> * <td>Allows the named provider to be added</td> * <td>Malicious code can insert rogue providers that steal data</td></tr> * <tr> * <td><code>removeProvider.</code><em>key</em></td> * <td>Allows the named provider to be removed</td> * <td>A missing provider can cripple code that relies on it</td></tr> * <tr> * <td><code>setSystemScope</code></td> * <td>Allows the system identity scope to be set</td> * <td>Malicious code can add certificates not available in the original * identity scope, to gain more permissions</td></tr> * <tr> * <td><code>setIdentityPublicKey</code></td> * <td>Allows the public key of an Identity to be set</td> * <td>Malicious code can install its own key to gain permissions not * allowed by the original identity scope</td></tr> * <tr> * <td><code>SetIdentityInfo</code></td> * <td>Allows the description of an Identity to be set</td> * <td>Malicious code can spoof users into trusting a fake identity</td></tr> * <tr> * <td><code>addIdentityCertificate</code></td> * <td>Allows a certificate to be set for the public key of an identity</td> * <td>The public key can become trusted to a wider audience than originally * intended</td></tr> * <tr> * <td><code>removeIdentityCertificate</code></td> * <td>Allows removal of a certificate from an identity's public key</td> * <td>The public key can become less trusted than it should be</td></tr> * <tr> * <td><code>printIdentity</code></td> * <td>View the name of the identity and scope, and whether they are * trusted</td> * <td>The scope may include a filename, which provides an entry point for * further security breaches</td></tr> * <tr> * <td><code>clearProviderProperties.</code><em>key</em></td> * <td>Allows the properties of the named provider to be cleared</td> * <td>This can disable parts of the program which depend on finding the * provider</td></tr> * <tr> * <td><code>putProviderProperty.</code><em>key</em></td> * <td>Allows the properties of the named provider to be changed</td> * <td>Malicious code can replace the implementation of a provider</td></tr> * <tr> * <td><code>removeProviderProperty.</code><em>key</em></td> * <td>Allows the properties of the named provider to be deleted</td> * <td>This can disable parts of the program which depend on finding the * provider</td></tr> * <tr> * <td><code>getSignerPrivateKey</code></td> * <td>Allows the retrieval of the private key for a signer</td> * <td>Anyone that can access the private key can claim to be the * Signer</td></tr> * <tr> * <td><code>setSignerKeyPair</code></td> * <td>Allows the public and private key of a Signer to be changed</td> * <td>The replacement might be a weaker encryption, or the attacker * can use knowledge of the replaced key to decrypt an entire * communication session</td></tr> * </table> * * <p>There is some degree of security risk in granting any of these * permissions. Some of them can completely compromise system security. * Please exercise extreme caution in granting these permissions. * * @author Aaron M. Renn (arenn@urbanophile.com) * @see Permission * @see SecurityManager * @since 1.1 * @status updated to 1.4 */ public final class SecurityPermission extends BasicPermission { /** * Compatible with JDK 1.1+. */ private static final long serialVersionUID = 5236109936224050470L; /** * Create a new instance with the specified name. * * @param name the name to assign to this permission */ public SecurityPermission(String name) { super(name); } /** * Create a new instance with the specified name. As SecurityPermission * carries no actions, the second parameter is ignored. * * @param name the name to assign to this permission * @param actions ignored */ public SecurityPermission(String name, String actions) { super(name); } } // class SecurityPermission
gpl-2.0
soovorov/d8intranet
drupal/core/modules/search/src/Tests/SearchMatchTest.php
8144
<?php /** * @file * Contains \Drupal\search\Tests\SearchMatchTest. */ namespace Drupal\search\Tests; use Drupal\Core\Language\LanguageInterface; use Drupal\simpletest\KernelTestBase; // The search index can contain different types of content. Typically the type // is 'node'. Here we test with _test_ and _test2_ as the type. const SEARCH_TYPE = '_test_'; const SEARCH_TYPE_2 = '_test2_'; const SEARCH_TYPE_JPN = '_test3_'; /** * Indexes content and queries it. * * @group search */ class SearchMatchTest extends KernelTestBase { /** * Modules to enable. * * @var array */ public static $modules = ['search']; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installSchema('search', ['search_index', 'search_dataset', 'search_total']); $this->installConfig(['search']); } /** * Test search indexing. */ function testMatching() { $this->_setup(); $this->_testQueries(); } /** * Set up a small index of items to test against. */ function _setup() { $this->config('search.settings')->set('index.minimum_word_size', 3)->save(); for ($i = 1; $i <= 7; ++$i) { search_index(SEARCH_TYPE, $i, LanguageInterface::LANGCODE_NOT_SPECIFIED, $this->getText($i)); } for ($i = 1; $i <= 5; ++$i) { search_index(SEARCH_TYPE_2, $i + 7, LanguageInterface::LANGCODE_NOT_SPECIFIED, $this->getText2($i)); } // No getText builder function for Japanese text; just a simple array. foreach (array( 13 => '以呂波耳・ほへとち。リヌルヲ。', 14 => 'ドルーパルが大好きよ!', 15 => 'コーヒーとケーキ', ) as $i => $jpn) { search_index(SEARCH_TYPE_JPN, $i, LanguageInterface::LANGCODE_NOT_SPECIFIED, $jpn); } search_update_totals(); } /** * _test_: Helper method for generating snippets of content. * * Generated items to test against: * 1 ipsum * 2 dolore sit * 3 sit am ut * 4 am ut enim am * 5 ut enim am minim veniam * 6 enim am minim veniam es cillum * 7 am minim veniam es cillum dolore eu */ function getText($n) { $words = explode(' ', "Ipsum dolore sit am. Ut enim am minim veniam. Es cillum dolore eu."); return implode(' ', array_slice($words, $n - 1, $n)); } /** * _test2_: Helper method for generating snippets of content. * * Generated items to test against: * 8 dear * 9 king philip * 10 philip came over * 11 came over from germany * 12 over from germany swimming */ function getText2($n) { $words = explode(' ', "Dear King Philip came over from Germany swimming."); return implode(' ', array_slice($words, $n - 1, $n)); } /** * Run predefine queries looking for indexed terms. */ function _testQueries() { // Note: OR queries that include short words in OR groups are only accepted // if the ORed terms are ANDed with at least one long word in the rest of // the query. Examples: // enim dolore OR ut = enim (dolore OR ut) = (enim dolor) OR (enim ut) // is good, and // dolore OR ut = (dolore) OR (ut) // is bad. This is a design limitation to avoid full table scans. $queries = array( // Simple AND queries. 'ipsum' => array(1), 'enim' => array(4, 5, 6), 'xxxxx' => array(), 'enim minim' => array(5, 6), 'enim xxxxx' => array(), 'dolore eu' => array(7), 'dolore xx' => array(), 'ut minim' => array(5), 'xx minim' => array(), 'enim veniam am minim ut' => array(5), // Simple OR and AND/OR queries. 'dolore OR ipsum' => array(1, 2, 7), 'dolore OR xxxxx' => array(2, 7), 'dolore OR ipsum OR enim' => array(1, 2, 4, 5, 6, 7), 'ipsum OR dolore sit OR cillum' => array(2, 7), 'minim dolore OR ipsum' => array(7), 'dolore OR ipsum veniam' => array(7), 'minim dolore OR ipsum OR enim' => array(5, 6, 7), 'dolore xx OR yy' => array(), 'xxxxx dolore OR ipsum' => array(), // Sequence of OR queries. 'minim' => array(5, 6, 7), 'minim OR xxxx' => array(5, 6, 7), 'minim OR xxxx OR minim' => array(5, 6, 7), 'minim OR xxxx minim' => array(5, 6, 7), 'minim OR xxxx minim OR yyyy' => array(5, 6, 7), 'minim OR xxxx minim OR cillum' => array(6, 7, 5), 'minim OR xxxx minim OR xxxx' => array(5, 6, 7), // Negative queries. 'dolore -sit' => array(7), 'dolore -eu' => array(2), 'dolore -xxxxx' => array(2, 7), 'dolore -xx' => array(2, 7), // Phrase queries. '"dolore sit"' => array(2), '"sit dolore"' => array(), '"am minim veniam es"' => array(6, 7), '"minim am veniam es"' => array(), // Mixed queries. '"am minim veniam es" OR dolore' => array(2, 6, 7), '"minim am veniam es" OR "dolore sit"' => array(2), '"minim am veniam es" OR "sit dolore"' => array(), '"am minim veniam es" -eu' => array(6), '"am minim veniam" -"cillum dolore"' => array(5, 6), '"am minim veniam" -"dolore cillum"' => array(5, 6, 7), 'xxxxx "minim am veniam es" OR dolore' => array(), 'xx "minim am veniam es" OR dolore' => array() ); foreach ($queries as $query => $results) { $result = db_select('search_index', 'i') ->extend('Drupal\search\SearchQuery') ->searchExpression($query, SEARCH_TYPE) ->execute(); $set = $result ? $result->fetchAll() : array(); $this->_testQueryMatching($query, $set, $results); $this->_testQueryScores($query, $set, $results); } // These queries are run against the second index type, SEARCH_TYPE_2. $queries = array( // Simple AND queries. 'ipsum' => array(), 'enim' => array(), 'enim minim' => array(), 'dear' => array(8), 'germany' => array(11, 12), ); foreach ($queries as $query => $results) { $result = db_select('search_index', 'i') ->extend('Drupal\search\SearchQuery') ->searchExpression($query, SEARCH_TYPE_2) ->execute(); $set = $result ? $result->fetchAll() : array(); $this->_testQueryMatching($query, $set, $results); $this->_testQueryScores($query, $set, $results); } // These queries are run against the third index type, SEARCH_TYPE_JPN. $queries = array( // Simple AND queries. '呂波耳' => array(13), '以呂波耳' => array(13), 'ほへと ヌルヲ' => array(13), 'とちリ' => array(), 'ドルーパル' => array(14), 'パルが大' => array(14), 'コーヒー' => array(15), 'ヒーキ' => array(), ); foreach ($queries as $query => $results) { $result = db_select('search_index', 'i') ->extend('Drupal\search\SearchQuery') ->searchExpression($query, SEARCH_TYPE_JPN) ->execute(); $set = $result ? $result->fetchAll() : array(); $this->_testQueryMatching($query, $set, $results); $this->_testQueryScores($query, $set, $results); } } /** * Test the matching abilities of the engine. * * Verify if a query produces the correct results. */ function _testQueryMatching($query, $set, $results) { // Get result IDs. $found = array(); foreach ($set as $item) { $found[] = $item->sid; } // Compare $results and $found. sort($found); sort($results); $this->assertEqual($found, $results, "Query matching '$query'"); } /** * Test the scoring abilities of the engine. * * Verify if a query produces normalized, monotonous scores. */ function _testQueryScores($query, $set, $results) { // Get result scores. $scores = array(); foreach ($set as $item) { $scores[] = $item->calculated_score; } // Check order. $sorted = $scores; sort($sorted); $this->assertEqual($scores, array_reverse($sorted), "Query order '$query'"); // Check range. $this->assertEqual(!count($scores) || (min($scores) > 0.0 && max($scores) <= 1.0001), TRUE, "Query scoring '$query'"); } }
gpl-2.0
freedesktop-unofficial-mirror/gstreamer-sdk__gcc
gcc/testsuite/g++.dg/compat/decimal/return-2_main.C
188
/* { dg-require-effective-target dfp } */ /* Test function return values for decimal classes. */ extern void return_2_x (void); int fails; int main () { return_2_x (); return 0; }
gpl-2.0
nolsherry/cdnjs
ajax/libs/ckeditor/4.5.6/plugins/showblocks/lang/gu.js
97
CKEDITOR.plugins.setLang("showblocks","gu",{toolbar:"બ્લૉક બતાવવું"});
mit
feiskyer/kubernetes
vendor/github.com/vishvananda/netlink/link_linux.go
88274
package netlink import ( "bytes" "encoding/binary" "fmt" "io/ioutil" "net" "os" "strconv" "strings" "syscall" "unsafe" "github.com/vishvananda/netlink/nl" "github.com/vishvananda/netns" "golang.org/x/sys/unix" ) const ( SizeofLinkStats32 = 0x5c SizeofLinkStats64 = 0xb8 ) const ( TUNTAP_MODE_TUN TuntapMode = unix.IFF_TUN TUNTAP_MODE_TAP TuntapMode = unix.IFF_TAP TUNTAP_DEFAULTS TuntapFlag = unix.IFF_TUN_EXCL | unix.IFF_ONE_QUEUE TUNTAP_VNET_HDR TuntapFlag = unix.IFF_VNET_HDR TUNTAP_TUN_EXCL TuntapFlag = unix.IFF_TUN_EXCL TUNTAP_NO_PI TuntapFlag = unix.IFF_NO_PI TUNTAP_ONE_QUEUE TuntapFlag = unix.IFF_ONE_QUEUE TUNTAP_MULTI_QUEUE TuntapFlag = unix.IFF_MULTI_QUEUE TUNTAP_MULTI_QUEUE_DEFAULTS TuntapFlag = TUNTAP_MULTI_QUEUE | TUNTAP_NO_PI ) const ( VF_LINK_STATE_AUTO uint32 = 0 VF_LINK_STATE_ENABLE uint32 = 1 VF_LINK_STATE_DISABLE uint32 = 2 ) var lookupByDump = false var macvlanModes = [...]uint32{ 0, nl.MACVLAN_MODE_PRIVATE, nl.MACVLAN_MODE_VEPA, nl.MACVLAN_MODE_BRIDGE, nl.MACVLAN_MODE_PASSTHRU, nl.MACVLAN_MODE_SOURCE, } func ensureIndex(link *LinkAttrs) { if link != nil && link.Index == 0 { newlink, _ := LinkByName(link.Name) if newlink != nil { link.Index = newlink.Attrs().Index } } } func (h *Handle) ensureIndex(link *LinkAttrs) { if link != nil && link.Index == 0 { newlink, _ := h.LinkByName(link.Name) if newlink != nil { link.Index = newlink.Attrs().Index } } } func (h *Handle) LinkSetARPOff(link Link) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Change |= unix.IFF_NOARP msg.Flags |= unix.IFF_NOARP msg.Index = int32(base.Index) req.AddData(msg) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } func LinkSetARPOff(link Link) error { return pkgHandle.LinkSetARPOff(link) } func (h *Handle) LinkSetARPOn(link Link) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Change |= unix.IFF_NOARP msg.Flags &= ^uint32(unix.IFF_NOARP) msg.Index = int32(base.Index) req.AddData(msg) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } func LinkSetARPOn(link Link) error { return pkgHandle.LinkSetARPOn(link) } func (h *Handle) SetPromiscOn(link Link) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Change = unix.IFF_PROMISC msg.Flags = unix.IFF_PROMISC msg.Index = int32(base.Index) req.AddData(msg) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetAllmulticastOn enables the reception of all hardware multicast packets for the link device. // Equivalent to: `ip link set $link allmulticast on` func LinkSetAllmulticastOn(link Link) error { return pkgHandle.LinkSetAllmulticastOn(link) } // LinkSetAllmulticastOn enables the reception of all hardware multicast packets for the link device. // Equivalent to: `ip link set $link allmulticast on` func (h *Handle) LinkSetAllmulticastOn(link Link) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Change = unix.IFF_ALLMULTI msg.Flags = unix.IFF_ALLMULTI msg.Index = int32(base.Index) req.AddData(msg) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetAllmulticastOff disables the reception of all hardware multicast packets for the link device. // Equivalent to: `ip link set $link allmulticast off` func LinkSetAllmulticastOff(link Link) error { return pkgHandle.LinkSetAllmulticastOff(link) } // LinkSetAllmulticastOff disables the reception of all hardware multicast packets for the link device. // Equivalent to: `ip link set $link allmulticast off` func (h *Handle) LinkSetAllmulticastOff(link Link) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Change = unix.IFF_ALLMULTI msg.Index = int32(base.Index) req.AddData(msg) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } func MacvlanMACAddrAdd(link Link, addr net.HardwareAddr) error { return pkgHandle.MacvlanMACAddrAdd(link, addr) } func (h *Handle) MacvlanMACAddrAdd(link Link, addr net.HardwareAddr) error { return h.macvlanMACAddrChange(link, []net.HardwareAddr{addr}, nl.MACVLAN_MACADDR_ADD) } func MacvlanMACAddrDel(link Link, addr net.HardwareAddr) error { return pkgHandle.MacvlanMACAddrDel(link, addr) } func (h *Handle) MacvlanMACAddrDel(link Link, addr net.HardwareAddr) error { return h.macvlanMACAddrChange(link, []net.HardwareAddr{addr}, nl.MACVLAN_MACADDR_DEL) } func MacvlanMACAddrFlush(link Link) error { return pkgHandle.MacvlanMACAddrFlush(link) } func (h *Handle) MacvlanMACAddrFlush(link Link) error { return h.macvlanMACAddrChange(link, nil, nl.MACVLAN_MACADDR_FLUSH) } func MacvlanMACAddrSet(link Link, addrs []net.HardwareAddr) error { return pkgHandle.MacvlanMACAddrSet(link, addrs) } func (h *Handle) MacvlanMACAddrSet(link Link, addrs []net.HardwareAddr) error { return h.macvlanMACAddrChange(link, addrs, nl.MACVLAN_MACADDR_SET) } func (h *Handle) macvlanMACAddrChange(link Link, addrs []net.HardwareAddr, mode uint32) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil) linkInfo.AddRtAttr(nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type())) inner := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) // IFLA_MACVLAN_MACADDR_MODE = mode b := make([]byte, 4) native.PutUint32(b, mode) inner.AddRtAttr(nl.IFLA_MACVLAN_MACADDR_MODE, b) // populate message with MAC addrs, if necessary switch mode { case nl.MACVLAN_MACADDR_ADD, nl.MACVLAN_MACADDR_DEL: if len(addrs) == 1 { inner.AddRtAttr(nl.IFLA_MACVLAN_MACADDR, []byte(addrs[0])) } case nl.MACVLAN_MACADDR_SET: mad := inner.AddRtAttr(nl.IFLA_MACVLAN_MACADDR_DATA, nil) for _, addr := range addrs { mad.AddRtAttr(nl.IFLA_MACVLAN_MACADDR, []byte(addr)) } } req.AddData(linkInfo) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } func BridgeSetMcastSnoop(link Link, on bool) error { return pkgHandle.BridgeSetMcastSnoop(link, on) } func (h *Handle) BridgeSetMcastSnoop(link Link, on bool) error { bridge := link.(*Bridge) bridge.MulticastSnooping = &on return h.linkModify(bridge, unix.NLM_F_ACK) } func SetPromiscOn(link Link) error { return pkgHandle.SetPromiscOn(link) } func (h *Handle) SetPromiscOff(link Link) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Change = unix.IFF_PROMISC msg.Index = int32(base.Index) req.AddData(msg) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } func SetPromiscOff(link Link) error { return pkgHandle.SetPromiscOff(link) } // LinkSetUp enables the link device. // Equivalent to: `ip link set $link up` func LinkSetUp(link Link) error { return pkgHandle.LinkSetUp(link) } // LinkSetUp enables the link device. // Equivalent to: `ip link set $link up` func (h *Handle) LinkSetUp(link Link) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Change = unix.IFF_UP msg.Flags = unix.IFF_UP msg.Index = int32(base.Index) req.AddData(msg) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetDown disables link device. // Equivalent to: `ip link set $link down` func LinkSetDown(link Link) error { return pkgHandle.LinkSetDown(link) } // LinkSetDown disables link device. // Equivalent to: `ip link set $link down` func (h *Handle) LinkSetDown(link Link) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Change = unix.IFF_UP msg.Index = int32(base.Index) req.AddData(msg) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetMTU sets the mtu of the link device. // Equivalent to: `ip link set $link mtu $mtu` func LinkSetMTU(link Link, mtu int) error { return pkgHandle.LinkSetMTU(link, mtu) } // LinkSetMTU sets the mtu of the link device. // Equivalent to: `ip link set $link mtu $mtu` func (h *Handle) LinkSetMTU(link Link, mtu int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) b := make([]byte, 4) native.PutUint32(b, uint32(mtu)) data := nl.NewRtAttr(unix.IFLA_MTU, b) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetName sets the name of the link device. // Equivalent to: `ip link set $link name $name` func LinkSetName(link Link, name string) error { return pkgHandle.LinkSetName(link, name) } // LinkSetName sets the name of the link device. // Equivalent to: `ip link set $link name $name` func (h *Handle) LinkSetName(link Link, name string) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_IFNAME, []byte(name)) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetAlias sets the alias of the link device. // Equivalent to: `ip link set dev $link alias $name` func LinkSetAlias(link Link, name string) error { return pkgHandle.LinkSetAlias(link, name) } // LinkSetAlias sets the alias of the link device. // Equivalent to: `ip link set dev $link alias $name` func (h *Handle) LinkSetAlias(link Link, name string) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_IFALIAS, []byte(name)) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetHardwareAddr sets the hardware address of the link device. // Equivalent to: `ip link set $link address $hwaddr` func LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error { return pkgHandle.LinkSetHardwareAddr(link, hwaddr) } // LinkSetHardwareAddr sets the hardware address of the link device. // Equivalent to: `ip link set $link address $hwaddr` func (h *Handle) LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_ADDRESS, []byte(hwaddr)) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetVfHardwareAddr sets the hardware address of a vf for the link. // Equivalent to: `ip link set $link vf $vf mac $hwaddr` func LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error { return pkgHandle.LinkSetVfHardwareAddr(link, vf, hwaddr) } // LinkSetVfHardwareAddr sets the hardware address of a vf for the link. // Equivalent to: `ip link set $link vf $vf mac $hwaddr` func (h *Handle) LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) vfmsg := nl.VfMac{ Vf: uint32(vf), } copy(vfmsg.Mac[:], []byte(hwaddr)) info.AddRtAttr(nl.IFLA_VF_MAC, vfmsg.Serialize()) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetVfVlan sets the vlan of a vf for the link. // Equivalent to: `ip link set $link vf $vf vlan $vlan` func LinkSetVfVlan(link Link, vf, vlan int) error { return pkgHandle.LinkSetVfVlan(link, vf, vlan) } // LinkSetVfVlan sets the vlan of a vf for the link. // Equivalent to: `ip link set $link vf $vf vlan $vlan` func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) vfmsg := nl.VfVlan{ Vf: uint32(vf), Vlan: uint32(vlan), } info.AddRtAttr(nl.IFLA_VF_VLAN, vfmsg.Serialize()) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetVfVlanQos sets the vlan and qos priority of a vf for the link. // Equivalent to: `ip link set $link vf $vf vlan $vlan qos $qos` func LinkSetVfVlanQos(link Link, vf, vlan, qos int) error { return pkgHandle.LinkSetVfVlanQos(link, vf, vlan, qos) } // LinkSetVfVlanQos sets the vlan and qos priority of a vf for the link. // Equivalent to: `ip link set $link vf $vf vlan $vlan qos $qos` func (h *Handle) LinkSetVfVlanQos(link Link, vf, vlan, qos int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) info := nl.NewRtAttrChild(data, nl.IFLA_VF_INFO, nil) vfmsg := nl.VfVlan{ Vf: uint32(vf), Vlan: uint32(vlan), Qos: uint32(qos), } nl.NewRtAttrChild(info, nl.IFLA_VF_VLAN, vfmsg.Serialize()) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetVfTxRate sets the tx rate of a vf for the link. // Equivalent to: `ip link set $link vf $vf rate $rate` func LinkSetVfTxRate(link Link, vf, rate int) error { return pkgHandle.LinkSetVfTxRate(link, vf, rate) } // LinkSetVfTxRate sets the tx rate of a vf for the link. // Equivalent to: `ip link set $link vf $vf rate $rate` func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) vfmsg := nl.VfTxRate{ Vf: uint32(vf), Rate: uint32(rate), } info.AddRtAttr(nl.IFLA_VF_TX_RATE, vfmsg.Serialize()) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetVfRate sets the min and max tx rate of a vf for the link. // Equivalent to: `ip link set $link vf $vf min_tx_rate $min_rate max_tx_rate $max_rate` func LinkSetVfRate(link Link, vf, minRate, maxRate int) error { return pkgHandle.LinkSetVfRate(link, vf, minRate, maxRate) } // LinkSetVfRate sets the min and max tx rate of a vf for the link. // Equivalent to: `ip link set $link vf $vf min_tx_rate $min_rate max_tx_rate $max_rate` func (h *Handle) LinkSetVfRate(link Link, vf, minRate, maxRate int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) vfmsg := nl.VfRate{ Vf: uint32(vf), MinTxRate: uint32(minRate), MaxTxRate: uint32(maxRate), } info.AddRtAttr(nl.IFLA_VF_RATE, vfmsg.Serialize()) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetVfState enables/disables virtual link state on a vf. // Equivalent to: `ip link set $link vf $vf state $state` func LinkSetVfState(link Link, vf int, state uint32) error { return pkgHandle.LinkSetVfState(link, vf, state) } // LinkSetVfState enables/disables virtual link state on a vf. // Equivalent to: `ip link set $link vf $vf state $state` func (h *Handle) LinkSetVfState(link Link, vf int, state uint32) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) vfmsg := nl.VfLinkState{ Vf: uint32(vf), LinkState: state, } info.AddRtAttr(nl.IFLA_VF_LINK_STATE, vfmsg.Serialize()) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetVfSpoofchk enables/disables spoof check on a vf for the link. // Equivalent to: `ip link set $link vf $vf spoofchk $check` func LinkSetVfSpoofchk(link Link, vf int, check bool) error { return pkgHandle.LinkSetVfSpoofchk(link, vf, check) } // LinkSetVfSpoofchk enables/disables spoof check on a vf for the link. // Equivalent to: `ip link set $link vf $vf spoofchk $check` func (h *Handle) LinkSetVfSpoofchk(link Link, vf int, check bool) error { var setting uint32 base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) if check { setting = 1 } vfmsg := nl.VfSpoofchk{ Vf: uint32(vf), Setting: setting, } info.AddRtAttr(nl.IFLA_VF_SPOOFCHK, vfmsg.Serialize()) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetVfTrust enables/disables trust state on a vf for the link. // Equivalent to: `ip link set $link vf $vf trust $state` func LinkSetVfTrust(link Link, vf int, state bool) error { return pkgHandle.LinkSetVfTrust(link, vf, state) } // LinkSetVfTrust enables/disables trust state on a vf for the link. // Equivalent to: `ip link set $link vf $vf trust $state` func (h *Handle) LinkSetVfTrust(link Link, vf int, state bool) error { var setting uint32 base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) if state { setting = 1 } vfmsg := nl.VfTrust{ Vf: uint32(vf), Setting: setting, } info.AddRtAttr(nl.IFLA_VF_TRUST, vfmsg.Serialize()) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetVfNodeGUID sets the node GUID of a vf for the link. // Equivalent to: `ip link set dev $link vf $vf node_guid $nodeguid` func LinkSetVfNodeGUID(link Link, vf int, nodeguid net.HardwareAddr) error { return pkgHandle.LinkSetVfGUID(link, vf, nodeguid, nl.IFLA_VF_IB_NODE_GUID) } // LinkSetVfPortGUID sets the port GUID of a vf for the link. // Equivalent to: `ip link set dev $link vf $vf port_guid $portguid` func LinkSetVfPortGUID(link Link, vf int, portguid net.HardwareAddr) error { return pkgHandle.LinkSetVfGUID(link, vf, portguid, nl.IFLA_VF_IB_PORT_GUID) } // LinkSetVfGUID sets the node or port GUID of a vf for the link. func (h *Handle) LinkSetVfGUID(link Link, vf int, vfGuid net.HardwareAddr, guidType int) error { var err error var guid uint64 buf := bytes.NewBuffer(vfGuid) err = binary.Read(buf, binary.BigEndian, &guid) if err != nil { return err } base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) vfmsg := nl.VfGUID{ Vf: uint32(vf), GUID: guid, } info.AddRtAttr(guidType, vfmsg.Serialize()) req.AddData(data) _, err = req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetMaster sets the master of the link device. // Equivalent to: `ip link set $link master $master` func LinkSetMaster(link Link, master Link) error { return pkgHandle.LinkSetMaster(link, master) } // LinkSetMaster sets the master of the link device. // Equivalent to: `ip link set $link master $master` func (h *Handle) LinkSetMaster(link Link, master Link) error { index := 0 if master != nil { masterBase := master.Attrs() h.ensureIndex(masterBase) index = masterBase.Index } if index <= 0 { return fmt.Errorf("Device does not exist") } return h.LinkSetMasterByIndex(link, index) } // LinkSetNoMaster removes the master of the link device. // Equivalent to: `ip link set $link nomaster` func LinkSetNoMaster(link Link) error { return pkgHandle.LinkSetNoMaster(link) } // LinkSetNoMaster removes the master of the link device. // Equivalent to: `ip link set $link nomaster` func (h *Handle) LinkSetNoMaster(link Link) error { return h.LinkSetMasterByIndex(link, 0) } // LinkSetMasterByIndex sets the master of the link device. // Equivalent to: `ip link set $link master $master` func LinkSetMasterByIndex(link Link, masterIndex int) error { return pkgHandle.LinkSetMasterByIndex(link, masterIndex) } // LinkSetMasterByIndex sets the master of the link device. // Equivalent to: `ip link set $link master $master` func (h *Handle) LinkSetMasterByIndex(link Link, masterIndex int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) b := make([]byte, 4) native.PutUint32(b, uint32(masterIndex)) data := nl.NewRtAttr(unix.IFLA_MASTER, b) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetNsPid puts the device into a new network namespace. The // pid must be a pid of a running process. // Equivalent to: `ip link set $link netns $pid` func LinkSetNsPid(link Link, nspid int) error { return pkgHandle.LinkSetNsPid(link, nspid) } // LinkSetNsPid puts the device into a new network namespace. The // pid must be a pid of a running process. // Equivalent to: `ip link set $link netns $pid` func (h *Handle) LinkSetNsPid(link Link, nspid int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) b := make([]byte, 4) native.PutUint32(b, uint32(nspid)) data := nl.NewRtAttr(unix.IFLA_NET_NS_PID, b) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetNsFd puts the device into a new network namespace. The // fd must be an open file descriptor to a network namespace. // Similar to: `ip link set $link netns $ns` func LinkSetNsFd(link Link, fd int) error { return pkgHandle.LinkSetNsFd(link, fd) } // LinkSetNsFd puts the device into a new network namespace. The // fd must be an open file descriptor to a network namespace. // Similar to: `ip link set $link netns $ns` func (h *Handle) LinkSetNsFd(link Link, fd int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) b := make([]byte, 4) native.PutUint32(b, uint32(fd)) data := nl.NewRtAttr(unix.IFLA_NET_NS_FD, b) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetXdpFd adds a bpf function to the driver. The fd must be a bpf // program loaded with bpf(type=BPF_PROG_TYPE_XDP) func LinkSetXdpFd(link Link, fd int) error { return LinkSetXdpFdWithFlags(link, fd, 0) } // LinkSetXdpFdWithFlags adds a bpf function to the driver with the given // options. The fd must be a bpf program loaded with bpf(type=BPF_PROG_TYPE_XDP) func LinkSetXdpFdWithFlags(link Link, fd, flags int) error { base := link.Attrs() ensureIndex(base) req := nl.NewNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) addXdpAttrs(&LinkXdp{Fd: fd, Flags: uint32(flags)}, req) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } func boolAttr(val bool) []byte { var v uint8 if val { v = 1 } return nl.Uint8Attr(v) } type vxlanPortRange struct { Lo, Hi uint16 } func addVxlanAttrs(vxlan *Vxlan, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) if vxlan.FlowBased { vxlan.VxlanId = 0 } data.AddRtAttr(nl.IFLA_VXLAN_ID, nl.Uint32Attr(uint32(vxlan.VxlanId))) if vxlan.VtepDevIndex != 0 { data.AddRtAttr(nl.IFLA_VXLAN_LINK, nl.Uint32Attr(uint32(vxlan.VtepDevIndex))) } if vxlan.SrcAddr != nil { ip := vxlan.SrcAddr.To4() if ip != nil { data.AddRtAttr(nl.IFLA_VXLAN_LOCAL, []byte(ip)) } else { ip = vxlan.SrcAddr.To16() if ip != nil { data.AddRtAttr(nl.IFLA_VXLAN_LOCAL6, []byte(ip)) } } } if vxlan.Group != nil { group := vxlan.Group.To4() if group != nil { data.AddRtAttr(nl.IFLA_VXLAN_GROUP, []byte(group)) } else { group = vxlan.Group.To16() if group != nil { data.AddRtAttr(nl.IFLA_VXLAN_GROUP6, []byte(group)) } } } data.AddRtAttr(nl.IFLA_VXLAN_TTL, nl.Uint8Attr(uint8(vxlan.TTL))) data.AddRtAttr(nl.IFLA_VXLAN_TOS, nl.Uint8Attr(uint8(vxlan.TOS))) data.AddRtAttr(nl.IFLA_VXLAN_LEARNING, boolAttr(vxlan.Learning)) data.AddRtAttr(nl.IFLA_VXLAN_PROXY, boolAttr(vxlan.Proxy)) data.AddRtAttr(nl.IFLA_VXLAN_RSC, boolAttr(vxlan.RSC)) data.AddRtAttr(nl.IFLA_VXLAN_L2MISS, boolAttr(vxlan.L2miss)) data.AddRtAttr(nl.IFLA_VXLAN_L3MISS, boolAttr(vxlan.L3miss)) data.AddRtAttr(nl.IFLA_VXLAN_UDP_ZERO_CSUM6_TX, boolAttr(vxlan.UDP6ZeroCSumTx)) data.AddRtAttr(nl.IFLA_VXLAN_UDP_ZERO_CSUM6_RX, boolAttr(vxlan.UDP6ZeroCSumRx)) if vxlan.UDPCSum { data.AddRtAttr(nl.IFLA_VXLAN_UDP_CSUM, boolAttr(vxlan.UDPCSum)) } if vxlan.GBP { data.AddRtAttr(nl.IFLA_VXLAN_GBP, []byte{}) } if vxlan.FlowBased { data.AddRtAttr(nl.IFLA_VXLAN_FLOWBASED, boolAttr(vxlan.FlowBased)) } if vxlan.NoAge { data.AddRtAttr(nl.IFLA_VXLAN_AGEING, nl.Uint32Attr(0)) } else if vxlan.Age > 0 { data.AddRtAttr(nl.IFLA_VXLAN_AGEING, nl.Uint32Attr(uint32(vxlan.Age))) } if vxlan.Limit > 0 { data.AddRtAttr(nl.IFLA_VXLAN_LIMIT, nl.Uint32Attr(uint32(vxlan.Limit))) } if vxlan.Port > 0 { data.AddRtAttr(nl.IFLA_VXLAN_PORT, htons(uint16(vxlan.Port))) } if vxlan.PortLow > 0 || vxlan.PortHigh > 0 { pr := vxlanPortRange{uint16(vxlan.PortLow), uint16(vxlan.PortHigh)} buf := new(bytes.Buffer) binary.Write(buf, binary.BigEndian, &pr) data.AddRtAttr(nl.IFLA_VXLAN_PORT_RANGE, buf.Bytes()) } } func addBondAttrs(bond *Bond, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) if bond.Mode >= 0 { data.AddRtAttr(nl.IFLA_BOND_MODE, nl.Uint8Attr(uint8(bond.Mode))) } if bond.ActiveSlave >= 0 { data.AddRtAttr(nl.IFLA_BOND_ACTIVE_SLAVE, nl.Uint32Attr(uint32(bond.ActiveSlave))) } if bond.Miimon >= 0 { data.AddRtAttr(nl.IFLA_BOND_MIIMON, nl.Uint32Attr(uint32(bond.Miimon))) } if bond.UpDelay >= 0 { data.AddRtAttr(nl.IFLA_BOND_UPDELAY, nl.Uint32Attr(uint32(bond.UpDelay))) } if bond.DownDelay >= 0 { data.AddRtAttr(nl.IFLA_BOND_DOWNDELAY, nl.Uint32Attr(uint32(bond.DownDelay))) } if bond.UseCarrier >= 0 { data.AddRtAttr(nl.IFLA_BOND_USE_CARRIER, nl.Uint8Attr(uint8(bond.UseCarrier))) } if bond.ArpInterval >= 0 { data.AddRtAttr(nl.IFLA_BOND_ARP_INTERVAL, nl.Uint32Attr(uint32(bond.ArpInterval))) } if bond.ArpIpTargets != nil { msg := data.AddRtAttr(nl.IFLA_BOND_ARP_IP_TARGET, nil) for i := range bond.ArpIpTargets { ip := bond.ArpIpTargets[i].To4() if ip != nil { msg.AddRtAttr(i, []byte(ip)) continue } ip = bond.ArpIpTargets[i].To16() if ip != nil { msg.AddRtAttr(i, []byte(ip)) } } } if bond.ArpValidate >= 0 { data.AddRtAttr(nl.IFLA_BOND_ARP_VALIDATE, nl.Uint32Attr(uint32(bond.ArpValidate))) } if bond.ArpAllTargets >= 0 { data.AddRtAttr(nl.IFLA_BOND_ARP_ALL_TARGETS, nl.Uint32Attr(uint32(bond.ArpAllTargets))) } if bond.Primary >= 0 { data.AddRtAttr(nl.IFLA_BOND_PRIMARY, nl.Uint32Attr(uint32(bond.Primary))) } if bond.PrimaryReselect >= 0 { data.AddRtAttr(nl.IFLA_BOND_PRIMARY_RESELECT, nl.Uint8Attr(uint8(bond.PrimaryReselect))) } if bond.FailOverMac >= 0 { data.AddRtAttr(nl.IFLA_BOND_FAIL_OVER_MAC, nl.Uint8Attr(uint8(bond.FailOverMac))) } if bond.XmitHashPolicy >= 0 { data.AddRtAttr(nl.IFLA_BOND_XMIT_HASH_POLICY, nl.Uint8Attr(uint8(bond.XmitHashPolicy))) } if bond.ResendIgmp >= 0 { data.AddRtAttr(nl.IFLA_BOND_RESEND_IGMP, nl.Uint32Attr(uint32(bond.ResendIgmp))) } if bond.NumPeerNotif >= 0 { data.AddRtAttr(nl.IFLA_BOND_NUM_PEER_NOTIF, nl.Uint8Attr(uint8(bond.NumPeerNotif))) } if bond.AllSlavesActive >= 0 { data.AddRtAttr(nl.IFLA_BOND_ALL_SLAVES_ACTIVE, nl.Uint8Attr(uint8(bond.AllSlavesActive))) } if bond.MinLinks >= 0 { data.AddRtAttr(nl.IFLA_BOND_MIN_LINKS, nl.Uint32Attr(uint32(bond.MinLinks))) } if bond.LpInterval >= 0 { data.AddRtAttr(nl.IFLA_BOND_LP_INTERVAL, nl.Uint32Attr(uint32(bond.LpInterval))) } if bond.PackersPerSlave >= 0 { data.AddRtAttr(nl.IFLA_BOND_PACKETS_PER_SLAVE, nl.Uint32Attr(uint32(bond.PackersPerSlave))) } if bond.LacpRate >= 0 { data.AddRtAttr(nl.IFLA_BOND_AD_LACP_RATE, nl.Uint8Attr(uint8(bond.LacpRate))) } if bond.AdSelect >= 0 { data.AddRtAttr(nl.IFLA_BOND_AD_SELECT, nl.Uint8Attr(uint8(bond.AdSelect))) } if bond.AdActorSysPrio >= 0 { data.AddRtAttr(nl.IFLA_BOND_AD_ACTOR_SYS_PRIO, nl.Uint16Attr(uint16(bond.AdActorSysPrio))) } if bond.AdUserPortKey >= 0 { data.AddRtAttr(nl.IFLA_BOND_AD_USER_PORT_KEY, nl.Uint16Attr(uint16(bond.AdUserPortKey))) } if bond.AdActorSystem != nil { data.AddRtAttr(nl.IFLA_BOND_AD_ACTOR_SYSTEM, []byte(bond.AdActorSystem)) } if bond.TlbDynamicLb >= 0 { data.AddRtAttr(nl.IFLA_BOND_TLB_DYNAMIC_LB, nl.Uint8Attr(uint8(bond.TlbDynamicLb))) } } func cleanupFds(fds []*os.File) { for _, f := range fds { f.Close() } } // LinkAdd adds a new link device. The type and features of the device // are taken from the parameters in the link object. // Equivalent to: `ip link add $link` func LinkAdd(link Link) error { return pkgHandle.LinkAdd(link) } // LinkAdd adds a new link device. The type and features of the device // are taken from the parameters in the link object. // Equivalent to: `ip link add $link` func (h *Handle) LinkAdd(link Link) error { return h.linkModify(link, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK) } func (h *Handle) linkModify(link Link, flags int) error { // TODO: support extra data for macvlan base := link.Attrs() // if tuntap, then the name can be empty, OS will provide a name tuntap, isTuntap := link.(*Tuntap) if base.Name == "" && !isTuntap { return fmt.Errorf("LinkAttrs.Name cannot be empty") } if isTuntap { // TODO: support user // TODO: support group if tuntap.Mode < unix.IFF_TUN || tuntap.Mode > unix.IFF_TAP { return fmt.Errorf("Tuntap.Mode %v unknown", tuntap.Mode) } queues := tuntap.Queues var fds []*os.File var req ifReq copy(req.Name[:15], base.Name) req.Flags = uint16(tuntap.Flags) if queues == 0 { //Legacy compatibility queues = 1 if tuntap.Flags == 0 { req.Flags = uint16(TUNTAP_DEFAULTS) } } else { // For best peformance set Flags to TUNTAP_MULTI_QUEUE_DEFAULTS | TUNTAP_VNET_HDR // when a) KVM has support for this ABI and // b) the value of the flag is queryable using the TUNGETIFF ioctl if tuntap.Flags == 0 { req.Flags = uint16(TUNTAP_MULTI_QUEUE_DEFAULTS) } } req.Flags |= uint16(tuntap.Mode) for i := 0; i < queues; i++ { localReq := req file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0) if err != nil { cleanupFds(fds) return err } fds = append(fds, file) _, _, errno := unix.Syscall(unix.SYS_IOCTL, file.Fd(), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&localReq))) if errno != 0 { cleanupFds(fds) return fmt.Errorf("Tuntap IOCTL TUNSETIFF failed [%d], errno %v", i, errno) } // 1) we only care for the name of the first tap in the multi queue set // 2) if the original name was empty, the localReq has now the actual name // // In addition: // This ensures that the link name is always identical to what the kernel returns. // Not only in case of an empty name, but also when using name templates. // e.g. when the provided name is "tap%d", the kernel replaces %d with the next available number. if i == 0 { link.Attrs().Name = strings.Trim(string(localReq.Name[:]), "\x00") } } // only persist interface if NonPersist is NOT set if !tuntap.NonPersist { _, _, errno := unix.Syscall(unix.SYS_IOCTL, fds[0].Fd(), uintptr(unix.TUNSETPERSIST), 1) if errno != 0 { cleanupFds(fds) return fmt.Errorf("Tuntap IOCTL TUNSETPERSIST failed, errno %v", errno) } } h.ensureIndex(base) // can't set master during create, so set it afterwards if base.MasterIndex != 0 { // TODO: verify MasterIndex is actually a bridge? err := h.LinkSetMasterByIndex(link, base.MasterIndex) if err != nil { // un-persist (e.g. allow the interface to be removed) the tuntap // should not hurt if not set prior, condition might be not needed if !tuntap.NonPersist { _, _, _ = unix.Syscall(unix.SYS_IOCTL, fds[0].Fd(), uintptr(unix.TUNSETPERSIST), 0) } cleanupFds(fds) return err } } if tuntap.Queues == 0 { cleanupFds(fds) } else { tuntap.Fds = fds } return nil } req := h.newNetlinkRequest(unix.RTM_NEWLINK, flags) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) // TODO: make it shorter if base.Flags&net.FlagUp != 0 { msg.Change = unix.IFF_UP msg.Flags = unix.IFF_UP } if base.Flags&net.FlagBroadcast != 0 { msg.Change |= unix.IFF_BROADCAST msg.Flags |= unix.IFF_BROADCAST } if base.Flags&net.FlagLoopback != 0 { msg.Change |= unix.IFF_LOOPBACK msg.Flags |= unix.IFF_LOOPBACK } if base.Flags&net.FlagPointToPoint != 0 { msg.Change |= unix.IFF_POINTOPOINT msg.Flags |= unix.IFF_POINTOPOINT } if base.Flags&net.FlagMulticast != 0 { msg.Change |= unix.IFF_MULTICAST msg.Flags |= unix.IFF_MULTICAST } if base.Index != 0 { msg.Index = int32(base.Index) } req.AddData(msg) if base.ParentIndex != 0 { b := make([]byte, 4) native.PutUint32(b, uint32(base.ParentIndex)) data := nl.NewRtAttr(unix.IFLA_LINK, b) req.AddData(data) } else if link.Type() == "ipvlan" || link.Type() == "ipoib" { return fmt.Errorf("Can't create %s link without ParentIndex", link.Type()) } nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(base.Name)) req.AddData(nameData) if base.MTU > 0 { mtu := nl.NewRtAttr(unix.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU))) req.AddData(mtu) } if base.TxQLen >= 0 { qlen := nl.NewRtAttr(unix.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen))) req.AddData(qlen) } if base.HardwareAddr != nil { hwaddr := nl.NewRtAttr(unix.IFLA_ADDRESS, []byte(base.HardwareAddr)) req.AddData(hwaddr) } if base.NumTxQueues > 0 { txqueues := nl.NewRtAttr(unix.IFLA_NUM_TX_QUEUES, nl.Uint32Attr(uint32(base.NumTxQueues))) req.AddData(txqueues) } if base.NumRxQueues > 0 { rxqueues := nl.NewRtAttr(unix.IFLA_NUM_RX_QUEUES, nl.Uint32Attr(uint32(base.NumRxQueues))) req.AddData(rxqueues) } if base.GSOMaxSegs > 0 { gsoAttr := nl.NewRtAttr(unix.IFLA_GSO_MAX_SEGS, nl.Uint32Attr(base.GSOMaxSegs)) req.AddData(gsoAttr) } if base.GSOMaxSize > 0 { gsoAttr := nl.NewRtAttr(unix.IFLA_GSO_MAX_SIZE, nl.Uint32Attr(base.GSOMaxSize)) req.AddData(gsoAttr) } if base.Group > 0 { groupAttr := nl.NewRtAttr(unix.IFLA_GROUP, nl.Uint32Attr(base.Group)) req.AddData(groupAttr) } if base.Namespace != nil { var attr *nl.RtAttr switch ns := base.Namespace.(type) { case NsPid: val := nl.Uint32Attr(uint32(ns)) attr = nl.NewRtAttr(unix.IFLA_NET_NS_PID, val) case NsFd: val := nl.Uint32Attr(uint32(ns)) attr = nl.NewRtAttr(unix.IFLA_NET_NS_FD, val) } req.AddData(attr) } if base.Xdp != nil { addXdpAttrs(base.Xdp, req) } linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil) linkInfo.AddRtAttr(nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type())) switch link := link.(type) { case *Vlan: b := make([]byte, 2) native.PutUint16(b, uint16(link.VlanId)) data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) data.AddRtAttr(nl.IFLA_VLAN_ID, b) if link.VlanProtocol != VLAN_PROTOCOL_UNKNOWN { data.AddRtAttr(nl.IFLA_VLAN_PROTOCOL, htons(uint16(link.VlanProtocol))) } case *Veth: data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) peer := data.AddRtAttr(nl.VETH_INFO_PEER, nil) nl.NewIfInfomsgChild(peer, unix.AF_UNSPEC) peer.AddRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(link.PeerName)) if base.TxQLen >= 0 { peer.AddRtAttr(unix.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen))) } if base.MTU > 0 { peer.AddRtAttr(unix.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU))) } if link.PeerHardwareAddr != nil { peer.AddRtAttr(unix.IFLA_ADDRESS, []byte(link.PeerHardwareAddr)) } case *Vxlan: addVxlanAttrs(link, linkInfo) case *Bond: addBondAttrs(link, linkInfo) case *IPVlan: data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) data.AddRtAttr(nl.IFLA_IPVLAN_MODE, nl.Uint16Attr(uint16(link.Mode))) data.AddRtAttr(nl.IFLA_IPVLAN_FLAG, nl.Uint16Attr(uint16(link.Flag))) case *Macvlan: if link.Mode != MACVLAN_MODE_DEFAULT { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) data.AddRtAttr(nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[link.Mode])) } case *Macvtap: if link.Mode != MACVLAN_MODE_DEFAULT { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) data.AddRtAttr(nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[link.Mode])) } case *Gretap: addGretapAttrs(link, linkInfo) case *Iptun: addIptunAttrs(link, linkInfo) case *Ip6tnl: addIp6tnlAttrs(link, linkInfo) case *Sittun: addSittunAttrs(link, linkInfo) case *Gretun: addGretunAttrs(link, linkInfo) case *Vti: addVtiAttrs(link, linkInfo) case *Vrf: addVrfAttrs(link, linkInfo) case *Bridge: addBridgeAttrs(link, linkInfo) case *GTP: addGTPAttrs(link, linkInfo) case *Xfrmi: addXfrmiAttrs(link, linkInfo) case *IPoIB: addIPoIBAttrs(link, linkInfo) } req.AddData(linkInfo) _, err := req.Execute(unix.NETLINK_ROUTE, 0) if err != nil { return err } h.ensureIndex(base) // can't set master during create, so set it afterwards if base.MasterIndex != 0 { // TODO: verify MasterIndex is actually a bridge? return h.LinkSetMasterByIndex(link, base.MasterIndex) } return nil } // LinkDel deletes link device. Either Index or Name must be set in // the link object for it to be deleted. The other values are ignored. // Equivalent to: `ip link del $link` func LinkDel(link Link) error { return pkgHandle.LinkDel(link) } // LinkDel deletes link device. Either Index or Name must be set in // the link object for it to be deleted. The other values are ignored. // Equivalent to: `ip link del $link` func (h *Handle) LinkDel(link Link) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_DELLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } func (h *Handle) linkByNameDump(name string) (Link, error) { links, err := h.LinkList() if err != nil { return nil, err } for _, link := range links { if link.Attrs().Name == name { return link, nil } } return nil, LinkNotFoundError{fmt.Errorf("Link %s not found", name)} } func (h *Handle) linkByAliasDump(alias string) (Link, error) { links, err := h.LinkList() if err != nil { return nil, err } for _, link := range links { if link.Attrs().Alias == alias { return link, nil } } return nil, LinkNotFoundError{fmt.Errorf("Link alias %s not found", alias)} } // LinkByName finds a link by name and returns a pointer to the object. func LinkByName(name string) (Link, error) { return pkgHandle.LinkByName(name) } // LinkByName finds a link by name and returns a pointer to the object. func (h *Handle) LinkByName(name string) (Link, error) { if h.lookupByDump { return h.linkByNameDump(name) } req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) req.AddData(msg) attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF)) req.AddData(attr) nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(name)) req.AddData(nameData) link, err := execGetLink(req) if err == unix.EINVAL { // older kernels don't support looking up via IFLA_IFNAME // so fall back to dumping all links h.lookupByDump = true return h.linkByNameDump(name) } return link, err } // LinkByAlias finds a link by its alias and returns a pointer to the object. // If there are multiple links with the alias it returns the first one func LinkByAlias(alias string) (Link, error) { return pkgHandle.LinkByAlias(alias) } // LinkByAlias finds a link by its alias and returns a pointer to the object. // If there are multiple links with the alias it returns the first one func (h *Handle) LinkByAlias(alias string) (Link, error) { if h.lookupByDump { return h.linkByAliasDump(alias) } req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) req.AddData(msg) attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF)) req.AddData(attr) nameData := nl.NewRtAttr(unix.IFLA_IFALIAS, nl.ZeroTerminated(alias)) req.AddData(nameData) link, err := execGetLink(req) if err == unix.EINVAL { // older kernels don't support looking up via IFLA_IFALIAS // so fall back to dumping all links h.lookupByDump = true return h.linkByAliasDump(alias) } return link, err } // LinkByIndex finds a link by index and returns a pointer to the object. func LinkByIndex(index int) (Link, error) { return pkgHandle.LinkByIndex(index) } // LinkByIndex finds a link by index and returns a pointer to the object. func (h *Handle) LinkByIndex(index int) (Link, error) { req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(index) req.AddData(msg) attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF)) req.AddData(attr) return execGetLink(req) } func execGetLink(req *nl.NetlinkRequest) (Link, error) { msgs, err := req.Execute(unix.NETLINK_ROUTE, 0) if err != nil { if errno, ok := err.(syscall.Errno); ok { if errno == unix.ENODEV { return nil, LinkNotFoundError{fmt.Errorf("Link not found")} } } return nil, err } switch { case len(msgs) == 0: return nil, LinkNotFoundError{fmt.Errorf("Link not found")} case len(msgs) == 1: return LinkDeserialize(nil, msgs[0]) default: return nil, fmt.Errorf("More than one link found") } } // linkDeserialize deserializes a raw message received from netlink into // a link object. func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) { msg := nl.DeserializeIfInfomsg(m) attrs, err := nl.ParseRouteAttr(m[msg.Len():]) if err != nil { return nil, err } base := LinkAttrs{Index: int(msg.Index), RawFlags: msg.Flags, Flags: linkFlags(msg.Flags), EncapType: msg.EncapType()} if msg.Flags&unix.IFF_PROMISC != 0 { base.Promisc = 1 } var ( link Link stats32 *LinkStatistics32 stats64 *LinkStatistics64 linkType string linkSlave LinkSlave slaveType string ) for _, attr := range attrs { switch attr.Attr.Type { case unix.IFLA_LINKINFO: infos, err := nl.ParseRouteAttr(attr.Value) if err != nil { return nil, err } for _, info := range infos { switch info.Attr.Type { case nl.IFLA_INFO_KIND: linkType = string(info.Value[:len(info.Value)-1]) switch linkType { case "dummy": link = &Dummy{} case "ifb": link = &Ifb{} case "bridge": link = &Bridge{} case "vlan": link = &Vlan{} case "veth": link = &Veth{} case "vxlan": link = &Vxlan{} case "bond": link = &Bond{} case "ipvlan": link = &IPVlan{} case "macvlan": link = &Macvlan{} case "macvtap": link = &Macvtap{} case "gretap": link = &Gretap{} case "ip6gretap": link = &Gretap{} case "ipip": link = &Iptun{} case "ip6tnl": link = &Ip6tnl{} case "sit": link = &Sittun{} case "gre": link = &Gretun{} case "ip6gre": link = &Gretun{} case "vti", "vti6": link = &Vti{} case "vrf": link = &Vrf{} case "gtp": link = &GTP{} case "xfrm": link = &Xfrmi{} case "tun": link = &Tuntap{} case "ipoib": link = &IPoIB{} default: link = &GenericLink{LinkType: linkType} } case nl.IFLA_INFO_DATA: data, err := nl.ParseRouteAttr(info.Value) if err != nil { return nil, err } switch linkType { case "vlan": parseVlanData(link, data) case "vxlan": parseVxlanData(link, data) case "bond": parseBondData(link, data) case "ipvlan": parseIPVlanData(link, data) case "macvlan": parseMacvlanData(link, data) case "macvtap": parseMacvtapData(link, data) case "gretap": parseGretapData(link, data) case "ip6gretap": parseGretapData(link, data) case "ipip": parseIptunData(link, data) case "ip6tnl": parseIp6tnlData(link, data) case "sit": parseSittunData(link, data) case "gre": parseGretunData(link, data) case "ip6gre": parseGretunData(link, data) case "vti", "vti6": parseVtiData(link, data) case "vrf": parseVrfData(link, data) case "bridge": parseBridgeData(link, data) case "gtp": parseGTPData(link, data) case "xfrm": parseXfrmiData(link, data) case "tun": parseTuntapData(link, data) case "ipoib": parseIPoIBData(link, data) } case nl.IFLA_INFO_SLAVE_KIND: slaveType = string(info.Value[:len(info.Value)-1]) switch slaveType { case "bond": linkSlave = &BondSlave{} } case nl.IFLA_INFO_SLAVE_DATA: switch slaveType { case "bond": data, err := nl.ParseRouteAttr(info.Value) if err != nil { return nil, err } parseBondSlaveData(linkSlave, data) } } } case unix.IFLA_ADDRESS: var nonzero bool for _, b := range attr.Value { if b != 0 { nonzero = true } } if nonzero { base.HardwareAddr = attr.Value[:] } case unix.IFLA_IFNAME: base.Name = string(attr.Value[:len(attr.Value)-1]) case unix.IFLA_MTU: base.MTU = int(native.Uint32(attr.Value[0:4])) case unix.IFLA_LINK: base.ParentIndex = int(native.Uint32(attr.Value[0:4])) case unix.IFLA_MASTER: base.MasterIndex = int(native.Uint32(attr.Value[0:4])) case unix.IFLA_TXQLEN: base.TxQLen = int(native.Uint32(attr.Value[0:4])) case unix.IFLA_IFALIAS: base.Alias = string(attr.Value[:len(attr.Value)-1]) case unix.IFLA_STATS: stats32 = new(LinkStatistics32) if err := binary.Read(bytes.NewBuffer(attr.Value[:]), nl.NativeEndian(), stats32); err != nil { return nil, err } case unix.IFLA_STATS64: stats64 = new(LinkStatistics64) if err := binary.Read(bytes.NewBuffer(attr.Value[:]), nl.NativeEndian(), stats64); err != nil { return nil, err } case unix.IFLA_XDP: xdp, err := parseLinkXdp(attr.Value[:]) if err != nil { return nil, err } base.Xdp = xdp case unix.IFLA_PROTINFO | unix.NLA_F_NESTED: if hdr != nil && hdr.Type == unix.RTM_NEWLINK && msg.Family == unix.AF_BRIDGE { attrs, err := nl.ParseRouteAttr(attr.Value[:]) if err != nil { return nil, err } protinfo := parseProtinfo(attrs) base.Protinfo = &protinfo } case unix.IFLA_OPERSTATE: base.OperState = LinkOperState(uint8(attr.Value[0])) case unix.IFLA_LINK_NETNSID: base.NetNsID = int(native.Uint32(attr.Value[0:4])) case unix.IFLA_GSO_MAX_SIZE: base.GSOMaxSize = native.Uint32(attr.Value[0:4]) case unix.IFLA_GSO_MAX_SEGS: base.GSOMaxSegs = native.Uint32(attr.Value[0:4]) case unix.IFLA_VFINFO_LIST: data, err := nl.ParseRouteAttr(attr.Value) if err != nil { return nil, err } vfs, err := parseVfInfoList(data) if err != nil { return nil, err } base.Vfs = vfs case unix.IFLA_NUM_TX_QUEUES: base.NumTxQueues = int(native.Uint32(attr.Value[0:4])) case unix.IFLA_NUM_RX_QUEUES: base.NumRxQueues = int(native.Uint32(attr.Value[0:4])) case unix.IFLA_GROUP: base.Group = native.Uint32(attr.Value[0:4]) } } if stats64 != nil { base.Statistics = (*LinkStatistics)(stats64) } else if stats32 != nil { base.Statistics = (*LinkStatistics)(stats32.to64()) } // Links that don't have IFLA_INFO_KIND are hardware devices if link == nil { link = &Device{} } *link.Attrs() = base link.Attrs().Slave = linkSlave // If the tuntap attributes are not updated by netlink due to // an older driver, use sysfs if link != nil && linkType == "tun" { tuntap := link.(*Tuntap) if tuntap.Mode == 0 { ifname := tuntap.Attrs().Name if flags, err := readSysPropAsInt64(ifname, "tun_flags"); err == nil { if flags&unix.IFF_TUN != 0 { tuntap.Mode = unix.IFF_TUN } else if flags&unix.IFF_TAP != 0 { tuntap.Mode = unix.IFF_TAP } tuntap.NonPersist = false if flags&unix.IFF_PERSIST == 0 { tuntap.NonPersist = true } } // The sysfs interface for owner/group returns -1 for root user, instead of returning 0. // So explicitly check for negative value, before assigning the owner uid/gid. if owner, err := readSysPropAsInt64(ifname, "owner"); err == nil && owner > 0 { tuntap.Owner = uint32(owner) } if group, err := readSysPropAsInt64(ifname, "group"); err == nil && group > 0 { tuntap.Group = uint32(group) } } } return link, nil } func readSysPropAsInt64(ifname, prop string) (int64, error) { fname := fmt.Sprintf("/sys/class/net/%s/%s", ifname, prop) contents, err := ioutil.ReadFile(fname) if err != nil { return 0, err } num, err := strconv.ParseInt(strings.TrimSpace(string(contents)), 0, 64) if err == nil { return num, nil } return 0, err } // LinkList gets a list of link devices. // Equivalent to: `ip link show` func LinkList() ([]Link, error) { return pkgHandle.LinkList() } // LinkList gets a list of link devices. // Equivalent to: `ip link show` func (h *Handle) LinkList() ([]Link, error) { // NOTE(vish): This duplicates functionality in net/iface_linux.go, but we need // to get the message ourselves to parse link type. req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) req.AddData(msg) attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF)) req.AddData(attr) msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWLINK) if err != nil { return nil, err } var res []Link for _, m := range msgs { link, err := LinkDeserialize(nil, m) if err != nil { return nil, err } res = append(res, link) } return res, nil } // LinkUpdate is used to pass information back from LinkSubscribe() type LinkUpdate struct { nl.IfInfomsg Header unix.NlMsghdr Link } // LinkSubscribe takes a chan down which notifications will be sent // when links change. Close the 'done' chan to stop subscription. func LinkSubscribe(ch chan<- LinkUpdate, done <-chan struct{}) error { return linkSubscribeAt(netns.None(), netns.None(), ch, done, nil, false) } // LinkSubscribeAt works like LinkSubscribe plus it allows the caller // to choose the network namespace in which to subscribe (ns). func LinkSubscribeAt(ns netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}) error { return linkSubscribeAt(ns, netns.None(), ch, done, nil, false) } // LinkSubscribeOptions contains a set of options to use with // LinkSubscribeWithOptions. type LinkSubscribeOptions struct { Namespace *netns.NsHandle ErrorCallback func(error) ListExisting bool } // LinkSubscribeWithOptions work like LinkSubscribe but enable to // provide additional options to modify the behavior. Currently, the // namespace can be provided as well as an error callback. func LinkSubscribeWithOptions(ch chan<- LinkUpdate, done <-chan struct{}, options LinkSubscribeOptions) error { if options.Namespace == nil { none := netns.None() options.Namespace = &none } return linkSubscribeAt(*options.Namespace, netns.None(), ch, done, options.ErrorCallback, options.ListExisting) } func linkSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}, cberr func(error), listExisting bool) error { s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_LINK) if err != nil { return err } if done != nil { go func() { <-done s.Close() }() } if listExisting { req := pkgHandle.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) req.AddData(msg) if err := s.Send(req); err != nil { return err } } go func() { defer close(ch) for { msgs, from, err := s.Receive() if err != nil { if cberr != nil { cberr(err) } return } if from.Pid != nl.PidKernel { if cberr != nil { cberr(fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel)) } continue } for _, m := range msgs { if m.Header.Type == unix.NLMSG_DONE { continue } if m.Header.Type == unix.NLMSG_ERROR { native := nl.NativeEndian() error := int32(native.Uint32(m.Data[0:4])) if error == 0 { continue } if cberr != nil { cberr(syscall.Errno(-error)) } return } ifmsg := nl.DeserializeIfInfomsg(m.Data) header := unix.NlMsghdr(m.Header) link, err := LinkDeserialize(&header, m.Data) if err != nil { if cberr != nil { cberr(err) } return } ch <- LinkUpdate{IfInfomsg: *ifmsg, Header: header, Link: link} } } }() return nil } func LinkSetHairpin(link Link, mode bool) error { return pkgHandle.LinkSetHairpin(link, mode) } func (h *Handle) LinkSetHairpin(link Link, mode bool) error { return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_MODE) } func LinkSetGuard(link Link, mode bool) error { return pkgHandle.LinkSetGuard(link, mode) } func (h *Handle) LinkSetGuard(link Link, mode bool) error { return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_GUARD) } func LinkSetFastLeave(link Link, mode bool) error { return pkgHandle.LinkSetFastLeave(link, mode) } func (h *Handle) LinkSetFastLeave(link Link, mode bool) error { return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_FAST_LEAVE) } func LinkSetLearning(link Link, mode bool) error { return pkgHandle.LinkSetLearning(link, mode) } func (h *Handle) LinkSetLearning(link Link, mode bool) error { return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_LEARNING) } func LinkSetRootBlock(link Link, mode bool) error { return pkgHandle.LinkSetRootBlock(link, mode) } func (h *Handle) LinkSetRootBlock(link Link, mode bool) error { return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROTECT) } func LinkSetFlood(link Link, mode bool) error { return pkgHandle.LinkSetFlood(link, mode) } func (h *Handle) LinkSetFlood(link Link, mode bool) error { return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_UNICAST_FLOOD) } func LinkSetBrProxyArp(link Link, mode bool) error { return pkgHandle.LinkSetBrProxyArp(link, mode) } func (h *Handle) LinkSetBrProxyArp(link Link, mode bool) error { return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROXYARP) } func LinkSetBrProxyArpWiFi(link Link, mode bool) error { return pkgHandle.LinkSetBrProxyArpWiFi(link, mode) } func (h *Handle) LinkSetBrProxyArpWiFi(link Link, mode bool) error { return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROXYARP_WIFI) } func (h *Handle) setProtinfoAttr(link Link, mode bool, attr int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_BRIDGE) msg.Index = int32(base.Index) req.AddData(msg) br := nl.NewRtAttr(unix.IFLA_PROTINFO|unix.NLA_F_NESTED, nil) br.AddRtAttr(attr, boolToByte(mode)) req.AddData(br) _, err := req.Execute(unix.NETLINK_ROUTE, 0) if err != nil { return err } return nil } // LinkSetTxQLen sets the transaction queue length for the link. // Equivalent to: `ip link set $link txqlen $qlen` func LinkSetTxQLen(link Link, qlen int) error { return pkgHandle.LinkSetTxQLen(link, qlen) } // LinkSetTxQLen sets the transaction queue length for the link. // Equivalent to: `ip link set $link txqlen $qlen` func (h *Handle) LinkSetTxQLen(link Link, qlen int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) b := make([]byte, 4) native.PutUint32(b, uint32(qlen)) data := nl.NewRtAttr(unix.IFLA_TXQLEN, b) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetGroup sets the link group id which can be used to perform mass actions // with iproute2 as well use it as a reference in nft filters. // Equivalent to: `ip link set $link group $id` func LinkSetGroup(link Link, group int) error { return pkgHandle.LinkSetGroup(link, group) } // LinkSetGroup sets the link group id which can be used to perform mass actions // with iproute2 as well use it as a reference in nft filters. // Equivalent to: `ip link set $link group $id` func (h *Handle) LinkSetGroup(link Link, group int) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) b := make([]byte, 4) native.PutUint32(b, uint32(group)) data := nl.NewRtAttr(unix.IFLA_GROUP, b) req.AddData(data) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } func parseVlanData(link Link, data []syscall.NetlinkRouteAttr) { vlan := link.(*Vlan) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_VLAN_ID: vlan.VlanId = int(native.Uint16(datum.Value[0:2])) case nl.IFLA_VLAN_PROTOCOL: vlan.VlanProtocol = VlanProtocol(int(ntohs(datum.Value[0:2]))) } } } func parseVxlanData(link Link, data []syscall.NetlinkRouteAttr) { vxlan := link.(*Vxlan) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_VXLAN_ID: vxlan.VxlanId = int(native.Uint32(datum.Value[0:4])) case nl.IFLA_VXLAN_LINK: vxlan.VtepDevIndex = int(native.Uint32(datum.Value[0:4])) case nl.IFLA_VXLAN_LOCAL: vxlan.SrcAddr = net.IP(datum.Value[0:4]) case nl.IFLA_VXLAN_LOCAL6: vxlan.SrcAddr = net.IP(datum.Value[0:16]) case nl.IFLA_VXLAN_GROUP: vxlan.Group = net.IP(datum.Value[0:4]) case nl.IFLA_VXLAN_GROUP6: vxlan.Group = net.IP(datum.Value[0:16]) case nl.IFLA_VXLAN_TTL: vxlan.TTL = int(datum.Value[0]) case nl.IFLA_VXLAN_TOS: vxlan.TOS = int(datum.Value[0]) case nl.IFLA_VXLAN_LEARNING: vxlan.Learning = int8(datum.Value[0]) != 0 case nl.IFLA_VXLAN_PROXY: vxlan.Proxy = int8(datum.Value[0]) != 0 case nl.IFLA_VXLAN_RSC: vxlan.RSC = int8(datum.Value[0]) != 0 case nl.IFLA_VXLAN_L2MISS: vxlan.L2miss = int8(datum.Value[0]) != 0 case nl.IFLA_VXLAN_L3MISS: vxlan.L3miss = int8(datum.Value[0]) != 0 case nl.IFLA_VXLAN_UDP_CSUM: vxlan.UDPCSum = int8(datum.Value[0]) != 0 case nl.IFLA_VXLAN_UDP_ZERO_CSUM6_TX: vxlan.UDP6ZeroCSumTx = int8(datum.Value[0]) != 0 case nl.IFLA_VXLAN_UDP_ZERO_CSUM6_RX: vxlan.UDP6ZeroCSumRx = int8(datum.Value[0]) != 0 case nl.IFLA_VXLAN_GBP: vxlan.GBP = true case nl.IFLA_VXLAN_FLOWBASED: vxlan.FlowBased = int8(datum.Value[0]) != 0 case nl.IFLA_VXLAN_AGEING: vxlan.Age = int(native.Uint32(datum.Value[0:4])) vxlan.NoAge = vxlan.Age == 0 case nl.IFLA_VXLAN_LIMIT: vxlan.Limit = int(native.Uint32(datum.Value[0:4])) case nl.IFLA_VXLAN_PORT: vxlan.Port = int(ntohs(datum.Value[0:2])) case nl.IFLA_VXLAN_PORT_RANGE: buf := bytes.NewBuffer(datum.Value[0:4]) var pr vxlanPortRange if binary.Read(buf, binary.BigEndian, &pr) != nil { vxlan.PortLow = int(pr.Lo) vxlan.PortHigh = int(pr.Hi) } } } } func parseBondData(link Link, data []syscall.NetlinkRouteAttr) { bond := link.(*Bond) for i := range data { switch data[i].Attr.Type { case nl.IFLA_BOND_MODE: bond.Mode = BondMode(data[i].Value[0]) case nl.IFLA_BOND_ACTIVE_SLAVE: bond.ActiveSlave = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_MIIMON: bond.Miimon = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_UPDELAY: bond.UpDelay = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_DOWNDELAY: bond.DownDelay = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_USE_CARRIER: bond.UseCarrier = int(data[i].Value[0]) case nl.IFLA_BOND_ARP_INTERVAL: bond.ArpInterval = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_ARP_IP_TARGET: bond.ArpIpTargets = parseBondArpIpTargets(data[i].Value) case nl.IFLA_BOND_ARP_VALIDATE: bond.ArpValidate = BondArpValidate(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_ARP_ALL_TARGETS: bond.ArpAllTargets = BondArpAllTargets(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_PRIMARY: bond.Primary = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_PRIMARY_RESELECT: bond.PrimaryReselect = BondPrimaryReselect(data[i].Value[0]) case nl.IFLA_BOND_FAIL_OVER_MAC: bond.FailOverMac = BondFailOverMac(data[i].Value[0]) case nl.IFLA_BOND_XMIT_HASH_POLICY: bond.XmitHashPolicy = BondXmitHashPolicy(data[i].Value[0]) case nl.IFLA_BOND_RESEND_IGMP: bond.ResendIgmp = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_NUM_PEER_NOTIF: bond.NumPeerNotif = int(data[i].Value[0]) case nl.IFLA_BOND_ALL_SLAVES_ACTIVE: bond.AllSlavesActive = int(data[i].Value[0]) case nl.IFLA_BOND_MIN_LINKS: bond.MinLinks = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_LP_INTERVAL: bond.LpInterval = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_PACKETS_PER_SLAVE: bond.PackersPerSlave = int(native.Uint32(data[i].Value[0:4])) case nl.IFLA_BOND_AD_LACP_RATE: bond.LacpRate = BondLacpRate(data[i].Value[0]) case nl.IFLA_BOND_AD_SELECT: bond.AdSelect = BondAdSelect(data[i].Value[0]) case nl.IFLA_BOND_AD_INFO: // TODO: implement case nl.IFLA_BOND_AD_ACTOR_SYS_PRIO: bond.AdActorSysPrio = int(native.Uint16(data[i].Value[0:2])) case nl.IFLA_BOND_AD_USER_PORT_KEY: bond.AdUserPortKey = int(native.Uint16(data[i].Value[0:2])) case nl.IFLA_BOND_AD_ACTOR_SYSTEM: bond.AdActorSystem = net.HardwareAddr(data[i].Value[0:6]) case nl.IFLA_BOND_TLB_DYNAMIC_LB: bond.TlbDynamicLb = int(data[i].Value[0]) } } } func parseBondArpIpTargets(value []byte) []net.IP { data, err := nl.ParseRouteAttr(value) if err != nil { return nil } targets := []net.IP{} for i := range data { target := net.IP(data[i].Value) if ip := target.To4(); ip != nil { targets = append(targets, ip) continue } if ip := target.To16(); ip != nil { targets = append(targets, ip) } } return targets } func addBondSlaveAttrs(bondSlave *BondSlave, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_SLAVE_DATA, nil) data.AddRtAttr(nl.IFLA_BOND_SLAVE_STATE, nl.Uint8Attr(uint8(bondSlave.State))) data.AddRtAttr(nl.IFLA_BOND_SLAVE_MII_STATUS, nl.Uint8Attr(uint8(bondSlave.MiiStatus))) data.AddRtAttr(nl.IFLA_BOND_SLAVE_LINK_FAILURE_COUNT, nl.Uint32Attr(bondSlave.LinkFailureCount)) data.AddRtAttr(nl.IFLA_BOND_SLAVE_QUEUE_ID, nl.Uint16Attr(bondSlave.QueueId)) data.AddRtAttr(nl.IFLA_BOND_SLAVE_AD_AGGREGATOR_ID, nl.Uint16Attr(bondSlave.AggregatorId)) data.AddRtAttr(nl.IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE, nl.Uint8Attr(bondSlave.AdActorOperPortState)) data.AddRtAttr(nl.IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE, nl.Uint16Attr(bondSlave.AdPartnerOperPortState)) if mac := bondSlave.PermHardwareAddr; mac != nil { data.AddRtAttr(nl.IFLA_BOND_SLAVE_PERM_HWADDR, []byte(mac)) } } func parseBondSlaveData(slave LinkSlave, data []syscall.NetlinkRouteAttr) { bondSlave := slave.(*BondSlave) for i := range data { switch data[i].Attr.Type { case nl.IFLA_BOND_SLAVE_STATE: bondSlave.State = BondSlaveState(data[i].Value[0]) case nl.IFLA_BOND_SLAVE_MII_STATUS: bondSlave.MiiStatus = BondSlaveMiiStatus(data[i].Value[0]) case nl.IFLA_BOND_SLAVE_LINK_FAILURE_COUNT: bondSlave.LinkFailureCount = native.Uint32(data[i].Value[0:4]) case nl.IFLA_BOND_SLAVE_PERM_HWADDR: bondSlave.PermHardwareAddr = net.HardwareAddr(data[i].Value[0:6]) case nl.IFLA_BOND_SLAVE_QUEUE_ID: bondSlave.QueueId = native.Uint16(data[i].Value[0:2]) case nl.IFLA_BOND_SLAVE_AD_AGGREGATOR_ID: bondSlave.AggregatorId = native.Uint16(data[i].Value[0:2]) case nl.IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE: bondSlave.AdActorOperPortState = uint8(data[i].Value[0]) case nl.IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE: bondSlave.AdPartnerOperPortState = native.Uint16(data[i].Value[0:2]) } } } func parseIPVlanData(link Link, data []syscall.NetlinkRouteAttr) { ipv := link.(*IPVlan) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_IPVLAN_MODE: ipv.Mode = IPVlanMode(native.Uint32(datum.Value[0:4])) case nl.IFLA_IPVLAN_FLAG: ipv.Flag = IPVlanFlag(native.Uint32(datum.Value[0:4])) } } } func parseMacvtapData(link Link, data []syscall.NetlinkRouteAttr) { macv := link.(*Macvtap) parseMacvlanData(&macv.Macvlan, data) } func parseMacvlanData(link Link, data []syscall.NetlinkRouteAttr) { macv := link.(*Macvlan) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_MACVLAN_MODE: switch native.Uint32(datum.Value[0:4]) { case nl.MACVLAN_MODE_PRIVATE: macv.Mode = MACVLAN_MODE_PRIVATE case nl.MACVLAN_MODE_VEPA: macv.Mode = MACVLAN_MODE_VEPA case nl.MACVLAN_MODE_BRIDGE: macv.Mode = MACVLAN_MODE_BRIDGE case nl.MACVLAN_MODE_PASSTHRU: macv.Mode = MACVLAN_MODE_PASSTHRU case nl.MACVLAN_MODE_SOURCE: macv.Mode = MACVLAN_MODE_SOURCE } case nl.IFLA_MACVLAN_MACADDR_COUNT: macv.MACAddrs = make([]net.HardwareAddr, 0, int(native.Uint32(datum.Value[0:4]))) case nl.IFLA_MACVLAN_MACADDR_DATA: macs, err := nl.ParseRouteAttr(datum.Value[:]) if err != nil { panic(fmt.Sprintf("failed to ParseRouteAttr for IFLA_MACVLAN_MACADDR_DATA: %v", err)) } for _, macDatum := range macs { macv.MACAddrs = append(macv.MACAddrs, net.HardwareAddr(macDatum.Value[0:6])) } } } } // copied from pkg/net_linux.go func linkFlags(rawFlags uint32) net.Flags { var f net.Flags if rawFlags&unix.IFF_UP != 0 { f |= net.FlagUp } if rawFlags&unix.IFF_BROADCAST != 0 { f |= net.FlagBroadcast } if rawFlags&unix.IFF_LOOPBACK != 0 { f |= net.FlagLoopback } if rawFlags&unix.IFF_POINTOPOINT != 0 { f |= net.FlagPointToPoint } if rawFlags&unix.IFF_MULTICAST != 0 { f |= net.FlagMulticast } return f } func addGretapAttrs(gretap *Gretap, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) if gretap.FlowBased { // In flow based mode, no other attributes need to be configured data.AddRtAttr(nl.IFLA_GRE_COLLECT_METADATA, boolAttr(gretap.FlowBased)) return } if ip := gretap.Local; ip != nil { if ip.To4() != nil { ip = ip.To4() } data.AddRtAttr(nl.IFLA_GRE_LOCAL, []byte(ip)) } if ip := gretap.Remote; ip != nil { if ip.To4() != nil { ip = ip.To4() } data.AddRtAttr(nl.IFLA_GRE_REMOTE, []byte(ip)) } if gretap.IKey != 0 { data.AddRtAttr(nl.IFLA_GRE_IKEY, htonl(gretap.IKey)) gretap.IFlags |= uint16(nl.GRE_KEY) } if gretap.OKey != 0 { data.AddRtAttr(nl.IFLA_GRE_OKEY, htonl(gretap.OKey)) gretap.OFlags |= uint16(nl.GRE_KEY) } data.AddRtAttr(nl.IFLA_GRE_IFLAGS, htons(gretap.IFlags)) data.AddRtAttr(nl.IFLA_GRE_OFLAGS, htons(gretap.OFlags)) if gretap.Link != 0 { data.AddRtAttr(nl.IFLA_GRE_LINK, nl.Uint32Attr(gretap.Link)) } data.AddRtAttr(nl.IFLA_GRE_PMTUDISC, nl.Uint8Attr(gretap.PMtuDisc)) data.AddRtAttr(nl.IFLA_GRE_TTL, nl.Uint8Attr(gretap.Ttl)) data.AddRtAttr(nl.IFLA_GRE_TOS, nl.Uint8Attr(gretap.Tos)) data.AddRtAttr(nl.IFLA_GRE_ENCAP_TYPE, nl.Uint16Attr(gretap.EncapType)) data.AddRtAttr(nl.IFLA_GRE_ENCAP_FLAGS, nl.Uint16Attr(gretap.EncapFlags)) data.AddRtAttr(nl.IFLA_GRE_ENCAP_SPORT, htons(gretap.EncapSport)) data.AddRtAttr(nl.IFLA_GRE_ENCAP_DPORT, htons(gretap.EncapDport)) } func parseGretapData(link Link, data []syscall.NetlinkRouteAttr) { gre := link.(*Gretap) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_GRE_OKEY: gre.IKey = ntohl(datum.Value[0:4]) case nl.IFLA_GRE_IKEY: gre.OKey = ntohl(datum.Value[0:4]) case nl.IFLA_GRE_LOCAL: gre.Local = net.IP(datum.Value) case nl.IFLA_GRE_REMOTE: gre.Remote = net.IP(datum.Value) case nl.IFLA_GRE_ENCAP_SPORT: gre.EncapSport = ntohs(datum.Value[0:2]) case nl.IFLA_GRE_ENCAP_DPORT: gre.EncapDport = ntohs(datum.Value[0:2]) case nl.IFLA_GRE_IFLAGS: gre.IFlags = ntohs(datum.Value[0:2]) case nl.IFLA_GRE_OFLAGS: gre.OFlags = ntohs(datum.Value[0:2]) case nl.IFLA_GRE_TTL: gre.Ttl = uint8(datum.Value[0]) case nl.IFLA_GRE_TOS: gre.Tos = uint8(datum.Value[0]) case nl.IFLA_GRE_PMTUDISC: gre.PMtuDisc = uint8(datum.Value[0]) case nl.IFLA_GRE_ENCAP_TYPE: gre.EncapType = native.Uint16(datum.Value[0:2]) case nl.IFLA_GRE_ENCAP_FLAGS: gre.EncapFlags = native.Uint16(datum.Value[0:2]) case nl.IFLA_GRE_COLLECT_METADATA: gre.FlowBased = true } } } func addGretunAttrs(gre *Gretun, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) if ip := gre.Local; ip != nil { if ip.To4() != nil { ip = ip.To4() } data.AddRtAttr(nl.IFLA_GRE_LOCAL, []byte(ip)) } if ip := gre.Remote; ip != nil { if ip.To4() != nil { ip = ip.To4() } data.AddRtAttr(nl.IFLA_GRE_REMOTE, []byte(ip)) } if gre.IKey != 0 { data.AddRtAttr(nl.IFLA_GRE_IKEY, htonl(gre.IKey)) gre.IFlags |= uint16(nl.GRE_KEY) } if gre.OKey != 0 { data.AddRtAttr(nl.IFLA_GRE_OKEY, htonl(gre.OKey)) gre.OFlags |= uint16(nl.GRE_KEY) } data.AddRtAttr(nl.IFLA_GRE_IFLAGS, htons(gre.IFlags)) data.AddRtAttr(nl.IFLA_GRE_OFLAGS, htons(gre.OFlags)) if gre.Link != 0 { data.AddRtAttr(nl.IFLA_GRE_LINK, nl.Uint32Attr(gre.Link)) } data.AddRtAttr(nl.IFLA_GRE_PMTUDISC, nl.Uint8Attr(gre.PMtuDisc)) data.AddRtAttr(nl.IFLA_GRE_TTL, nl.Uint8Attr(gre.Ttl)) data.AddRtAttr(nl.IFLA_GRE_TOS, nl.Uint8Attr(gre.Tos)) data.AddRtAttr(nl.IFLA_GRE_ENCAP_TYPE, nl.Uint16Attr(gre.EncapType)) data.AddRtAttr(nl.IFLA_GRE_ENCAP_FLAGS, nl.Uint16Attr(gre.EncapFlags)) data.AddRtAttr(nl.IFLA_GRE_ENCAP_SPORT, htons(gre.EncapSport)) data.AddRtAttr(nl.IFLA_GRE_ENCAP_DPORT, htons(gre.EncapDport)) } func parseGretunData(link Link, data []syscall.NetlinkRouteAttr) { gre := link.(*Gretun) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_GRE_IKEY: gre.IKey = ntohl(datum.Value[0:4]) case nl.IFLA_GRE_OKEY: gre.OKey = ntohl(datum.Value[0:4]) case nl.IFLA_GRE_LOCAL: gre.Local = net.IP(datum.Value) case nl.IFLA_GRE_REMOTE: gre.Remote = net.IP(datum.Value) case nl.IFLA_GRE_IFLAGS: gre.IFlags = ntohs(datum.Value[0:2]) case nl.IFLA_GRE_OFLAGS: gre.OFlags = ntohs(datum.Value[0:2]) case nl.IFLA_GRE_TTL: gre.Ttl = uint8(datum.Value[0]) case nl.IFLA_GRE_TOS: gre.Tos = uint8(datum.Value[0]) case nl.IFLA_GRE_PMTUDISC: gre.PMtuDisc = uint8(datum.Value[0]) case nl.IFLA_GRE_ENCAP_TYPE: gre.EncapType = native.Uint16(datum.Value[0:2]) case nl.IFLA_GRE_ENCAP_FLAGS: gre.EncapFlags = native.Uint16(datum.Value[0:2]) case nl.IFLA_GRE_ENCAP_SPORT: gre.EncapSport = ntohs(datum.Value[0:2]) case nl.IFLA_GRE_ENCAP_DPORT: gre.EncapDport = ntohs(datum.Value[0:2]) } } } func addXdpAttrs(xdp *LinkXdp, req *nl.NetlinkRequest) { attrs := nl.NewRtAttr(unix.IFLA_XDP|unix.NLA_F_NESTED, nil) b := make([]byte, 4) native.PutUint32(b, uint32(xdp.Fd)) attrs.AddRtAttr(nl.IFLA_XDP_FD, b) if xdp.Flags != 0 { b := make([]byte, 4) native.PutUint32(b, xdp.Flags) attrs.AddRtAttr(nl.IFLA_XDP_FLAGS, b) } req.AddData(attrs) } func parseLinkXdp(data []byte) (*LinkXdp, error) { attrs, err := nl.ParseRouteAttr(data) if err != nil { return nil, err } xdp := &LinkXdp{} for _, attr := range attrs { switch attr.Attr.Type { case nl.IFLA_XDP_FD: xdp.Fd = int(native.Uint32(attr.Value[0:4])) case nl.IFLA_XDP_ATTACHED: xdp.Attached = attr.Value[0] != 0 case nl.IFLA_XDP_FLAGS: xdp.Flags = native.Uint32(attr.Value[0:4]) case nl.IFLA_XDP_PROG_ID: xdp.ProgId = native.Uint32(attr.Value[0:4]) } } return xdp, nil } func addIptunAttrs(iptun *Iptun, linkInfo *nl.RtAttr) { if iptun.FlowBased { // In flow based mode, no other attributes need to be configured linkInfo.AddRtAttr(nl.IFLA_IPTUN_COLLECT_METADATA, boolAttr(iptun.FlowBased)) return } data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) ip := iptun.Local.To4() if ip != nil { data.AddRtAttr(nl.IFLA_IPTUN_LOCAL, []byte(ip)) } ip = iptun.Remote.To4() if ip != nil { data.AddRtAttr(nl.IFLA_IPTUN_REMOTE, []byte(ip)) } if iptun.Link != 0 { data.AddRtAttr(nl.IFLA_IPTUN_LINK, nl.Uint32Attr(iptun.Link)) } data.AddRtAttr(nl.IFLA_IPTUN_PMTUDISC, nl.Uint8Attr(iptun.PMtuDisc)) data.AddRtAttr(nl.IFLA_IPTUN_TTL, nl.Uint8Attr(iptun.Ttl)) data.AddRtAttr(nl.IFLA_IPTUN_TOS, nl.Uint8Attr(iptun.Tos)) data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_TYPE, nl.Uint16Attr(iptun.EncapType)) data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_FLAGS, nl.Uint16Attr(iptun.EncapFlags)) data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_SPORT, htons(iptun.EncapSport)) data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_DPORT, htons(iptun.EncapDport)) } func parseIptunData(link Link, data []syscall.NetlinkRouteAttr) { iptun := link.(*Iptun) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_IPTUN_LOCAL: iptun.Local = net.IP(datum.Value[0:4]) case nl.IFLA_IPTUN_REMOTE: iptun.Remote = net.IP(datum.Value[0:4]) case nl.IFLA_IPTUN_TTL: iptun.Ttl = uint8(datum.Value[0]) case nl.IFLA_IPTUN_TOS: iptun.Tos = uint8(datum.Value[0]) case nl.IFLA_IPTUN_PMTUDISC: iptun.PMtuDisc = uint8(datum.Value[0]) case nl.IFLA_IPTUN_ENCAP_SPORT: iptun.EncapSport = ntohs(datum.Value[0:2]) case nl.IFLA_IPTUN_ENCAP_DPORT: iptun.EncapDport = ntohs(datum.Value[0:2]) case nl.IFLA_IPTUN_ENCAP_TYPE: iptun.EncapType = native.Uint16(datum.Value[0:2]) case nl.IFLA_IPTUN_ENCAP_FLAGS: iptun.EncapFlags = native.Uint16(datum.Value[0:2]) case nl.IFLA_IPTUN_COLLECT_METADATA: iptun.FlowBased = int8(datum.Value[0]) != 0 } } } func addIp6tnlAttrs(ip6tnl *Ip6tnl, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) if ip6tnl.Link != 0 { data.AddRtAttr(nl.IFLA_IPTUN_LINK, nl.Uint32Attr(ip6tnl.Link)) } ip := ip6tnl.Local.To16() if ip != nil { data.AddRtAttr(nl.IFLA_IPTUN_LOCAL, []byte(ip)) } ip = ip6tnl.Remote.To16() if ip != nil { data.AddRtAttr(nl.IFLA_IPTUN_REMOTE, []byte(ip)) } data.AddRtAttr(nl.IFLA_IPTUN_TTL, nl.Uint8Attr(ip6tnl.Ttl)) data.AddRtAttr(nl.IFLA_IPTUN_TOS, nl.Uint8Attr(ip6tnl.Tos)) data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_LIMIT, nl.Uint8Attr(ip6tnl.EncapLimit)) data.AddRtAttr(nl.IFLA_IPTUN_FLAGS, nl.Uint32Attr(ip6tnl.Flags)) data.AddRtAttr(nl.IFLA_IPTUN_PROTO, nl.Uint8Attr(ip6tnl.Proto)) data.AddRtAttr(nl.IFLA_IPTUN_FLOWINFO, nl.Uint32Attr(ip6tnl.FlowInfo)) } func parseIp6tnlData(link Link, data []syscall.NetlinkRouteAttr) { ip6tnl := link.(*Ip6tnl) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_IPTUN_LOCAL: ip6tnl.Local = net.IP(datum.Value[:16]) case nl.IFLA_IPTUN_REMOTE: ip6tnl.Remote = net.IP(datum.Value[:16]) case nl.IFLA_IPTUN_TTL: ip6tnl.Ttl = uint8(datum.Value[0]) case nl.IFLA_IPTUN_TOS: ip6tnl.Tos = uint8(datum.Value[0]) case nl.IFLA_IPTUN_ENCAP_LIMIT: ip6tnl.EncapLimit = uint8(datum.Value[0]) case nl.IFLA_IPTUN_FLAGS: ip6tnl.Flags = native.Uint32(datum.Value[:4]) case nl.IFLA_IPTUN_PROTO: ip6tnl.Proto = uint8(datum.Value[0]) case nl.IFLA_IPTUN_FLOWINFO: ip6tnl.FlowInfo = native.Uint32(datum.Value[:4]) } } } func addSittunAttrs(sittun *Sittun, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) if sittun.Link != 0 { data.AddRtAttr(nl.IFLA_IPTUN_LINK, nl.Uint32Attr(sittun.Link)) } ip := sittun.Local.To4() if ip != nil { data.AddRtAttr(nl.IFLA_IPTUN_LOCAL, []byte(ip)) } ip = sittun.Remote.To4() if ip != nil { data.AddRtAttr(nl.IFLA_IPTUN_REMOTE, []byte(ip)) } if sittun.Ttl > 0 { // Would otherwise fail on 3.10 kernel data.AddRtAttr(nl.IFLA_IPTUN_TTL, nl.Uint8Attr(sittun.Ttl)) } data.AddRtAttr(nl.IFLA_IPTUN_TOS, nl.Uint8Attr(sittun.Tos)) data.AddRtAttr(nl.IFLA_IPTUN_PMTUDISC, nl.Uint8Attr(sittun.PMtuDisc)) data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_TYPE, nl.Uint16Attr(sittun.EncapType)) data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_FLAGS, nl.Uint16Attr(sittun.EncapFlags)) data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_SPORT, htons(sittun.EncapSport)) data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_DPORT, htons(sittun.EncapDport)) } func parseSittunData(link Link, data []syscall.NetlinkRouteAttr) { sittun := link.(*Sittun) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_IPTUN_LOCAL: sittun.Local = net.IP(datum.Value[0:4]) case nl.IFLA_IPTUN_REMOTE: sittun.Remote = net.IP(datum.Value[0:4]) case nl.IFLA_IPTUN_TTL: sittun.Ttl = uint8(datum.Value[0]) case nl.IFLA_IPTUN_TOS: sittun.Tos = uint8(datum.Value[0]) case nl.IFLA_IPTUN_PMTUDISC: sittun.PMtuDisc = uint8(datum.Value[0]) case nl.IFLA_IPTUN_ENCAP_TYPE: sittun.EncapType = native.Uint16(datum.Value[0:2]) case nl.IFLA_IPTUN_ENCAP_FLAGS: sittun.EncapFlags = native.Uint16(datum.Value[0:2]) case nl.IFLA_IPTUN_ENCAP_SPORT: sittun.EncapSport = ntohs(datum.Value[0:2]) case nl.IFLA_IPTUN_ENCAP_DPORT: sittun.EncapDport = ntohs(datum.Value[0:2]) } } } func addVtiAttrs(vti *Vti, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) family := FAMILY_V4 if vti.Local.To4() == nil { family = FAMILY_V6 } var ip net.IP if family == FAMILY_V4 { ip = vti.Local.To4() } else { ip = vti.Local } if ip != nil { data.AddRtAttr(nl.IFLA_VTI_LOCAL, []byte(ip)) } if family == FAMILY_V4 { ip = vti.Remote.To4() } else { ip = vti.Remote } if ip != nil { data.AddRtAttr(nl.IFLA_VTI_REMOTE, []byte(ip)) } if vti.Link != 0 { data.AddRtAttr(nl.IFLA_VTI_LINK, nl.Uint32Attr(vti.Link)) } data.AddRtAttr(nl.IFLA_VTI_IKEY, htonl(vti.IKey)) data.AddRtAttr(nl.IFLA_VTI_OKEY, htonl(vti.OKey)) } func parseVtiData(link Link, data []syscall.NetlinkRouteAttr) { vti := link.(*Vti) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_VTI_LOCAL: vti.Local = net.IP(datum.Value) case nl.IFLA_VTI_REMOTE: vti.Remote = net.IP(datum.Value) case nl.IFLA_VTI_IKEY: vti.IKey = ntohl(datum.Value[0:4]) case nl.IFLA_VTI_OKEY: vti.OKey = ntohl(datum.Value[0:4]) } } } func addVrfAttrs(vrf *Vrf, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) b := make([]byte, 4) native.PutUint32(b, uint32(vrf.Table)) data.AddRtAttr(nl.IFLA_VRF_TABLE, b) } func parseVrfData(link Link, data []syscall.NetlinkRouteAttr) { vrf := link.(*Vrf) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_VRF_TABLE: vrf.Table = native.Uint32(datum.Value[0:4]) } } } func addBridgeAttrs(bridge *Bridge, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) if bridge.MulticastSnooping != nil { data.AddRtAttr(nl.IFLA_BR_MCAST_SNOOPING, boolToByte(*bridge.MulticastSnooping)) } if bridge.HelloTime != nil { data.AddRtAttr(nl.IFLA_BR_HELLO_TIME, nl.Uint32Attr(*bridge.HelloTime)) } if bridge.VlanFiltering != nil { data.AddRtAttr(nl.IFLA_BR_VLAN_FILTERING, boolToByte(*bridge.VlanFiltering)) } } func parseBridgeData(bridge Link, data []syscall.NetlinkRouteAttr) { br := bridge.(*Bridge) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_BR_HELLO_TIME: helloTime := native.Uint32(datum.Value[0:4]) br.HelloTime = &helloTime case nl.IFLA_BR_MCAST_SNOOPING: mcastSnooping := datum.Value[0] == 1 br.MulticastSnooping = &mcastSnooping case nl.IFLA_BR_VLAN_FILTERING: vlanFiltering := datum.Value[0] == 1 br.VlanFiltering = &vlanFiltering } } } func addGTPAttrs(gtp *GTP, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) data.AddRtAttr(nl.IFLA_GTP_FD0, nl.Uint32Attr(uint32(gtp.FD0))) data.AddRtAttr(nl.IFLA_GTP_FD1, nl.Uint32Attr(uint32(gtp.FD1))) data.AddRtAttr(nl.IFLA_GTP_PDP_HASHSIZE, nl.Uint32Attr(131072)) if gtp.Role != nl.GTP_ROLE_GGSN { data.AddRtAttr(nl.IFLA_GTP_ROLE, nl.Uint32Attr(uint32(gtp.Role))) } } func parseGTPData(link Link, data []syscall.NetlinkRouteAttr) { gtp := link.(*GTP) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_GTP_FD0: gtp.FD0 = int(native.Uint32(datum.Value)) case nl.IFLA_GTP_FD1: gtp.FD1 = int(native.Uint32(datum.Value)) case nl.IFLA_GTP_PDP_HASHSIZE: gtp.PDPHashsize = int(native.Uint32(datum.Value)) case nl.IFLA_GTP_ROLE: gtp.Role = int(native.Uint32(datum.Value)) } } } func parseVfInfoList(data []syscall.NetlinkRouteAttr) ([]VfInfo, error) { var vfs []VfInfo for i, element := range data { if element.Attr.Type != nl.IFLA_VF_INFO { return nil, fmt.Errorf("Incorrect element type in vf info list: %d", element.Attr.Type) } vfAttrs, err := nl.ParseRouteAttr(element.Value) if err != nil { return nil, err } vfs = append(vfs, parseVfInfo(vfAttrs, i)) } return vfs, nil } func parseVfInfo(data []syscall.NetlinkRouteAttr, id int) VfInfo { vf := VfInfo{ID: id} for _, element := range data { switch element.Attr.Type { case nl.IFLA_VF_MAC: mac := nl.DeserializeVfMac(element.Value[:]) vf.Mac = mac.Mac[:6] case nl.IFLA_VF_VLAN: vl := nl.DeserializeVfVlan(element.Value[:]) vf.Vlan = int(vl.Vlan) vf.Qos = int(vl.Qos) case nl.IFLA_VF_TX_RATE: txr := nl.DeserializeVfTxRate(element.Value[:]) vf.TxRate = int(txr.Rate) case nl.IFLA_VF_SPOOFCHK: sp := nl.DeserializeVfSpoofchk(element.Value[:]) vf.Spoofchk = sp.Setting != 0 case nl.IFLA_VF_LINK_STATE: ls := nl.DeserializeVfLinkState(element.Value[:]) vf.LinkState = ls.LinkState case nl.IFLA_VF_RATE: vfr := nl.DeserializeVfRate(element.Value[:]) vf.MaxTxRate = vfr.MaxTxRate vf.MinTxRate = vfr.MinTxRate } } return vf } func addXfrmiAttrs(xfrmi *Xfrmi, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) data.AddRtAttr(nl.IFLA_XFRM_LINK, nl.Uint32Attr(uint32(xfrmi.ParentIndex))) data.AddRtAttr(nl.IFLA_XFRM_IF_ID, nl.Uint32Attr(xfrmi.Ifid)) } func parseXfrmiData(link Link, data []syscall.NetlinkRouteAttr) { xfrmi := link.(*Xfrmi) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_XFRM_LINK: xfrmi.ParentIndex = int(native.Uint32(datum.Value)) case nl.IFLA_XFRM_IF_ID: xfrmi.Ifid = native.Uint32(datum.Value) } } } // LinkSetBondSlave add slave to bond link via ioctl interface. func LinkSetBondSlave(link Link, master *Bond) error { fd, err := getSocketUDP() if err != nil { return err } defer syscall.Close(fd) ifreq := newIocltSlaveReq(link.Attrs().Name, master.Attrs().Name) _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), unix.SIOCBONDENSLAVE, uintptr(unsafe.Pointer(ifreq))) if errno != 0 { return fmt.Errorf("Failed to enslave %q to %q, errno=%v", link.Attrs().Name, master.Attrs().Name, errno) } return nil } // LinkSetBondSlaveQueueId modify bond slave queue-id. func (h *Handle) LinkSetBondSlaveQueueId(link Link, queueId uint16) error { base := link.Attrs() h.ensureIndex(base) req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) msg := nl.NewIfInfomsg(unix.AF_UNSPEC) msg.Index = int32(base.Index) req.AddData(msg) linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil) data := linkInfo.AddRtAttr(nl.IFLA_INFO_SLAVE_DATA, nil) data.AddRtAttr(nl.IFLA_BOND_SLAVE_QUEUE_ID, nl.Uint16Attr(queueId)) req.AddData(linkInfo) _, err := req.Execute(unix.NETLINK_ROUTE, 0) return err } // LinkSetBondSlaveQueueId modify bond slave queue-id. func LinkSetBondSlaveQueueId(link Link, queueId uint16) error { return pkgHandle.LinkSetBondSlaveQueueId(link, queueId) } func vethStatsSerialize(stats ethtoolStats) ([]byte, error) { statsSize := int(unsafe.Sizeof(stats)) + int(stats.nStats)*int(unsafe.Sizeof(uint64(0))) b := make([]byte, 0, statsSize) buf := bytes.NewBuffer(b) err := binary.Write(buf, nl.NativeEndian(), stats) return buf.Bytes()[:statsSize], err } type vethEthtoolStats struct { Cmd uint32 NStats uint32 Peer uint64 // Newer kernels have XDP stats in here, but we only care // to extract the peer ifindex here. } func vethStatsDeserialize(b []byte) (vethEthtoolStats, error) { var stats = vethEthtoolStats{} err := binary.Read(bytes.NewReader(b), nl.NativeEndian(), &stats) return stats, err } // VethPeerIndex get veth peer index. func VethPeerIndex(link *Veth) (int, error) { fd, err := getSocketUDP() if err != nil { return -1, err } defer syscall.Close(fd) ifreq, sSet := newIocltStringSetReq(link.Name) _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), SIOCETHTOOL, uintptr(unsafe.Pointer(ifreq))) if errno != 0 { return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno) } stats := ethtoolStats{ cmd: ETHTOOL_GSTATS, nStats: sSet.data[0], } buffer, err := vethStatsSerialize(stats) if err != nil { return -1, err } ifreq.Data = uintptr(unsafe.Pointer(&buffer[0])) _, _, errno = syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), SIOCETHTOOL, uintptr(unsafe.Pointer(ifreq))) if errno != 0 { return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno) } vstats, err := vethStatsDeserialize(buffer) if err != nil { return -1, err } return int(vstats.Peer), nil } func parseTuntapData(link Link, data []syscall.NetlinkRouteAttr) { tuntap := link.(*Tuntap) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_TUN_OWNER: tuntap.Owner = native.Uint32(datum.Value) case nl.IFLA_TUN_GROUP: tuntap.Group = native.Uint32(datum.Value) case nl.IFLA_TUN_TYPE: tuntap.Mode = TuntapMode(uint8(datum.Value[0])) case nl.IFLA_TUN_PERSIST: tuntap.NonPersist = false if uint8(datum.Value[0]) == 0 { tuntap.NonPersist = true } } } } func parseIPoIBData(link Link, data []syscall.NetlinkRouteAttr) { ipoib := link.(*IPoIB) for _, datum := range data { switch datum.Attr.Type { case nl.IFLA_IPOIB_PKEY: ipoib.Pkey = uint16(native.Uint16(datum.Value)) case nl.IFLA_IPOIB_MODE: ipoib.Mode = IPoIBMode(native.Uint16(datum.Value)) case nl.IFLA_IPOIB_UMCAST: ipoib.Umcast = uint16(native.Uint16(datum.Value)) } } } func addIPoIBAttrs(ipoib *IPoIB, linkInfo *nl.RtAttr) { data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) data.AddRtAttr(nl.IFLA_IPOIB_PKEY, nl.Uint16Attr(uint16(ipoib.Pkey))) data.AddRtAttr(nl.IFLA_IPOIB_MODE, nl.Uint16Attr(uint16(ipoib.Mode))) data.AddRtAttr(nl.IFLA_IPOIB_UMCAST, nl.Uint16Attr(uint16(ipoib.Umcast))) }
apache-2.0
Rinnegatamante/easyrpg-player-3ds
lib/boost/fusion/adapted/boost_array/detail/value_at_impl.hpp
939
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2005-2006 Dan Marsden Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_VALUE_AT_IMPL_27122005_1256) #define BOOST_FUSION_VALUE_AT_IMPL_27122005_1256 namespace boost { namespace fusion { struct boost_array_tag; namespace extension { template<typename T> struct value_at_impl; template <> struct value_at_impl<boost_array_tag> { template <typename Sequence, typename N> struct apply { typedef typename Sequence::value_type type; }; }; } }} #endif
gpl-3.0
nerviozzo/estudiando
PHP/Libro Anaya/Cap10/ZendFramework-2.3.0/library/Zend/Log/LoggerAwareTrait.php
823
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Log; trait LoggerAwareTrait { /** * @var LoggerInterface */ protected $logger = null; /** * Set logger object * * @param LoggerInterface $logger * @return mixed */ public function setLogger(LoggerInterface $logger) { $this->logger = $logger; return $this; } /** * Get logger object * * @return null|LoggerInterface */ public function getLogger() { return $this->logger; } }
gpl-3.0
HereSinceres/TypeScript
tests/cases/conformance/parser/ecmascript5/Statements/BreakStatements/parser_breakNotInIterationOrSwitchStatement1.ts
6
break;
apache-2.0
BoldBigflank/attbee
src/pixi/renderers/webgl/utils/WebGLShaderManager.js
3356
/** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * @class WebGLShaderManager * @constructor * @param gl {WebGLContext} the current WebGL drawing context * @private */ PIXI.WebGLShaderManager = function(gl) { this.maxAttibs = 10; this.attribState = []; this.tempAttribState = []; for (var i = 0; i < this.maxAttibs; i++) { this.attribState[i] = false; } this.setContext(gl); // the final one is used for the rendering strips //this.stripShader = new PIXI.StripShader(gl); }; /** * Initialises the context and the properties * @method setContext * @param gl {WebGLContext} the current WebGL drawing context * @param transparent {Boolean} Whether or not the drawing context should be transparent */ PIXI.WebGLShaderManager.prototype.setContext = function(gl) { this.gl = gl; // the next one is used for rendering primatives this.primitiveShader = new PIXI.PrimitiveShader(gl); // this shader is used for the default sprite rendering this.defaultShader = new PIXI.PixiShader(gl); // this shader is used for the fast sprite rendering this.fastShader = new PIXI.PixiFastShader(gl); this.activateShader(this.defaultShader); }; /** * Takes the attributes given in parameters * @method setAttribs * @param attribs {Array} attribs */ PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs) { // reset temp state var i; for (i = 0; i < this.tempAttribState.length; i++) { this.tempAttribState[i] = false; } // set the new attribs for (i = 0; i < attribs.length; i++) { var attribId = attribs[i]; this.tempAttribState[attribId] = true; } var gl = this.gl; for (i = 0; i < this.attribState.length; i++) { if(this.attribState[i] !== this.tempAttribState[i]) { this.attribState[i] = this.tempAttribState[i]; if(this.tempAttribState[i]) { gl.enableVertexAttribArray(i); } else { gl.disableVertexAttribArray(i); } } } }; /** * Sets-up the given shader * * @method activateShader * @param shader {Object} the shader that is going to be activated */ PIXI.WebGLShaderManager.prototype.activateShader = function(shader) { //if(this.currentShader == shader)return; this.currentShader = shader; this.gl.useProgram(shader.program); this.setAttribs(shader.attributes); }; /** * Triggers the primitive shader * @method activatePrimitiveShader */ PIXI.WebGLShaderManager.prototype.activatePrimitiveShader = function() { var gl = this.gl; gl.useProgram(this.primitiveShader.program); this.setAttribs(this.primitiveShader.attributes); }; /** * Disable the primitive shader * @method deactivatePrimitiveShader */ PIXI.WebGLShaderManager.prototype.deactivatePrimitiveShader = function() { var gl = this.gl; gl.useProgram(this.defaultShader.program); this.setAttribs(this.defaultShader.attributes); }; /** * Destroys * @method destroy */ PIXI.WebGLShaderManager.prototype.destroy = function() { this.attribState = null; this.tempAttribState = null; this.primitiveShader.destroy(); this.defaultShader.destroy(); this.fastShader.destroy(); this.gl = null; };
mit
Jay5066/drupalDockerCompose
web/core/modules/filter/src/Plugin/Filter/FilterHtml.php
20468
<?php namespace Drupal\filter\Plugin\Filter; use Drupal\Component\Utility\Xss; use Drupal\Core\Form\FormStateInterface; use Drupal\Component\Utility\Html; use Drupal\filter\FilterProcessResult; use Drupal\filter\Plugin\FilterBase; /** * Provides a filter to limit allowed HTML tags. * * The attributes in the annotation show examples of allowing all attributes * by only having the attribute name, or allowing a fixed list of values, or * allowing a value with a wildcard prefix. * * @Filter( * id = "filter_html", * title = @Translation("Limit allowed HTML tags and correct faulty HTML"), * type = Drupal\filter\Plugin\FilterInterface::TYPE_HTML_RESTRICTOR, * settings = { * "allowed_html" = "<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type='1 A I'> <li> <dl> <dt> <dd> <h2 id='jump-*'> <h3 id> <h4 id> <h5 id> <h6 id>", * "filter_html_help" = TRUE, * "filter_html_nofollow" = FALSE * }, * weight = -10 * ) */ class FilterHtml extends FilterBase { /** * The processed HTML restrictions. * * @var array */ protected $restrictions; /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $form['allowed_html'] = [ '#type' => 'textarea', '#title' => $this->t('Allowed HTML tags'), '#default_value' => $this->settings['allowed_html'], '#description' => $this->t('A list of HTML tags that can be used. By default only the <em>lang</em> and <em>dir</em> attributes are allowed for all HTML tags. Each HTML tag may have attributes which are treated as allowed attribute names for that HTML tag. Each attribute may allow all values, or only allow specific values. Attribute names or values may be written as a prefix and wildcard like <em>jump-*</em>. JavaScript event attributes, JavaScript URLs, and CSS are always stripped.'), '#attached' => [ 'library' => [ 'filter/drupal.filter.filter_html.admin', ], ], ]; $form['filter_html_help'] = [ '#type' => 'checkbox', '#title' => $this->t('Display basic HTML help in long filter tips'), '#default_value' => $this->settings['filter_html_help'], ]; $form['filter_html_nofollow'] = [ '#type' => 'checkbox', '#title' => $this->t('Add rel="nofollow" to all links'), '#default_value' => $this->settings['filter_html_nofollow'], ]; return $form; } /** * {@inheritdoc} */ public function setConfiguration(array $configuration) { if (isset($configuration['settings']['allowed_html'])) { // The javascript in core/modules/filter/filter.filter_html.admin.js // removes new lines and double spaces so, for consistency when javascript // is disabled, remove them. $configuration['settings']['allowed_html'] = preg_replace('/\s+/', ' ', $configuration['settings']['allowed_html']); } parent::setConfiguration($configuration); // Force restrictions to be calculated again. $this->restrictions = NULL; } /** * {@inheritdoc} */ public function process($text, $langcode) { $restrictions = $this->getHtmlRestrictions(); // Split the work into two parts. For filtering HTML tags out of the content // we rely on the well-tested Xss::filter() code. Since there is no '*' tag // that needs to be removed from the list. unset($restrictions['allowed']['*']); $text = Xss::filter($text, array_keys($restrictions['allowed'])); // After we've done tag filtering, we do attribute and attribute value // filtering as the second part. return new FilterProcessResult($this->filterAttributes($text)); } /** * Provides filtering of tag attributes into accepted HTML. * * @param string $text * The HTML text string to be filtered. * * @return string * Filtered HTML with attributes filtered according to the settings. */ public function filterAttributes($text) { $restrictions = $this->getHTMLRestrictions(); $global_allowed_attributes = array_filter($restrictions['allowed']['*']); unset($restrictions['allowed']['*']); // Apply attribute restrictions to tags. $html_dom = Html::load($text); $xpath = new \DOMXPath($html_dom); foreach ($restrictions['allowed'] as $allowed_tag => $tag_attributes) { // By default, no attributes are allowed for a tag, but due to the // globally whitelisted attributes, it is impossible for a tag to actually // completely disallow attributes. if ($tag_attributes === FALSE) { $tag_attributes = []; } $allowed_attributes = ['exact' => [], 'prefix' => []]; foreach (($global_allowed_attributes + $tag_attributes) as $name => $values) { // A trailing * indicates wildcard, but it must have some prefix. if (substr($name, -1) === '*' && $name[0] !== '*') { $allowed_attributes['prefix'][str_replace('*', '', $name)] = $this->prepareAttributeValues($values); } else { $allowed_attributes['exact'][$name] = $this->prepareAttributeValues($values); } } krsort($allowed_attributes['prefix']); // Find all matching elements that have any attributes and filter the // attributes by name and value. foreach ($xpath->query('//' . $allowed_tag . '[@*]') as $element) { $this->filterElementAttributes($element, $allowed_attributes); } } if ($this->settings['filter_html_nofollow']) { $links = $html_dom->getElementsByTagName('a'); foreach ($links as $link) { $link->setAttribute('rel', 'nofollow'); } } $text = Html::serialize($html_dom); return trim($text); } /** * Filter attributes on an element by name and value according to a whitelist. * * @param \DOMElement $element * The element to be processed. * @param array $allowed_attributes * The attributes whitelist as an array of names and values. */ protected function filterElementAttributes(\DOMElement $element, array $allowed_attributes) { $modified_attributes = []; foreach ($element->attributes as $name => $attribute) { // Remove attributes not in the whitelist. $allowed_value = $this->findAllowedValue($allowed_attributes, $name); if (empty($allowed_value)) { $modified_attributes[$name] = FALSE; } elseif ($allowed_value !== TRUE) { // Check the attribute values whitelist. $attribute_values = preg_split('/\s+/', $attribute->value, -1, PREG_SPLIT_NO_EMPTY); $modified_attributes[$name] = []; foreach ($attribute_values as $value) { if ($this->findAllowedValue($allowed_value, $value)) { $modified_attributes[$name][] = $value; } } } } // If the $allowed_value was TRUE for an attribute name, it does not // appear in this array so the value on the DOM element is left unchanged. foreach ($modified_attributes as $name => $values) { if ($values) { $element->setAttribute($name, implode(' ', $values)); } else { $element->removeAttribute($name); } } } /** * Helper function to handle prefix matching. * * @param array $allowed * Array of allowed names and prefixes. * @param string $name * The name to find or match against a prefix. * * @return bool|array */ protected function findAllowedValue(array $allowed, $name) { if (isset($allowed['exact'][$name])) { return $allowed['exact'][$name]; } // Handle prefix (wildcard) matches. foreach ($allowed['prefix'] as $prefix => $value) { if (strpos($name, $prefix) === 0) { return $value; } } return FALSE; } /** * Helper function to prepare attribute values including wildcards. * * Splits the values into two lists, one for values that must match exactly * and the other for values that are wildcard prefixes. * * @param bool|array $attribute_values * TRUE, FALSE, or an array of allowed values. * * @return bool|array */ protected function prepareAttributeValues($attribute_values) { if ($attribute_values === TRUE || $attribute_values === FALSE) { return $attribute_values; } $result = ['exact' => [], 'prefix' => []]; foreach ($attribute_values as $name => $allowed) { // A trailing * indicates wildcard, but it must have some prefix. if (substr($name, -1) === '*' && $name[0] !== '*') { $result['prefix'][str_replace('*', '', $name)] = $allowed; } else { $result['exact'][$name] = $allowed; } } krsort($result['prefix']); return $result; } /** * {@inheritdoc} */ public function getHTMLRestrictions() { if ($this->restrictions) { return $this->restrictions; } // Parse the allowed HTML setting, and gradually make the whitelist more // specific. $restrictions = ['allowed' => []]; // Make all the tags self-closing, so they will be parsed into direct // children of the body tag in the DomDocument. $html = str_replace('>', ' />', $this->settings['allowed_html']); // Protect any trailing * characters in attribute names, since DomDocument // strips them as invalid. $star_protector = '__zqh6vxfbk3cg__'; $html = str_replace('*', $star_protector, $html); $body_child_nodes = Html::load($html)->getElementsByTagName('body')->item(0)->childNodes; foreach ($body_child_nodes as $node) { if ($node->nodeType !== XML_ELEMENT_NODE) { // Skip the empty text nodes inside tags. continue; } $tag = $node->tagName; if ($node->hasAttributes()) { // Mark the tag as allowed, assigning TRUE for each attribute name if // all values are allowed, or an array of specific allowed values. $restrictions['allowed'][$tag] = []; // Iterate over any attributes, and mark them as allowed. foreach ($node->attributes as $name => $attribute) { // Put back any trailing * on wildcard attribute name. $name = str_replace($star_protector, '*', $name); // Put back any trailing * on wildcard attribute value and parse out // the allowed attribute values. $allowed_attribute_values = preg_split('/\s+/', str_replace($star_protector, '*', $attribute->value), -1, PREG_SPLIT_NO_EMPTY); // Sanitize the attribute value: it lists the allowed attribute values // but one allowed attribute value that some may be tempted to use // is specifically nonsensical: the asterisk. A prefix is required for // allowed attribute values with a wildcard. A wildcard by itself // would mean whitelisting all possible attribute values. But in that // case, one would not specify an attribute value at all. $allowed_attribute_values = array_filter($allowed_attribute_values, function ($value) use ($star_protector) { return $value !== '*'; }); if (empty($allowed_attribute_values)) { // If the value is the empty string all values are allowed. $restrictions['allowed'][$tag][$name] = TRUE; } else { // A non-empty attribute value is assigned, mark each of the // specified attribute values as allowed. foreach ($allowed_attribute_values as $value) { $restrictions['allowed'][$tag][$name][$value] = TRUE; } } } } else { // Mark the tag as allowed, but with no attributes allowed. $restrictions['allowed'][$tag] = FALSE; } } // The 'style' and 'on*' ('onClick' etc.) attributes are always forbidden, // and are removed by Xss::filter(). // The 'lang', and 'dir' attributes apply to all elements and are always // allowed. The value whitelist for the 'dir' attribute is enforced by // self::filterAttributes(). Note that those two attributes are in the // short list of globally usable attributes in HTML5. They are always // allowed since the correct values of lang and dir may only be known to // the content author. Of the other global attributes, they are not usually // added by hand to content, and especially the class attribute can have // undesired visual effects by allowing content authors to apply any // available style, so specific values should be explicitly whitelisted. // @see http://www.w3.org/TR/html5/dom.html#global-attributes $restrictions['allowed']['*'] = [ 'style' => FALSE, 'on*' => FALSE, 'lang' => TRUE, 'dir' => ['ltr' => TRUE, 'rtl' => TRUE], ]; // Save this calculated result for re-use. $this->restrictions = $restrictions; return $restrictions; } /** * {@inheritdoc} */ public function tips($long = FALSE) { global $base_url; if (!($allowed_html = $this->settings['allowed_html'])) { return; } $output = $this->t('Allowed HTML tags: @tags', ['@tags' => $allowed_html]); if (!$long) { return $output; } $output = '<p>' . $output . '</p>'; if (!$this->settings['filter_html_help']) { return $output; } $output .= '<p>' . $this->t('This site allows HTML content. While learning all of HTML may feel intimidating, learning how to use a very small number of the most basic HTML "tags" is very easy. This table provides examples for each tag that is enabled on this site.') . '</p>'; $output .= '<p>' . $this->t('For more information see W3C\'s <a href=":html-specifications">HTML Specifications</a> or use your favorite search engine to find other sites that explain HTML.', [':html-specifications' => 'http://www.w3.org/TR/html/']) . '</p>'; $tips = [ 'a' => [$this->t('Anchors are used to make links to other pages.'), '<a href="' . $base_url . '">' . Html::escape(\Drupal::config('system.site')->get('name')) . '</a>'], 'br' => [$this->t('By default line break tags are automatically added, so use this tag to add additional ones. Use of this tag is different because it is not used with an open/close pair like all the others. Use the extra " /" inside the tag to maintain XHTML 1.0 compatibility'), $this->t('Text with <br />line break')], 'p' => [$this->t('By default paragraph tags are automatically added, so use this tag to add additional ones.'), '<p>' . $this->t('Paragraph one.') . '</p> <p>' . $this->t('Paragraph two.') . '</p>'], 'strong' => [$this->t('Strong', [], ['context' => 'Font weight']), '<strong>' . $this->t('Strong', [], ['context' => 'Font weight']) . '</strong>'], 'em' => [$this->t('Emphasized'), '<em>' . $this->t('Emphasized') . '</em>'], 'cite' => [$this->t('Cited'), '<cite>' . $this->t('Cited') . '</cite>'], 'code' => [$this->t('Coded text used to show programming source code'), '<code>' . $this->t('Coded') . '</code>'], 'b' => [$this->t('Bolded'), '<b>' . $this->t('Bolded') . '</b>'], 'u' => [$this->t('Underlined'), '<u>' . $this->t('Underlined') . '</u>'], 'i' => [$this->t('Italicized'), '<i>' . $this->t('Italicized') . '</i>'], 'sup' => [$this->t('Superscripted'), $this->t('<sup>Super</sup>scripted')], 'sub' => [$this->t('Subscripted'), $this->t('<sub>Sub</sub>scripted')], 'pre' => [$this->t('Preformatted'), '<pre>' . $this->t('Preformatted') . '</pre>'], 'abbr' => [$this->t('Abbreviation'), $this->t('<abbr title="Abbreviation">Abbrev.</abbr>')], 'acronym' => [$this->t('Acronym'), $this->t('<acronym title="Three-Letter Acronym">TLA</acronym>')], 'blockquote' => [$this->t('Block quoted'), '<blockquote>' . $this->t('Block quoted') . '</blockquote>'], 'q' => [$this->t('Quoted inline'), '<q>' . $this->t('Quoted inline') . '</q>'], // Assumes and describes tr, td, th. 'table' => [$this->t('Table'), '<table> <tr><th>' . $this->t('Table header') . '</th></tr> <tr><td>' . $this->t('Table cell') . '</td></tr> </table>'], 'tr' => NULL, 'td' => NULL, 'th' => NULL, 'del' => [$this->t('Deleted'), '<del>' . $this->t('Deleted') . '</del>'], 'ins' => [$this->t('Inserted'), '<ins>' . $this->t('Inserted') . '</ins>'], // Assumes and describes li. 'ol' => [$this->t('Ordered list - use the &lt;li&gt; to begin each list item'), '<ol> <li>' . $this->t('First item') . '</li> <li>' . $this->t('Second item') . '</li> </ol>'], 'ul' => [$this->t('Unordered list - use the &lt;li&gt; to begin each list item'), '<ul> <li>' . $this->t('First item') . '</li> <li>' . $this->t('Second item') . '</li> </ul>'], 'li' => NULL, // Assumes and describes dt and dd. 'dl' => [$this->t('Definition lists are similar to other HTML lists. &lt;dl&gt; begins the definition list, &lt;dt&gt; begins the definition term and &lt;dd&gt; begins the definition description.'), '<dl> <dt>' . $this->t('First term') . '</dt> <dd>' . $this->t('First definition') . '</dd> <dt>' . $this->t('Second term') . '</dt> <dd>' . $this->t('Second definition') . '</dd> </dl>'], 'dt' => NULL, 'dd' => NULL, 'h1' => [$this->t('Heading'), '<h1>' . $this->t('Title') . '</h1>'], 'h2' => [$this->t('Heading'), '<h2>' . $this->t('Subtitle') . '</h2>'], 'h3' => [$this->t('Heading'), '<h3>' . $this->t('Subtitle three') . '</h3>'], 'h4' => [$this->t('Heading'), '<h4>' . $this->t('Subtitle four') . '</h4>'], 'h5' => [$this->t('Heading'), '<h5>' . $this->t('Subtitle five') . '</h5>'], 'h6' => [$this->t('Heading'), '<h6>' . $this->t('Subtitle six') . '</h6>'] ]; $header = [$this->t('Tag Description'), $this->t('You Type'), $this->t('You Get')]; preg_match_all('/<([a-z0-9]+)[^a-z0-9]/i', $allowed_html, $out); foreach ($out[1] as $tag) { if (!empty($tips[$tag])) { $rows[] = [ ['data' => $tips[$tag][0], 'class' => ['description']], // The markup must be escaped because this is the example code for the // user. ['data' => [ '#prefix' => '<code>', '#plain_text' => $tips[$tag][1], '#suffix' => '</code>' ], 'class' => ['type']], // The markup must not be escaped because this is the example output // for the user. ['data' => ['#markup' => $tips[$tag][1]], 'class' => ['get'], ], ]; } else { $rows[] = [ ['data' => $this->t('No help provided for tag %tag.', ['%tag' => $tag]), 'class' => ['description'], 'colspan' => 3], ]; } } $table = [ '#type' => 'table', '#header' => $header, '#rows' => $rows, ]; $output .= drupal_render($table); $output .= '<p>' . $this->t('Most unusual characters can be directly entered without any problems.') . '</p>'; $output .= '<p>' . $this->t('If you do encounter problems, try using HTML character entities. A common example looks like &amp;amp; for an ampersand &amp; character. For a full list of entities see HTML\'s <a href=":html-entities">entities</a> page. Some of the available characters include:', [':html-entities' => 'http://www.w3.org/TR/html4/sgml/entities.html']) . '</p>'; $entities = [ [$this->t('Ampersand'), '&amp;'], [$this->t('Greater than'), '&gt;'], [$this->t('Less than'), '&lt;'], [$this->t('Quotation mark'), '&quot;'], ]; $header = [$this->t('Character Description'), $this->t('You Type'), $this->t('You Get')]; unset($rows); foreach ($entities as $entity) { $rows[] = [ ['data' => $entity[0], 'class' => ['description']], // The markup must be escaped because this is the example code for the // user. [ 'data' => [ '#prefix' => '<code>', '#plain_text' => $entity[1], '#suffix' => '</code>', ], 'class' => ['type'], ], // The markup must not be escaped because this is the example output // for the user. [ 'data' => ['#markup' => $entity[1]], 'class' => ['get'], ], ]; } $table = [ '#type' => 'table', '#header' => $header, '#rows' => $rows, ]; $output .= drupal_render($table); return $output; } }
gpl-2.0
Pramodf/justaboutself
wp-includes/class-wp-editor.php
53026
<?php /** * Facilitates adding of the WordPress editor as used on the Write and Edit screens. * * @package WordPress * @since 3.3.0 * * Private, not included by default. See wp_editor() in wp-includes/general-template.php. */ final class _WP_Editors { public static $mce_locale; private static $mce_settings = array(); private static $qt_settings = array(); private static $plugins = array(); private static $qt_buttons = array(); private static $ext_plugins; private static $baseurl; private static $first_init; private static $this_tinymce = false; private static $this_quicktags = false; private static $has_tinymce = false; private static $has_quicktags = false; private static $has_medialib = false; private static $editor_buttons_css = true; private static $drag_drop_upload = false; private function __construct() {} /** * Parse default arguments for the editor instance. * * @param string $editor_id ID for the current editor instance. * @param array $settings { * Array of editor arguments. * * @type bool $wpautop Whether to use wpautop(). Default true. * @type bool $media_buttons Whether to show the Add Media/other media buttons. * @type string $default_editor When both TinyMCE and Quicktags are used, set which * editor is shown on page load. Default empty. * @type bool $drag_drop_upload Whether to enable drag & drop on the editor uploading. Default false. * Requires the media modal. * @type string $textarea_name Give the textarea a unique name here. Square brackets * can be used here. Default $editor_id. * @type int $textarea_rows Number rows in the editor textarea. Default 20. * @type string|int $tabindex Tabindex value to use. Default empty. * @type string $tabfocus_elements The previous and next element ID to move the focus to * when pressing the Tab key in TinyMCE. Defualt ':prev,:next'. * @type string $editor_css Intended for extra styles for both Visual and Text editors. * Should include `<style>` tags, and can use "scoped". Default empty. * @type string $editor_class Extra classes to add to the editor textarea elemen. Default empty. * @type bool $teeny Whether to output the minimal editor config. Examples include * Press This and the Comment editor. Default false. * @type bool $dfw Whether to replace the default fullscreen with "Distraction Free * Writing". DFW requires specific DOM elements and css). Default false. * @type bool|array $tinymce Whether to load TinyMCE. Can be used to pass settings directly to * TinyMCE using an array. Default true. * @type bool|array $quicktags Whether to load Quicktags. Can be used to pass settings directly to * Quicktags using an array. Default true. * } * @return array Parsed arguments array. */ public static function parse_settings( $editor_id, $settings ) { /** * Filter the wp_editor() settings. * * @since 4.0.0 * * @see _WP_Editors()::parse_settings() * * @param array $settings Array of editor arguments. * @param string $editor_id ID for the current editor instance. */ $settings = apply_filters( 'wp_editor_settings', $settings, $editor_id ); $set = wp_parse_args( $settings, array( 'wpautop' => true, 'media_buttons' => true, 'default_editor' => '', 'drag_drop_upload' => false, 'textarea_name' => $editor_id, 'textarea_rows' => 20, 'tabindex' => '', 'tabfocus_elements' => ':prev,:next', 'editor_css' => '', 'editor_class' => '', 'teeny' => false, 'dfw' => false, '_content_editor_dfw' => false, 'tinymce' => true, 'quicktags' => true ) ); self::$this_tinymce = ( $set['tinymce'] && user_can_richedit() ); if ( self::$this_tinymce ) { if ( false !== strpos( $editor_id, '[' ) ) { self::$this_tinymce = false; _deprecated_argument( 'wp_editor()', '3.9', 'TinyMCE editor IDs cannot have brackets.' ); } } self::$this_quicktags = (bool) $set['quicktags']; if ( self::$this_tinymce ) self::$has_tinymce = true; if ( self::$this_quicktags ) self::$has_quicktags = true; if ( empty( $set['editor_height'] ) ) return $set; if ( 'content' === $editor_id && empty( $set['tinymce']['wp_autoresize_on'] ) ) { // A cookie (set when a user resizes the editor) overrides the height. $cookie = (int) get_user_setting( 'ed_size' ); if ( $cookie ) $set['editor_height'] = $cookie; } if ( $set['editor_height'] < 50 ) $set['editor_height'] = 50; elseif ( $set['editor_height'] > 5000 ) $set['editor_height'] = 5000; return $set; } /** * Outputs the HTML for a single instance of the editor. * * @param string $content The initial content of the editor. * @param string $editor_id ID for the textarea and TinyMCE and Quicktags instances (can contain only ASCII letters and numbers). * @param array $settings See the _parse_settings() method for description. */ public static function editor( $content, $editor_id, $settings = array() ) { $set = self::parse_settings( $editor_id, $settings ); $editor_class = ' class="' . trim( $set['editor_class'] . ' wp-editor-area' ) . '"'; $tabindex = $set['tabindex'] ? ' tabindex="' . (int) $set['tabindex'] . '"' : ''; $switch_class = 'html-active'; $toolbar = $buttons = $autocomplete = ''; if ( $set['drag_drop_upload'] ) { self::$drag_drop_upload = true; } if ( ! empty( $set['editor_height'] ) ) $height = ' style="height: ' . $set['editor_height'] . 'px"'; else $height = ' rows="' . $set['textarea_rows'] . '"'; if ( !current_user_can( 'upload_files' ) ) $set['media_buttons'] = false; if ( ! self::$this_quicktags && self::$this_tinymce ) { $switch_class = 'tmce-active'; $autocomplete = ' autocomplete="off"'; } elseif ( self::$this_quicktags && self::$this_tinymce ) { $default_editor = $set['default_editor'] ? $set['default_editor'] : wp_default_editor(); $autocomplete = ' autocomplete="off"'; // 'html' is used for the "Text" editor tab. if ( 'html' === $default_editor ) { add_filter('the_editor_content', 'wp_htmledit_pre'); $switch_class = 'html-active'; } else { add_filter('the_editor_content', 'wp_richedit_pre'); $switch_class = 'tmce-active'; } $buttons .= '<button type="button" id="' . $editor_id . '-tmce" class="wp-switch-editor switch-tmce" onclick="switchEditors.switchto(this);">' . __('Visual') . "</button>\n"; $buttons .= '<button type="button" id="' . $editor_id . '-html" class="wp-switch-editor switch-html" onclick="switchEditors.switchto(this);">' . _x( 'Text', 'Name for the Text editor tab (formerly HTML)' ) . "</button>\n"; } $wrap_class = 'wp-core-ui wp-editor-wrap ' . $switch_class; if ( $set['_content_editor_dfw'] ) { $wrap_class .= ' has-dfw'; } echo '<div id="wp-' . $editor_id . '-wrap" class="' . $wrap_class . '">'; if ( self::$editor_buttons_css ) { wp_print_styles('editor-buttons'); self::$editor_buttons_css = false; } if ( !empty($set['editor_css']) ) echo $set['editor_css'] . "\n"; if ( !empty($buttons) || $set['media_buttons'] ) { echo '<div id="wp-' . $editor_id . '-editor-tools" class="wp-editor-tools hide-if-no-js">'; if ( $set['media_buttons'] ) { self::$has_medialib = true; if ( !function_exists('media_buttons') ) include(ABSPATH . 'wp-admin/includes/media.php'); echo '<div id="wp-' . $editor_id . '-media-buttons" class="wp-media-buttons">'; /** * Fires after the default media button(s) are displayed. * * @since 2.5.0 * * @param string $editor_id Unique editor identifier, e.g. 'content'. */ do_action( 'media_buttons', $editor_id ); echo "</div>\n"; } echo '<div class="wp-editor-tabs">' . $buttons . "</div>\n"; echo "</div>\n"; } /** * Filter the HTML markup output that displays the editor. * * @since 2.1.0 * * @param string $output Editor's HTML markup. */ $the_editor = apply_filters( 'the_editor', '<div id="wp-' . $editor_id . '-editor-container" class="wp-editor-container">' . '<textarea' . $editor_class . $height . $tabindex . $autocomplete . ' cols="40" name="' . $set['textarea_name'] . '" ' . 'id="' . $editor_id . '">%s</textarea></div>' ); /** * Filter the default editor content. * * @since 2.1.0 * * @param string $content Default editor content. */ $content = apply_filters( 'the_editor_content', $content ); printf( $the_editor, $content ); echo "\n</div>\n\n"; self::editor_settings($editor_id, $set); } /** * @param string $editor_id * @param array $set */ public static function editor_settings($editor_id, $set) { $first_run = false; if ( empty(self::$first_init) ) { if ( is_admin() ) { add_action( 'admin_print_footer_scripts', array( __CLASS__, 'editor_js' ), 50 ); add_action( 'admin_print_footer_scripts', array( __CLASS__, 'enqueue_scripts' ), 1 ); } else { add_action( 'wp_print_footer_scripts', array( __CLASS__, 'editor_js' ), 50 ); add_action( 'wp_print_footer_scripts', array( __CLASS__, 'enqueue_scripts' ), 1 ); } } if ( self::$this_quicktags ) { $qtInit = array( 'id' => $editor_id, 'buttons' => '' ); if ( is_array($set['quicktags']) ) $qtInit = array_merge($qtInit, $set['quicktags']); if ( empty($qtInit['buttons']) ) $qtInit['buttons'] = 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close'; if ( $set['dfw'] ) $qtInit['buttons'] .= ',fullscreen'; if ( $set['_content_editor_dfw'] ) { $qtInit['buttons'] .= ',dfw'; } /** * Filter the Quicktags settings. * * @since 3.3.0 * * @param array $qtInit Quicktags settings. * @param string $editor_id The unique editor ID, e.g. 'content'. */ $qtInit = apply_filters( 'quicktags_settings', $qtInit, $editor_id ); self::$qt_settings[$editor_id] = $qtInit; self::$qt_buttons = array_merge( self::$qt_buttons, explode(',', $qtInit['buttons']) ); } if ( self::$this_tinymce ) { if ( empty( self::$first_init ) ) { self::$baseurl = includes_url( 'js/tinymce' ); $mce_locale = get_locale(); self::$mce_locale = $mce_locale = empty( $mce_locale ) ? 'en' : strtolower( substr( $mce_locale, 0, 2 ) ); // ISO 639-1 /** This filter is documented in wp-admin/includes/media.php */ $no_captions = (bool) apply_filters( 'disable_captions', '' ); $first_run = true; $ext_plugins = ''; if ( $set['teeny'] ) { /** * Filter the list of teenyMCE plugins. * * @since 2.7.0 * * @param array $plugins An array of teenyMCE plugins. * @param string $editor_id Unique editor identifier, e.g. 'content'. */ self::$plugins = $plugins = apply_filters( 'teeny_mce_plugins', array( 'colorpicker', 'lists', 'fullscreen', 'image', 'wordpress', 'wpeditimage', 'wplink' ), $editor_id ); } else { /** * Filter the list of TinyMCE external plugins. * * The filter takes an associative array of external plugins for * TinyMCE in the form 'plugin_name' => 'url'. * * The url should be absolute, and should include the js filename * to be loaded. For example: * 'myplugin' => 'http://mysite.com/wp-content/plugins/myfolder/mce_plugin.js'. * * If the external plugin adds a button, it should be added with * one of the 'mce_buttons' filters. * * @since 2.5.0 * * @param array $external_plugins An array of external TinyMCE plugins. */ $mce_external_plugins = apply_filters( 'mce_external_plugins', array() ); $plugins = array( 'charmap', 'colorpicker', 'hr', 'lists', 'media', 'paste', 'tabfocus', 'textcolor', 'fullscreen', 'wordpress', 'wpautoresize', 'wpeditimage', 'wpgallery', 'wplink', 'wpdialogs', 'wpview', ); if ( ! self::$has_medialib ) { $plugins[] = 'image'; } /** * Filter the list of default TinyMCE plugins. * * The filter specifies which of the default plugins included * in WordPress should be added to the TinyMCE instance. * * @since 3.3.0 * * @param array $plugins An array of default TinyMCE plugins. */ $plugins = array_unique( apply_filters( 'tiny_mce_plugins', $plugins ) ); if ( ( $key = array_search( 'spellchecker', $plugins ) ) !== false ) { // Remove 'spellchecker' from the internal plugins if added with 'tiny_mce_plugins' filter to prevent errors. // It can be added with 'mce_external_plugins'. unset( $plugins[$key] ); } if ( ! empty( $mce_external_plugins ) ) { /** * Filter the translations loaded for external TinyMCE 3.x plugins. * * The filter takes an associative array ('plugin_name' => 'path') * where 'path' is the include path to the file. * * The language file should follow the same format as wp_mce_translation(), * and should define a variable ($strings) that holds all translated strings. * * @since 2.5.0 * * @param array $translations Translations for external TinyMCE plugins. */ $mce_external_languages = apply_filters( 'mce_external_languages', array() ); $loaded_langs = array(); $strings = ''; if ( ! empty( $mce_external_languages ) ) { foreach ( $mce_external_languages as $name => $path ) { if ( @is_file( $path ) && @is_readable( $path ) ) { include_once( $path ); $ext_plugins .= $strings . "\n"; $loaded_langs[] = $name; } } } foreach ( $mce_external_plugins as $name => $url ) { if ( in_array( $name, $plugins, true ) ) { unset( $mce_external_plugins[ $name ] ); continue; } $url = set_url_scheme( $url ); $mce_external_plugins[ $name ] = $url; $plugurl = dirname( $url ); $strings = ''; // Try to load langs/[locale].js and langs/[locale]_dlg.js if ( ! in_array( $name, $loaded_langs, true ) ) { $path = str_replace( content_url(), '', $plugurl ); $path = WP_CONTENT_DIR . $path . '/langs/'; if ( function_exists('realpath') ) $path = trailingslashit( realpath($path) ); if ( @is_file( $path . $mce_locale . '.js' ) ) $strings .= @file_get_contents( $path . $mce_locale . '.js' ) . "\n"; if ( @is_file( $path . $mce_locale . '_dlg.js' ) ) $strings .= @file_get_contents( $path . $mce_locale . '_dlg.js' ) . "\n"; if ( 'en' != $mce_locale && empty( $strings ) ) { if ( @is_file( $path . 'en.js' ) ) { $str1 = @file_get_contents( $path . 'en.js' ); $strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str1, 1 ) . "\n"; } if ( @is_file( $path . 'en_dlg.js' ) ) { $str2 = @file_get_contents( $path . 'en_dlg.js' ); $strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str2, 1 ) . "\n"; } } if ( ! empty( $strings ) ) $ext_plugins .= "\n" . $strings . "\n"; } $ext_plugins .= 'tinyMCEPreInit.load_ext("' . $plugurl . '", "' . $mce_locale . '");' . "\n"; $ext_plugins .= 'tinymce.PluginManager.load("' . $name . '", "' . $url . '");' . "\n"; } } } if ( $set['dfw'] ) $plugins[] = 'wpfullscreen'; self::$plugins = $plugins; self::$ext_plugins = $ext_plugins; self::$first_init = array( 'theme' => 'modern', 'skin' => 'lightgray', 'language' => self::$mce_locale, 'formats' => "{ alignleft: [ {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'left'}}, {selector: 'img,table,dl.wp-caption', classes: 'alignleft'} ], aligncenter: [ {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'center'}}, {selector: 'img,table,dl.wp-caption', classes: 'aligncenter'} ], alignright: [ {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'right'}}, {selector: 'img,table,dl.wp-caption', classes: 'alignright'} ], strikethrough: {inline: 'del'} }", 'block_formats' => 'Paragraph=p;' . 'Pre=pre;' . 'Heading 1=h1;' . 'Heading 2=h2;' . 'Heading 3=h3;' . 'Heading 4=h4;' . 'Heading 5=h5;' . 'Heading 6=h6', 'relative_urls' => false, 'remove_script_host' => false, 'convert_urls' => false, 'browser_spellcheck' => true, 'fix_list_elements' => true, 'entities' => '38,amp,60,lt,62,gt', 'entity_encoding' => 'raw', 'keep_styles' => false, 'cache_suffix' => 'wp-mce-' . $GLOBALS['tinymce_version'], // Limit the preview styles in the menu/toolbar 'preview_styles' => 'font-family font-size font-weight font-style text-decoration text-transform', 'wpeditimage_disable_captions' => $no_captions, 'wpeditimage_html5_captions' => current_theme_supports( 'html5', 'caption' ), 'plugins' => implode( ',', $plugins ), ); if ( ! empty( $mce_external_plugins ) ) { self::$first_init['external_plugins'] = wp_json_encode( $mce_external_plugins ); } $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; $version = 'ver=' . $GLOBALS['wp_version']; $dashicons = includes_url( "css/dashicons$suffix.css?$version" ); // WordPress default stylesheet and dashicons $mce_css = array( $dashicons, self::$baseurl . '/skins/wordpress/wp-content.css?' . $version ); $editor_styles = get_editor_stylesheets(); if ( ! empty( $editor_styles ) ) { foreach ( $editor_styles as $style ) { $mce_css[] = $style; } } /** * Filter the comma-delimited list of stylesheets to load in TinyMCE. * * @since 2.1.0 * * @param array $stylesheets Comma-delimited list of stylesheets. */ $mce_css = trim( apply_filters( 'mce_css', implode( ',', $mce_css ) ), ' ,' ); if ( ! empty($mce_css) ) self::$first_init['content_css'] = $mce_css; } if ( $set['teeny'] ) { /** * Filter the list of teenyMCE buttons (Text tab). * * @since 2.7.0 * * @param array $buttons An array of teenyMCE buttons. * @param string $editor_id Unique editor identifier, e.g. 'content'. */ $mce_buttons = apply_filters( 'teeny_mce_buttons', array('bold', 'italic', 'underline', 'blockquote', 'strikethrough', 'bullist', 'numlist', 'alignleft', 'aligncenter', 'alignright', 'undo', 'redo', 'link', 'unlink', 'fullscreen'), $editor_id ); $mce_buttons_2 = $mce_buttons_3 = $mce_buttons_4 = array(); } else { $mce_buttons = array( 'bold', 'italic', 'strikethrough', 'bullist', 'numlist', 'blockquote', 'hr', 'alignleft', 'aligncenter', 'alignright', 'link', 'unlink', 'wp_more', 'spellchecker' ); if ( $set['_content_editor_dfw'] ) { $mce_buttons[] = 'dfw'; } else { $mce_buttons[] = 'fullscreen'; } $mce_buttons[] = 'wp_adv'; /** * Filter the first-row list of TinyMCE buttons (Visual tab). * * @since 2.0.0 * * @param array $buttons First-row list of buttons. * @param string $editor_id Unique editor identifier, e.g. 'content'. */ $mce_buttons = apply_filters( 'mce_buttons', $mce_buttons, $editor_id ); /** * Filter the second-row list of TinyMCE buttons (Visual tab). * * @since 2.0.0 * * @param array $buttons Second-row list of buttons. * @param string $editor_id Unique editor identifier, e.g. 'content'. */ $mce_buttons_2 = apply_filters( 'mce_buttons_2', array( 'formatselect', 'underline', 'alignjustify', 'forecolor', 'pastetext', 'removeformat', 'charmap', 'outdent', 'indent', 'undo', 'redo', 'wp_help' ), $editor_id ); /** * Filter the third-row list of TinyMCE buttons (Visual tab). * * @since 2.0.0 * * @param array $buttons Third-row list of buttons. * @param string $editor_id Unique editor identifier, e.g. 'content'. */ $mce_buttons_3 = apply_filters( 'mce_buttons_3', array(), $editor_id ); /** * Filter the fourth-row list of TinyMCE buttons (Visual tab). * * @since 2.5.0 * * @param array $buttons Fourth-row list of buttons. * @param string $editor_id Unique editor identifier, e.g. 'content'. */ $mce_buttons_4 = apply_filters( 'mce_buttons_4', array(), $editor_id ); } $body_class = $editor_id; if ( $post = get_post() ) { $body_class .= ' post-type-' . sanitize_html_class( $post->post_type ) . ' post-status-' . sanitize_html_class( $post->post_status ); if ( post_type_supports( $post->post_type, 'post-formats' ) ) { $post_format = get_post_format( $post ); if ( $post_format && ! is_wp_error( $post_format ) ) $body_class .= ' post-format-' . sanitize_html_class( $post_format ); else $body_class .= ' post-format-standard'; } } $body_class .= ' locale-' . sanitize_html_class( strtolower( str_replace( '_', '-', get_locale() ) ) ); if ( !empty($set['tinymce']['body_class']) ) { $body_class .= ' ' . $set['tinymce']['body_class']; unset($set['tinymce']['body_class']); } if ( $set['dfw'] ) { // replace the first 'fullscreen' with 'wp_fullscreen' if ( ($key = array_search('fullscreen', $mce_buttons)) !== false ) $mce_buttons[$key] = 'wp_fullscreen'; elseif ( ($key = array_search('fullscreen', $mce_buttons_2)) !== false ) $mce_buttons_2[$key] = 'wp_fullscreen'; elseif ( ($key = array_search('fullscreen', $mce_buttons_3)) !== false ) $mce_buttons_3[$key] = 'wp_fullscreen'; elseif ( ($key = array_search('fullscreen', $mce_buttons_4)) !== false ) $mce_buttons_4[$key] = 'wp_fullscreen'; } $mceInit = array ( 'selector' => "#$editor_id", 'resize' => 'vertical', 'menubar' => false, 'wpautop' => (bool) $set['wpautop'], 'indent' => ! $set['wpautop'], 'toolbar1' => implode($mce_buttons, ','), 'toolbar2' => implode($mce_buttons_2, ','), 'toolbar3' => implode($mce_buttons_3, ','), 'toolbar4' => implode($mce_buttons_4, ','), 'tabfocus_elements' => $set['tabfocus_elements'], 'body_class' => $body_class ); if ( $first_run ) $mceInit = array_merge( self::$first_init, $mceInit ); if ( is_array( $set['tinymce'] ) ) $mceInit = array_merge( $mceInit, $set['tinymce'] ); /* * For people who really REALLY know what they're doing with TinyMCE * You can modify $mceInit to add, remove, change elements of the config * before tinyMCE.init. Setting "valid_elements", "invalid_elements" * and "extended_valid_elements" can be done through this filter. Best * is to use the default cleanup by not specifying valid_elements, * as TinyMCE contains full set of XHTML 1.0. */ if ( $set['teeny'] ) { /** * Filter the teenyMCE config before init. * * @since 2.7.0 * * @param array $mceInit An array with teenyMCE config. * @param string $editor_id Unique editor identifier, e.g. 'content'. */ $mceInit = apply_filters( 'teeny_mce_before_init', $mceInit, $editor_id ); } else { /** * Filter the TinyMCE config before init. * * @since 2.5.0 * * @param array $mceInit An array with TinyMCE config. * @param string $editor_id Unique editor identifier, e.g. 'content'. */ $mceInit = apply_filters( 'tiny_mce_before_init', $mceInit, $editor_id ); } if ( empty( $mceInit['toolbar3'] ) && ! empty( $mceInit['toolbar4'] ) ) { $mceInit['toolbar3'] = $mceInit['toolbar4']; $mceInit['toolbar4'] = ''; } self::$mce_settings[$editor_id] = $mceInit; } // end if self::$this_tinymce } private static function _parse_init($init) { $options = ''; foreach ( $init as $k => $v ) { if ( is_bool($v) ) { $val = $v ? 'true' : 'false'; $options .= $k . ':' . $val . ','; continue; } elseif ( !empty($v) && is_string($v) && ( ('{' == $v{0} && '}' == $v{strlen($v) - 1}) || ('[' == $v{0} && ']' == $v{strlen($v) - 1}) || preg_match('/^\(?function ?\(/', $v) ) ) { $options .= $k . ':' . $v . ','; continue; } $options .= $k . ':"' . $v . '",'; } return '{' . trim( $options, ' ,' ) . '}'; } public static function enqueue_scripts() { wp_enqueue_script('word-count'); if ( self::$has_tinymce ) wp_enqueue_script('editor'); if ( self::$has_quicktags ) { wp_enqueue_script( 'quicktags' ); wp_enqueue_style( 'buttons' ); } if ( in_array('wplink', self::$plugins, true) || in_array('link', self::$qt_buttons, true) ) { wp_enqueue_script('wplink'); } if ( in_array('wpfullscreen', self::$plugins, true) || in_array('fullscreen', self::$qt_buttons, true) ) wp_enqueue_script('wp-fullscreen'); if ( self::$has_medialib ) { add_thickbox(); wp_enqueue_script('media-upload'); } /** * Fires when scripts and styles are enqueued for the editor. * * @since 3.9.0 * * @param array $to_load An array containing boolean values whether TinyMCE * and Quicktags are being loaded. */ do_action( 'wp_enqueue_editor', array( 'tinymce' => self::$has_tinymce, 'quicktags' => self::$has_quicktags, ) ); } /** * Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(). * Can be used directly (_WP_Editors::wp_mce_translation()) by passing the same locale as set in the TinyMCE init object. * * @param string $mce_locale The locale used for the editor. * @param bool $json_only optional Whether to include the JavaScript calls to tinymce.addI18n() and tinymce.ScriptLoader.markDone(). * @return string Translation object, JSON encoded. */ public static function wp_mce_translation( $mce_locale = '', $json_only = false ) { $mce_translation = array( // Default TinyMCE strings 'New document' => __( 'New document' ), 'Formats' => _x( 'Formats', 'TinyMCE' ), 'Headings' => _x( 'Headings', 'TinyMCE' ), 'Heading 1' => __( 'Heading 1' ), 'Heading 2' => __( 'Heading 2' ), 'Heading 3' => __( 'Heading 3' ), 'Heading 4' => __( 'Heading 4' ), 'Heading 5' => __( 'Heading 5' ), 'Heading 6' => __( 'Heading 6' ), /* translators: block tags */ 'Blocks' => _x( 'Blocks', 'TinyMCE' ), 'Paragraph' => __( 'Paragraph' ), 'Blockquote' => __( 'Blockquote' ), 'Div' => _x( 'Div', 'HTML tag' ), 'Pre' => _x( 'Pre', 'HTML tag' ), 'Address' => _x( 'Address', 'HTML tag' ), 'Inline' => _x( 'Inline', 'HTML elements' ), 'Underline' => __( 'Underline' ), 'Strikethrough' => __( 'Strikethrough' ), 'Subscript' => __( 'Subscript' ), 'Superscript' => __( 'Superscript' ), 'Clear formatting' => __( 'Clear formatting' ), 'Bold' => __( 'Bold' ), 'Italic' => __( 'Italic' ), 'Code' => _x( 'Code', 'editor button' ), 'Source code' => __( 'Source code' ), 'Font Family' => __( 'Font Family' ), 'Font Sizes' => __( 'Font Sizes' ), 'Align center' => __( 'Align center' ), 'Align right' => __( 'Align right' ), 'Align left' => __( 'Align left' ), 'Justify' => __( 'Justify' ), 'Increase indent' => __( 'Increase indent' ), 'Decrease indent' => __( 'Decrease indent' ), 'Cut' => __( 'Cut' ), 'Copy' => __( 'Copy' ), 'Paste' => __( 'Paste' ), 'Select all' => __( 'Select all' ), 'Undo' => __( 'Undo' ), 'Redo' => __( 'Redo' ), 'Ok' => __( 'OK' ), 'Cancel' => __( 'Cancel' ), 'Close' => __( 'Close' ), 'Visual aids' => __( 'Visual aids' ), 'Bullet list' => __( 'Bulleted list' ), 'Numbered list' => __( 'Numbered list' ), 'Square' => _x( 'Square', 'list style' ), 'Default' => _x( 'Default', 'list style' ), 'Circle' => _x( 'Circle', 'list style' ), 'Disc' => _x('Disc', 'list style' ), 'Lower Greek' => _x( 'Lower Greek', 'list style' ), 'Lower Alpha' => _x( 'Lower Alpha', 'list style' ), 'Upper Alpha' => _x( 'Upper Alpha', 'list style' ), 'Upper Roman' => _x( 'Upper Roman', 'list style' ), 'Lower Roman' => _x( 'Lower Roman', 'list style' ), // Anchor plugin 'Name' => _x( 'Name', 'Name of link anchor (TinyMCE)' ), 'Anchor' => _x( 'Anchor', 'Link anchor (TinyMCE)' ), 'Anchors' => _x( 'Anchors', 'Link anchors (TinyMCE)' ), // Fullpage plugin 'Document properties' => __( 'Document properties' ), 'Robots' => __( 'Robots' ), 'Title' => __( 'Title' ), 'Keywords' => __( 'Keywords' ), 'Encoding' => __( 'Encoding' ), 'Description' => __( 'Description' ), 'Author' => __( 'Author' ), // Media, image plugins 'Insert/edit image' => __( 'Insert/edit image' ), 'General' => __( 'General' ), 'Advanced' => __( 'Advanced' ), 'Source' => __( 'Source' ), 'Border' => __( 'Border' ), 'Constrain proportions' => __( 'Constrain proportions' ), 'Vertical space' => __( 'Vertical space' ), 'Image description' => __( 'Image description' ), 'Style' => __( 'Style' ), 'Dimensions' => __( 'Dimensions' ), 'Insert image' => __( 'Insert image' ), 'Insert date/time' => __( 'Insert date/time' ), 'Insert/edit video' => __( 'Insert/edit video' ), 'Poster' => __( 'Poster' ), 'Alternative source' => __( 'Alternative source' ), 'Paste your embed code below:' => __( 'Paste your embed code below:' ), 'Insert video' => __( 'Insert video' ), 'Embed' => __( 'Embed' ), // Each of these have a corresponding plugin 'Special character' => __( 'Special character' ), 'Right to left' => _x( 'Right to left', 'editor button' ), 'Left to right' => _x( 'Left to right', 'editor button' ), 'Emoticons' => __( 'Emoticons' ), 'Nonbreaking space' => __( 'Nonbreaking space' ), 'Page break' => __( 'Page break' ), 'Paste as text' => __( 'Paste as text' ), 'Preview' => __( 'Preview' ), 'Print' => __( 'Print' ), 'Save' => __( 'Save' ), 'Fullscreen' => __( 'Fullscreen' ), 'Horizontal line' => __( 'Horizontal line' ), 'Horizontal space' => __( 'Horizontal space' ), 'Restore last draft' => __( 'Restore last draft' ), 'Insert/edit link' => __( 'Insert/edit link' ), 'Remove link' => __( 'Remove link' ), 'Color' => __( 'Color' ), 'Custom color' => __( 'Custom color' ), 'Custom...' => _x( 'Custom...', 'label for custom color' ), 'No color' => __( 'No color' ), // Spelling, search/replace plugins 'Could not find the specified string.' => __( 'Could not find the specified string.' ), 'Replace' => _x( 'Replace', 'find/replace' ), 'Next' => _x( 'Next', 'find/replace' ), /* translators: previous */ 'Prev' => _x( 'Prev', 'find/replace' ), 'Whole words' => _x( 'Whole words', 'find/replace' ), 'Find and replace' => __( 'Find and replace' ), 'Replace with' => _x('Replace with', 'find/replace' ), 'Find' => _x( 'Find', 'find/replace' ), 'Replace all' => _x( 'Replace all', 'find/replace' ), 'Match case' => __( 'Match case' ), 'Spellcheck' => __( 'Check Spelling' ), 'Finish' => _x( 'Finish', 'spellcheck' ), 'Ignore all' => _x( 'Ignore all', 'spellcheck' ), 'Ignore' => _x( 'Ignore', 'spellcheck' ), 'Add to Dictionary' => __( 'Add to Dictionary' ), // TinyMCE tables 'Insert table' => __( 'Insert table' ), 'Delete table' => __( 'Delete table' ), 'Table properties' => __( 'Table properties' ), 'Row properties' => __( 'Table row properties' ), 'Cell properties' => __( 'Table cell properties' ), 'Border color' => __( 'Border color' ), 'Row' => __( 'Row' ), 'Rows' => __( 'Rows' ), 'Column' => _x( 'Column', 'table column' ), 'Cols' => _x( 'Cols', 'table columns' ), 'Cell' => _x( 'Cell', 'table cell' ), 'Header cell' => __( 'Header cell' ), 'Header' => _x( 'Header', 'table header' ), 'Body' => _x( 'Body', 'table body' ), 'Footer' => _x( 'Footer', 'table footer' ), 'Insert row before' => __( 'Insert row before' ), 'Insert row after' => __( 'Insert row after' ), 'Insert column before' => __( 'Insert column before' ), 'Insert column after' => __( 'Insert column after' ), 'Paste row before' => __( 'Paste table row before' ), 'Paste row after' => __( 'Paste table row after' ), 'Delete row' => __( 'Delete row' ), 'Delete column' => __( 'Delete column' ), 'Cut row' => __( 'Cut table row' ), 'Copy row' => __( 'Copy table row' ), 'Merge cells' => __( 'Merge table cells' ), 'Split cell' => __( 'Split table cell' ), 'Height' => __( 'Height' ), 'Width' => __( 'Width' ), 'Caption' => __( 'Caption' ), 'Alignment' => __( 'Alignment' ), 'H Align' => _x( 'H Align', 'horizontal table cell alignment' ), 'Left' => __( 'Left' ), 'Center' => __( 'Center' ), 'Right' => __( 'Right' ), 'None' => _x( 'None', 'table cell alignment attribute' ), 'V Align' => _x( 'V Align', 'vertical table cell alignment' ), 'Top' => __( 'Top' ), 'Middle' => __( 'Middle' ), 'Bottom' => __( 'Bottom' ), 'Row group' => __( 'Row group' ), 'Column group' => __( 'Column group' ), 'Row type' => __( 'Row type' ), 'Cell type' => __( 'Cell type' ), 'Cell padding' => __( 'Cell padding' ), 'Cell spacing' => __( 'Cell spacing' ), 'Scope' => _x( 'Scope', 'table cell scope attribute' ), 'Insert template' => _x( 'Insert template', 'TinyMCE' ), 'Templates' => _x( 'Templates', 'TinyMCE' ), 'Background color' => __( 'Background color' ), 'Text color' => __( 'Text color' ), 'Show blocks' => _x( 'Show blocks', 'editor button' ), 'Show invisible characters' => __( 'Show invisible characters' ), /* translators: word count */ 'Words: {0}' => sprintf( __( 'Words: %s' ), '{0}' ), 'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.' => __( 'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.' ) . "\n\n" . __( 'If you&#8217;re looking to paste rich content from Microsoft Word, try turning this option off. The editor will clean up text pasted from Word automatically.' ), 'Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help' => __( 'Rich Text Area. Press Alt-Shift-H for help' ), 'You have unsaved changes are you sure you want to navigate away?' => __( 'The changes you made will be lost if you navigate away from this page.' ), 'Your browser doesn\'t support direct access to the clipboard. Please use the Ctrl+X/C/V keyboard shortcuts instead.' => __( 'Your browser does not support direct access to the clipboard. Please use keyboard shortcuts or your browser&#8217;s edit menu instead.' ), // TinyMCE menus 'Insert' => _x( 'Insert', 'TinyMCE menu' ), 'File' => _x( 'File', 'TinyMCE menu' ), 'Edit' => _x( 'Edit', 'TinyMCE menu' ), 'Tools' => _x( 'Tools', 'TinyMCE menu' ), 'View' => _x( 'View', 'TinyMCE menu' ), 'Table' => _x( 'Table', 'TinyMCE menu' ), 'Format' => _x( 'Format', 'TinyMCE menu' ), // WordPress strings 'Keyboard Shortcuts' => __( 'Keyboard Shortcuts' ), 'Toolbar Toggle' => __( 'Toolbar Toggle' ), 'Insert Read More tag' => __( 'Insert Read More tag' ), 'Read more...' => __( 'Read more...' ), // Title on the placeholder inside the editor 'Distraction-free writing mode' => __( 'Distraction-free writing mode' ), 'No alignment' => __( 'No alignment' ), // Tooltip for the 'alignnone' button in the image toolbar 'Remove' => __( 'Remove' ), // Tooltip for the 'remove' button in the image toolbar 'Edit ' => __( 'Edit' ), // Tooltip for the 'edit' button in the image toolbar ); /** * Link plugin (not included): * Insert link * Target * New window * Text to display * The URL you entered seems to be an email address. Do you want to add the required mailto: prefix? * The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix? * Url */ if ( ! $mce_locale ) { $mce_locale = self::$mce_locale; } /** * Filter translated strings prepared for TinyMCE. * * @since 3.9.0 * * @param array $mce_translation Key/value pairs of strings. * @param string $mce_locale Locale. */ $mce_translation = apply_filters( 'wp_mce_translation', $mce_translation, $mce_locale ); foreach ( $mce_translation as $key => $value ) { // Remove strings that are not translated. if ( $key === $value ) { unset( $mce_translation[$key] ); continue; } if ( false !== strpos( $value, '&' ) ) { $mce_translation[$key] = html_entity_decode( $value, ENT_QUOTES, 'UTF-8' ); } } // Set direction if ( is_rtl() ) { $mce_translation['_dir'] = 'rtl'; } if ( $json_only ) { return wp_json_encode( $mce_translation ); } $baseurl = self::$baseurl ? self::$baseurl : includes_url( 'js/tinymce' ); return "tinymce.addI18n( '$mce_locale', " . wp_json_encode( $mce_translation ) . ");\n" . "tinymce.ScriptLoader.markDone( '$baseurl/langs/$mce_locale.js' );\n"; } public static function editor_js() { global $tinymce_version, $concatenate_scripts, $compress_scripts; /** * Filter "tiny_mce_version" is deprecated * * The tiny_mce_version filter is not needed since external plugins are loaded directly by TinyMCE. * These plugins can be refreshed by appending query string to the URL passed to "mce_external_plugins" filter. * If the plugin has a popup dialog, a query string can be added to the button action that opens it (in the plugin's code). */ $version = 'ver=' . $tinymce_version; $tmce_on = !empty(self::$mce_settings); if ( ! isset($concatenate_scripts) ) script_concat_settings(); $compressed = $compress_scripts && $concatenate_scripts && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'); $mceInit = $qtInit = ''; if ( $tmce_on ) { foreach ( self::$mce_settings as $editor_id => $init ) { $options = self::_parse_init( $init ); $mceInit .= "'$editor_id':{$options},"; } $mceInit = '{' . trim($mceInit, ',') . '}'; } else { $mceInit = '{}'; } if ( !empty(self::$qt_settings) ) { foreach ( self::$qt_settings as $editor_id => $init ) { $options = self::_parse_init( $init ); $qtInit .= "'$editor_id':{$options},"; } $qtInit = '{' . trim($qtInit, ',') . '}'; } else { $qtInit = '{}'; } $ref = array( 'plugins' => implode( ',', self::$plugins ), 'theme' => 'modern', 'language' => self::$mce_locale ); $suffix = ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) ? '' : '.min'; /** * Fires immediately before the TinyMCE settings are printed. * * @since 3.2.0 * * @param array $mce_settings TinyMCE settings array. */ do_action( 'before_wp_tiny_mce', self::$mce_settings ); ?> <script type="text/javascript"> tinyMCEPreInit = { baseURL: "<?php echo self::$baseurl; ?>", suffix: "<?php echo $suffix; ?>", <?php if ( self::$drag_drop_upload ) { echo 'dragDropUpload: true,'; } ?> mceInit: <?php echo $mceInit; ?>, qtInit: <?php echo $qtInit; ?>, ref: <?php echo self::_parse_init( $ref ); ?>, load_ext: function(url,lang){var sl=tinymce.ScriptLoader;sl.markDone(url+'/langs/'+lang+'.js');sl.markDone(url+'/langs/'+lang+'_dlg.js');} }; </script> <?php $baseurl = self::$baseurl; // Load tinymce.js when running from /src, else load wp-tinymce.js.gz (production) or tinymce.min.js (SCRIPT_DEBUG) $mce_suffix = false !== strpos( $GLOBALS['wp_version'], '-src' ) ? '' : '.min'; if ( $tmce_on ) { if ( $compressed ) { echo "<script type='text/javascript' src='{$baseurl}/wp-tinymce.php?c=1&amp;$version'></script>\n"; } else { echo "<script type='text/javascript' src='{$baseurl}/tinymce{$mce_suffix}.js?$version'></script>\n"; echo "<script type='text/javascript' src='{$baseurl}/plugins/compat3x/plugin{$suffix}.js?$version'></script>\n"; } echo "<script type='text/javascript'>\n" . self::wp_mce_translation() . "</script>\n"; if ( self::$ext_plugins ) { // Load the old-format English strings to prevent unsightly labels in old style popups echo "<script type='text/javascript' src='{$baseurl}/langs/wp-langs-en.js?$version'></script>\n"; } } /** * Fires after tinymce.js is loaded, but before any TinyMCE editor * instances are created. * * @since 3.9.0 * * @param array $mce_settings TinyMCE settings array. */ do_action( 'wp_tiny_mce_init', self::$mce_settings ); ?> <script type="text/javascript"> <?php if ( self::$ext_plugins ) echo self::$ext_plugins . "\n"; if ( ! is_admin() ) echo 'var ajaxurl = "' . admin_url( 'admin-ajax.php', 'relative' ) . '";'; ?> ( function() { var init, edId, qtId, firstInit, wrapper; if ( typeof tinymce !== 'undefined' ) { for ( edId in tinyMCEPreInit.mceInit ) { if ( firstInit ) { init = tinyMCEPreInit.mceInit[edId] = tinymce.extend( {}, firstInit, tinyMCEPreInit.mceInit[edId] ); } else { init = firstInit = tinyMCEPreInit.mceInit[edId]; } wrapper = tinymce.DOM.select( '#wp-' + edId + '-wrap' )[0]; if ( ( tinymce.DOM.hasClass( wrapper, 'tmce-active' ) || ! tinyMCEPreInit.qtInit.hasOwnProperty( edId ) ) && ! init.wp_skip_init ) { try { tinymce.init( init ); if ( ! window.wpActiveEditor ) { window.wpActiveEditor = edId; } } catch(e){} } } } if ( typeof quicktags !== 'undefined' ) { for ( qtId in tinyMCEPreInit.qtInit ) { try { quicktags( tinyMCEPreInit.qtInit[qtId] ); if ( ! window.wpActiveEditor ) { window.wpActiveEditor = qtId; } } catch(e){}; } } if ( typeof jQuery !== 'undefined' ) { jQuery('.wp-editor-wrap').on( 'click.wp-editor', function() { if ( this.id ) { window.wpActiveEditor = this.id.slice( 3, -5 ); } }); } else { for ( qtId in tinyMCEPreInit.qtInit ) { document.getElementById( 'wp-' + qtId + '-wrap' ).onclick = function() { window.wpActiveEditor = this.id.slice( 3, -5 ); } } } }()); </script> <?php if ( in_array( 'wplink', self::$plugins, true ) || in_array( 'link', self::$qt_buttons, true ) ) self::wp_link_dialog(); if ( in_array( 'wpfullscreen', self::$plugins, true ) || in_array( 'fullscreen', self::$qt_buttons, true ) ) self::wp_fullscreen_html(); /** * Fires after any core TinyMCE editor instances are created. * * @since 3.2.0 * * @param array $mce_settings TinyMCE settings array. */ do_action( 'after_wp_tiny_mce', self::$mce_settings ); } public static function wp_fullscreen_html() { global $content_width; $post = get_post(); $width = isset( $content_width ) && 800 > $content_width ? $content_width : 800; $width = $width + 22; // compensate for the padding and border $dfw_width = get_user_setting( 'dfw_width', $width ); $save = isset( $post->post_status ) && $post->post_status == 'publish' ? __('Update') : __('Save'); ?> <div id="wp-fullscreen-body" class="wp-core-ui<?php if ( is_rtl() ) echo ' rtl'; ?>" data-theme-width="<?php echo (int) $width; ?>" data-dfw-width="<?php echo (int) $dfw_width; ?>"> <div id="fullscreen-topbar"> <div id="wp-fullscreen-toolbar"> <div id="wp-fullscreen-close"><a href="#" onclick="wp.editor.fullscreen.off();return false;"><?php _e('Exit fullscreen'); ?></a></div> <div id="wp-fullscreen-central-toolbar" style="width:<?php echo $width; ?>px;"> <div id="wp-fullscreen-mode-bar"> <div id="wp-fullscreen-modes" class="button-group"> <a class="button wp-fullscreen-mode-tinymce" href="#" onclick="wp.editor.fullscreen.switchmode( 'tinymce' ); return false;"><?php _e( 'Visual' ); ?></a> <a class="button wp-fullscreen-mode-html" href="#" onclick="wp.editor.fullscreen.switchmode( 'html' ); return false;"><?php _ex( 'Text', 'Name for the Text editor tab (formerly HTML)' ); ?></a> </div> </div> <div id="wp-fullscreen-button-bar"><div id="wp-fullscreen-buttons" class="mce-toolbar"> <?php $buttons = array( // format: title, onclick, show in both editors 'bold' => array( 'title' => __('Bold (Ctrl + B)'), 'both' => false ), 'italic' => array( 'title' => __('Italic (Ctrl + I)'), 'both' => false ), 'bullist' => array( 'title' => __('Unordered list (Alt + Shift + U)'), 'both' => false ), 'numlist' => array( 'title' => __('Ordered list (Alt + Shift + O)'), 'both' => false ), 'blockquote' => array( 'title' => __('Blockquote (Alt + Shift + Q)'), 'both' => false ), 'wp-media-library' => array( 'title' => __('Media library (Alt + Shift + M)'), 'both' => true ), 'link' => array( 'title' => __('Insert/edit link (Alt + Shift + A)'), 'both' => true ), 'unlink' => array( 'title' => __('Unlink (Alt + Shift + S)'), 'both' => false ), 'help' => array( 'title' => __('Help (Alt + Shift + H)'), 'both' => false ), ); /** * Filter the list of TinyMCE buttons for the fullscreen * 'Distraction-Free Writing' editor. * * @since 3.2.0 * * @param array $buttons An array of TinyMCE buttons for the DFW editor. */ $buttons = apply_filters( 'wp_fullscreen_buttons', $buttons ); foreach ( $buttons as $button => $args ) { if ( 'separator' == $args ) { continue; } $onclick = ! empty( $args['onclick'] ) ? ' onclick="' . $args['onclick'] . '"' : ''; $title = esc_attr( $args['title'] ); ?> <div class="mce-widget mce-btn<?php if ( $args['both'] ) { ?> wp-fullscreen-both<?php } ?>"> <button type="button" aria-label="<?php echo $title; ?>" title="<?php echo $title; ?>"<?php echo $onclick; ?> id="wp_fs_<?php echo $button; ?>"> <i class="mce-ico mce-i-<?php echo $button; ?>"></i> </button> </div> <?php } ?> </div></div> <div id="wp-fullscreen-save"> <input type="button" class="button button-primary right" value="<?php echo $save; ?>" onclick="wp.editor.fullscreen.save();" /> <span class="wp-fullscreen-saved-message"><?php if ( $post->post_status == 'publish' ) _e('Updated.'); else _e('Saved.'); ?></span> <span class="wp-fullscreen-error-message"><?php _e('Save failed.'); ?></span> <span class="spinner"></span> </div> </div> </div> </div> <div id="wp-fullscreen-statusbar"> <div id="wp-fullscreen-status"> <div id="wp-fullscreen-count"><?php printf( __( 'Word count: %s' ), '<span class="word-count">0</span>' ); ?></div> <div id="wp-fullscreen-tagline"><?php _e('Just write.'); ?></div> </div> </div> </div> <div class="fullscreen-overlay" id="fullscreen-overlay"></div> <div class="fullscreen-overlay fullscreen-fader fade-300" id="fullscreen-fader"></div> <?php } /** * Performs post queries for internal linking. * * @since 3.1.0 * * @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments. * @return false|array Results. */ public static function wp_link_query( $args = array() ) { $pts = get_post_types( array( 'public' => true ), 'objects' ); $pt_names = array_keys( $pts ); $query = array( 'post_type' => $pt_names, 'suppress_filters' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'post_status' => 'publish', 'posts_per_page' => 20, ); $args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1; if ( isset( $args['s'] ) ) $query['s'] = $args['s']; $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0; /** * Filter the link query arguments. * * Allows modification of the link query arguments before querying. * * @see WP_Query for a full list of arguments * * @since 3.7.0 * * @param array $query An array of WP_Query arguments. */ $query = apply_filters( 'wp_link_query_args', $query ); // Do main query. $get_posts = new WP_Query; $posts = $get_posts->query( $query ); // Check if any posts were found. if ( ! $get_posts->post_count ) return false; // Build results. $results = array(); foreach ( $posts as $post ) { if ( 'post' == $post->post_type ) $info = mysql2date( __( 'Y/m/d' ), $post->post_date ); else $info = $pts[ $post->post_type ]->labels->singular_name; $results[] = array( 'ID' => $post->ID, 'title' => trim( esc_html( strip_tags( get_the_title( $post ) ) ) ), 'permalink' => get_permalink( $post->ID ), 'info' => $info, ); } /** * Filter the link query results. * * Allows modification of the returned link query results. * * @since 3.7.0 * * @see 'wp_link_query_args' filter * * @param array $results { * An associative array of query results. * * @type array { * @type int $ID Post ID. * @type string $title The trimmed, escaped post title. * @type string $permalink Post permalink. * @type string $info A 'Y/m/d'-formatted date for 'post' post type, * the 'singular_name' post type label otherwise. * } * } * @param array $query An array of WP_Query arguments. */ return apply_filters( 'wp_link_query', $results, $query ); } /** * Dialog for internal linking. * * @since 3.1.0 */ public static function wp_link_dialog() { $search_panel_visible = '1' == get_user_setting( 'wplink', '0' ) ? ' search-panel-visible' : ''; // display: none is required here, see #WP27605 ?> <div id="wp-link-backdrop" style="display: none"></div> <div id="wp-link-wrap" class="wp-core-ui<?php echo $search_panel_visible; ?>" style="display: none"> <form id="wp-link" tabindex="-1"> <?php wp_nonce_field( 'internal-linking', '_ajax_linking_nonce', false ); ?> <div id="link-modal-title"> <?php _e( 'Insert/edit link' ) ?> <button type="button" id="wp-link-close"><span class="screen-reader-text"><?php _e( 'Close' ); ?></span></button> </div> <div id="link-selector"> <div id="link-options"> <p class="howto"><?php _e( 'Enter the destination URL' ); ?></p> <div> <label><span><?php _e( 'URL' ); ?></span><input id="url-field" type="text" name="href" /></label> </div> <div> <label><span><?php _e( 'Title' ); ?></span><input id="link-title-field" type="text" name="linktitle" /></label> </div> <div class="link-target"> <label><span>&nbsp;</span><input type="checkbox" id="link-target-checkbox" /> <?php _e( 'Open link in a new window/tab' ); ?></label> </div> </div> <p class="howto"><a href="#" id="wp-link-search-toggle"><?php _e( 'Or link to existing content' ); ?></a></p> <div id="search-panel"> <div class="link-search-wrapper"> <label> <span class="search-label"><?php _e( 'Search' ); ?></span> <input type="search" id="search-field" class="link-search-field" autocomplete="off" /> <span class="spinner"></span> </label> </div> <div id="search-results" class="query-results" tabindex="0"> <ul></ul> <div class="river-waiting"> <span class="spinner"></span> </div> </div> <div id="most-recent-results" class="query-results" tabindex="0"> <div class="query-notice" id="query-notice-message"> <em class="query-notice-default"><?php _e( 'No search term specified. Showing recent items.' ); ?></em> <em class="query-notice-hint screen-reader-text"><?php _e( 'Search or use up and down arrow keys to select an item.' ); ?></em> </div> <ul></ul> <div class="river-waiting"> <span class="spinner"></span> </div> </div> </div> </div> <div class="submitbox"> <div id="wp-link-cancel"> <a class="submitdelete deletion" href="#"><?php _e( 'Cancel' ); ?></a> </div> <div id="wp-link-update"> <input type="submit" value="<?php esc_attr_e( 'Add Link' ); ?>" class="button button-primary" id="wp-link-submit" name="wp-link-submit"> </div> </div> </form> </div> <?php } }
gpl-2.0
Auraya86/PerpetuumCantabile
administrator/components/com_menus/helpers/html/menus.php
4088
<?php /** * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // no direct access defined('_JEXEC') or die; JLoader::register('MenusHelper', JPATH_ADMINISTRATOR . '/components/com_menus/helpers/menus.php'); /** * @package Joomla.Administrator * @subpackage com_menus */ abstract class MenusHtmlMenus { /** * @param int $itemid The menu item id */ static function association($itemid) { // Get the associations $associations = MenusHelper::getAssociations($itemid); // Get the associated menu items $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('m.*'); $query->select('mt.title as menu_title'); $query->from('#__menu as m'); $query->leftJoin('#__menu_types as mt ON mt.menutype=m.menutype'); $query->where('m.id IN ('.implode(',', array_values($associations)).')'); $query->leftJoin('#__languages as l ON m.language=l.lang_code'); $query->select('l.image'); $query->select('l.title as language_title'); $db->setQuery($query); $items = $db->loadObjectList('id'); // Check for a database error. if ($error = $db->getErrorMsg()) { JError::raiseWarning(500, $error); return false; } // Construct html $text = array(); foreach ($associations as $tag=>$associated) { if ($associated != $itemid) { $text[] = JText::sprintf('COM_MENUS_TIP_ASSOCIATED_LANGUAGE', JHtml::_('image', 'mod_languages/'.$items[$associated]->image.'.gif', $items[$associated]->language_title, array('title'=>$items[$associated]->language_title), true), $items[$associated]->title, $items[$associated]->menu_title); } } return JHtml::_('tooltip', implode('<br />', $text), JText::_('COM_MENUS_TIP_ASSOCIATION'), 'menu/icon-16-links.png'); } /** * Returns a published state on a grid * * @param integer $value The state value. * @param integer $i The row index * @param boolean $enabled An optional setting for access control on the action. * @param string $checkbox An optional prefix for checkboxes. * * @return string The Html code * * @see JHtmlJGrid::state * * @since 1.7.1 */ public static function state($value, $i, $enabled = true, $checkbox = 'cb') { $states = array( 7 => array( 'unpublish', '', 'COM_MENUS_HTML_UNPUBLISH_SEPARATOR', '', false, 'publish', 'publish' ), 6 => array( 'publish', '', 'COM_MENUS_HTML_PUBLISH_SEPARATOR', '', false, 'unpublish', 'unpublish' ), 5 => array( 'unpublish', '', 'COM_MENUS_HTML_UNPUBLISH_ALIAS', '', false, 'publish', 'publish' ), 4 => array( 'publish', '', 'COM_MENUS_HTML_PUBLISH_ALIAS', '', false, 'unpublish', 'unpublish' ), 3 => array( 'unpublish', '', 'COM_MENUS_HTML_UNPUBLISH_URL', '', false, 'publish', 'publish' ), 2 => array( 'publish', '', 'COM_MENUS_HTML_PUBLISH_URL', '', false, 'unpublish', 'unpublish' ), 1 => array( 'unpublish', 'COM_MENUS_EXTENSION_PUBLISHED_ENABLED', 'COM_MENUS_HTML_UNPUBLISH_ENABLED', 'COM_MENUS_EXTENSION_PUBLISHED_ENABLED', true, 'publish', 'publish' ), 0 => array( 'publish', 'COM_MENUS_EXTENSION_UNPUBLISHED_ENABLED', 'COM_MENUS_HTML_PUBLISH_ENABLED', 'COM_MENUS_EXTENSION_UNPUBLISHED_ENABLED', true, 'unpublish', 'unpublish' ), -1 => array( 'unpublish', 'COM_MENUS_EXTENSION_PUBLISHED_DISABLED', 'COM_MENUS_HTML_UNPUBLISH_DISABLED', 'COM_MENUS_EXTENSION_PUBLISHED_DISABLED', true, 'warning', 'warning' ), -2 => array( 'publish', 'COM_MENUS_EXTENSION_UNPUBLISHED_DISABLED', 'COM_MENUS_HTML_PUBLISH_DISABLED', 'COM_MENUS_EXTENSION_UNPUBLISHED_DISABLED', true, 'unpublish', 'unpublish' ), ); return JHtml::_('jgrid.state', $states, $value, $i, 'items.', $enabled, true, $checkbox); } }
gpl-2.0
sajochiu/cdnjs
ajax/libs/mobile-angular-ui/1.1.0-beta.13/js/mobile-angular-ui-scrollable-overthrow.js
15752
/*! Overthrow. An overflow:auto polyfill for responsive design. (c) 2012: Scott Jehl, Filament Group, Inc. http://filamentgroup.github.com/Overthrow/license.txt */ (function( w, undefined ){ var doc = w.document, docElem = doc.documentElement, enabledClassName = "overthrow-enabled", // Touch events are used in the polyfill, and thus are a prerequisite canBeFilledWithPoly = "ontouchmove" in doc, // The following attempts to determine whether the browser has native overflow support // so we can enable it but not polyfill nativeOverflow = // Features-first. iOS5 overflow scrolling property check - no UA needed here. thanks Apple :) "WebkitOverflowScrolling" in docElem.style || // Test the windows scrolling property as well "msOverflowStyle" in docElem.style || // Touch events aren't supported and screen width is greater than X // ...basically, this is a loose "desktop browser" check. // It may wrongly opt-in very large tablets with no touch support. ( !canBeFilledWithPoly && w.screen.width > 800 ) || // Hang on to your hats. // Whitelist some popular, overflow-supporting mobile browsers for now and the future // These browsers are known to get overlow support right, but give us no way of detecting it. (function(){ var ua = w.navigator.userAgent, // Webkit crosses platforms, and the browsers on our list run at least version 534 webkit = ua.match( /AppleWebKit\/([0-9]+)/ ), wkversion = webkit && webkit[1], wkLte534 = webkit && wkversion >= 534; return ( /* Android 3+ with webkit gte 534 ~: Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13 */ ua.match( /Android ([0-9]+)/ ) && RegExp.$1 >= 3 && wkLte534 || /* Blackberry 7+ with webkit gte 534 ~: Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en-US) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.0.0 Mobile Safari/534.11+ */ ua.match( / Version\/([0-9]+)/ ) && RegExp.$1 >= 0 && w.blackberry && wkLte534 || /* Blackberry Playbook with webkit gte 534 ~: Mozilla/5.0 (PlayBook; U; RIM Tablet OS 1.0.0; en-US) AppleWebKit/534.8+ (KHTML, like Gecko) Version/0.0.1 Safari/534.8+ */ ua.indexOf( "PlayBook" ) > -1 && wkLte534 && !ua.indexOf( "Android 2" ) === -1 || /* Firefox Mobile (Fennec) 4 and up ~: Mozilla/5.0 (Mobile; rv:15.0) Gecko/15.0 Firefox/15.0 */ ua.match(/Firefox\/([0-9]+)/) && RegExp.$1 >= 4 || /* WebOS 3 and up (TouchPad too) ~: Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.48 Safari/534.6 TouchPad/1.0 */ ua.match( /wOSBrowser\/([0-9]+)/ ) && RegExp.$1 >= 233 && wkLte534 || /* Nokia Browser N8 ~: Mozilla/5.0 (Symbian/3; Series60/5.2 NokiaN8-00/012.002; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.0 Mobile Safari/533.4 3gpp-gba ~: Note: the N9 doesn't have native overflow with one-finger touch. wtf */ ua.match( /NokiaBrowser\/([0-9\.]+)/ ) && parseFloat(RegExp.$1) === 7.3 && webkit && wkversion >= 533 ); })(); // Expose overthrow API w.overthrow = {}; w.overthrow.enabledClassName = enabledClassName; w.overthrow.addClass = function(){ if( docElem.className.indexOf( w.overthrow.enabledClassName ) === -1 ){ docElem.className += " " + w.overthrow.enabledClassName; } }; w.overthrow.removeClass = function(){ docElem.className = docElem.className.replace( w.overthrow.enabledClassName, "" ); }; // Enable and potentially polyfill overflow w.overthrow.set = function(){ // If nativeOverflow or at least the element canBeFilledWithPoly, add a class to cue CSS that assumes overflow scrolling will work (setting height on elements and such) if( nativeOverflow ){ w.overthrow.addClass(); } }; // expose polyfillable w.overthrow.canBeFilledWithPoly = canBeFilledWithPoly; // Destroy everything later. If you want to. w.overthrow.forget = function(){ w.overthrow.removeClass(); }; // Expose overthrow API w.overthrow.support = nativeOverflow ? "native" : "none"; })( this ); /*! Overthrow. An overflow:auto polyfill for responsive design. (c) 2012: Scott Jehl, Filament Group, Inc. http://filamentgroup.github.com/Overthrow/license.txt */ (function( w, undefined ){ // Auto-init w.overthrow.set(); }( this )); /*! Overthrow. An overflow:auto polyfill for responsive design. (c) 2012: Scott Jehl, Filament Group, Inc. http://filamentgroup.github.com/Overthrow/license.txt */ (function( w, o, undefined ){ // o is overthrow reference from overthrow-polyfill.js if( o === undefined ){ return; } o.scrollIndicatorClassName = "overthrow"; var doc = w.document, docElem = doc.documentElement, // o api nativeOverflow = o.support === "native", canBeFilledWithPoly = o.canBeFilledWithPoly, configure = o.configure, set = o.set, forget = o.forget, scrollIndicatorClassName = o.scrollIndicatorClassName; // find closest overthrow (elem or a parent) o.closest = function( target, ascend ){ return !ascend && target.className && target.className.indexOf( scrollIndicatorClassName ) > -1 && target || o.closest( target.parentNode ); }; // polyfill overflow var enabled = false; o.set = function(){ set(); // If nativeOverflow or it doesn't look like the browser canBeFilledWithPoly, our job is done here. Exit viewport left. if( enabled || nativeOverflow || !canBeFilledWithPoly ){ return; } w.overthrow.addClass(); enabled = true; o.support = "polyfilled"; o.forget = function(){ forget(); enabled = false; // Remove touch binding (check for method support since this part isn't qualified by touch support like the rest) if( doc.removeEventListener ){ doc.removeEventListener( "touchstart", start, false ); } }; // Fill 'er up! // From here down, all logic is associated with touch scroll handling // elem references the overthrow element in use var elem, // The last several Y values are kept here lastTops = [], // The last several X values are kept here lastLefts = [], // lastDown will be true if the last scroll direction was down, false if it was up lastDown, // lastRight will be true if the last scroll direction was right, false if it was left lastRight, // For a new gesture, or change in direction, reset the values from last scroll resetVertTracking = function(){ lastTops = []; lastDown = null; }, resetHorTracking = function(){ lastLefts = []; lastRight = null; }, // On webkit, touch events hardly trickle through textareas and inputs // Disabling CSS pointer events makes sure they do, but it also makes the controls innaccessible // Toggling pointer events at the right moments seems to do the trick // Thanks Thomas Bachem http://stackoverflow.com/a/5798681 for the following inputs, setPointers = function( val ){ inputs = elem.querySelectorAll( "textarea, input" ); for( var i = 0, il = inputs.length; i < il; i++ ) { inputs[ i ].style.pointerEvents = val; } }, // For nested overthrows, changeScrollTarget restarts a touch event cycle on a parent or child overthrow changeScrollTarget = function( startEvent, ascend ){ if( doc.createEvent ){ var newTarget = ( !ascend || ascend === undefined ) && elem.parentNode || elem.touchchild || elem, tEnd; if( newTarget !== elem ){ tEnd = doc.createEvent( "HTMLEvents" ); tEnd.initEvent( "touchend", true, true ); elem.dispatchEvent( tEnd ); newTarget.touchchild = elem; elem = newTarget; newTarget.dispatchEvent( startEvent ); } } }, // Touchstart handler // On touchstart, touchmove and touchend are freshly bound, and all three share a bunch of vars set by touchstart // Touchend unbinds them again, until next time start = function( e ){ // Stop any throw in progress if( o.intercept ){ o.intercept(); } // Reset the distance and direction tracking resetVertTracking(); resetHorTracking(); elem = o.closest( e.target ); if( !elem || elem === docElem || e.touches.length > 1 ){ return; } setPointers( "none" ); var touchStartE = e, scrollT = elem.scrollTop, scrollL = elem.scrollLeft, height = elem.offsetHeight, width = elem.offsetWidth, startY = e.touches[ 0 ].pageY, startX = e.touches[ 0 ].pageX, scrollHeight = elem.scrollHeight, scrollWidth = elem.scrollWidth, // Touchmove handler move = function( e ){ var ty = scrollT + startY - e.touches[ 0 ].pageY, tx = scrollL + startX - e.touches[ 0 ].pageX, down = ty >= ( lastTops.length ? lastTops[ 0 ] : 0 ), right = tx >= ( lastLefts.length ? lastLefts[ 0 ] : 0 ); // If there's room to scroll the current container, prevent the default window scroll if( ( ty > 0 && ty < scrollHeight - height ) || ( tx > 0 && tx < scrollWidth - width ) ){ e.preventDefault(); } // This bubbling is dumb. Needs a rethink. else { changeScrollTarget( touchStartE ); } // If down and lastDown are inequal, the y scroll has changed direction. Reset tracking. if( lastDown && down !== lastDown ){ resetVertTracking(); } // If right and lastRight are inequal, the x scroll has changed direction. Reset tracking. if( lastRight && right !== lastRight ){ resetHorTracking(); } // remember the last direction in which we were headed lastDown = down; lastRight = right; // set the container's scroll elem.scrollTop = ty; elem.scrollLeft = tx; lastTops.unshift( ty ); lastLefts.unshift( tx ); if( lastTops.length > 3 ){ lastTops.pop(); } if( lastLefts.length > 3 ){ lastLefts.pop(); } }, // Touchend handler end = function( e ){ // Bring the pointers back setPointers( "auto" ); setTimeout( function(){ setPointers( "none" ); }, 450 ); elem.removeEventListener( "touchmove", move, false ); elem.removeEventListener( "touchend", end, false ); }; elem.addEventListener( "touchmove", move, false ); elem.addEventListener( "touchend", end, false ); }; // Bind to touch, handle move and end within doc.addEventListener( "touchstart", start, false ); }; })( this, this.overthrow ); /*! Overthrow. An overflow:auto polyfill for responsive design. (c) 2012: Scott Jehl, Filament Group, Inc. http://filamentgroup.github.com/Overthrow/license.txt */ (function( w, o, undefined ){ // o is overthrow reference from overthrow-polyfill.js if( o === undefined ){ return; } // Easing can use any of Robert Penner's equations (http://www.robertpenner.com/easing_terms_of_use.html). By default, overthrow includes ease-out-cubic // arguments: t = current iteration, b = initial value, c = end value, d = total iterations // use w.overthrow.easing to provide a custom function externally, or pass an easing function as a callback to the toss method o.easing = function (t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }; // tossing property is true during a programatic scroll o.tossing = false; // Keeper of intervals var timeKeeper; /* toss scrolls and element with easing // elem is the element to scroll // options hash: * left is the desired horizontal scroll. Default is "+0". For relative distances, pass a string with "+" or "-" in front. * top is the desired vertical scroll. Default is "+0". For relative distances, pass a string with "+" or "-" in front. * duration is the number of milliseconds the throw will take. Default is 100. * easing is an optional custom easing function. Default is w.overthrow.easing. Must follow the easing function signature */ o.toss = function( elem, options ){ o.intercept(); var i = 0, sLeft = elem.scrollLeft, sTop = elem.scrollTop, // Toss defaults op = { top: "+0", left: "+0", duration: 50, easing: o.easing, finished: function() {} }, endLeft, endTop, finished = false; // Mixin based on predefined defaults if( options ){ for( var j in op ){ if( options[ j ] !== undefined ){ op[ j ] = options[ j ]; } } } // Convert relative values to ints // First the left val if( typeof op.left === "string" ){ op.left = parseFloat( op.left ); endLeft = op.left + sLeft; } else { endLeft = op.left; op.left = op.left - sLeft; } // Then the top val if( typeof op.top === "string" ){ op.top = parseFloat( op.top ); endTop = op.top + sTop; } else { endTop = op.top; op.top = op.top - sTop; } o.tossing = true; timeKeeper = setInterval(function(){ if( i++ < op.duration ){ elem.scrollLeft = op.easing( i, sLeft, op.left, op.duration ); elem.scrollTop = op.easing( i, sTop, op.top, op.duration ); } else{ if( endLeft !== elem.scrollLeft ){ elem.scrollLeft = endLeft; } else { // if the end of the vertical scrolling has taken place // we know that we're done here call the callback // otherwise signal that horizontal scrolling is complete if( finished ) { op.finished(); } finished = true; } if( endTop !== elem.scrollTop ){ elem.scrollTop = endTop; } else { // if the end of the horizontal scrolling has taken place // we know that we're done here call the callback if( finished ) { op.finished(); } finished = true; } o.intercept(); } }, 1 ); // Return the values, post-mixin, with end values specified return { top: endTop, left: endLeft, duration: o.duration, easing: o.easing }; }; // Intercept any throw in progress o.intercept = function(){ clearInterval( timeKeeper ); o.tossing = false; }; })( this, this.overthrow ); (function() { var adjustScrollableHeight, adjustScrollablesHeight; adjustScrollableHeight = function(e) { var p, paddingAndBordersHeight, rightHeight; p = e.offsetParent; paddingAndBordersHeight = e.offsetHeight - e.clientHeight; if (e.offsetTop + e.offsetHeight > p.clientHeight) { rightHeight = p.clientHeight - paddingAndBordersHeight - e.offsetTop; if (rightHeight > 0) { return e.setAttribute("style", "max-height:" + rightHeight + "px"); } } else { return e.setAttribute("style", "max-height:99999px"); } }; adjustScrollablesHeight = function() { var scrollables; scrollables = document.getElementsByClassName("scrollable"); return angular.forEach(scrollables, function(e) { return adjustScrollableHeight(e); }); }; return angular.module("mobile-angular-ui.scrollable", []).run([ "$window", function($window) { adjustScrollablesHeight(); return angular.element($window).bind('resize', function() { return adjustScrollablesHeight(); }); } ]).directive("scrollableContent", function() { return { replace: false, restrict: "C", link: function(scope, element, attr) { adjustScrollableHeight(element.parent()[0]); if (overthrow.support === "native") { return element.attr("style", "overflow: auto; -webkit-overflow-scrolling: touch;"); } else { element.addClass("overthrow"); overthrow.forget(); return overthrow.set(); } } }; }); })();
mit
android-ia/platform_external_chromium_org
third_party/harfbuzz-ng/src/hb-ot-shape-complex-tibetan.cc
1983
/* * Copyright © 2010,2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Google Author(s): Behdad Esfahbod */ #include "hb-ot-shape-complex-private.hh" static const hb_tag_t tibetan_features[] = { HB_TAG('a','b','v','s'), HB_TAG('b','l','w','s'), HB_TAG('a','b','v','m'), HB_TAG('b','l','w','m'), HB_TAG_NONE }; static void collect_features_tibetan (hb_ot_shape_planner_t *plan) { for (const hb_tag_t *script_features = tibetan_features; script_features && *script_features; script_features++) plan->map.add_global_bool_feature (*script_features); } const hb_ot_complex_shaper_t _hb_ot_complex_shaper_tibetan = { "default", collect_features_tibetan, NULL, /* override_features */ NULL, /* data_create */ NULL, /* data_destroy */ NULL, /* preprocess_text */ HB_OT_SHAPE_NORMALIZATION_MODE_DEFAULT, NULL, /* decompose */ NULL, /* compose */ NULL, /* setup_masks */ HB_OT_SHAPE_ZERO_WIDTH_MARKS_DEFAULT, true, /* fallback_position */ };
bsd-3-clause
lavalamp/heapster
Godeps/_workspace/src/github.com/GoogleCloudPlatform/kubernetes/pkg/api/resource/quantity_test.go
15149
/* Copyright 2014 The Kubernetes 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. */ package resource import ( //"reflect" "encoding/json" "testing" fuzz "github.com/google/gofuzz" "github.com/spf13/pflag" "speter.net/go/exp/math/dec/inf" ) var ( testQuantityFlag = QuantityFlag("quantityFlag", "1M", "dummy flag for testing the quantity flag mechanism") ) func dec(i int64, exponent int) *inf.Dec { // See the below test-- scale is the negative of an exponent. return inf.NewDec(i, inf.Scale(-exponent)) } func TestDec(t *testing.T) { table := []struct { got *inf.Dec expect string }{ {dec(1, 0), "1"}, {dec(1, 1), "10"}, {dec(5, 2), "500"}, {dec(8, 3), "8000"}, {dec(2, 0), "2"}, {dec(1, -1), "0.1"}, {dec(3, -2), "0.03"}, {dec(4, -3), "0.004"}, } for _, item := range table { if e, a := item.expect, item.got.String(); e != a { t.Errorf("expected %v, got %v", e, a) } } } // TestQuantityParseZero ensures that when a 0 quantity is passed, its string value is 0 func TestQuantityParseZero(t *testing.T) { zero := MustParse("0") if expected, actual := "0", zero.String(); expected != actual { t.Errorf("Expected %v, actual %v", expected, actual) } } // Verifies that you get 0 as canonical value if internal value is 0, and not 0<suffix> func TestQuantityCanocicalizeZero(t *testing.T) { val := MustParse("1000m") x := val.Amount y := dec(1, 0) z := val.Amount.Sub(x, y) zero := Quantity{z, DecimalSI} if expected, actual := "0", zero.String(); expected != actual { t.Errorf("Expected %v, actual %v", expected, actual) } } func TestQuantityParse(t *testing.T) { table := []struct { input string expect Quantity }{ {"0", Quantity{dec(0, 0), DecimalSI}}, {"0m", Quantity{dec(0, 0), DecimalSI}}, {"0Ki", Quantity{dec(0, 0), BinarySI}}, {"0k", Quantity{dec(0, 0), DecimalSI}}, {"0Mi", Quantity{dec(0, 0), BinarySI}}, {"0M", Quantity{dec(0, 0), DecimalSI}}, {"0Gi", Quantity{dec(0, 0), BinarySI}}, {"0G", Quantity{dec(0, 0), DecimalSI}}, {"0Ti", Quantity{dec(0, 0), BinarySI}}, {"0T", Quantity{dec(0, 0), DecimalSI}}, // Binary suffixes {"1Ki", Quantity{dec(1024, 0), BinarySI}}, {"8Ki", Quantity{dec(8*1024, 0), BinarySI}}, {"7Mi", Quantity{dec(7*1024*1024, 0), BinarySI}}, {"6Gi", Quantity{dec(6*1024*1024*1024, 0), BinarySI}}, {"5Ti", Quantity{dec(5*1024*1024*1024*1024, 0), BinarySI}}, {"4Pi", Quantity{dec(4*1024*1024*1024*1024*1024, 0), BinarySI}}, {"3Ei", Quantity{dec(3*1024*1024*1024*1024*1024*1024, 0), BinarySI}}, {"10Ti", Quantity{dec(10*1024*1024*1024*1024, 0), BinarySI}}, {"100Ti", Quantity{dec(100*1024*1024*1024*1024, 0), BinarySI}}, // Decimal suffixes {"3m", Quantity{dec(3, -3), DecimalSI}}, {"9", Quantity{dec(9, 0), DecimalSI}}, {"8k", Quantity{dec(8, 3), DecimalSI}}, {"7M", Quantity{dec(7, 6), DecimalSI}}, {"6G", Quantity{dec(6, 9), DecimalSI}}, {"5T", Quantity{dec(5, 12), DecimalSI}}, {"40T", Quantity{dec(4, 13), DecimalSI}}, {"300T", Quantity{dec(3, 14), DecimalSI}}, {"2P", Quantity{dec(2, 15), DecimalSI}}, {"1E", Quantity{dec(1, 18), DecimalSI}}, // Decimal exponents {"1E-3", Quantity{dec(1, -3), DecimalExponent}}, {"1e3", Quantity{dec(1, 3), DecimalExponent}}, {"1E6", Quantity{dec(1, 6), DecimalExponent}}, {"1e9", Quantity{dec(1, 9), DecimalExponent}}, {"1E12", Quantity{dec(1, 12), DecimalExponent}}, {"1e15", Quantity{dec(1, 15), DecimalExponent}}, {"1E18", Quantity{dec(1, 18), DecimalExponent}}, // Nonstandard but still parsable {"1e14", Quantity{dec(1, 14), DecimalExponent}}, {"1e13", Quantity{dec(1, 13), DecimalExponent}}, {"1e3", Quantity{dec(1, 3), DecimalExponent}}, {"100.035k", Quantity{dec(100035, 0), DecimalSI}}, // Things that look like floating point {"0.001", Quantity{dec(1, -3), DecimalSI}}, {"0.0005k", Quantity{dec(5, -1), DecimalSI}}, {"0.005", Quantity{dec(5, -3), DecimalSI}}, {"0.05", Quantity{dec(5, -2), DecimalSI}}, {"0.5", Quantity{dec(5, -1), DecimalSI}}, {"0.00050k", Quantity{dec(5, -1), DecimalSI}}, {"0.00500", Quantity{dec(5, -3), DecimalSI}}, {"0.05000", Quantity{dec(5, -2), DecimalSI}}, {"0.50000", Quantity{dec(5, -1), DecimalSI}}, {"0.5e0", Quantity{dec(5, -1), DecimalExponent}}, {"0.5e-1", Quantity{dec(5, -2), DecimalExponent}}, {"0.5e-2", Quantity{dec(5, -3), DecimalExponent}}, {"0.5e0", Quantity{dec(5, -1), DecimalExponent}}, {"10.035M", Quantity{dec(10035, 3), DecimalSI}}, {"1.2e3", Quantity{dec(12, 2), DecimalExponent}}, {"1.3E+6", Quantity{dec(13, 5), DecimalExponent}}, {"1.40e9", Quantity{dec(14, 8), DecimalExponent}}, {"1.53E12", Quantity{dec(153, 10), DecimalExponent}}, {"1.6e15", Quantity{dec(16, 14), DecimalExponent}}, {"1.7E18", Quantity{dec(17, 17), DecimalExponent}}, {"9.01", Quantity{dec(901, -2), DecimalSI}}, {"8.1k", Quantity{dec(81, 2), DecimalSI}}, {"7.123456M", Quantity{dec(7123456, 0), DecimalSI}}, {"6.987654321G", Quantity{dec(6987654321, 0), DecimalSI}}, {"5.444T", Quantity{dec(5444, 9), DecimalSI}}, {"40.1T", Quantity{dec(401, 11), DecimalSI}}, {"300.2T", Quantity{dec(3002, 11), DecimalSI}}, {"2.5P", Quantity{dec(25, 14), DecimalSI}}, {"1.01E", Quantity{dec(101, 16), DecimalSI}}, // Things that saturate/round {"3.001m", Quantity{dec(4, -3), DecimalSI}}, {"1.1E-3", Quantity{dec(2, -3), DecimalExponent}}, {"0.0001", Quantity{dec(1, -3), DecimalSI}}, {"0.0005", Quantity{dec(1, -3), DecimalSI}}, {"0.00050", Quantity{dec(1, -3), DecimalSI}}, {"0.5e-3", Quantity{dec(1, -3), DecimalExponent}}, {"0.9m", Quantity{dec(1, -3), DecimalSI}}, {"0.12345", Quantity{dec(124, -3), DecimalSI}}, {"0.12354", Quantity{dec(124, -3), DecimalSI}}, {"9Ei", Quantity{maxAllowed, BinarySI}}, {"9223372036854775807Ki", Quantity{maxAllowed, BinarySI}}, {"12E", Quantity{maxAllowed, DecimalSI}}, // We'll accept fractional binary stuff, too. {"100.035Ki", Quantity{dec(10243584, -2), BinarySI}}, {"0.5Mi", Quantity{dec(.5*1024*1024, 0), BinarySI}}, {"0.05Gi", Quantity{dec(536870912, -1), BinarySI}}, {"0.025Ti", Quantity{dec(274877906944, -1), BinarySI}}, // Things written by trolls {"0.000001Ki", Quantity{dec(2, -3), DecimalSI}}, // rounds up, changes format {".001", Quantity{dec(1, -3), DecimalSI}}, {".0001k", Quantity{dec(100, -3), DecimalSI}}, {"1.", Quantity{dec(1, 0), DecimalSI}}, {"1.G", Quantity{dec(1, 9), DecimalSI}}, } for _, item := range table { got, err := ParseQuantity(item.input) if err != nil { t.Errorf("%v: unexpected error: %v", item.input, err) continue } if e, a := item.expect.Amount, got.Amount; e.Cmp(a) != 0 { t.Errorf("%v: expected %v, got %v", item.input, e, a) } if e, a := item.expect.Format, got.Format; e != a { t.Errorf("%v: expected %#v, got %#v", item.input, e, a) } } // Try the negative version of everything desired := &inf.Dec{} for _, item := range table { got, err := ParseQuantity("-" + item.input) if err != nil { t.Errorf("-%v: unexpected error: %v", item.input, err) continue } desired.Neg(item.expect.Amount) if e, a := desired, got.Amount; e.Cmp(a) != 0 { t.Errorf("%v: expected %v, got %v", item.input, e, a) } if e, a := item.expect.Format, got.Format; e != a { t.Errorf("%v: expected %#v, got %#v", item.input, e, a) } } // Try everything with an explicit + for _, item := range table { got, err := ParseQuantity("+" + item.input) if err != nil { t.Errorf("-%v: unexpected error: %v", item.input, err) continue } if e, a := item.expect.Amount, got.Amount; e.Cmp(a) != 0 { t.Errorf("%v: expected %v, got %v", item.input, e, a) } if e, a := item.expect.Format, got.Format; e != a { t.Errorf("%v: expected %#v, got %#v", item.input, e, a) } } invalid := []string{ "1.1.M", "1+1.0M", "0.1mi", "0.1am", "aoeu", ".5i", "1i", "-3.01i", } for _, item := range invalid { _, err := ParseQuantity(item) if err == nil { t.Errorf("%v parsed unexpectedly", item) } } } func TestQuantityString(t *testing.T) { table := []struct { in Quantity expect string }{ {Quantity{dec(1024*1024*1024, 0), BinarySI}, "1Gi"}, {Quantity{dec(300*1024*1024, 0), BinarySI}, "300Mi"}, {Quantity{dec(6*1024, 0), BinarySI}, "6Ki"}, {Quantity{dec(1001*1024*1024*1024, 0), BinarySI}, "1001Gi"}, {Quantity{dec(1024*1024*1024*1024, 0), BinarySI}, "1Ti"}, {Quantity{dec(5, 0), BinarySI}, "5"}, {Quantity{dec(500, -3), BinarySI}, "500m"}, {Quantity{dec(1, 9), DecimalSI}, "1G"}, {Quantity{dec(1000, 6), DecimalSI}, "1G"}, {Quantity{dec(1000000, 3), DecimalSI}, "1G"}, {Quantity{dec(1000000000, 0), DecimalSI}, "1G"}, {Quantity{dec(1, -3), DecimalSI}, "1m"}, {Quantity{dec(80, -3), DecimalSI}, "80m"}, {Quantity{dec(1080, -3), DecimalSI}, "1080m"}, {Quantity{dec(108, -2), DecimalSI}, "1080m"}, {Quantity{dec(10800, -4), DecimalSI}, "1080m"}, {Quantity{dec(300, 6), DecimalSI}, "300M"}, {Quantity{dec(1, 12), DecimalSI}, "1T"}, {Quantity{dec(1234567, 6), DecimalSI}, "1234567M"}, {Quantity{dec(1234567, -3), BinarySI}, "1234567m"}, {Quantity{dec(3, 3), DecimalSI}, "3k"}, {Quantity{dec(1025, 0), BinarySI}, "1025"}, {Quantity{dec(0, 0), DecimalSI}, "0"}, {Quantity{dec(0, 0), BinarySI}, "0"}, {Quantity{dec(1, 9), DecimalExponent}, "1e9"}, {Quantity{dec(1, -3), DecimalExponent}, "1e-3"}, {Quantity{dec(80, -3), DecimalExponent}, "80e-3"}, {Quantity{dec(300, 6), DecimalExponent}, "300e6"}, {Quantity{dec(1, 12), DecimalExponent}, "1e12"}, {Quantity{dec(1, 3), DecimalExponent}, "1e3"}, {Quantity{dec(3, 3), DecimalExponent}, "3e3"}, {Quantity{dec(3, 3), DecimalSI}, "3k"}, {Quantity{dec(0, 0), DecimalExponent}, "0"}, } for _, item := range table { got := item.in.String() if e, a := item.expect, got; e != a { t.Errorf("%#v: expected %v, got %v", item.in, e, a) } } desired := &inf.Dec{} // Avoid modifying the values in the table. for _, item := range table { if item.in.Amount.Cmp(decZero) == 0 { // Don't expect it to print "-0" ever continue } q := item.in q.Amount = desired.Neg(q.Amount) if e, a := "-"+item.expect, q.String(); e != a { t.Errorf("%#v: expected %v, got %v", item.in, e, a) } } } func TestQuantityParseEmit(t *testing.T) { table := []struct { in string expect string }{ {"1Ki", "1Ki"}, {"1Mi", "1Mi"}, {"1Gi", "1Gi"}, {"1024Mi", "1Gi"}, {"1000M", "1G"}, {".000001Ki", "2m"}, } for _, item := range table { q, err := ParseQuantity(item.in) if err != nil { t.Errorf("Couldn't parse %v", item.in) continue } if e, a := item.expect, q.String(); e != a { t.Errorf("%#v: expected %v, got %v", item.in, e, a) } } for _, item := range table { q, err := ParseQuantity("-" + item.in) if err != nil { t.Errorf("Couldn't parse %v", item.in) continue } if q.Amount.Cmp(decZero) == 0 { continue } if e, a := "-"+item.expect, q.String(); e != a { t.Errorf("%#v: expected %v, got %v", item.in, e, a) } } } var fuzzer = fuzz.New().Funcs( func(q *Quantity, c fuzz.Continue) { q.Amount = &inf.Dec{} if c.RandBool() { q.Format = BinarySI if c.RandBool() { q.Amount.SetScale(0) q.Amount.SetUnscaled(c.Int63()) return } // Be sure to test cases like 1Mi q.Amount.SetScale(0) q.Amount.SetUnscaled(c.Int63n(1024) << uint(10*c.Intn(5))) return } if c.RandBool() { q.Format = DecimalSI } else { q.Format = DecimalExponent } if c.RandBool() { q.Amount.SetScale(inf.Scale(c.Intn(4))) q.Amount.SetUnscaled(c.Int63()) return } // Be sure to test cases like 1M q.Amount.SetScale(inf.Scale(3 - c.Intn(15))) q.Amount.SetUnscaled(c.Int63n(1000)) }, ) func TestJSON(t *testing.T) { for i := 0; i < 500; i++ { q := &Quantity{} fuzzer.Fuzz(q) b, err := json.Marshal(q) if err != nil { t.Errorf("error encoding %v", q) } q2 := &Quantity{} err = json.Unmarshal(b, q2) if err != nil { t.Errorf("%v: error decoding %v", q, string(b)) } if q2.Amount.Cmp(q.Amount) != 0 { t.Errorf("Expected equal: %v, %v (json was '%v')", q, q2, string(b)) } } } func TestMilliNewSet(t *testing.T) { table := []struct { value int64 format Format expect string exact bool }{ {1, DecimalSI, "1m", true}, {1000, DecimalSI, "1", true}, {1234000, DecimalSI, "1234", true}, {1024, BinarySI, "1024m", false}, // Format changes {1000000, "invalidFormatDefaultsToExponent", "1e3", true}, {1024 * 1024, BinarySI, "1048576m", false}, // Format changes } for _, item := range table { q := NewMilliQuantity(item.value, item.format) if e, a := item.expect, q.String(); e != a { t.Errorf("Expected %v, got %v; %#v", e, a, q) } if !item.exact { continue } q2, err := ParseQuantity(q.String()) if err != nil { t.Errorf("Round trip failed on %v", q) } if e, a := item.value, q2.MilliValue(); e != a { t.Errorf("Expected %v, got %v", e, a) } } for _, item := range table { q := NewQuantity(0, item.format) q.SetMilli(item.value) if e, a := item.expect, q.String(); e != a { t.Errorf("Set: Expected %v, got %v; %#v", e, a, q) } } } func TestNewSet(t *testing.T) { table := []struct { value int64 format Format expect string }{ {1, DecimalSI, "1"}, {1000, DecimalSI, "1k"}, {1234000, DecimalSI, "1234k"}, {1024, BinarySI, "1Ki"}, {1000000, "invalidFormatDefaultsToExponent", "1e6"}, {1024 * 1024, BinarySI, "1Mi"}, } for _, item := range table { q := NewQuantity(item.value, item.format) if e, a := item.expect, q.String(); e != a { t.Errorf("Expected %v, got %v; %#v", e, a, q) } q2, err := ParseQuantity(q.String()) if err != nil { t.Errorf("Round trip failed on %v", q) } if e, a := item.value, q2.Value(); e != a { t.Errorf("Expected %v, got %v", e, a) } } for _, item := range table { q := NewQuantity(0, item.format) q.Set(item.value) if e, a := item.expect, q.String(); e != a { t.Errorf("Set: Expected %v, got %v; %#v", e, a, q) } } } func TestUninitializedNoCrash(t *testing.T) { var q Quantity q.Value() q.MilliValue() q.Copy() q.String() q.MarshalJSON() } func TestCopy(t *testing.T) { q := NewQuantity(5, DecimalSI) c := q.Copy() c.Set(6) if q.Value() == 6 { t.Errorf("Copy didn't") } } func TestQFlagSet(t *testing.T) { qf := qFlag{&Quantity{}} qf.Set("1Ki") if e, a := "1Ki", qf.String(); e != a { t.Errorf("Unexpected result %v != %v", e, a) } } func TestQFlagIsPFlag(t *testing.T) { var pfv pflag.Value = qFlag{} if e, a := "quantity", pfv.Type(); e != a { t.Errorf("Unexpected result %v != %v", e, a) } }
apache-2.0
totalspectrum/gcc-propeller
gcc/testsuite/g++.old-deja/g++.mike/p8154.C
399
// { dg-do assemble } // { dg-options "-w -fpermissive" } // prms-id: 8154 class QvFieldData; class QvNode { QvFieldData *fieldData; }; class QvGroup : public QvNode { static QvFieldData *fieldData; }; class QvUnknownNode : public QvGroup { public: QvUnknownNode :: QvUnknownNode (); private: static QvFieldData *fieldData; virtual QvFieldData *getFieldData() { return fieldData; } };
gpl-2.0
eigentor/drupal-commons-test
profiles/commons/modules/contrib/navbar/js/jquery/ducktape.events.js
756
/** * Navbar 1.x depends on jQuery >=1.7 (it uses jQuery.fn.on & jQuery.fn.off). * We re-implement these in terms of jQuery.fn.bind, jQuery.fn.delegate, * jQuery.fn.unbind, and jQuery.fn.undelegate. * This allows us to use Backbone 1.x with Drupal 7's jQuery 1.4. */ if (!jQuery.fn.on && !jQuery.fn.off) { jQuery.fn.on = function (types, selector, data, fn) { if (typeof selector !== "string") { return this.bind(types, selector, data); } else { return this.delegate(selector, types, data, fn); } }; jQuery.fn.off = function (types, selector, fn) { if (typeof selector !== "string") { return this.unbind(types, selector, fn); } else { return this.undelegate(selector, types, fn); } }; }
gpl-2.0
krichter722/gcc
gcc/testsuite/g++.old-deja/g++.pt/explicit56.C
206
// { dg-do run } template <class T> T* create (); template <class T> T* create2() { return create<T>(); } template <class T> T* create () { return new T; } int main() { int *p = create2<int>(); }
gpl-2.0
freedesktop-unofficial-mirror/gstreamer-sdk__gcc
gcc/testsuite/g++.old-deja/g++.pt/t12.C
467
// { dg-do assemble } class OBJECT {int a;}; class STDFILE {int b;}; template <class T> class VECTOR { T *v; int sz; public: T& elem(int i) { return v[i]; } T& operator[] (int i); }; template <class T> class PVECTOR : VECTOR<void *> { public: T*& elem(int i) {return (T*&) VECTOR<void *>::elem(i); } T*& operator[] (int i) {return (T*&) VECTOR<void *>::operator[](i);} }; PVECTOR<OBJECT *> *foo; PVECTOR<STDFILE *> *goo;
gpl-2.0