repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
maisem/kubernetes
pkg/util/dbus/fake_dbus.go
3738
/* Copyright 2015 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 dbus import ( "fmt" "sync" godbus "github.com/godbus/dbus" ) // Fake is a simple fake Interface type. type Fake struct { systemBus *FakeConnection sessionBus *FakeConnection } // FakeConnection represents a fake D-Bus connection type FakeConnection struct { lock sync.Mutex busObject *fakeObject objects map[string]*fakeObject signalHandlers []chan<- *godbus.Signal } // FakeHandler is used to handle fake D-Bus method calls type FakeHandler func(method string, args ...interface{}) ([]interface{}, error) type fakeObject struct { handler FakeHandler } type fakeCall struct { ret []interface{} err error } // NewFake returns a new Interface which will fake talking to D-Bus func NewFake(systemBus *FakeConnection, sessionBus *FakeConnection) *Fake { return &Fake{systemBus, sessionBus} } // NewFakeConnection returns a FakeConnection Interface func NewFakeConnection() *FakeConnection { return &FakeConnection{ objects: make(map[string]*fakeObject), } } // SystemBus is part of Interface func (db *Fake) SystemBus() (Connection, error) { if db.systemBus != nil { return db.systemBus, nil } return nil, fmt.Errorf("DBus is not running") } // SessionBus is part of Interface func (db *Fake) SessionBus() (Connection, error) { if db.sessionBus != nil { return db.sessionBus, nil } return nil, fmt.Errorf("DBus is not running") } // BusObject is part of the Connection interface func (conn *FakeConnection) BusObject() Object { return conn.busObject } // Object is part of the Connection interface func (conn *FakeConnection) Object(name, path string) Object { return conn.objects[name+path] } // Signal is part of the Connection interface func (conn *FakeConnection) Signal(ch chan<- *godbus.Signal) { conn.lock.Lock() defer conn.lock.Unlock() for i := range conn.signalHandlers { if conn.signalHandlers[i] == ch { conn.signalHandlers = append(conn.signalHandlers[:i], conn.signalHandlers[i+1:]...) return } } conn.signalHandlers = append(conn.signalHandlers, ch) } // SetBusObject sets the handler for the BusObject of conn func (conn *FakeConnection) SetBusObject(handler FakeHandler) { conn.busObject = &fakeObject{handler} } // AddObject adds a handler for the Object at name and path func (conn *FakeConnection) AddObject(name, path string, handler FakeHandler) { conn.objects[name+path] = &fakeObject{handler} } // EmitSignal emits a signal on conn func (conn *FakeConnection) EmitSignal(name, path, iface, signal string, args ...interface{}) { conn.lock.Lock() defer conn.lock.Unlock() sig := &godbus.Signal{ Sender: name, Path: godbus.ObjectPath(path), Name: iface + "." + signal, Body: args, } for _, ch := range conn.signalHandlers { ch <- sig } } // Call is part of the Object interface func (obj *fakeObject) Call(method string, flags godbus.Flags, args ...interface{}) Call { ret, err := obj.handler(method, args...) return &fakeCall{ret, err} } // Store is part of the Call interface func (call *fakeCall) Store(retvalues ...interface{}) error { if call.err != nil { return call.err } return godbus.Store(call.ret, retvalues...) }
apache-2.0
shimingsg/corefx
src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterManager.cs
1236
// 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; namespace System.Diagnostics { public sealed class PerformanceCounterManager : ICollectData { [ObsoleteAttribute("This class has been deprecated. Use the PerformanceCounters through the System.Diagnostics.PerformanceCounter class instead. https://go.microsoft.com/fwlink/?linkid=14202")] public PerformanceCounterManager() { } [ObsoleteAttribute("This class has been deprecated. Use the PerformanceCounters through the System.Diagnostics.PerformanceCounter class instead. https://go.microsoft.com/fwlink/?linkid=14202")] void ICollectData.CollectData(int callIdx, IntPtr valueNamePtr, IntPtr dataPtr, int totalBytes, out IntPtr res) { res = (IntPtr)(-1); } [ObsoleteAttribute("This class has been deprecated. Use the PerformanceCounters through the System.Diagnostics.PerformanceCounter class instead. https://go.microsoft.com/fwlink/?linkid=14202")] void ICollectData.CloseData() { } } }
mit
mdolian/sugarcrm_dev
include/database/DBHelper.php
3068
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected]. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ /********************************************************************************* * Description: The functionality of the abstract DBHelper class has been moved to DBManager and * its database specific derivatives. This class is no longer used and no code should be added * this file or reference anything in this class. The sole purpose of keeping this class as * an empty, deprecated and final class is to cause a conflict when merging functionality or bug fixes * from upstream projects. MERGE CONFLICTS should be resolved by inspecting DBManager and derivatives * for similar fixes and if none exist by porting the changes from DBHelper to DBManager or its derivatives. * * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. * All Rights Reserved. * Contributor(s): ______________________________________.. ********************************************************************************/ /** * @deprecated * @internal */ final class DBHelper { } ?>
agpl-3.0
apixandru/intellij-community
plugins/InspectionGadgets/test/com/siyeh/igtest/bugs/class_new_instance/ClassNewInstance.java
592
package com.siyeh.igtest.bugs.class_new_instance; public class ClassNewInstance { void good() throws IllegalAccessException, InstantiationException { String.class.<warning descr="Call to 'newInstance()' may throw undeclared checked exceptions">newInstance</warning>(); } Object newInstance() { return null; } void bad() { newInstance(); } void alsoBad(Class<XX> xx) throws IllegalAccessException { xx.<warning descr="Call to 'newInstance()' may throw undeclared checked exceptions">newInstance</warning>(); } } class XX {}
apache-2.0
huangzl233/zxing
core/src/main/java/com/google/zxing/oned/UPCEReader.java
4628
/* * Copyright 2008 ZXing 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 com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * <p>Implements decoding of the UPC-E format.</p> * <p><a href="http://www.barcodeisland.com/upce.phtml">This</a> is a great reference for * UPC-E information.</p> * * @author Sean Owen */ public final class UPCEReader extends UPCEANReader { /** * The pattern that marks the middle, and end, of a UPC-E pattern. * There is no "second half" to a UPC-E barcode. */ private static final int[] MIDDLE_END_PATTERN = {1, 1, 1, 1, 1, 1}; /** * See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of * even-odd parity encodings of digits that imply both the number system (0 or 1) * used, and the check digit. */ private static final int[][] NUMSYS_AND_CHECK_DIGIT_PATTERNS = { {0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25}, {0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A} }; private final int[] decodeMiddleCounters; public UPCEReader() { decodeMiddleCounters = new int[4]; } @Override protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder result) throws NotFoundException { int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; int lgPatternFound = 0; for (int x = 0; x < 6 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); result.append((char) ('0' + bestMatch % 10)); for (int counter : counters) { rowOffset += counter; } if (bestMatch >= 10) { lgPatternFound |= 1 << (5 - x); } } determineNumSysAndCheckDigit(result, lgPatternFound); return rowOffset; } @Override protected int[] decodeEnd(BitArray row, int endStart) throws NotFoundException { return findGuardPattern(row, endStart, true, MIDDLE_END_PATTERN); } @Override protected boolean checkChecksum(String s) throws FormatException { return super.checkChecksum(convertUPCEtoUPCA(s)); } private static void determineNumSysAndCheckDigit(StringBuilder resultString, int lgPatternFound) throws NotFoundException { for (int numSys = 0; numSys <= 1; numSys++) { for (int d = 0; d < 10; d++) { if (lgPatternFound == NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]) { resultString.insert(0, (char) ('0' + numSys)); resultString.append((char) ('0' + d)); return; } } } throw NotFoundException.getNotFoundInstance(); } @Override BarcodeFormat getBarcodeFormat() { return BarcodeFormat.UPC_E; } /** * Expands a UPC-E value back into its full, equivalent UPC-A code value. * * @param upce UPC-E code as string of digits * @return equivalent UPC-A code as string of digits */ public static String convertUPCEtoUPCA(String upce) { char[] upceChars = new char[6]; upce.getChars(1, 7, upceChars, 0); StringBuilder result = new StringBuilder(12); result.append(upce.charAt(0)); char lastChar = upceChars[5]; switch (lastChar) { case '0': case '1': case '2': result.append(upceChars, 0, 2); result.append(lastChar); result.append("0000"); result.append(upceChars, 2, 3); break; case '3': result.append(upceChars, 0, 3); result.append("00000"); result.append(upceChars, 3, 2); break; case '4': result.append(upceChars, 0, 4); result.append("00000"); result.append(upceChars[4]); break; default: result.append(upceChars, 0, 5); result.append("0000"); result.append(lastChar); break; } result.append(upce.charAt(7)); return result.toString(); } }
apache-2.0
fitermay/intellij-community
plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/replace_with_add_all/SimpleFor.after.java
112
import java.util.*; class T { void f(Set<String> t, String[] f) { Collections.addAll(t, f); } }
apache-2.0
kidebit/https-github.com-wicedfast-appinventor-sources
appinventor/components/tests/com/google/appinventor/components/runtime/WebTest.java
7639
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.components.runtime; import com.google.appinventor.components.runtime.util.ErrorMessages; import com.google.appinventor.components.runtime.util.YailList; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; /** * Tests Web.java. * * @author [email protected] (Liz Looney) */ public class WebTest extends TestCase { private Web web; @Override protected void setUp() throws Exception { web = new Web(); } public void testDecodeJsonText() throws Exception { // String values. assertEquals("\t tab \t tab \t", web.decodeJsonText("\"\\t tab \\t tab \\t\"")); assertEquals("\n newline \n newline \n", web.decodeJsonText("\"\\n newline \\n newline \\n\"")); assertEquals("/ slash / slash /", web.decodeJsonText("\"\\/ slash \\/ slash \\/\"")); assertEquals("\\ backslash \\ backslash \\", web.decodeJsonText("\"\\\\ backslash \\\\ backslash \\\\\"")); assertEquals("\" quote \" quote \"", web.decodeJsonText("\"\\\" quote \\\" quote \\\"\"")); assertEquals("~ encoded tilda ~ encoded tilda ~", web.decodeJsonText("\"\\u007E encoded tilda \\u007E encoded tilda \\u007E\"")); assertEquals("A normal string without quotes.", web.decodeJsonText("A normal string without quotes.")); // Boolean values. assertEquals(Boolean.TRUE, web.decodeJsonText("True")); assertEquals(Boolean.FALSE, web.decodeJsonText("False")); // Numeric values. assertEquals(new Integer(1), web.decodeJsonText("1")); assertEquals(new Double(57.43), web.decodeJsonText("57.43")); // A JSON encoded object. Object decodedObject = web.decodeJsonText("{\"YaVersion\":\"41\",\"Source\":\"Form\"}"); assertTrue(decodedObject instanceof ArrayList); ArrayList outerList = (ArrayList) decodedObject; assertEquals(2, outerList.size()); // The items are sorted by the field name, so Source comes before YaVersion Object item0 = outerList.get(0); assertTrue(item0 instanceof ArrayList); ArrayList firstNameValuePair = (ArrayList) item0; assertEquals(2, firstNameValuePair.size()); assertEquals("Source", firstNameValuePair.get(0)); assertEquals("Form", firstNameValuePair.get(1)); Object item1 = outerList.get(1); assertTrue(item1 instanceof ArrayList); ArrayList secondNameValuePair = (ArrayList) item1; assertEquals(2, secondNameValuePair.size()); assertEquals("YaVersion", secondNameValuePair.get(0)); assertEquals("41", secondNameValuePair.get(1)); // A JSON encoded array. Object decodedArray = web.decodeJsonText("[\"Billy\",\"Sam\",\"Bobby\",\"Fred\"]"); assertTrue(decodedArray instanceof ArrayList); ArrayList list = (ArrayList) decodedArray; assertEquals(4, list.size()); assertEquals("Billy", list.get(0)); assertEquals("Sam", list.get(1)); assertEquals("Bobby", list.get(2)); assertEquals("Fred", list.get(3)); try { web.decodeJsonText("{\"not\":\"valid\":\"json\"}"); fail(); } catch (IllegalArgumentException e) { // Expected. } } public void testDecodeXMLText() throws Exception { Object decodedObject = web.XMLTextDecode("<foo>123</foo>"); // should be the list of one element, which is a pair of "foo" and 123 assertTrue(decodedObject instanceof ArrayList); ArrayList outerList = (ArrayList) decodedObject; assertEquals(1, outerList.size()); Object pairObject = outerList.get(0); assertTrue(pairObject instanceof ArrayList); ArrayList pair = (ArrayList) pairObject; assertEquals(2, pair.size()); assertEquals("foo", pair.get(0)); // check why this isn't actually the string 123 assertEquals(123, pair.get(1)); } public void testDecodeXMLText2() throws Exception { Object decodedObject = web.XMLTextDecode("<a><foo>1 2 3</foo><bar>456</bar></a>"); // should be the list of one element, which is a pair of "a" and a list X. // X is a list two pairs. The first pair is "bar" and 456 and the second pair is // "foo" and the string "1 2 3". // The order of these is bar before foo because it's alphabetical by according to // the tags. assertTrue(decodedObject instanceof ArrayList); ArrayList outerList = (ArrayList) decodedObject; assertEquals(1, outerList.size()); Object pairObject = outerList.get(0); assertTrue(pairObject instanceof ArrayList); ArrayList pair = (ArrayList) pairObject; assertEquals(2, pair.size()); assertEquals("a", pair.get(0)); Object XObject = pair.get(1); assertTrue(XObject instanceof ArrayList); ArrayList X = (ArrayList) XObject; assertEquals(2, X.size()); Object firstPairObject = X.get(0); Object secondPairObject = X.get(1); assertTrue(firstPairObject instanceof ArrayList); assertTrue(secondPairObject instanceof ArrayList); ArrayList firstPair = (ArrayList) firstPairObject; ArrayList secondPair = (ArrayList) secondPairObject; assertEquals("bar", firstPair.get(0)); assertEquals(456, firstPair.get(1)); assertEquals("foo", secondPair.get(0)); assertEquals("1 2 3", secondPair.get(1)); } public void testbuildRequestData() throws Exception { List<Object> list = new ArrayList<Object>(); list.add(YailList.makeList(new String[] { "First Name", "Barack" })); list.add(YailList.makeList(new String[] { "Last Name", "Obama" })); list.add(YailList.makeList(new String[] { "Title", "President of the United States" })); assertEquals("First+Name=Barack&Last+Name=Obama&Title=President+of+the+United+States", web.buildRequestData(YailList.makeList(list))); list.clear(); list.add(YailList.makeList(new String[] { "First Name", "Barack" })); list.add("This is not a list!"); list.add(YailList.makeList(new String[] { "Last Name", "Obama" })); list.add(YailList.makeList(new String[] { "Title", "President of the United States" })); try { web.buildRequestData(YailList.makeList(list)); fail(); } catch (Web.BuildRequestDataException e) { assertEquals(ErrorMessages.ERROR_WEB_BUILD_REQUEST_DATA_NOT_LIST, e.errorNumber); assertEquals(2, e.index); } list.clear(); list.add(YailList.makeList(new String[] { "First Name", "Barack" })); list.add(YailList.makeList(new String[] { "Last Name", "Obama" })); list.add(YailList.makeList(new String[] { "Title", "President of the United States", "This list has too many items" })); try { web.buildRequestData(YailList.makeList(list)); fail(); } catch (Web.BuildRequestDataException e) { assertEquals(ErrorMessages.ERROR_WEB_BUILD_REQUEST_DATA_NOT_TWO_ELEMENTS, e.errorNumber); assertEquals(3, e.index); } list.clear(); list.add(YailList.makeList(new String[] { "First Name", "Barack" })); list.add(YailList.makeList(new String[] { "Last Name", "Obama" })); list.add(YailList.makeList(new String[] { "Title", "President of the United States" })); list.add(YailList.makeList(new String[] { "This list has too few items" })); try { web.buildRequestData(YailList.makeList(list)); fail(); } catch (Web.BuildRequestDataException e) { assertEquals(ErrorMessages.ERROR_WEB_BUILD_REQUEST_DATA_NOT_TWO_ELEMENTS, e.errorNumber); assertEquals(4, e.index); } } }
apache-2.0
aiunderstand/vive-unity-farmhack
Assets/Packages/SteamVR/InteractionSystem/Core/Scripts/ItemPackageReference.cs
493
//======= Copyright (c) Valve Corporation, All rights reserved. =============== // // Purpose: Keeps track of the ItemPackage this object is a part of // //============================================================================= using UnityEngine; using System.Collections; namespace Valve.VR.InteractionSystem { //------------------------------------------------------------------------- public class ItemPackageReference : MonoBehaviour { public ItemPackage itemPackage; } }
mit
Raegann/p20
wp-content/plugins/the-events-calendar/src/Tribe/Event_Tickets/Main.php
2051
<?php /** * The Events Calendar integration with Event Tickets class * * @package The Events Calendar * @subpackage Event Tickets * @since 4.0.1 */ class Tribe__Events__Event_Tickets__Main { /** * Private variable holding the class instance * * @since 4.0.1 * * @var Tribe__Events__Event_Tickets__Main */ private static $instance; /** * Contains an instance of the Attendees Report integration class * * @since 4.0.1 * * @var Tribe__Events__Event_Tickets__Attendees_Report */ private $attendees_report; /** * Contains an instance of the Ticket Email integration class * * @since 4.0.2 * * @var Tribe__Events__Event_Tickets__Ticket_Email */ private $ticket_email; /** * Method to return the private instance of the class * * @since 4.0.1 * * @return Tribe__Events__Event_Tickets__Main */ public static function instance() { if ( ! self::$instance ) { self::$instance = new self; } return self::$instance; } /** * Constructor */ public function __construct() { $this->attendees_report(); $this->ticket_email(); } /** * Attendees Report integration class object accessor method * * @since 4.0.1 * * @param object $object Override Attendees Report object * @return Tribe__Events__Event_Tickets__Attendees_Report */ public function attendees_report( $object = null ) { if ( $object ) { $this->attendees_report = $object; } elseif ( ! $this->attendees_report ) { $this->attendees_report = new Tribe__Events__Event_Tickets__Attendees_Report; } return $this->attendees_report; } /** * Ticket email integration class object accessor method * * @since 4.0.2 * * @param object $object Override Ticket Email object * @return Tribe__Events__Event_Tickets__Ticket_Email */ public function ticket_email( $object = null ) { if ( $object ) { $this->ticket_email = $object; } elseif ( ! $this->ticket_email ) { $this->ticket_email = new Tribe__Events__Event_Tickets__Ticket_Email; } return $this->ticket_email; } }
gpl-2.0
alexmojaki/cdnjs
ajax/libs/numbro/1.1.1/min/languages/zh-CN.min.js
658
/*! * numbro.js language configuration * language : simplified chinese * author : badplum : https://github.com/badplum */ !function(){var a={delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"千",million:"百万",billion:"十亿",trillion:"兆"},ordinal:function(a){return"."},currency:{symbol:"¥",position:"prefix"},defaults:{currencyFormat:",0000 a"},formats:{fourDigits:"0000 a",fullWithTwoDecimals:"$ ,0.00",fullWithTwoDecimalsNoCurrency:",0.00",fullWithNoDecimals:"$ ,0"}};"undefined"!=typeof module&&module.exports&&(module.exports=a),"undefined"!=typeof window&&this.numbro&&this.numbro.language&&this.numbro.language("zh-CN",a)}();
mit
rolandzwaga/DefinitelyTyped
types/rpio/index.d.ts
12594
// Type definitions for node-rpio // Project: https://github.com/jperkin/node-rpio // Definitions by: Dominik Palo <https://github.com/DominikPalo> // Hannes Früchtenicht <https://github.com/Pencl> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> declare var rpio: Rpio; declare module 'rpio' { export = rpio; } interface Rpio { /** * Initialise the bcm2835 library. This will be called automatically by .open() using the default option values if not called explicitly. * @param options */ init(options: RPIO.Options): void; /** * Open a pin for input or output. Valid modes are: * INPUT: pin is input (read-only). * OUTPUT: pin is output (read-write). * PWM: configure pin for hardware PWM. * * For input pins, option can be used to configure the internal pullup or pulldown resistors using options as described in the .pud() documentation below. * * For output pins, option defines the initial isMotionDetected of the pin, rather than having to issue a separate .write() call. This can be critical for devices which must have a stable value, rather than relying on the initial floating value when a pin is enabled for output but hasn't yet been configured with a value. * @param pin * @param mode * @param options */ open(pin: number, mode: number, options?: number): void; /** * Switch a pin that has already been opened in one mode to a different mode. * This is provided primarily for performance reasons, as it avoids some of the setup work done by .open(). * @param pin * @param mode */ mode(pin: number, mode: number): void; /** * Read the current value of pin, returning either 1 (high) or 0 (low). * @param pin */ read(pin: number): number; /** * Read length bits from pin into buffer as fast as possible. If length isn't specified it defaults to buffer.length. * @param pin * @param buffer * @param length */ readbuf(pin: number, buffer: Buffer, length?: number): void; /** * Set the specified pin either high or low, using either the HIGH/LOW constants, or simply 1 or 0. * @param pin * @param value */ write(pin: number, value: number): void; /** * Write length bits to pin from buffer as fast as possible. If length isn't specified it defaults to buffer.length. * @param pin * @param buffer * @param length */ writebuf(pin: number, buffer: Buffer, length?: number): void; /** * Read the current isMotionDetected of the GPIO pad control for the specified GPIO group. On current models of Raspberry Pi there are three groups with corresponding defines: * PAD_GROUP_0_27: GPIO0 - GPIO27. Use this for the main GPIO header. * PAD_GROUP_28_45: GPIO28 - GPIO45. Use this to configure the P5 header. * PAD_GROUP_46_53: GPIO46 - GPIO53. Internal, you probably won't need this. * * The value returned will be a bit mask of the following defines: * PAD_SLEW_UNLIMITED: 0x10. Slew rate unlimited if set. * PAD_HYSTERESIS: 0x08. Hysteresis is enabled if set. * * The bottom three bits determine the drive current: * PAD_DRIVE_2mA: 0b000 * PAD_DRIVE_4mA: 0b001 * PAD_DRIVE_6mA: 0b010 * PAD_DRIVE_8mA: 0b011 * PAD_DRIVE_10mA: 0b100 * PAD_DRIVE_12mA: 0b101 * PAD_DRIVE_14mA: 0b110 * PAD_DRIVE_16mA: 0b111 * * @note Note that the pad control registers are not available via /dev/gpiomem, so you will need to use .init({gpiomem: false}) and run as root. * @param group */ readpad(group: number): number; /** * Write control settings to the pad control for group. Uses the same defines as above for .readpad(). * @param group * @param control */ writepad(group: number, control: number): void; /** * Configure the pin's internal pullup or pulldown resistors, using the following isMotionDetected constants: * PULL_OFF: disable configured resistors. * PULL_DOWN: enable the pulldown resistor. * PULL_UP: enable the pullup resistor. * * @param pin * @param state */ pud(pin: number, state: number): void; /** * Watch pin for changes and execute the callback cb() on events. cb() takes a single argument, the pin which triggered the callback. * * The optional direction argument can be used to watch for specific events: * POLL_LOW: poll for falling edge transitions to low. * POLL_HIGH: poll for rising edge transitions to high. * POLL_BOTH: poll for both transitions (the default). * * Due to hardware/kernel limitations we can only poll for changes, and the event detection only says that an event occurred, not which one. The poll interval is a 1ms setInterval() and transitions could come in between detecting the event and reading the value. Therefore this interface is only useful for events which transition slower than approximately 1kHz. * * To stop watching for pin changes, call .poll() again, setting the callback to null. * @param pin * @param cb * @param direction */ poll(pin: number, cb: RPIO.CallbackFunction | null, direction?: number): void; /** * Reset pin to INPUT and clear any pullup/pulldown resistors and poll events. * @param pin */ close(pin: number): void; // I²C /** * Assign pins 3 and 5 to i²c use. Until .i2cEnd() is called they won't be available for GPIO use. * * The pin assignments are: * Pin 3: SDA (Serial Data) * Pin 5: SCL (Serial Clock) */ i2cBegin(): void; /** * Configure the slave address. This is between 0 - 0x7f, and it can be helpful to * run the i2cdetect program to figure out where your devices are if you are unsure. * @param address */ i2cSetSlaveAddress(address: number): void; /** * Set the baud rate - directly set the speed in hertz. * @param baudRate */ i2cSetBaudRate(baudRate: number): void; /** * Read from the i²c slave. * Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified. * @param buffer * @param length */ i2cRead(buffer: Buffer, length?: number): void; /** * Write to the i²c slave. * Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified. * @param biffer * @param length */ i2cWrite(biffer: Buffer, length?: number): void; /** * Set the baud rate - based on a divisor of the base 250MHz rate. * @param clockDivider */ i2cSetClockDivider(clockDivider: number): void; /** * Turn off the i²c interface and return the pins to GPIO. */ i2cEnd(): void; // PWM /** * Set the PWM refresh rate. * @param clockDivider: power-of-two divisor of the base 19.2MHz rate, with a maximum value of 4096 (4.6875kHz). */ pwmSetClockDivider(clockDivider: number): void; /** * Set the PWM range for a pin. This determines the maximum pulse width. * @param pin * @param range */ pwmSetRange(pin: number, range: number): void; /** * Set the PWM width for a pin. * @param pin * @param data */ pwmSetData(pin: number, data: number): void; // SPI /** * Switch pins 119, 21, 23, 24 and 25 (GPIO7-GPIO11) to SPI mode * * Pin | Function * -----|---------- * 19 | MOSI * 21 | MISO * 23 | SCLK * 24 | CE0 * 25 | CE1 */ spiBegin(): void; /** * Choose which of the chip select / chip enable pins to control. * * Value | Pin * ------|--------------------- * 0 | SPI_CE0 (24 / GPIO8) * 1 | SPI_CE1 (25 / GPIO7) * 2 | Both * * @param chip */ spiChipSelect(cePin: number): void; /** * Commonly chip enable (CE) pins are active low, and this is the default. * If your device's CE pin is active high, use spiSetCSPolarity() to change the polarity. * @param cePin * @param polarity */ spiSetCSPolarity(cePin: number, polarity: number): void; /** * Set the SPI clock speed with. * @param clockDivider: an even divisor of the base 250MHz rate ranging between 0 and 65536. */ spiSetClockDivider(clockDivider: number): void; /** * Transfer data. Data is sent and received in 8-bit chunks via buffers which should be the same size. * @param txBuffer * @param rxBuffer * @param txLength */ spiTransfer(txBuffer: Buffer, rxBuffer: Buffer, txLength: number): void; /** * Send data and do not care about the data coming back. * @param txBuffer * @param txLength */ spiWrite(txBuffer: Buffer, txLength: number): void; /** * Release the pins back to general purpose use. */ spiEnd(): void; // Misc /** * Sleep for n seconds. * @param n: number of seconds to sleep */ sleep(n: number): void; /** * Sleep for n milliseconds. * @param n: number of milliseconds to sleep */ msleep(n: number): void; /** * Sleep for n microseconds. * @param n: number of microseconds to sleep */ usleep(n: number): void; // Constants: HIGH: number; LOW: number; INPUT: number; OUTPUT: number; PWM: number; PULL_OFF: number; PULL_DOWN: number; PULL_UP: number; PAD_GROUP_0_27: number; PAD_GROUP_28_45: number; PAD_GROUP_46_53: number; PAD_SLEW_UNLIMITED: number; PAD_HYSTERESIS: number; PAD_DRIVE_2mA: number; PAD_DRIVE_4mA: number; PAD_DRIVE_6mA: number; PAD_DRIVE_8mA: number; PAD_DRIVE_10mA: number; PAD_DRIVE_12mA: number; PAD_DRIVE_14mA: number; PAD_DRIVE_16mA: number; POLL_LOW: number; POLL_HIGH: number; POLL_BOTH: number; } declare namespace RPIO { interface Options { /** * There are two device nodes for GPIO access. The default is /dev/gpiomem which, when configured with gpio group access, allows users in that group to read/write directly to that device. This removes the need to run as root, but is limited to GPIO functions. * For non-GPIO functions (i²c, PWM, SPI) the /dev/mem device is required for full access to the Broadcom peripheral address range and the program needs to be executed as the root user (e.g. via sudo). If you do not explicitly call .init() when using those functions, the library will do it for you with gpiomem: false. * You may also need to use gpiomem: false if you are running on an older Linux kernel which does not support the gpiomem module. * rpio will throw an exception if you try to use one of the non-GPIO functions after already opening with /dev/gpiomem, as well as checking to see if you have the necessary permissions. * * Valid options: * true: use /dev/gpiomem for non-root but GPIO-only access * false: use /dev/mem for full access but requires root */ gpiomem?: boolean; /** * There are two naming schemes when referring to GPIO pins: * By their physical header location: Pins 1 to 26 (A/B) or Pins 1 to 40 (A+/B+) * Using the Broadcom hardware map: GPIO 0-25 (B rev1), GPIO 2-27 (A/B rev2, A+/B+) * * Confusingly however, the Broadcom GPIO map changes between revisions, so for example P3 maps to GPIO0 on Model B Revision 1 models, but maps to GPIO2 on all later models. * This means the only sane default mapping is the physical layout, so that the same code will work on all models regardless of the underlying GPIO mapping. * If you prefer to use the Broadcom GPIO scheme for whatever reason (e.g. to use the P5 header pins on the Raspberry Pi 1 revision 2.0 model which aren't currently mapped to the physical layout), you can set mapping to gpio to switch to the GPIOxx naming. * * Valid options: * gpio: use the Broadcom GPIOxx naming * physical: use the physical P01-P40 header layou */ mapping?: "gpio" | "physical"; } interface CallbackFunction { /** * @param pin: The pin which triggered the callback. */ (pin: number): void; } }
mit
mohitsethi/fog
lib/fog/cloudstack/requests/compute/configure_netscaler_load_balancer.rb
689
module Fog module Compute class Cloudstack class Real # configures a netscaler load balancer device # # {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.4/root_admin/configureNetscalerLoadBalancer.html] def configure_netscaler_load_balancer(*args) options = {} if args[0].is_a? Hash options = args[0] options.merge!('command' => 'configureNetscalerLoadBalancer') else options.merge!('command' => 'configureNetscalerLoadBalancer', 'lbdeviceid' => args[0]) end request(options) end end end end end
mit
lucianobapo/phpMyAdmin-4.5.0-beta1-all-languages
libraries/sql-parser/autoload.php
1358
<?php /** * The autoloader used for loading sql-parser's components. * * This file is based on Composer's autoloader. * * (c) Nils Adermann <[email protected]> * Jordi Boggiano <[email protected]> * * @package SqlParser * @subpackage Autoload */ namespace SqlParser\Autoload; if (!class_exists('SqlParser\\Autoload\\ClassLoader')) { include_once './libraries/sql-parser/ClassLoader.php'; } use SqlParser\Autoload\ClassLoader; /** * Initializes the autoloader. * * @package SqlParser * @subpackage Autoload */ class AutoloaderInit { /** * The loader instance. * * @var ClassLoader */ public static $loader; /** * Constructs and returns the class loader. * * @param array $map Array containing path to each namespace. * * @return ClassLoader */ public static function getLoader(array $map) { if (null !== self::$loader) { return self::$loader; } self::$loader = $loader = new ClassLoader(); foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $loader->register(true); return $loader; } } // Initializing the autoloader. return AutoloaderInit::getLoader( array( 'SqlParser\\' => array(dirname(__FILE__) . '/src'), ) );
gpl-2.0
strapdata/cassandra
src/java/org/apache/cassandra/utils/WrappedBoolean.java
1175
/* * 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.cassandra.utils; /** * Simple wrapper for native boolean type */ public class WrappedBoolean { private boolean value; public WrappedBoolean(boolean initial) { this.value = initial; } public boolean get() { return value; } public void set(boolean value) { this.value = value; } }
apache-2.0
gressole/Werewolf
Werewolf for Telegram/Werewolf Website/plugins/slider.revolution.v5/js/extensions/source/revolution.extension.navigation.js
41407
/******************************************** * REVOLUTION 5.2 EXTENSION - NAVIGATION * @version: 1.2.4 (10.03.2016) * @requires jquery.themepunch.revolution.js * @author ThemePunch *********************************************/ (function($) { var _R = jQuery.fn.revolution, _ISM = _R.is_mobile(); /////////////////////////////////////////// // EXTENDED FUNCTIONS AVAILABLE GLOBAL // /////////////////////////////////////////// jQuery.extend(true,_R, { hideUnHideNav : function(opt) { var w = opt.c.width(), a = opt.navigation.arrows, b = opt.navigation.bullets, c = opt.navigation.thumbnails, d = opt.navigation.tabs; if (ckNO(a)) biggerNav(opt.c.find('.tparrows'),a.hide_under,w,a.hide_over); if (ckNO(b)) biggerNav(opt.c.find('.tp-bullets'),b.hide_under,w,b.hide_over); if (ckNO(c)) biggerNav(opt.c.parent().find('.tp-thumbs'),c.hide_under,w,c.hide_over); if (ckNO(d)) biggerNav(opt.c.parent().find('.tp-tabs'),d.hide_under,w,d.hide_over); setONHeights(opt); }, resizeThumbsTabs : function(opt,force) { if ((opt.navigation && opt.navigation.tabs.enable) || (opt.navigation && opt.navigation.thumbnails.enable)) { var f = (jQuery(window).width()-480) / 500, tws = new punchgs.TimelineLite(), otab = opt.navigation.tabs, othu = opt.navigation.thumbnails, otbu = opt.navigation.bullets; tws.pause(); f = f>1 ? 1 : f<0 ? 0 : f; if (ckNO(otab) && (force || otab.width>otab.min_width)) rtt(f,tws,opt.c,otab,opt.slideamount,'tab'); if (ckNO(othu) && (force || othu.width>othu.min_width)) rtt(f,tws,opt.c,othu,opt.slideamount,'thumb'); if (ckNO(otbu) && force) { // SET BULLET SPACES AND POSITION var bw = opt.c.find('.tp-bullets'); bw.find('.tp-bullet').each(function(i){ var b = jQuery(this), am = i+1, w = b.outerWidth()+parseInt((otbu.space===undefined? 0:otbu.space),0), h = b.outerHeight()+parseInt((otbu.space===undefined? 0:otbu.space),0); if (otbu.direction==="vertical") { b.css({top:((am-1)*h)+"px", left:"0px"}); bw.css({height:(((am-1)*h) + b.outerHeight()),width:b.outerWidth()}); } else { b.css({left:((am-1)*w)+"px", top:"0px"}); bw.css({width:(((am-1)*w) + b.outerWidth()),height:b.outerHeight()}); } }); } tws.play(); setONHeights(opt); } return true; }, updateNavIndexes : function(opt) { var _ = opt.c; function setNavIndex(a) { if (_.find(a).lenght>0) { _.find(a).each(function(i) { jQuery(this).data('liindex',i); }) } } setNavIndex('.tp-tab'); setNavIndex('.tp-bullet'); setNavIndex('.tp-thumb'); _R.resizeThumbsTabs(opt,true); _R.manageNavigation(opt); }, // PUT NAVIGATION IN POSITION AND MAKE SURE THUMBS AND TABS SHOWING TO THE RIGHT POSITION manageNavigation : function(opt) { var lof = _R.getHorizontalOffset(opt.c.parent(),"left"), rof = _R.getHorizontalOffset(opt.c.parent(),"right"); if (ckNO(opt.navigation.bullets)) { if (opt.sliderLayout!="fullscreen" && opt.sliderLayout!="fullwidth") { // OFFSET ADJUSTEMENT FOR LEFT ARROWS BASED ON THUMBNAILS AND TABS OUTTER opt.navigation.bullets.h_offset_old = opt.navigation.bullets.h_offset_old === undefined ? opt.navigation.bullets.h_offset : opt.navigation.bullets.h_offset_old; opt.navigation.bullets.h_offset = opt.navigation.bullets.h_align==="center" ? opt.navigation.bullets.h_offset_old+lof/2 -rof/2: opt.navigation.bullets.h_offset_old+lof-rof; } setNavElPositions(opt.c.find('.tp-bullets'),opt.navigation.bullets,opt); } if (ckNO(opt.navigation.thumbnails)) setNavElPositions(opt.c.parent().find('.tp-thumbs'),opt.navigation.thumbnails,opt); if (ckNO(opt.navigation.tabs)) setNavElPositions(opt.c.parent().find('.tp-tabs'),opt.navigation.tabs,opt); if (ckNO(opt.navigation.arrows)) { if (opt.sliderLayout!="fullscreen" && opt.sliderLayout!="fullwidth") { // OFFSET ADJUSTEMENT FOR LEFT ARROWS BASED ON THUMBNAILS AND TABS OUTTER opt.navigation.arrows.left.h_offset_old = opt.navigation.arrows.left.h_offset_old === undefined ? opt.navigation.arrows.left.h_offset : opt.navigation.arrows.left.h_offset_old; opt.navigation.arrows.left.h_offset = opt.navigation.arrows.left.h_align==="right" ? opt.navigation.arrows.left.h_offset_old+rof : opt.navigation.arrows.left.h_offset_old+lof; opt.navigation.arrows.right.h_offset_old = opt.navigation.arrows.right.h_offset_old === undefined ? opt.navigation.arrows.right.h_offset : opt.navigation.arrows.right.h_offset_old; opt.navigation.arrows.right.h_offset = opt.navigation.arrows.right.h_align==="right" ? opt.navigation.arrows.right.h_offset_old+rof : opt.navigation.arrows.right.h_offset_old+lof; } setNavElPositions(opt.c.find('.tp-leftarrow.tparrows'),opt.navigation.arrows.left,opt); setNavElPositions(opt.c.find('.tp-rightarrow.tparrows'),opt.navigation.arrows.right,opt); } if (ckNO(opt.navigation.thumbnails)) moveThumbsInPosition(opt.c.parent().find('.tp-thumbs'),opt.navigation.thumbnails); if (ckNO(opt.navigation.tabs)) moveThumbsInPosition(opt.c.parent().find('.tp-tabs'),opt.navigation.tabs); }, // MANAGE THE NAVIGATION createNavigation : function(container,opt) { var cp = container.parent(), _a = opt.navigation.arrows, _b = opt.navigation.bullets, _c = opt.navigation.thumbnails, _d = opt.navigation.tabs, a = ckNO(_a), b = ckNO(_b), c = ckNO(_c), d = ckNO(_d); // Initialise Keyboard Navigation if Option set so initKeyboard(container,opt); // Initialise Mouse Scroll Navigation if Option set so initMouseScroll(container,opt); //Draw the Arrows if (a) initArrows(container,_a,opt); // BUILD BULLETS, THUMBS and TABS opt.li.each(function(index) { var li_rtl = jQuery(opt.li[opt.li.length-1-index]); var li = jQuery(this); if (b) if (opt.navigation.bullets.rtl) addBullet(container,_b,li_rtl,opt); else addBullet(container,_b,li,opt); if (c) if (opt.navigation.thumbnails.rtl) addThumb(container,_c,li_rtl,'tp-thumb',opt); else addThumb(container,_c,li,'tp-thumb',opt); if (d) if (opt.navigation.tabs.rtl) addThumb(container,_d,li_rtl,'tp-tab',opt); else addThumb(container,_d,li,'tp-tab',opt); }); // LISTEN TO SLIDE CHANGE - SET ACTIVE SLIDE BULLET container.bind('revolution.slide.onafterswap revolution.nextslide.waiting',function() { //cp.find('.tp-bullet, .tp-thumb, .tp-tab').removeClass("selected"); var si = container.find(".next-revslide").length==0 ? container.find(".active-revslide").data("index") : container.find(".next-revslide").data("index"); container.find('.tp-bullet').each(function() { var _t = jQuery(this); if (_t.data('liref')===si) _t.addClass("selected"); else _t.removeClass("selected"); }); cp.find('.tp-thumb, .tp-tab').each(function() { var _t = jQuery(this); if (_t.data('liref')===si) { _t.addClass("selected"); if (_t.hasClass("tp-tab")) moveThumbsInPosition(cp.find('.tp-tabs'),_d); else moveThumbsInPosition(cp.find('.tp-thumbs'),_c); } else _t.removeClass("selected"); }); var ai = 0, f = false; if (opt.thumbs) jQuery.each(opt.thumbs,function(i,obj) { ai = f === false ? i : ai; f = obj.id === si || i === si ? true : f; }); var pi = ai>0 ? ai-1 : opt.slideamount-1, ni = (ai+1)==opt.slideamount ? 0 : ai+1; if (_a.enable === true) { var inst = _a.tmp; jQuery.each(opt.thumbs[pi].params,function(i,obj) { inst = inst.replace(obj.from,obj.to); }); _a.left.j.html(inst); inst = _a.tmp; if (ni>opt.slideamount) return; jQuery.each(opt.thumbs[ni].params,function(i,obj) { inst = inst.replace(obj.from,obj.to); }); _a.right.j.html(inst); punchgs.TweenLite.set(_a.left.j.find('.tp-arr-imgholder'),{backgroundImage:"url("+opt.thumbs[pi].src+")"}); punchgs.TweenLite.set(_a.right.j.find('.tp-arr-imgholder'),{backgroundImage:"url("+opt.thumbs[ni].src+")"}); } }); hdResets(_a); hdResets(_b); hdResets(_c); hdResets(_d); // HOVER OVER ELEMENTS SHOULD SHOW/HIDE NAVIGATION ELEMENTS cp.on("mouseenter mousemove",function() { if (!cp.hasClass("tp-mouseover")) { cp.addClass("tp-mouseover"); punchgs.TweenLite.killDelayedCallsTo(showHideNavElements); if (a && _a.hide_onleave) showHideNavElements(cp.find('.tparrows'),_a,"show"); if (b && _b.hide_onleave) showHideNavElements(cp.find('.tp-bullets'),_b,"show"); if (c && _c.hide_onleave) showHideNavElements(cp.find('.tp-thumbs'),_c,"show"); if (d && _d.hide_onleave) showHideNavElements(cp.find('.tp-tabs'),_d,"show"); // ON MOBILE WE NEED TO HIDE ELEMENTS EVEN AFTER TOUCH if (_ISM) { cp.removeClass("tp-mouseover"); callAllDelayedCalls(container,opt); } } }); cp.on("mouseleave",function() { cp.removeClass("tp-mouseover"); callAllDelayedCalls(container,opt); }); // FIRST RUN HIDE ALL ELEMENTS if (a && _a.hide_onleave) showHideNavElements(cp.find('.tparrows'),_a,"hide",0); if (b && _b.hide_onleave) showHideNavElements(cp.find('.tp-bullets'),_b,"hide",0); if (c && _c.hide_onleave) showHideNavElements(cp.find('.tp-thumbs'),_c,"hide",0); if (d && _d.hide_onleave) showHideNavElements(cp.find('.tp-tabs'),_d,"hide",0); // Initialise Swipe Navigation if (c) swipeAction(cp.find('.tp-thumbs'),opt); if (d) swipeAction(cp.find('.tp-tabs'),opt); if (opt.sliderType==="carousel") swipeAction(container,opt,true); if (opt.navigation.touch.touchenabled=="on") swipeAction(container,opt,"swipebased"); } }); ///////////////////////////////// // - INTERNAL FUNCTIONS - /// ///////////////////////////////// var moveThumbsInPosition = function(container,opt) { var thumbs = container.hasClass("tp-thumbs") ? ".tp-thumbs" : ".tp-tabs", thumbmask = container.hasClass("tp-thumbs") ? ".tp-thumb-mask" : ".tp-tab-mask", thumbsiw = container.hasClass("tp-thumbs") ? ".tp-thumbs-inner-wrapper" : ".tp-tabs-inner-wrapper", thumb = container.hasClass("tp-thumbs") ? ".tp-thumb" : ".tp-tab", t=container.find(thumbmask), el = t.find(thumbsiw), thumbdir = opt.direction, tw = thumbdir==="vertical" ? t.find(thumb).first().outerHeight(true)+opt.space : t.find(thumb).first().outerWidth(true)+opt.space, tmw = thumbdir==="vertical" ? t.height() : t.width(), ti = parseInt(t.find(thumb+'.selected').data('liindex'),0), me = tmw/tw, ts = thumbdir==="vertical" ? t.height() : t.width(), tp = 0-(ti * tw), els = thumbdir==="vertical" ? el.height() : el.width(), curpos = tp < 0-(els-ts) ? 0-(els-ts) : curpos > 0 ? 0 : tp, elp = el.data('offset'); if (me>2) { curpos = tp - (elp+tw) <= 0 ? tp - (elp+tw) < 0-tw ? elp : curpos + tw : curpos; curpos = ( (tp-tw + elp + tmw)< tw && tp + (Math.round(me)-2)*tw < elp) ? tp + (Math.round(me)-2)*tw : curpos; } curpos = curpos < 0-(els-ts) ? 0-(els-ts) : curpos > 0 ? 0 : curpos; if (thumbdir!=="vertical" && t.width()>=el.width()) curpos = 0; if (thumbdir==="vertical" && t.height()>=el.height()) curpos = 0; if (!container.hasClass("dragged")) { if (thumbdir==="vertical") el.data('tmmove',punchgs.TweenLite.to(el,0.5,{top:curpos+"px",ease:punchgs.Power3.easeInOut})); else el.data('tmmove',punchgs.TweenLite.to(el,0.5,{left:curpos+"px",ease:punchgs.Power3.easeInOut})); el.data('offset',curpos); } }; // RESIZE THE THUMBS BASED ON ORIGINAL SIZE AND CURRENT SIZE OF WINDOW var rtt = function(f,tws,c,o,lis,wh) { var h = c.parent().find('.tp-'+wh+'s'), ins = h.find('.tp-'+wh+'s-inner-wrapper'), mask = h.find('.tp-'+wh+'-mask'), cw = o.width*f < o.min_width ? o.min_width : Math.round(o.width*f), ch = Math.round((cw/o.width) * o.height), iw = o.direction === "vertical" ? cw : (cw*lis) + ((o.space)*(lis-1)), ih = o.direction === "vertical" ? (ch*lis) + ((o.space)*(lis-1)) : ch, anm = o.direction === "vertical" ? {width:cw+"px"} : {height:ch+"px"}; tws.add(punchgs.TweenLite.set(h,anm)); tws.add(punchgs.TweenLite.set(ins,{width:iw+"px",height:ih+"px"})); tws.add(punchgs.TweenLite.set(mask,{width:iw+"px",height:ih+"px"})); var fin = ins.find('.tp-'+wh+''); if (fin) jQuery.each(fin,function(i,el) { if (o.direction === "vertical") tws.add(punchgs.TweenLite.set(el,{top:(i*(ch+parseInt((o.space===undefined? 0:o.space),0))),width:cw+"px",height:ch+"px"})); else if (o.direction === "horizontal") tws.add(punchgs.TweenLite.set(el,{left:(i*(cw+parseInt((o.space===undefined? 0:o.space),0))),width:cw+"px",height:ch+"px"})); }); return tws; }; // INTERNAL FUNCTIONS var normalizeWheel = function( event) /*object*/ { var sX = 0, sY = 0, // spinX, spinY pX = 0, pY = 0, // pixelX, pixelY PIXEL_STEP = 1, LINE_HEIGHT = 1, PAGE_HEIGHT = 1; // Legacy if ('detail' in event) { sY = event.detail; } if ('wheelDelta' in event) { sY = -event.wheelDelta / 120; } if ('wheelDeltaY' in event) { sY = -event.wheelDeltaY / 120; } if ('wheelDeltaX' in event) { sX = -event.wheelDeltaX / 120; } //sY = navigator.userAgent.match(/mozilla/i) ? sY*10 : sY; // side scrolling on FF with DOMMouseScroll if ( 'axis' in event && event.axis === event.HORIZONTAL_AXIS ) { sX = sY; sY = 0; } pX = sX * PIXEL_STEP; pY = sY * PIXEL_STEP; if ('deltaY' in event) { pY = event.deltaY; } if ('deltaX' in event) { pX = event.deltaX; } if ((pX || pY) && event.deltaMode) { if (event.deltaMode == 1) { // delta in LINE units pX *= LINE_HEIGHT; pY *= LINE_HEIGHT; } else { // delta in PAGE units pX *= PAGE_HEIGHT; pY *= PAGE_HEIGHT; } } // Fall-back if spin cannot be determined if (pX && !sX) { sX = (pX < 1) ? -1 : 1; } if (pY && !sY) { sY = (pY < 1) ? -1 : 1; } pY = navigator.userAgent.match(/mozilla/i) ? pY*10 : pY; if (pY>300 || pY<-300) pY = pY/10; return { spinX : sX, spinY : sY, pixelX : pX, pixelY : pY }; }; var initKeyboard = function(container,opt) { if (opt.navigation.keyboardNavigation!=="on") return; jQuery(document).keydown(function(e){ if ((opt.navigation.keyboard_direction=="horizontal" && e.keyCode == 39) || (opt.navigation.keyboard_direction=="vertical" && e.keyCode==40)) { opt.sc_indicator="arrow"; opt.sc_indicator_dir = 0; _R.callingNewSlide(opt,container,1); } if ((opt.navigation.keyboard_direction=="horizontal" && e.keyCode == 37) || (opt.navigation.keyboard_direction=="vertical" && e.keyCode==38)) { opt.sc_indicator="arrow"; opt.sc_indicator_dir = 1; _R.callingNewSlide(opt,container,-1); } }); }; var initMouseScroll = function(container,opt) { if (opt.navigation.mouseScrollNavigation!=="on" && opt.navigation.mouseScrollNavigation!=="carousel") return; opt.isIEEleven = !!navigator.userAgent.match(/Trident.*rv\:11\./); opt.isSafari = !!navigator.userAgent.match(/safari/i); opt.ischrome = !!navigator.userAgent.match(/chrome/i); var bl = opt.ischrome ? -49 : opt.isIEEleven || opt.isSafari ? -9 : navigator.userAgent.match(/mozilla/i) ? -29 : -49, tl = opt.ischrome ? 49 : opt.isIEEleven || opt.isSafari ? 9 : navigator.userAgent.match(/mozilla/i) ? 29 : 49; container.on('mousewheel DOMMouseScroll', function(e) { var res = normalizeWheel(e.originalEvent), asi = container.find('.tp-revslider-slidesli.active-revslide').index(), psi = container.find('.tp-revslider-slidesli.processing-revslide').index(), fs = asi!=-1 && asi==0 || psi!=-1 && psi==0 ? true : false, ls = asi!=-1 && asi==opt.slideamount-1 || psi!=1 && psi==opt.slideamount-1 ? true:false, ret = true; if (opt.navigation.mouseScrollNavigation=="carousel") fs = ls = false; if (psi==-1) { if(res.pixelY<bl) { if (!fs) { opt.sc_indicator="arrow"; if (opt.navigation.mouseScrollReverse!=="reverse") { opt.sc_indicator_dir = 0; _R.callingNewSlide(opt,container,-1); } ret = false; } if (!ls) { opt.sc_indicator="arrow"; if (opt.navigation.mouseScrollReverse==="reverse") { opt.sc_indicator_dir = 1; _R.callingNewSlide(opt,container,1); } ret = false; } } else if(res.pixelY>tl) { if (!ls) { opt.sc_indicator="arrow"; if (opt.navigation.mouseScrollReverse!=="reverse") { opt.sc_indicator_dir = 1; _R.callingNewSlide(opt,container,1); } ret = false; } if (!fs) { opt.sc_indicator="arrow"; if (opt.navigation.mouseScrollReverse==="reverse") { opt.sc_indicator_dir = 0; _R.callingNewSlide(opt,container,-1); } ret = false; } } } else { ret = false; } var tc = opt.c.offset().top-jQuery('body').scrollTop(), bc = tc+opt.c.height(); if (opt.navigation.mouseScrollNavigation!="carousel") { if (opt.navigation.mouseScrollReverse!=="reverse") if ((tc>0 && res.pixelY>0) || (bc<jQuery(window).height() && res.pixelY<0)) ret = true; if (opt.navigation.mouseScrollReverse==="reverse") if ((tc<0 && res.pixelY<0) || (bc>jQuery(window).height() && res.pixelY>0)) ret = true; } else { ret=false; } if (ret==false) { e.preventDefault(e); return false; } else { return; } }); }; var isme = function (a,c,e) { a = _ISM ? jQuery(e.target).closest('.'+a).length || jQuery(e.srcElement).closest('.'+a).length : jQuery(e.toElement).closest('.'+a).length || jQuery(e.originalTarget).closest('.'+a).length; return a === true || a=== 1 ? 1 : 0; }; // - SET THE SWIPE FUNCTION // var swipeAction = function(container,opt,vertical) { container.data('opt',opt); // TOUCH ENABLED SCROLL var _ = opt.carousel; jQuery(".bullet, .bullets, .tp-bullets, .tparrows").addClass("noSwipe"); _.Limit = "endless"; var notonbody = _ISM || _R.get_browser()==="Firefox", SwipeOn = container, //notonbody ? container : jQuery('body'), pagescroll = opt.navigation.thumbnails.direction==="vertical" || opt.navigation.tabs.direction==="vertical"? "none" : "vertical", swipe_wait_dir = opt.navigation.touch.swipe_direction || "horizontal"; pagescroll = vertical == "swipebased" && swipe_wait_dir=="vertical" ? "none" : vertical ? "vertical" : pagescroll; if (!jQuery.fn.swipetp) jQuery.fn.swipetp = jQuery.fn.swipe; if (!jQuery.fn.swipetp.defaults || !jQuery.fn.swipetp.defaults.excludedElements) if (!jQuery.fn.swipetp.defaults) jQuery.fn.swipetp.defaults = new Object(); jQuery.fn.swipetp.defaults.excludedElements = "label, button, input, select, textarea, .noSwipe" SwipeOn.swipetp({ allowPageScroll:pagescroll, triggerOnTouchLeave:true, treshold:opt.navigation.touch.swipe_treshold, fingers:opt.navigation.touch.swipe_min_touches, excludeElements:jQuery.fn.swipetp.defaults.excludedElements, swipeStatus:function(event,phase,direction,distance,duration,fingerCount,fingerData) { var withinslider = isme('rev_slider_wrapper',container,event), withinthumbs = isme('tp-thumbs',container,event), withintabs = isme('tp-tabs',container,event), starget = jQuery(this).attr('class'), istt = starget.match(/tp-tabs|tp-thumb/gi) ? true : false; // SWIPE OVER SLIDER, TO SWIPE SLIDES IN CAROUSEL MODE if (opt.sliderType==="carousel" && (((phase==="move" || phase==="end" || phase=="cancel") && (opt.dragStartedOverSlider && !opt.dragStartedOverThumbs && !opt.dragStartedOverTabs)) || (phase==="start" && withinslider>0 && withinthumbs===0 && withintabs===0))) { opt.dragStartedOverSlider = true; distance = (direction && direction.match(/left|up/g)) ? Math.round(distance * -1) : distance = Math.round(distance * 1); switch (phase) { case "start": if (_.positionanim!==undefined) { _.positionanim.kill(); _.slide_globaloffset = _.infinity==="off" ? _.slide_offset : _R.simp(_.slide_offset, _.maxwidth); } _.overpull = "none"; _.wrap.addClass("dragged"); break; case "move": _.slide_offset = _.infinity==="off" ? _.slide_globaloffset + distance : _R.simp(_.slide_globaloffset + distance, _.maxwidth); if (_.infinity==="off") { var bb = _.horizontal_align==="center" ? ((_.wrapwidth/2-_.slide_width/2) - _.slide_offset) / _.slide_width : (0 - _.slide_offset) / _.slide_width; if ((_.overpull ==="none" || _.overpull===0) && (bb<0 || bb>opt.slideamount-1)) _.overpull = distance; else if (bb>=0 && bb<=opt.slideamount-1 && ((bb>=0 && distance>_.overpull) || (bb<=opt.slideamount-1 && distance<_.overpull))) _.overpull = 0; _.slide_offset = bb<0 ? _.slide_offset+ (_.overpull-distance)/1.1 + Math.sqrt(Math.abs((_.overpull-distance)/1.1)) : bb>opt.slideamount-1 ? _.slide_offset+ (_.overpull-distance)/1.1 - Math.sqrt(Math.abs((_.overpull-distance)/1.1)) : _.slide_offset ; } _R.organiseCarousel(opt,direction,true,true); break; case "end": case "cancel": //duration !! _.slide_globaloffset = _.slide_offset; _.wrap.removeClass("dragged"); _R.carouselToEvalPosition(opt,direction); opt.dragStartedOverSlider = false; opt.dragStartedOverThumbs = false; opt.dragStartedOverTabs = false; break; } } else // SWIPE OVER THUMBS OR TABS if (( ((phase==="move" || phase==="end" || phase=="cancel") && (!opt.dragStartedOverSlider && (opt.dragStartedOverThumbs || opt.dragStartedOverTabs))) || (phase==="start" && (withinslider>0 && (withinthumbs>0 || withintabs>0))))) { if (withinthumbs>0) opt.dragStartedOverThumbs = true; if (withintabs>0) opt.dragStartedOverTabs = true; var thumbs = opt.dragStartedOverThumbs ? ".tp-thumbs" : ".tp-tabs", thumbmask = opt.dragStartedOverThumbs ? ".tp-thumb-mask" : ".tp-tab-mask", thumbsiw = opt.dragStartedOverThumbs ? ".tp-thumbs-inner-wrapper" : ".tp-tabs-inner-wrapper", thumb = opt.dragStartedOverThumbs ? ".tp-thumb" : ".tp-tab", _o = opt.dragStartedOverThumbs ? opt.navigation.thumbnails : opt.navigation.tabs; distance = (direction && direction.match(/left|up/g)) ? Math.round(distance * -1) : distance = Math.round(distance * 1); var t= container.parent().find(thumbmask), el = t.find(thumbsiw), tdir = _o.direction, els = tdir==="vertical" ? el.height() : el.width(), ts = tdir==="vertical" ? t.height() : t.width(), tw = tdir==="vertical" ? t.find(thumb).first().outerHeight(true)+_o.space : t.find(thumb).first().outerWidth(true)+_o.space, newpos = (el.data('offset') === undefined ? 0 : parseInt(el.data('offset'),0)), curpos = 0; switch (phase) { case "start": container.parent().find(thumbs).addClass("dragged"); newpos = tdir === "vertical" ? el.position().top : el.position().left; el.data('offset',newpos); if (el.data('tmmove')) el.data('tmmove').pause(); break; case "move": if (els<=ts) return false; curpos = newpos + distance; curpos = curpos>0 ? tdir==="horizontal" ? curpos - (el.width() * (curpos/el.width() * curpos/el.width())) : curpos - (el.height() * (curpos/el.height() * curpos/el.height())) : curpos; var dif = tdir==="vertical" ? 0-(el.height()-t.height()) : 0-(el.width()-t.width()); curpos = curpos < dif ? tdir==="horizontal" ? curpos + (el.width() * (curpos-dif)/el.width() * (curpos-dif)/el.width()) : curpos + (el.height() * (curpos-dif)/el.height() * (curpos-dif)/el.height()) : curpos; if (tdir==="vertical") punchgs.TweenLite.set(el,{top:curpos+"px"}); else punchgs.TweenLite.set(el,{left:curpos+"px"}); break; case "end": case "cancel": if (istt) { curpos = newpos + distance; curpos = tdir==="vertical" ? curpos < 0-(el.height()-t.height()) ? 0-(el.height()-t.height()) : curpos : curpos < 0-(el.width()-t.width()) ? 0-(el.width()-t.width()) : curpos; curpos = curpos > 0 ? 0 : curpos; curpos = Math.abs(distance)>tw/10 ? distance<=0 ? Math.floor(curpos/tw)*tw : Math.ceil(curpos/tw)*tw : distance<0 ? Math.ceil(curpos/tw)*tw : Math.floor(curpos/tw)*tw; curpos = tdir==="vertical" ? curpos < 0-(el.height()-t.height()) ? 0-(el.height()-t.height()) : curpos : curpos < 0-(el.width()-t.width()) ? 0-(el.width()-t.width()) : curpos; curpos = curpos > 0 ? 0 : curpos; if (tdir==="vertical") punchgs.TweenLite.to(el,0.5,{top:curpos+"px",ease:punchgs.Power3.easeOut}); else punchgs.TweenLite.to(el,0.5,{left:curpos+"px",ease:punchgs.Power3.easeOut}); curpos = !curpos ? tdir==="vertical" ? el.position().top : el.position().left : curpos; el.data('offset',curpos); el.data('distance',distance); setTimeout(function() { opt.dragStartedOverSlider = false; opt.dragStartedOverThumbs = false; opt.dragStartedOverTabs = false; },100); container.parent().find(thumbs).removeClass("dragged"); return false; } break; } } else { if (phase=="end" && !istt) { opt.sc_indicator="arrow"; if ((swipe_wait_dir=="horizontal" && direction == "left") || (swipe_wait_dir=="vertical" && direction == "up")) { opt.sc_indicator_dir = 0; _R.callingNewSlide(opt,opt.c,1); return false; } if ((swipe_wait_dir=="horizontal" && direction == "right") || (swipe_wait_dir=="vertical" && direction == "down")) { opt.sc_indicator_dir = 1; _R.callingNewSlide(opt,opt.c,-1); return false; } } opt.dragStartedOverSlider = false; opt.dragStartedOverThumbs = false; opt.dragStartedOverTabs = false; return true; } } }); }; // NAVIGATION HELPER FUNCTIONS var hdResets = function(o) { o.hide_delay = !jQuery.isNumeric(parseInt(o.hide_delay,0)) ? 0.2 : o.hide_delay/1000; o.hide_delay_mobile = !jQuery.isNumeric(parseInt(o.hide_delay_mobile,0)) ? 0.2 : o.hide_delay_mobile/1000; }; var ckNO = function(opt) { return opt && opt.enable; }; var ckNOLO = function(opt) { return opt && opt.enable && opt.hide_onleave===true && (opt.position===undefined ? true : !opt.position.match(/outer/g)); }; var callAllDelayedCalls = function(container,opt) { var cp = container.parent(); if (ckNOLO(opt.navigation.arrows)) punchgs.TweenLite.delayedCall(_ISM ? opt.navigation.arrows.hide_delay_mobile : opt.navigation.arrows.hide_delay,showHideNavElements,[cp.find('.tparrows'),opt.navigation.arrows,"hide"]); if (ckNOLO(opt.navigation.bullets)) punchgs.TweenLite.delayedCall(_ISM ? opt.navigation.bullets.hide_delay_mobile : opt.navigation.bullets.hide_delay,showHideNavElements,[cp.find('.tp-bullets'),opt.navigation.bullets,"hide"]); if (ckNOLO(opt.navigation.thumbnails)) punchgs.TweenLite.delayedCall(_ISM ? opt.navigation.thumbnails.hide_delay_mobile : opt.navigation.thumbnails.hide_delay,showHideNavElements,[cp.find('.tp-thumbs'),opt.navigation.thumbnails,"hide"]); if (ckNOLO(opt.navigation.tabs)) punchgs.TweenLite.delayedCall(_ISM ? opt.navigation.tabs.hide_delay_mobile : opt.navigation.tabs.hide_delay,showHideNavElements,[cp.find('.tp-tabs'),opt.navigation.tabs,"hide"]); }; var showHideNavElements = function(container,opt,dir,speed) { speed = speed===undefined ? 0.5 : speed; switch (dir) { case "show": punchgs.TweenLite.to(container,speed, {autoAlpha:1,ease:punchgs.Power3.easeInOut,overwrite:"auto"}); break; case "hide": punchgs.TweenLite.to(container,speed, {autoAlpha:0,ease:punchgs.Power3.easeInOu,overwrite:"auto"}); break; } }; // ADD ARROWS var initArrows = function(container,o,opt) { // SET oIONAL CLASSES o.style = o.style === undefined ? "" : o.style; o.left.style = o.left.style === undefined ? "" : o.left.style; o.right.style = o.right.style === undefined ? "" : o.right.style; // ADD LEFT AND RIGHT ARROWS if (container.find('.tp-leftarrow.tparrows').length===0) container.append('<div class="tp-leftarrow tparrows '+o.style+' '+o.left.style+'">'+o.tmp+'</div>'); if (container.find('.tp-rightarrow.tparrows').length===0) container.append('<div class="tp-rightarrow tparrows '+o.style+' '+o.right.style+'">'+o.tmp+'</div>'); var la = container.find('.tp-leftarrow.tparrows'), ra = container.find('.tp-rightarrow.tparrows'); if (o.rtl) { // CLICK HANDLINGS ON LEFT AND RIGHT ARROWS la.click(function() { opt.sc_indicator="arrow"; opt.sc_indicator_dir = 0;container.revnext();}); ra.click(function() { opt.sc_indicator="arrow"; opt.sc_indicator_dir = 1;container.revprev();}); } else { // CLICK HANDLINGS ON LEFT AND RIGHT ARROWS ra.click(function() { opt.sc_indicator="arrow"; opt.sc_indicator_dir = 0;container.revnext();}); la.click(function() { opt.sc_indicator="arrow"; opt.sc_indicator_dir = 1;container.revprev();}); } // SHORTCUTS o.right.j = container.find('.tp-rightarrow.tparrows'); o.left.j = container.find('.tp-leftarrow.tparrows') // OUTTUER PADDING DEFAULTS o.padding_top = parseInt((opt.carousel.padding_top||0),0), o.padding_bottom = parseInt((opt.carousel.padding_bottom||0),0); // POSITION OF ARROWS setNavElPositions(la,o.left,opt); setNavElPositions(ra,o.right,opt); o.left.opt = opt; o.right.opt = opt; if (o.position=="outer-left" || o.position=="outer-right") opt.outernav = true; }; // PUT ELEMENTS VERTICAL / HORIZONTAL IN THE RIGHT POSITION var putVinPosition = function(el,o,opt) { var elh = el.outerHeight(true), elw = el.outerWidth(true), oh = o.opt== undefined ? 0 : opt.conh == 0 ? opt.height : opt.conh, by = o.container=="layergrid" ? opt.sliderLayout=="fullscreen" ? opt.height/2 - (opt.gridheight[opt.curWinRange]*opt.bh)/2 : (opt.autoHeight=="on" || (opt.minHeight!=undefined && opt.minHeight>0)) ? oh/2 - (opt.gridheight[opt.curWinRange]*opt.bh)/2 : 0 : 0, a = o.v_align === "top" ? {top:"0px",y:Math.round(o.v_offset+by)+"px"} : o.v_align === "center" ? {top:"50%",y:Math.round(((0-elh/2)+o.v_offset))+"px"} : {top:"100%",y:Math.round((0-(elh+o.v_offset+by)))+"px"}; if (!el.hasClass("outer-bottom")) punchgs.TweenLite.set(el,a); }; var putHinPosition = function(el,o,opt) { var elh = el.outerHeight(true), elw = el.outerWidth(true), bx = o.container=="layergrid" ? opt.sliderType==="carousel" ? 0 : opt.width/2 - (opt.gridwidth[opt.curWinRange]*opt.bw)/2 : 0, a = o.h_align === "left" ? {left:"0px",x:Math.round(o.h_offset+bx)+"px"} : o.h_align === "center" ? {left:"50%",x:Math.round(((0-elw/2)+o.h_offset))+"px"} : {left:"100%",x:Math.round((0-(elw+o.h_offset+bx)))+"px"}; punchgs.TweenLite.set(el,a); }; // SET POSITION OF ELEMENTS var setNavElPositions = function(el,o,opt) { var wrapper = el.closest('.tp-simpleresponsive').length>0 ? el.closest('.tp-simpleresponsive') : el.closest('.tp-revslider-mainul').length>0 ? el.closest('.tp-revslider-mainul') : el.closest('.rev_slider_wrapper').length>0 ? el.closest('.rev_slider_wrapper'): el.parent().find('.tp-revslider-mainul'), ww = wrapper.width(), wh = wrapper.height(); putVinPosition(el,o,opt); putHinPosition(el,o,opt); if (o.position==="outer-left" && (o.sliderLayout=="fullwidth" || o.sliderLayout=="fullscreen")) punchgs.TweenLite.set(el,{left:(0-el.outerWidth())+"px",x:o.h_offset+"px"}); else if (o.position==="outer-right" && (o.sliderLayout=="fullwidth" || o.sliderLayout=="fullscreen")) punchgs.TweenLite.set(el,{right:(0-el.outerWidth())+"px",x:o.h_offset+"px"}); // MAX WIDTH AND HEIGHT BASED ON THE SOURROUNDING CONTAINER if (el.hasClass("tp-thumbs") || el.hasClass("tp-tabs")) { var wpad = el.data('wr_padding'), maxw = el.data('maxw'), maxh = el.data('maxh'), mask = el.hasClass("tp-thumbs") ? el.find('.tp-thumb-mask') : el.find('.tp-tab-mask'), cpt = parseInt((o.padding_top||0),0), cpb = parseInt((o.padding_bottom||0),0); // ARE THE CONTAINERS BIGGER THAN THE SLIDER WIDTH OR HEIGHT ? if (maxw>ww && o.position!=="outer-left" && o.position!=="outer-right") { punchgs.TweenLite.set(el,{left:"0px",x:0,maxWidth:(ww-2*wpad)+"px"}); punchgs.TweenLite.set(mask,{maxWidth:(ww-2*wpad)+"px"}); } else { punchgs.TweenLite.set(el,{maxWidth:(maxw)+"px"}); punchgs.TweenLite.set(mask,{maxWidth:(maxw)+"px"}); } if (maxh+2*wpad>wh && o.position!=="outer-bottom" && o.position!=="outer-top") { punchgs.TweenLite.set(el,{top:"0px",y:0,maxHeight:(cpt+cpb+(wh-2*wpad))+"px"}); punchgs.TweenLite.set(mask,{maxHeight:(cpt+cpb+(wh-2*wpad))+"px"}); } else { punchgs.TweenLite.set(el,{maxHeight:(maxh)+"px"}); punchgs.TweenLite.set(mask,{maxHeight:maxh+"px"}); } if (o.position!=="outer-left" && o.position!=="outer-right") { cpt = 0; cpb = 0; } // SPAN IS ENABLED if (o.span===true && o.direction==="vertical") { punchgs.TweenLite.set(el,{maxHeight:(cpt+cpb+(wh-2*wpad))+"px",height:(cpt+cpb+(wh-2*wpad))+"px",top:(0-cpt),y:0}); putVinPosition(mask,o,opt); } else if (o.span===true && o.direction==="horizontal") { punchgs.TweenLite.set(el,{maxWidth:"100%",width:(ww-2*wpad)+"px",left:0,x:0}); putHinPosition(mask,o,opt); } } }; // ADD A BULLET var addBullet = function(container,o,li,opt) { // Check if Bullet exists already ? if (container.find('.tp-bullets').length===0) { o.style = o.style === undefined ? "" : o.style; container.append('<div class="tp-bullets '+o.style+' '+o.direction+'"></div>'); } // Add Bullet Structure to the Bullet Container var bw = container.find('.tp-bullets'), linkto = li.data('index'), inst = o.tmp; jQuery.each(opt.thumbs[li.index()].params,function(i,obj) { inst = inst.replace(obj.from,obj.to);}) bw.append('<div class="justaddedbullet tp-bullet">'+inst+'</div>'); // SET BULLET SPACES AND POSITION var b = container.find('.justaddedbullet'), am = container.find('.tp-bullet').length, w = b.outerWidth()+parseInt((o.space===undefined? 0:o.space),0), h = b.outerHeight()+parseInt((o.space===undefined? 0:o.space),0); //bgimage = li.data('thumb') !==undefined ? li.data('thumb') : li.find('.defaultimg').data('lazyload') !==undefined && li.find('.defaultimg').data('lazyload') !== 'undefined' ? li.find('.defaultimg').data('lazyload') : li.find('.defaultimg').data('src'); if (o.direction==="vertical") { b.css({top:((am-1)*h)+"px", left:"0px"}); bw.css({height:(((am-1)*h) + b.outerHeight()),width:b.outerWidth()}); } else { b.css({left:((am-1)*w)+"px", top:"0px"}); bw.css({width:(((am-1)*w) + b.outerWidth()),height:b.outerHeight()}); } b.find('.tp-bullet-image').css({backgroundImage:'url('+opt.thumbs[li.index()].src+')'}); // SET LINK TO AND LISTEN TO CLICK b.data('liref',linkto); b.click(function() { opt.sc_indicator="bullet"; container.revcallslidewithid(linkto); container.find('.tp-bullet').removeClass("selected"); jQuery(this).addClass("selected"); }); // REMOVE HELP CLASS b.removeClass("justaddedbullet"); // OUTTUER PADDING DEFAULTS o.padding_top = parseInt((opt.carousel.padding_top||0),0), o.padding_bottom = parseInt((opt.carousel.padding_bottom||0),0); o.opt = opt; if (o.position=="outer-left" || o.position=="outer-right") opt.outernav = true; bw.addClass("nav-pos-hor-"+o.h_align); bw.addClass("nav-pos-ver-"+o.v_align); bw.addClass("nav-dir-"+o.direction); // PUT ALL CONTAINER IN POSITION setNavElPositions(bw,o,opt); }; var cHex = function(hex,o){ o = parseFloat(o); hex = hex.replace('#',''); var r = parseInt(hex.substring(0,2), 16), g = parseInt(hex.substring(2,4), 16), b = parseInt(hex.substring(4,6), 16), result = 'rgba('+r+','+g+','+b+','+o+')'; return result; }; // ADD THUMBNAILS var addThumb = function(container,o,li,what,opt) { var thumbs = what==="tp-thumb" ? ".tp-thumbs" : ".tp-tabs", thumbmask = what==="tp-thumb" ? ".tp-thumb-mask" : ".tp-tab-mask", thumbsiw = what==="tp-thumb" ? ".tp-thumbs-inner-wrapper" : ".tp-tabs-inner-wrapper", thumb = what==="tp-thumb" ? ".tp-thumb" : ".tp-tab", timg = what ==="tp-thumb" ? ".tp-thumb-image" : ".tp-tab-image"; o.visibleAmount = o.visibleAmount>opt.slideamount ? opt.slideamount : o.visibleAmount; o.sliderLayout = opt.sliderLayout; // Check if THUNBS/TABS exists already ? if (container.parent().find(thumbs).length===0) { o.style = o.style === undefined ? "" : o.style; var spanw = o.span===true ? "tp-span-wrapper" : "", addcontent = '<div class="'+what+'s '+spanw+" "+o.position+" "+o.style+'"><div class="'+what+'-mask"><div class="'+what+'s-inner-wrapper" style="position:relative;"></div></div></div>'; if (o.position==="outer-top") container.parent().prepend(addcontent) else if (o.position==="outer-bottom") container.after(addcontent); else container.append(addcontent); // OUTTUER PADDING DEFAULTS o.padding_top = parseInt((opt.carousel.padding_top||0),0), o.padding_bottom = parseInt((opt.carousel.padding_bottom||0),0); if (o.position=="outer-left" || o.position=="outer-right") opt.outernav = true; } // Add Thumb/TAB Structure to the THUMB/TAB Container var linkto = li.data('index'), t = container.parent().find(thumbs), tm = t.find(thumbmask), tw = tm.find(thumbsiw), maxw = o.direction==="horizontal" ? (o.width * o.visibleAmount) + (o.space*(o.visibleAmount-1)) : o.width, maxh = o.direction==="horizontal" ? o.height : (o.height * o.visibleAmount) + (o.space*(o.visibleAmount-1)), inst = o.tmp; jQuery.each(opt.thumbs[li.index()].params,function(i,obj) { inst = inst.replace(obj.from,obj.to); }) tw.append('<div data-liindex="'+li.index()+'" data-liref="'+linkto+'" class="justaddedthumb '+what+'" style="width:'+o.width+'px;height:'+o.height+'px;">'+inst+'</div>'); // SET BULLET SPACES AND POSITION var b = t.find('.justaddedthumb'), am = t.find(thumb).length, w = b.outerWidth()+parseInt((o.space===undefined? 0:o.space),0), h = b.outerHeight()+parseInt((o.space===undefined? 0:o.space),0); // FILL CONTENT INTO THE TAB / THUMBNAIL b.find(timg).css({backgroundImage:"url("+opt.thumbs[li.index()].src+")"}); if (o.direction==="vertical") { b.css({top:((am-1)*h)+"px", left:"0px"}); tw.css({height:(((am-1)*h) + b.outerHeight()),width:b.outerWidth()}); } else { b.css({left:((am-1)*w)+"px", top:"0px"}); tw.css({width:(((am-1)*w) + b.outerWidth()),height:b.outerHeight()}); } t.data('maxw',maxw); t.data('maxh',maxh); t.data('wr_padding',o.wrapper_padding); var position = o.position === "outer-top" || o.position==="outer-bottom" ? "relative" : "absolute", _margin = (o.position === "outer-top" || o.position==="outer-bottom") && (o.h_align==="center") ? "auto" : "0"; tm.css({maxWidth:maxw+"px",maxHeight:maxh+"px",overflow:"hidden",position:"relative"}); t.css({maxWidth:(maxw)+"px",/*margin:_margin, */maxHeight:maxh+"px",overflow:"visible",position:position,background:cHex(o.wrapper_color,o.wrapper_opacity),padding:o.wrapper_padding+"px",boxSizing:"contet-box"}); // SET LINK TO AND LISTEN TO CLICK b.click(function() { opt.sc_indicator="bullet"; var dis = container.parent().find(thumbsiw).data('distance'); dis = dis === undefined ? 0 : dis; if (Math.abs(dis)<10) { container.revcallslidewithid(linkto); container.parent().find(thumbs).removeClass("selected"); jQuery(this).addClass("selected"); } }); // REMOVE HELP CLASS b.removeClass("justaddedthumb"); o.opt = opt; t.addClass("nav-pos-hor-"+o.h_align); t.addClass("nav-pos-ver-"+o.v_align); t.addClass("nav-dir-"+o.direction); // PUT ALL CONTAINER IN POSITION setNavElPositions(t,o,opt); }; var setONHeights = function(o) { var ot = o.c.parent().find('.outer-top'), ob = o.c.parent().find('.outer-bottom'); o.top_outer = !ot.hasClass("tp-forcenotvisible") ? ot.outerHeight() || 0 : 0; o.bottom_outer = !ob.hasClass("tp-forcenotvisible") ? ob.outerHeight() || 0 : 0; }; // HIDE NAVIGATION ON PURPOSE var biggerNav = function(el,a,b,c) { if (a>b || b>c) el.addClass("tp-forcenotvisible") else el.removeClass("tp-forcenotvisible"); }; })(jQuery);
gpl-3.0
rachoo/connectbot
tests/src/org/connectbot/HostListActivityTest.java
1538
/* * ConnectBot: simple, powerful, open-source SSH client for Android * Copyright 2007 Kenny Root, Jeffrey Sharkey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.connectbot; import android.app.Activity; import android.test.ActivityInstrumentationTestCase2; /** * This is a simple framework for a test of an Application. See * {@link android.test.ApplicationTestCase ApplicationTestCase} for more * information on how to write and extend Application tests. * <p/> * To run this test, you can type: adb shell am instrument -w \ -e class * org.connectbot.HostListActivityTest \ * org.connectbot.tests/android.test.InstrumentationTestRunner */ public class HostListActivityTest extends ActivityInstrumentationTestCase2<HostListActivity> { private Activity mActivity; public HostListActivityTest() { super("org.connectbot", HostListActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); setActivityInitialTouchMode(false); mActivity = getActivity(); } }
apache-2.0
jakobwilm/pcl
surface/src/3rdparty/opennurbs/opennurbs_brep_extrude.cpp
38785
/* $NoKeywords: $ */ /* // // Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved. // OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert // McNeel & Associates. // // THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. // ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF // MERCHANTABILITY ARE HEREBY DISCLAIMED. // // For complete openNURBS copyright information see <http://www.opennurbs.org>. // //////////////////////////////////////////////////////////////// */ #include "pcl/surface/3rdparty/opennurbs/opennurbs.h" static void ON_BrepExtrudeHelper_ReserveSpace( ON_Brep& brep, int extruded_trim_count, int cap_count ) { if ( extruded_trim_count >= 0 && cap_count >= 0 ) { const int vertex_count0 = brep.m_V.Count(); const int trim_count0 = brep.m_T.Count(); const int loop_count0 = brep.m_L.Count(); const int edge_count0 = brep.m_E.Count(); const int face_count0 = brep.m_F.Count(); const int srf_count0 = brep.m_S.Count(); const int c2_count0 = brep.m_C2.Count(); const int c3_count0 = brep.m_C3.Count(); // the +1's are for open loops brep.m_V.Reserve( vertex_count0 + extruded_trim_count + 1 ); brep.m_T.Reserve( trim_count0 + (4+cap_count)*extruded_trim_count ); brep.m_F.Reserve( face_count0 + extruded_trim_count + cap_count ); brep.m_E.Reserve( edge_count0 + 2*extruded_trim_count + 1 ); brep.m_L.Reserve( loop_count0 + extruded_trim_count + cap_count ); brep.m_S.Reserve( srf_count0 + extruded_trim_count + cap_count ); brep.m_C2.Reserve( c2_count0 + (4+cap_count)*extruded_trim_count ); brep.m_C3.Reserve( c3_count0 + 2*extruded_trim_count + 1 ); } } static ON_SumSurface* ON_BrepExtrudeHelper_MakeSumSrf( const ON_Curve& path_curve, const ON_BrepEdge& base_edge, ON_BOOL32 bRev ) { ON_SumSurface* sum_srf = 0; // create side surface if ( base_edge.ProxyCurve() ) { ON_Curve* srf_path_curve = path_curve.DuplicateCurve(); ON_Curve* srf_base_curve = base_edge.DuplicateCurve(); if ( !bRev ) srf_base_curve->Reverse(); ON_3dPoint sum_basepoint = -ON_3dVector(srf_path_curve->PointAtStart()); sum_srf = new ON_SumSurface(); sum_srf->m_curve[0] = srf_base_curve; sum_srf->m_curve[1] = srf_path_curve; sum_srf->m_basepoint = sum_basepoint; sum_srf->BoundingBox(); // fills in sum_srf->m_bbox } return sum_srf; } static ON_NurbsSurface* ON_BrepExtrudeHelper_MakeConeSrf( const ON_3dPoint& apex_point, const ON_BrepEdge& edge, ON_BOOL32 bRev ) { // The "s" parameter runs along the edge. // The "t" parameter is the ruling parameter; // t=0 is at the base_edge and t=max is at the apex. // surface side location // south base_edge // east line from bRev?START:END of edge to apex // north singular side at apex // west line from bRev?END:START of edge to apex. ON_NurbsSurface* cone_srf = new ON_NurbsSurface(); if ( cone_srf->CreateConeSurface( apex_point, edge ) ) { if ( bRev ) cone_srf->Reverse(0); // get a decent interval for the ruling parameter double d = 0.0; ON_Interval edom = edge.Domain(); ON_3dPoint pt; int i, hint=0; for ( i = 0; i <= 16; i++ ) { if ( !edge.EvPoint( edom.ParameterAt(i/16.0), pt, 0, &hint ) ) continue; if ( pt.DistanceTo(apex_point) > d ) d = pt.DistanceTo(apex_point); } if ( d > ON_SQRT_EPSILON ) cone_srf->SetDomain(1,0.0,d); } else { delete cone_srf; cone_srf = 0; } return cone_srf; } static ON_BOOL32 ON_BrepExtrudeHelper_MakeSides( ON_Brep& brep, int loop_index, const ON_Curve& path_curve, ON_BOOL32 bCap, ON_SimpleArray<int>& side_face_index ) { int lti, ti, i, vid[4], eid[4], bRev3d[4]; // indices of new faces appended to the side_face_index[] array // (1 face index for each trim, -1 is used for singular trims) // count number of new objects so we can grow arrays // efficiently and use refs to dynamic array elements. const int loop_trim_count = brep.m_L[loop_index].m_ti.Count(); if ( loop_trim_count == 0 ) return false; // save input trim and edge counts for use below const int trim_count0 = brep.m_T.Count(); const int edge_count0 = brep.m_E.Count(); ON_BrepExtrudeHelper_ReserveSpace( brep, loop_trim_count, bCap?1:0 ); side_face_index.Reserve( side_face_index.Count() + loop_trim_count); // index of new face above brep.m_L[loop_index].m_ti[lti] int prev_face_index = -1; int first_face_east_trim_index = -1; for ( lti = 0; lti < loop_trim_count; lti++ ) { ON_SumSurface* sum_srf = 0; side_face_index.Append(-1); ti = brep.m_L[loop_index].m_ti[lti]; if ( ti < 0 || ti >= trim_count0 ) continue; for ( i = 0; i < 4; i++ ) { vid[i] = -1; eid[i] = -1; } bRev3d[0] = false; bRev3d[1] = false; bRev3d[2] = false; bRev3d[3] = false; // get side surface for new face { ON_BrepTrim& trim = brep.m_T[ti]; if ( trim.m_ei >= 0 && trim.m_ei < edge_count0 ) { const ON_BrepEdge& base_edge = brep.m_E[trim.m_ei]; // 5 September, 2003 Dale Lear // do not extrude seams - fixes rectangle slabe bug if ( trim.m_type == ON_BrepTrim::seam ) { prev_face_index = -1; continue; } // connect new face to existing topology on trim vid[0] = trim.m_vi[1]; vid[1] = trim.m_vi[0]; eid[0] = base_edge.m_edge_index; bRev3d[0] = (trim.m_bRev3d?false:true); sum_srf = ON_BrepExtrudeHelper_MakeSumSrf( path_curve, base_edge, trim.m_bRev3d ); } } if ( !sum_srf ) continue; if ( prev_face_index >= 0 ) { const ON_BrepTrim& prev_west_trim = brep.m_T[ brep.m_L[ brep.m_F[prev_face_index].m_li[0]].m_ti[3] ]; vid[2] = prev_west_trim.m_vi[0]; eid[1] = prev_west_trim.m_ei; bRev3d[1] = (prev_west_trim.m_bRev3d?false:true); } if ( first_face_east_trim_index >= 0 && brep.m_T[first_face_east_trim_index].m_vi[0] == vid[0] ) { const ON_BrepTrim& first_face_east_trim = brep.m_T[first_face_east_trim_index]; vid[3] = first_face_east_trim.m_vi[1]; eid[3] = first_face_east_trim.m_ei; bRev3d[3] = (first_face_east_trim.m_bRev3d?false:true); } const ON_BrepFace* side_face = brep.NewFace(sum_srf,vid,eid,bRev3d); if ( side_face ) { *side_face_index.Last() = side_face->m_face_index; prev_face_index = side_face->m_face_index; if ( first_face_east_trim_index < 0 ) first_face_east_trim_index = brep.m_L[ side_face->m_li[0] ].m_ti[1]; } } return true; } static bool ON_BrepExtrudeHelper_CheckPathCurve( const ON_Curve& path_curve, ON_3dVector& path_vector ) { ON_Line path_line; path_line.from = path_curve.PointAtStart(); path_line.to = path_curve.PointAtEnd(); path_vector = path_line.Direction(); return ( path_vector.IsZero() ? false : true ); } static bool ON_BrepExtrudeHelper_MakeTopLoop( ON_Brep& brep, ON_BrepFace& top_face, int bottom_loop_index, const ON_3dVector path_vector, const int* side_face_index // array of brep.m_L[bottom_loop_index].m_ti.Count() face indices ) { bool rc = true; int lti, top_trim_index, i; if ( bottom_loop_index < 0 || bottom_loop_index >= brep.m_L.Count() ) return false; ON_BrepLoop::TYPE loop_type = brep.m_L[bottom_loop_index].m_type; if ( loop_type != ON_BrepLoop::inner ) loop_type = ON_BrepLoop::outer; ON_BrepLoop& top_loop = brep.NewLoop( loop_type, top_face ); const ON_BrepLoop& bottom_loop = brep.m_L[bottom_loop_index]; const int loop_trim_count = bottom_loop.m_ti.Count(); brep.m_T.Reserve( brep.m_T.Count() + loop_trim_count ); // Set top_vertex_index[lti] = index of vertex above // vertex brep.m_V[brep.m_T[bottom_loop.m_ti[lti]].m_vi[0]]. // Set top_vertex_index[lti] = index of edge above // edge of brep.m_T[bottom_loop.m_ti[lti]]. // This informtion is needed for singular and seam trims. ON_SimpleArray<int> top_vertex_index(loop_trim_count); ON_SimpleArray<int> top_edge_index(loop_trim_count); ON_SimpleArray<bool> top_trim_bRev3d(loop_trim_count); for ( lti = 0; lti < loop_trim_count; lti++ ) { top_vertex_index.Append(-1); top_edge_index.Append(-1); top_trim_bRev3d.Append(false); } // some (often all of) of the "top" vertices are already on // the side faces for ( lti = 0; lti < loop_trim_count; lti++ ) { if ( side_face_index[lti] >= 0 ) { const ON_BrepFace& side_face = brep.m_F[side_face_index[lti]]; const ON_BrepLoop& side_loop = brep.m_L[side_face.m_li[0]]; const ON_BrepTrim& side_north_trim = brep.m_T[side_loop.m_ti[2]]; top_vertex_index[lti] = side_north_trim.m_vi[0]; top_vertex_index[(lti+1)%loop_trim_count] = side_north_trim.m_vi[1]; top_edge_index[lti] = side_north_trim.m_ei; } else { // fix for RR 20423 int lti_prev = (lti+loop_trim_count-1)%loop_trim_count; int lti_next = (lti+1)%loop_trim_count; if ( side_face_index[lti_prev] < 0 && side_face_index[lti_next] < 0 && top_vertex_index[lti] < 0 && top_vertex_index[lti_next] < 0 ) { int bottom_ti_prev = bottom_loop.m_ti[lti_prev]; int bottom_ti = bottom_loop.m_ti[lti]; int bottom_ti_next = bottom_loop.m_ti[lti_next]; if ( bottom_ti >= 0 && bottom_ti < brep.m_T.Count() && bottom_ti_prev >= 0 && bottom_ti_prev < brep.m_T.Count() && bottom_ti_next >= 0 && bottom_ti_next < brep.m_T.Count() ) { const ON_BrepTrim& bottom_trim_prev = brep.m_T[bottom_ti_prev]; const ON_BrepTrim& bottom_trim = brep.m_T[bottom_ti]; const ON_BrepTrim& bottom_trim_next = brep.m_T[bottom_ti_next]; if ( ON_BrepTrim::seam == bottom_trim_prev.m_type && ON_BrepTrim::singular == bottom_trim.m_type && ON_BrepTrim::seam == bottom_trim_next.m_type && bottom_trim.m_vi[0] == bottom_trim.m_vi[1] ) { int vi = bottom_trim.m_vi[0]; if ( vi >= 0 && vi < brep.m_V.Count() ) { ON_BrepVertex& top_vertex = brep.NewVertex(brep.m_V[vi].point+path_vector,0.0); top_vertex_index[lti] = top_vertex.m_vertex_index; top_vertex_index[lti_next] = top_vertex_index[lti]; } } } } } } // Fill in the missing "top" vertices that // are associated with singular and trim edges by looking // at their neighbors. { bool bKeepChecking = true; while( bKeepChecking ) { // set back to true if we make a change. This handles the // (very rare) cases of multiple adjacent singular trims. bKeepChecking = false; for ( lti = 0; lti < loop_trim_count; lti++ ) { if ( top_vertex_index[lti] == -1 ) { for ( i = lti+1; i < loop_trim_count; i++ ) { if ( ON_BrepTrim::singular != brep.m_T[bottom_loop.m_ti[i-1]].m_type ) break; if ( top_vertex_index[i] >= 0 ) { top_vertex_index[lti] = top_vertex_index[i]; bKeepChecking = true; break; } } } if ( top_vertex_index[lti] == -1 ) { for ( i = lti-1; i >= 0; i-- ) { if ( ON_BrepTrim::singular != brep.m_T[bottom_loop.m_ti[i+1]].m_type ) break; if ( top_vertex_index[i] >= 0 ) { top_vertex_index[lti] = top_vertex_index[i]; bKeepChecking = true; break; } } } } } } // Fill in missing edges of "seam" trims. for ( lti = 0; lti < loop_trim_count; lti++ ) { if ( -1 != top_edge_index[lti] ) continue; int bottom_ti = bottom_loop.m_ti[lti]; if ( bottom_ti < 0 || bottom_ti >= brep.m_T.Count() ) continue; const ON_BrepTrim& bottom_trim = brep.m_T[bottom_ti]; if ( ON_BrepTrim::seam != bottom_trim.m_type ) continue; if ( bottom_trim.m_ei < 0 ) continue; if ( bottom_trim.m_ei >= brep.m_E.Count() ) continue; // duplicate bottom edge curve const ON_BrepEdge& bottom_edge = brep.m_E[bottom_trim.m_ei]; ON_Curve* top_c3 = bottom_edge.DuplicateCurve(); if ( 0 == top_c3 ) continue; // move new edge curve to top location top_c3->Translate(path_vector); ON_3dPoint P0 = top_c3->PointAtStart(); ON_3dPoint P1 = top_c3->PointAtEnd(); int top_c3i = brep.AddEdgeCurve(top_c3); top_c3 = 0; // get vertices at start/end of the new edge int e_vi0 = top_vertex_index[lti]; int e_vi1 = top_vertex_index[(lti+1)%loop_trim_count]; if ( bottom_trim.m_bRev3d ) { // put points in trim order ON_3dPoint tmp_P = P0; P0 = P1; P1 = tmp_P; } if ( e_vi0 < 0 ) { e_vi0 = brep.NewVertex(P0).m_vertex_index; top_vertex_index[lti] = e_vi0; } if ( e_vi1 < 0 ) { e_vi1 = brep.NewVertex(P1).m_vertex_index; top_vertex_index[(lti+1)%loop_trim_count] = e_vi1; } if ( bottom_trim.m_bRev3d ) { // put edge vertex indices in edge order int tmp_i = e_vi0; e_vi0 = e_vi1; e_vi1 = tmp_i; } ON_BrepEdge& top_edge = brep.NewEdge(brep.m_V[e_vi0],brep.m_V[e_vi1],top_c3i); top_edge.m_tolerance = bottom_edge.m_tolerance; top_edge_index[lti] = top_edge.m_edge_index; top_trim_bRev3d[lti] = bottom_trim.m_bRev3d?true:false; // find seam mate and set it's // top_edge_index[] to top_edge.m_edge_index. int mate_lti; for( mate_lti = lti+1; mate_lti < loop_trim_count; mate_lti++ ) { if ( top_edge_index[mate_lti] != -1 ) continue; int bottom_mate_ti = bottom_loop.m_ti[mate_lti]; if ( bottom_mate_ti < 0 || bottom_mate_ti >= brep.m_T.Count() ) continue; const ON_BrepTrim& bottom_mate_trim = brep.m_T[bottom_mate_ti]; if ( bottom_mate_trim.m_type != ON_BrepTrim::seam ) continue; if ( bottom_mate_trim.m_ei != bottom_trim.m_ei ) continue; top_edge_index[mate_lti] = top_edge.m_edge_index; top_trim_bRev3d[mate_lti] = bottom_mate_trim.m_bRev3d?true:false; break; } } for ( lti = 0; lti < loop_trim_count; lti++ ) { const ON_BrepTrim& bottom_trim = brep.m_T[ bottom_loop.m_ti[lti] ]; ON_Curve* top_c2 = bottom_trim.DuplicateCurve(); int top_c2i = (0!=top_c2) ? brep.AddTrimCurve(top_c2) : bottom_trim.m_c2i; top_trim_index = -1; if ( bottom_trim.m_type == ON_BrepTrim::singular && top_vertex_index[lti] >= 0 ) { top_trim_index = brep.NewSingularTrim(brep.m_V[top_vertex_index[lti]], top_loop, bottom_trim.m_iso, top_c2i ).m_trim_index; } else if ( bottom_trim.m_type != ON_BrepTrim::singular && top_edge_index[lti] >= 0 && top_edge_index[lti] < brep.m_E.Count() ) { ON_BrepEdge& top_edge = brep.m_E[top_edge_index[lti]]; top_trim_index = brep.NewTrim( top_edge, top_trim_bRev3d[lti], top_loop, top_c2i ).m_trim_index; } else { ON_ERROR("ON_BrepExtrudeHelper_MakeTopLoop ran into capping trouble."); rc = false; break; } ON_BrepTrim& top_trim = brep.m_T[top_trim_index]; top_trim.m_pline = bottom_trim.m_pline; top_trim.m_pbox = bottom_trim.m_pbox; top_trim.m_iso = bottom_trim.m_iso; top_trim.m_type = bottom_trim.m_type; top_trim.m_tolerance[0] = bottom_trim.m_tolerance[0]; top_trim.m_tolerance[1] = bottom_trim.m_tolerance[1]; top_trim.m__legacy_2d_tol = bottom_trim.m__legacy_2d_tol; top_trim.m__legacy_3d_tol = bottom_trim.m__legacy_2d_tol; top_trim.m__legacy_flags = bottom_trim.m__legacy_flags; } if (rc) { top_loop.m_pbox = bottom_loop.m_pbox; } return rc; } static bool ON_BrepExtrudeHelper_CheckLoop( const ON_Brep& brep, int loop_index ) { bool rc = false; if ( loop_index >= 0 ) { ON_BrepLoop::TYPE loop_type = brep.m_L[loop_index].m_type; if ( loop_type == ON_BrepLoop::inner || loop_type == ON_BrepLoop::outer ) rc = true; } return rc; } static bool ON_BrepExtrudeHelper_MakeCap( ON_Brep& brep, int bottom_loop_index, const ON_3dVector path_vector, const int* side_face_index ) { bool bCap = true; // make cap if ( !ON_BrepExtrudeHelper_CheckLoop( brep, bottom_loop_index ) ) return false; brep.m_F.Reserve(brep.m_F.Count() + 1); brep.m_L.Reserve(brep.m_L.Count() + 1); const ON_BrepLoop& bottom_loop = brep.m_L[bottom_loop_index]; const ON_BrepFace& bottom_face = brep.m_F[bottom_loop.m_fi]; const ON_Surface* bottom_surface = bottom_face.SurfaceOf(); ON_Surface* top_surface = bottom_surface->Duplicate(); top_surface->Translate( path_vector ); int top_surface_index = brep.AddSurface( top_surface ); ON_BrepFace& top_face = brep.NewFace( top_surface_index ); bCap = ON_BrepExtrudeHelper_MakeTopLoop( brep, top_face, bottom_loop_index, path_vector, side_face_index ); if ( bCap ) { ON_BrepLoop& top_loop = brep.m_L[brep.m_L.Count()-1]; if ( bottom_loop.m_type == ON_BrepLoop::inner ) { // we capped an inner boundary // top_loop.m_type = ON_BrepLoop::outer; // done in ON_BrepExtrudeHelper_MakeTopLoop brep.FlipLoop(top_loop); } else if ( bottom_loop.m_type == ON_BrepLoop::outer ) { // we capped an outer boundary // top_loop.m_type = ON_BrepLoop::outer; // done in ON_BrepExtrudeHelper_MakeTopLoop brep.FlipFace(top_face); } } else { // delete partially made cap face brep.DeleteFace( top_face, false ); delete brep.m_S[top_surface_index]; brep.m_S[top_surface_index] = 0; } return bCap; } int ON_BrepExtrudeFace( ON_Brep& brep, int face_index, const ON_Curve& path_curve, bool bCap ) { int rc = 0; // returns 1 for success with no cap, 2 for success with a cap if ( face_index < 0 || face_index >= brep.m_F.Count() ) return false; const int face_loop_count = brep.m_F[face_index].m_li.Count(); if ( face_loop_count < 1 ) return false; if ( brep.m_F[face_index].m_li.Count() == 1 ) { rc = ON_BrepExtrudeLoop( brep, brep.m_F[face_index].m_li[0], path_curve, bCap ); } else { ON_3dVector path_vector; ON_SimpleArray<int> side_face_index; ON_SimpleArray<int> side_face_index_loop_mark; int li, fli; if ( !ON_BrepExtrudeHelper_CheckPathCurve( path_curve, path_vector ) ) return 0; //const int trim_count0 = brep.m_T.Count(); const int loop_count0 = brep.m_L.Count(); const int face_count0 = brep.m_F.Count(); // count number of new objects so we can grow arrays // efficiently and use refs to dynamic array elements. int new_side_trim_count = 0; for ( fli = 0; fli < face_loop_count; fli++ ) { li = brep.m_F[face_index].m_li[fli]; if ( li < 0 || li >= loop_count0 ) return false; if ( !ON_BrepExtrudeHelper_CheckLoop( brep, li ) ) continue; new_side_trim_count += brep.m_L[li].m_ti.Count(); } if ( new_side_trim_count == 0 ) return false; ON_BrepExtrudeHelper_ReserveSpace( brep, new_side_trim_count, bCap?1:0 ); side_face_index.Reserve(new_side_trim_count); side_face_index_loop_mark.Reserve(face_loop_count); const ON_BrepFace& face = brep.m_F[face_index]; rc = true; int outer_loop_index = -1; int outer_fli = -1; for ( fli = 0; fli < face_loop_count && rc; fli++ ) { side_face_index_loop_mark.Append( side_face_index.Count() ); li = face.m_li[fli]; if ( !ON_BrepExtrudeHelper_CheckLoop( brep, li ) ) continue; ON_BrepLoop& loop = brep.m_L[li]; if ( bCap && loop.m_type == ON_BrepLoop::outer ) { if ( outer_loop_index >= 0 ) bCap = false; else { outer_loop_index = li; outer_fli = fli; } } rc = ON_BrepExtrudeHelper_MakeSides( brep, li, path_curve, bCap, side_face_index ); } if ( bCap && rc && outer_loop_index >= 0 ) { const int face_count1 = brep.m_F.Count(); bCap = ON_BrepExtrudeHelper_MakeCap( brep, outer_loop_index, path_vector, side_face_index.Array() + side_face_index_loop_mark[outer_fli] ); if ( bCap && brep.m_F.Count() > face_count1) { // put inner bondaries on the cap rc = 2; ON_BrepFace& cap_face = brep.m_F[brep.m_F.Count()-1]; for ( fli = 0; fli < face_loop_count && rc; fli++ ) { li = face.m_li[fli]; if ( li == outer_loop_index ) continue; if ( !ON_BrepExtrudeHelper_CheckLoop( brep, li ) ) continue; if ( ON_BrepExtrudeHelper_MakeTopLoop( brep, cap_face, li, path_vector, side_face_index.Array() + side_face_index_loop_mark[fli] ) ) { ON_BrepLoop& top_loop = brep.m_L[brep.m_L.Count()-1]; top_loop.m_type = brep.m_L[li].m_type; } } } } if ( brep.m_F[face_index].m_bRev ) { for ( int fi = face_count0; fi < brep.m_F.Count(); fi++ ) { brep.FlipFace(brep.m_F[fi]); } } } return rc; } int ON_BrepExtrudeLoop( ON_Brep& brep, int loop_index, const ON_Curve& path_curve, bool bCap ) { ON_SimpleArray<int> side_face_index; // index of new face above brep.m_L[loop_index].m_ti[lti] ON_3dVector path_vector; const int face_count0 = brep.m_F.Count(); if ( loop_index < 0 || loop_index >= brep.m_L.Count() ) return false; if ( !ON_BrepExtrudeHelper_CheckPathCurve(path_curve,path_vector) ) return false; // can only cap closed loops ( for now, just test for inner and outer loops). if ( brep.m_L[loop_index].m_type != ON_BrepLoop::outer && brep.m_L[loop_index].m_type != ON_BrepLoop::inner ) bCap = false; // make sides if ( !ON_BrepExtrudeHelper_MakeSides( brep, loop_index, path_curve, bCap, side_face_index ) ) return false; // make cap if ( bCap ) bCap = ON_BrepExtrudeHelper_MakeCap( brep, loop_index, path_vector, side_face_index.Array() ); const ON_BrepLoop& loop = brep.m_L[loop_index]; if ( loop.m_fi >= 0 && loop.m_fi < brep.m_F.Count() && brep.m_F[loop.m_fi].m_bRev ) { for ( int fi = face_count0; fi < brep.m_F.Count(); fi++ ) { brep.FlipFace( brep.m_F[fi] ); } } return (bCap?2:1); } int ON_BrepExtrudeEdge( ON_Brep& brep, int edge_index, const ON_Curve& path_curve ) { ON_3dVector path_vector; if ( edge_index < 0 && edge_index >= brep.m_E.Count() ) return false; if ( !ON_BrepExtrudeHelper_CheckPathCurve(path_curve,path_vector) ) return false; // make sides bool bRev = false; ON_SumSurface* sum_srf = ON_BrepExtrudeHelper_MakeSumSrf( path_curve, brep.m_E[edge_index], bRev ); if ( !sum_srf ) return false; int vid[4], eid[4], bRev3d[4]; vid[0] = brep.m_E[edge_index].m_vi[bRev?0:1]; vid[1] = brep.m_E[edge_index].m_vi[bRev?1:0]; vid[2] = -1; vid[3] = -1; eid[0] = edge_index; // "south side edge" eid[1] = -1; eid[2] = -1; eid[3] = -1; bRev3d[0] = bRev?0:1; bRev3d[1] = 0; bRev3d[2] = 0; bRev3d[3] = 0; return brep.NewFace( sum_srf, vid, eid, bRev3d ) ? true : false; } bool ON_BrepExtrude( ON_Brep& brep, const ON_Curve& path_curve, bool bCap ) { ON_Workspace ws; const int vcount0 = brep.m_V.Count(); const int tcount0 = brep.m_T.Count(); const int lcount0 = brep.m_L.Count(); const int ecount0 = brep.m_E.Count(); const int fcount0 = brep.m_F.Count(); const ON_3dPoint PathStart = path_curve.PointAtStart(); ON_3dPoint P = path_curve.PointAtEnd(); if ( !PathStart.IsValid() || !P.IsValid() ) return false; const ON_3dVector height = P - PathStart; if ( !height.IsValid() || height.Length() <= ON_ZERO_TOLERANCE ) return false; ON_Xform tr; tr.Translation(height); // count number of new sides int side_count = 0; int i, vi, ei, fi; bool* bSideEdge = (bool*)ws.GetIntMemory(ecount0*sizeof(bSideEdge[0])); for ( ei = 0; ei < ecount0; ei++ ) { const ON_BrepEdge& e = brep.m_E[ei]; if ( 1 == e.m_ti.Count() ) { side_count++; bSideEdge[ei] = true; } else { bSideEdge[ei] = false; } } brep.m_V.Reserve( 2*vcount0 ); i = 4*side_count + (bCap?tcount0:0); brep.m_T.Reserve( tcount0 + i ); brep.m_C2.Reserve( brep.m_C2.Count() + i ); brep.m_L.Reserve( lcount0 + side_count + (bCap?lcount0:0) ); i = side_count + (bCap?ecount0:side_count); brep.m_E.Reserve( ecount0 + i ); brep.m_C3.Reserve( brep.m_C3.Count() + i ); i = side_count + (bCap?fcount0:0); brep.m_F.Reserve( fcount0 + i ); brep.m_S.Reserve( brep.m_S.Count() + i ); bool bOK = true; // build top vertices int* topvimap = ws.GetIntMemory(vcount0); memset(topvimap,0,vcount0*sizeof(topvimap[0])); if ( bCap ) { for ( vi = 0; vi < vcount0; vi++ ) { const ON_BrepVertex& bottomv = brep.m_V[vi]; ON_BrepVertex& topv = brep.NewVertex(bottomv.point+height,bottomv.m_tolerance); topvimap[vi] = topv.m_vertex_index; } } else { for ( ei = 0; ei < ecount0; ei++ ) { if ( bSideEdge[ei] ) { const ON_BrepEdge& bottome = brep.m_E[ei]; int bottomvi0 = bottome.m_vi[0]; if ( bottomvi0 < 0 || bottomvi0 >= vcount0 ) { bOK = false; break; } int bottomvi1 = bottome.m_vi[1]; if ( bottomvi1 < 0 || bottomvi1 >= vcount0 ) { bOK = false; break; } if ( !topvimap[bottomvi0] ) { const ON_BrepVertex& bottomv = brep.m_V[bottomvi0]; ON_BrepVertex& topv = brep.NewVertex(bottomv.point+height,bottomv.m_tolerance); topvimap[bottomvi0] = topv.m_vertex_index; } if ( !topvimap[bottomvi1] ) { const ON_BrepVertex& bottomv = brep.m_V[bottomvi1]; ON_BrepVertex& topv = brep.NewVertex(bottomv.point+height,bottomv.m_tolerance); topvimap[bottomvi1] = topv.m_vertex_index; } } } } // build top edges int* topeimap = ws.GetIntMemory(ecount0); memset(topeimap,0,ecount0*sizeof(topeimap[0])); if ( bOK ) for ( ei = 0; ei < ecount0; ei++ ) { if ( bCap || bSideEdge[ei] ) { const ON_BrepEdge& bottome = brep.m_E[ei]; ON_BrepVertex& topv0 = brep.m_V[topvimap[bottome.m_vi[0]]]; ON_BrepVertex& topv1 = brep.m_V[topvimap[bottome.m_vi[1]]]; ON_Curve* c3 = bottome.DuplicateCurve(); if ( !c3 ) { bOK = false; break; } c3->Transform(tr); int c3i = brep.AddEdgeCurve(c3); ON_BrepEdge& tope = brep.NewEdge(topv0,topv1,c3i,0,bottome.m_tolerance); topeimap[ei] = tope.m_edge_index; } } // build side edges int* sideveimap = ws.GetIntMemory(vcount0); memset(sideveimap,0,vcount0*sizeof(sideveimap[0])); if ( bOK ) for ( vi = 0; vi < vcount0; vi++ ) { ON_BrepVertex& bottomv = brep.m_V[vi]; for ( int vei = 0; vei < bottomv.m_ei.Count(); vei++ ) { if ( bSideEdge[bottomv.m_ei[vei]] && topvimap[vi] ) { ON_BrepVertex& topv = brep.m_V[topvimap[vi]]; ON_Curve* c3 = path_curve.DuplicateCurve(); if ( !c3 ) { bOK = false; } else { ON_3dVector D = bottomv.point - PathStart; c3->Translate(D); int c3i = brep.AddEdgeCurve(c3); const ON_BrepEdge& e = brep.NewEdge(bottomv,topv,c3i,0,0.0); sideveimap[vi] = e.m_edge_index; } break; } } } if ( bOK && bCap ) { // build top faces for (fi = 0; fi < fcount0; fi++ ) { const ON_BrepFace& bottomf = brep.m_F[fi]; ON_Surface* srf = bottomf.DuplicateSurface(); if ( !srf ) { bOK = false; break; } srf->Transform(tr); int si = brep.AddSurface(srf); ON_BrepFace& topf = brep.NewFace(si); topf.m_bRev = !bottomf.m_bRev; const int loop_count = bottomf.m_li.Count(); topf.m_li.Reserve(loop_count); for ( int fli = 0; fli < loop_count; fli++ ) { const ON_BrepLoop& bottoml = brep.m_L[bottomf.m_li[fli]]; ON_BrepLoop& topl = brep.NewLoop(bottoml.m_type,topf); const int loop_trim_count = bottoml.m_ti.Count(); topl.m_ti.Reserve(loop_trim_count); for ( int lti = 0; lti < loop_trim_count; lti++ ) { const ON_BrepTrim& bottomt = brep.m_T[bottoml.m_ti[lti]]; ON_NurbsCurve* c2 = ON_NurbsCurve::New(); if ( !bottomt.GetNurbForm(*c2) ) { delete c2; bOK = false; break; } int c2i = brep.AddTrimCurve(c2); ON_BrepTrim* topt = 0; if ( bottomt.m_ei >= 0 ) { ON_BrepEdge& tope = brep.m_E[topeimap[bottomt.m_ei]]; topt = &brep.NewTrim(tope,bottomt.m_bRev3d,topl,c2i); } else { // singular trim ON_BrepVertex& topv = brep.m_V[topvimap[bottomt.m_vi[0]]]; topt = &brep.NewSingularTrim(topv,topl,bottomt.m_iso,c2i); } topt->m_tolerance[0] = bottomt.m_tolerance[0]; topt->m_tolerance[1] = bottomt.m_tolerance[1]; topt->m_pbox = bottomt.m_pbox; topt->m_type = bottomt.m_type; topt->m_iso = bottomt.m_iso; } topl.m_pbox = bottoml.m_pbox; } } } // build sides int bRev3d[4] = {0,0,1,1}; int vid[4], eid[4]; if( bOK ) for ( ei = 0; ei < ecount0; ei++ ) { if ( bSideEdge[ei] && topeimap[ei] ) { ON_BrepEdge& bottome = brep.m_E[ei]; ON_BrepEdge& tope = brep.m_E[topeimap[ei]]; vid[0] = bottome.m_vi[0]; vid[1] = bottome.m_vi[1]; vid[2] = topvimap[vid[1]]; vid[3] = topvimap[vid[0]]; if ( sideveimap[vid[0]] && sideveimap[vid[1]] ) { ON_BrepEdge& leftedge = brep.m_E[sideveimap[vid[0]]]; ON_BrepEdge& rightedge = brep.m_E[sideveimap[vid[1]]]; ON_Curve* cx = bottome.DuplicateCurve(); if ( !cx ) { bOK = false; break; } ON_Curve* cy = leftedge.DuplicateCurve(); if ( !cy ) { delete cx; bOK = false; break; } ON_SumSurface* srf = new ON_SumSurface(); srf->m_curve[0] = cx; srf->m_curve[1] = cy; srf->m_basepoint = srf->m_curve[1]->PointAtStart(); srf->m_basepoint.x = -srf->m_basepoint.x; srf->m_basepoint.y = -srf->m_basepoint.y; srf->m_basepoint.z = -srf->m_basepoint.z; eid[0] = bottome.m_edge_index; eid[1] = rightedge.m_edge_index; eid[2] = tope.m_edge_index; eid[3] = leftedge.m_edge_index; ON_BrepFace* face = brep.NewFace(srf,vid,eid,bRev3d); if ( !face ) { bOK = false; break; } else if ( bottome.m_ti.Count() == 2 ) { const ON_BrepTrim& trim0 = brep.m_T[bottome.m_ti[0]]; const ON_BrepTrim& trim1 = brep.m_T[bottome.m_ti[1]]; const ON_BrepLoop& loop0 = brep.m_L[trim0.m_li]; const ON_BrepLoop& loop1 = brep.m_L[trim1.m_li]; bool bBottomFaceRev = brep.m_F[(loop0.m_fi != face->m_face_index) ? loop0.m_fi : loop1.m_fi].m_bRev; bool bSideFaceRev = ( trim0.m_bRev3d != trim1.m_bRev3d ) ? bBottomFaceRev : !bBottomFaceRev; face->m_bRev = bSideFaceRev; } } } } if ( !bOK ) { for ( vi = brep.m_V.Count(); vi >= vcount0; vi-- ) { brep.DeleteVertex(brep.m_V[vi]); } } return bOK; } int ON_BrepExtrudeVertex( ON_Brep& brep, int vertex_index, const ON_Curve& path_curve ) { ON_3dVector path_vector; if ( vertex_index < 0 && vertex_index >= brep.m_V.Count() ) return false; if ( !ON_BrepExtrudeHelper_CheckPathCurve(path_curve,path_vector) ) return false; ON_Curve* c3 = path_curve.Duplicate(); brep.m_V.Reserve( brep.m_V.Count() + 1 ); ON_BrepVertex& v0 = brep.m_V[vertex_index]; ON_BrepVertex& v1 = brep.NewVertex( v0.point + path_vector, 0.0 ); c3->Translate( v0.point - c3->PointAtStart() ); int c3i = brep.AddEdgeCurve( c3 ); ON_BrepEdge& edge = brep.NewEdge( v0, v1, c3i ); edge.m_tolerance = 0.0; return true; } int ON_BrepConeFace( ON_Brep& brep, int face_index, ON_3dPoint apex_point ) { int rc = 0; // returns 1 for success with no cap, 2 for success with a cap if ( face_index < 0 || face_index >= brep.m_F.Count() ) return false; const int face_loop_count = brep.m_F[face_index].m_li.Count(); if ( face_loop_count < 1 ) return false; if ( brep.m_F[face_index].m_li.Count() == 1 ) { rc = ON_BrepConeLoop( brep, brep.m_F[face_index].m_li[0], apex_point ); } else { int li, fli; //const int trim_count0 = brep.m_T.Count(); const int loop_count0 = brep.m_L.Count(); //const int face_count0 = brep.m_F.Count(); // count number of new objects so we can grow arrays // efficiently and use refs to dynamic array elements. int new_side_trim_count = 0; for ( fli = 0; fli < face_loop_count; fli++ ) { li = brep.m_F[face_index].m_li[fli]; if ( li < 0 || li >= loop_count0 ) return false; if ( !ON_BrepExtrudeHelper_CheckLoop( brep, li ) ) continue; new_side_trim_count += brep.m_L[li].m_ti.Count(); } if ( new_side_trim_count == 0 ) return false; ON_BrepExtrudeHelper_ReserveSpace( brep, new_side_trim_count, 0 ); const ON_BrepFace& face = brep.m_F[face_index]; //ON_BrepVertex& apex_vertex = brep.NewVertex( apex_point, 0.0 ); rc = true; for ( fli = 0; fli < face_loop_count && rc; fli++ ) { li = face.m_li[fli]; if ( !ON_BrepExtrudeHelper_CheckLoop( brep, li ) ) continue; rc = ON_BrepConeLoop( brep, li, apex_point ); } } return rc; } bool ON_BrepConeLoop( ON_Brep& brep, int loop_index, ON_3dPoint apex_point ) { if ( loop_index < 0 && loop_index >= brep.m_L.Count() ) return false; int lti, ti, i, vid[4], eid[4], bRev3d[4]; // indices of new faces appended to the side_face_index[] array // (1 face index for each trim, -1 is used for singular trims) // count number of new objects so we can grow arrays // efficiently and use refs to dynamic array elements. const int loop_trim_count = brep.m_L[loop_index].m_ti.Count(); if ( loop_trim_count == 0 ) return false; // save input trim and edge counts for use below const int trim_count0 = brep.m_T.Count(); const int edge_count0 = brep.m_E.Count(); ON_BrepExtrudeHelper_ReserveSpace( brep, loop_trim_count, 0 ); int prev_face_index = -1; int first_face_east_trim_index = -1; ON_BrepVertex& apex_vertex = brep.NewVertex( apex_point, 0.0 ); for ( lti = 0; lti < loop_trim_count; lti++ ) { ON_NurbsSurface* cone_srf = 0; ti = brep.m_L[loop_index].m_ti[lti]; if ( ti < 0 || ti >= trim_count0 ) continue; for ( i = 0; i < 4; i++ ) { vid[i] = -1; eid[i] = -1; } bRev3d[0] = false; bRev3d[1] = false; bRev3d[2] = false; bRev3d[3] = false; // get side surface for new face // get side surface for new face { ON_BrepTrim& trim = brep.m_T[ti]; if ( trim.m_ei >= 0 && trim.m_ei < edge_count0 ) { const ON_BrepEdge& base_edge = brep.m_E[trim.m_ei]; // connect new face to existing topology on trim vid[0] = trim.m_vi[1]; vid[1] = trim.m_vi[0]; eid[0] = base_edge.m_edge_index; bRev3d[0] = (trim.m_bRev3d?false:true); cone_srf = ON_BrepExtrudeHelper_MakeConeSrf( apex_point, base_edge, bRev3d[0] ); } } if ( !cone_srf ) continue; vid[2] = apex_vertex.m_vertex_index; vid[3] = apex_vertex.m_vertex_index; if ( prev_face_index >= 0 ) { const ON_BrepTrim& prev_west_trim = brep.m_T[ brep.m_L[ brep.m_F[prev_face_index].m_li[0]].m_ti[3] ]; vid[2] = prev_west_trim.m_vi[0]; eid[1] = prev_west_trim.m_ei; bRev3d[1] = (prev_west_trim.m_bRev3d?false:true); } if ( first_face_east_trim_index >= 0 && brep.m_T[first_face_east_trim_index].m_vi[0] == vid[0] ) { const ON_BrepTrim& first_face_east_trim = brep.m_T[first_face_east_trim_index]; vid[3] = first_face_east_trim.m_vi[1]; eid[3] = first_face_east_trim.m_ei; bRev3d[3] = (first_face_east_trim.m_bRev3d?false:true); } const ON_BrepFace* side_face = brep.NewFace(cone_srf,vid,eid,bRev3d); if ( side_face ) { prev_face_index = side_face->m_face_index; if ( first_face_east_trim_index < 0 ) first_face_east_trim_index = brep.m_L[ side_face->m_li[0] ].m_ti[1]; } } return true; } int ON_BrepConeEdge( ON_Brep& brep, int edge_index, ON_3dPoint apex_point ) { //ON_3dVector path_vector; if ( edge_index < 0 && edge_index >= brep.m_E.Count() ) return false; // make sides ON_NurbsSurface* cone_srf = ON_BrepExtrudeHelper_MakeConeSrf( apex_point, brep.m_E[edge_index], false ); if ( !cone_srf ) return false; int vid[4], eid[4], bRev3d[4]; vid[0] = brep.m_E[edge_index].m_vi[0]; vid[1] = brep.m_E[edge_index].m_vi[1]; vid[2] = -1; vid[3] = -1; eid[0] = edge_index; eid[1] = -1; eid[2] = -1; eid[3] = -1; bRev3d[0] = 0; bRev3d[1] = 0; bRev3d[2] = 0; bRev3d[3] = 0; return brep.NewFace( cone_srf, vid, eid, bRev3d ) ? true : false; }
bsd-3-clause
cognitiveclass/edx-platform
lms/djangoapps/instructor/enrollment_report.py
3294
""" Defines abstract class for the Enrollment Reports. """ from django.contrib.auth.models import User from student.models import UserProfile import collections import json import abc class AbstractEnrollmentReportProvider(object): """ Abstract interface for Detailed Enrollment Report Provider """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def get_enrollment_info(self, user, course_id): """ Returns the User Enrollment information. """ raise NotImplementedError() @abc.abstractmethod def get_user_profile(self, user_id): """ Returns the UserProfile information. """ raise NotImplementedError() @abc.abstractmethod def get_payment_info(self, user, course_id): """ Returns the User Payment information. """ raise NotImplementedError() class BaseAbstractEnrollmentReportProvider(AbstractEnrollmentReportProvider): """ The base abstract class for all Enrollment Reports that can support multiple backend such as MySQL/Django-ORM. # don't allow instantiation of this class, it must be subclassed """ def get_user_profile(self, user_id): """ Returns the UserProfile information. """ user_info = User.objects.select_related('profile').get(id=user_id) # extended user profile fields are stored in the user_profile meta column meta = {} if user_info.profile.meta: meta = json.loads(user_info.profile.meta) user_data = collections.OrderedDict() user_data['User ID'] = user_info.id user_data['Username'] = user_info.username user_data['Email'] = user_info.email user_data['Full Name'] = user_info.profile.name user_data['First Name'] = meta.get('first-name', '') user_data['Last Name'] = meta.get('last-name', '') user_data['Company Name'] = meta.get('company', '') user_data['Title'] = meta.get('title', '') user_data['Language'] = user_info.profile.language user_data['Country'] = user_info.profile.country user_data['Year of Birth'] = user_info.profile.year_of_birth user_data['Gender'] = None gender = user_info.profile.gender for _gender in UserProfile.GENDER_CHOICES: if gender == _gender[0]: user_data['Gender'] = _gender[1] break user_data['Level of Education'] = None level_of_education = user_info.profile.level_of_education for _loe in UserProfile.LEVEL_OF_EDUCATION_CHOICES: if level_of_education == _loe[0]: user_data['Level of Education'] = _loe[1] user_data['Mailing Address'] = user_info.profile.mailing_address user_data['Goals'] = user_info.profile.goals user_data['City'] = user_info.profile.city user_data['Country'] = user_info.profile.country return user_data def get_enrollment_info(self, user, course_id): """ Returns the User Enrollment information. """ raise NotImplementedError() def get_payment_info(self, user, course_id): """ Returns the User Payment information. """ raise NotImplementedError()
agpl-3.0
wenlock/oneview-golang
vendor/github.com/docker/machine/libmachine/drivers/serial_test.go
8005
package drivers import ( "testing" "github.com/docker/machine/libmachine/mcnflag" "github.com/docker/machine/libmachine/state" "github.com/stretchr/testify/assert" ) type CallRecorder struct { calls []string } func (c *CallRecorder) record(call string) { c.calls = append(c.calls, call) } type MockLocker struct { calls *CallRecorder } func (l *MockLocker) Lock() { l.calls.record("Lock") } func (l *MockLocker) Unlock() { l.calls.record("Unlock") } type MockDriver struct { calls *CallRecorder driverName string flags []mcnflag.Flag ip string machineName string sshHostname string sshKeyPath string sshPort int sshUsername string url string state state.State } func (d *MockDriver) Create() error { d.calls.record("Create") return nil } func (d *MockDriver) DriverName() string { d.calls.record("DriverName") return d.driverName } func (d *MockDriver) GetCreateFlags() []mcnflag.Flag { d.calls.record("GetCreateFlags") return d.flags } func (d *MockDriver) GetIP() (string, error) { d.calls.record("GetIP") return d.ip, nil } func (d *MockDriver) GetMachineName() string { d.calls.record("GetMachineName") return d.machineName } func (d *MockDriver) GetSSHHostname() (string, error) { d.calls.record("GetSSHHostname") return d.sshHostname, nil } func (d *MockDriver) GetSSHKeyPath() string { d.calls.record("GetSSHKeyPath") return d.sshKeyPath } func (d *MockDriver) GetSSHPort() (int, error) { d.calls.record("GetSSHPort") return d.sshPort, nil } func (d *MockDriver) GetSSHUsername() string { d.calls.record("GetSSHUsername") return d.sshUsername } func (d *MockDriver) GetURL() (string, error) { d.calls.record("GetURL") return d.url, nil } func (d *MockDriver) GetState() (state.State, error) { d.calls.record("GetState") return d.state, nil } func (d *MockDriver) Kill() error { d.calls.record("Kill") return nil } func (d *MockDriver) PreCreateCheck() error { d.calls.record("PreCreateCheck") return nil } func (d *MockDriver) Remove() error { d.calls.record("Remove") return nil } func (d *MockDriver) Restart() error { d.calls.record("Restart") return nil } func (d *MockDriver) SetConfigFromFlags(opts DriverOptions) error { d.calls.record("SetConfigFromFlags") return nil } func (d *MockDriver) Start() error { d.calls.record("Start") return nil } func (d *MockDriver) Stop() error { d.calls.record("Stop") return nil } func TestSerialDriverCreate(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{calls: callRecorder}, &MockLocker{calls: callRecorder}) err := driver.Create() assert.NoError(t, err) assert.Equal(t, []string{"Lock", "Create", "Unlock"}, callRecorder.calls) } func TestSerialDriverDriverName(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{driverName: "DRIVER", calls: callRecorder}, &MockLocker{calls: callRecorder}) driverName := driver.DriverName() assert.Equal(t, "DRIVER", driverName) assert.Equal(t, []string{"Lock", "DriverName", "Unlock"}, callRecorder.calls) } func TestSerialDriverGetIP(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{ip: "IP", calls: callRecorder}, &MockLocker{calls: callRecorder}) ip, _ := driver.GetIP() assert.Equal(t, "IP", ip) assert.Equal(t, []string{"Lock", "GetIP", "Unlock"}, callRecorder.calls) } func TestSerialDriverGetMachineName(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{machineName: "MACHINE_NAME", calls: callRecorder}, &MockLocker{calls: callRecorder}) machineName := driver.GetMachineName() assert.Equal(t, "MACHINE_NAME", machineName) assert.Equal(t, []string{"Lock", "GetMachineName", "Unlock"}, callRecorder.calls) } func TestSerialDriverGetSSHHostname(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{sshHostname: "SSH_HOSTNAME", calls: callRecorder}, &MockLocker{calls: callRecorder}) sshHostname, _ := driver.GetSSHHostname() assert.Equal(t, "SSH_HOSTNAME", sshHostname) assert.Equal(t, []string{"Lock", "GetSSHHostname", "Unlock"}, callRecorder.calls) } func TestSerialDriverGetSSHKeyPath(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{sshKeyPath: "PATH", calls: callRecorder}, &MockLocker{calls: callRecorder}) path := driver.GetSSHKeyPath() assert.Equal(t, "PATH", path) assert.Equal(t, []string{"Lock", "GetSSHKeyPath", "Unlock"}, callRecorder.calls) } func TestSerialDriverGetSSHPort(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{sshPort: 42, calls: callRecorder}, &MockLocker{calls: callRecorder}) sshPort, _ := driver.GetSSHPort() assert.Equal(t, 42, sshPort) assert.Equal(t, []string{"Lock", "GetSSHPort", "Unlock"}, callRecorder.calls) } func TestSerialDriverGetSSHUsername(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{sshUsername: "SSH_USER", calls: callRecorder}, &MockLocker{calls: callRecorder}) sshUsername := driver.GetSSHUsername() assert.Equal(t, "SSH_USER", sshUsername) assert.Equal(t, []string{"Lock", "GetSSHUsername", "Unlock"}, callRecorder.calls) } func TestSerialDriverGetURL(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{url: "URL", calls: callRecorder}, &MockLocker{calls: callRecorder}) url, _ := driver.GetURL() assert.Equal(t, "URL", url) assert.Equal(t, []string{"Lock", "GetURL", "Unlock"}, callRecorder.calls) } func TestSerialDriverGetState(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{state: state.Running, calls: callRecorder}, &MockLocker{calls: callRecorder}) machineState, _ := driver.GetState() assert.Equal(t, state.Running, machineState) assert.Equal(t, []string{"Lock", "GetState", "Unlock"}, callRecorder.calls) } func TestSerialDriverKill(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{calls: callRecorder}, &MockLocker{calls: callRecorder}) driver.Kill() assert.Equal(t, []string{"Lock", "Kill", "Unlock"}, callRecorder.calls) } func TestSerialDriverPreCreateCheck(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{calls: callRecorder}, &MockLocker{calls: callRecorder}) driver.PreCreateCheck() assert.Equal(t, []string{"Lock", "PreCreateCheck", "Unlock"}, callRecorder.calls) } func TestSerialDriverRemove(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{calls: callRecorder}, &MockLocker{calls: callRecorder}) driver.Remove() assert.Equal(t, []string{"Lock", "Remove", "Unlock"}, callRecorder.calls) } func TestSerialDriverRestart(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{calls: callRecorder}, &MockLocker{calls: callRecorder}) driver.Restart() assert.Equal(t, []string{"Lock", "Restart", "Unlock"}, callRecorder.calls) } func TestSerialDriverSetConfigFromFlags(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{calls: callRecorder}, &MockLocker{calls: callRecorder}) driver.SetConfigFromFlags(nil) assert.Equal(t, []string{"Lock", "SetConfigFromFlags", "Unlock"}, callRecorder.calls) } func TestSerialDriverStart(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{calls: callRecorder}, &MockLocker{calls: callRecorder}) driver.Start() assert.Equal(t, []string{"Lock", "Start", "Unlock"}, callRecorder.calls) } func TestSerialDriverStop(t *testing.T) { callRecorder := &CallRecorder{} driver := newSerialDriverWithLock(&MockDriver{calls: callRecorder}, &MockLocker{calls: callRecorder}) driver.Stop() assert.Equal(t, []string{"Lock", "Stop", "Unlock"}, callRecorder.calls) }
apache-2.0
rooshilp/CMPUT410W15-project
testenv/lib/python2.7/site-packages/django/contrib/contenttypes/tests/tests.py
10142
from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.views import shortcut from django.contrib.sites.shortcuts import get_current_site from django.http import HttpRequest, Http404 from django.test import TestCase, override_settings from django.utils import six from .models import ConcreteModel, ProxyModel, FooWithoutUrl, FooWithUrl, FooWithBrokenAbsoluteUrl class ContentTypesTests(TestCase): def setUp(self): ContentType.objects.clear_cache() def tearDown(self): ContentType.objects.clear_cache() def test_lookup_cache(self): """ Make sure that the content type cache (see ContentTypeManager) works correctly. Lookups for a particular content type -- by model, ID or natural key -- should hit the database only on the first lookup. """ # At this point, a lookup for a ContentType should hit the DB with self.assertNumQueries(1): ContentType.objects.get_for_model(ContentType) # A second hit, though, won't hit the DB, nor will a lookup by ID # or natural key with self.assertNumQueries(0): ct = ContentType.objects.get_for_model(ContentType) with self.assertNumQueries(0): ContentType.objects.get_for_id(ct.id) with self.assertNumQueries(0): ContentType.objects.get_by_natural_key('contenttypes', 'contenttype') # Once we clear the cache, another lookup will again hit the DB ContentType.objects.clear_cache() with self.assertNumQueries(1): ContentType.objects.get_for_model(ContentType) # The same should happen with a lookup by natural key ContentType.objects.clear_cache() with self.assertNumQueries(1): ContentType.objects.get_by_natural_key('contenttypes', 'contenttype') # And a second hit shouldn't hit the DB with self.assertNumQueries(0): ContentType.objects.get_by_natural_key('contenttypes', 'contenttype') def test_get_for_models_empty_cache(self): # Empty cache. with self.assertNumQueries(1): cts = ContentType.objects.get_for_models(ContentType, FooWithUrl) self.assertEqual(cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), }) def test_get_for_models_partial_cache(self): # Partial cache ContentType.objects.get_for_model(ContentType) with self.assertNumQueries(1): cts = ContentType.objects.get_for_models(ContentType, FooWithUrl) self.assertEqual(cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), }) def test_get_for_models_full_cache(self): # Full cache ContentType.objects.get_for_model(ContentType) ContentType.objects.get_for_model(FooWithUrl) with self.assertNumQueries(0): cts = ContentType.objects.get_for_models(ContentType, FooWithUrl) self.assertEqual(cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), }) def test_get_for_concrete_model(self): """ Make sure the `for_concrete_model` kwarg correctly works with concrete, proxy and deferred models """ concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel) self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(ProxyModel)) self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(ConcreteModel, for_concrete_model=False)) proxy_model_ct = ContentType.objects.get_for_model(ProxyModel, for_concrete_model=False) self.assertNotEqual(concrete_model_ct, proxy_model_ct) # Make sure deferred model are correctly handled ConcreteModel.objects.create(name="Concrete") DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__ DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__ self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(DeferredConcreteModel)) self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(DeferredConcreteModel, for_concrete_model=False)) self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(DeferredProxyModel)) self.assertEqual(proxy_model_ct, ContentType.objects.get_for_model(DeferredProxyModel, for_concrete_model=False)) def test_get_for_concrete_models(self): """ Make sure the `for_concrete_models` kwarg correctly works with concrete, proxy and deferred models. """ concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel) cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel) self.assertEqual(cts, { ConcreteModel: concrete_model_ct, ProxyModel: concrete_model_ct, }) proxy_model_ct = ContentType.objects.get_for_model(ProxyModel, for_concrete_model=False) cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel, for_concrete_models=False) self.assertEqual(cts, { ConcreteModel: concrete_model_ct, ProxyModel: proxy_model_ct, }) # Make sure deferred model are correctly handled ConcreteModel.objects.create(name="Concrete") DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__ DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__ cts = ContentType.objects.get_for_models(DeferredConcreteModel, DeferredProxyModel) self.assertEqual(cts, { DeferredConcreteModel: concrete_model_ct, DeferredProxyModel: concrete_model_ct, }) cts = ContentType.objects.get_for_models(DeferredConcreteModel, DeferredProxyModel, for_concrete_models=False) self.assertEqual(cts, { DeferredConcreteModel: concrete_model_ct, DeferredProxyModel: proxy_model_ct, }) @override_settings(ALLOWED_HOSTS=['example.com']) def test_shortcut_view(self): """ Check that the shortcut view (used for the admin "view on site" functionality) returns a complete URL regardless of whether the sites framework is installed """ request = HttpRequest() request.META = { "SERVER_NAME": "Example.com", "SERVER_PORT": "80", } user_ct = ContentType.objects.get_for_model(FooWithUrl) obj = FooWithUrl.objects.create(name="john") with self.modify_settings(INSTALLED_APPS={'append': 'django.contrib.sites'}): response = shortcut(request, user_ct.id, obj.id) self.assertEqual("http://%s/users/john/" % get_current_site(request).domain, response._headers.get("location")[1]) with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}): response = shortcut(request, user_ct.id, obj.id) self.assertEqual("http://Example.com/users/john/", response._headers.get("location")[1]) def test_shortcut_view_without_get_absolute_url(self): """ Check that the shortcut view (used for the admin "view on site" functionality) returns 404 when get_absolute_url is not defined. """ request = HttpRequest() request.META = { "SERVER_NAME": "Example.com", "SERVER_PORT": "80", } user_ct = ContentType.objects.get_for_model(FooWithoutUrl) obj = FooWithoutUrl.objects.create(name="john") self.assertRaises(Http404, shortcut, request, user_ct.id, obj.id) def test_shortcut_view_with_broken_get_absolute_url(self): """ Check that the shortcut view does not catch an AttributeError raised by the model's get_absolute_url method. Refs #8997. """ request = HttpRequest() request.META = { "SERVER_NAME": "Example.com", "SERVER_PORT": "80", } user_ct = ContentType.objects.get_for_model(FooWithBrokenAbsoluteUrl) obj = FooWithBrokenAbsoluteUrl.objects.create(name="john") self.assertRaises(AttributeError, shortcut, request, user_ct.id, obj.id) def test_missing_model(self): """ Ensures that displaying content types in admin (or anywhere) doesn't break on leftover content type records in the DB for which no model is defined anymore. """ ct = ContentType.objects.create( name='Old model', app_label='contenttypes', model='OldModel', ) self.assertEqual(six.text_type(ct), 'Old model') self.assertIsNone(ct.model_class()) # Make sure stale ContentTypes can be fetched like any other object. # Before Django 1.6 this caused a NoneType error in the caching mechanism. # Instead, just return the ContentType object and let the app detect stale states. ct_fetched = ContentType.objects.get_for_id(ct.pk) self.assertIsNone(ct_fetched.model_class())
gpl-2.0
michaelgallacher/intellij-community
platform/lang-impl/src/com/intellij/execution/ui/layout/impl/DockableGridContainerFactory.java
1298
/* * Copyright 2000-2012 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. */ package com.intellij.execution.ui.layout.impl; import com.intellij.ui.docking.DockContainer; import com.intellij.ui.docking.DockContainerFactory; import com.intellij.ui.docking.DockableContent; /** * @author Dennis.Ushakov */ public class DockableGridContainerFactory implements DockContainerFactory { public static final String TYPE = "runner-grid"; @Override public DockContainer createContainer(DockableContent content) { final RunnerContentUi.DockableGrid dockableGrid = (RunnerContentUi.DockableGrid)content; return new RunnerContentUi(dockableGrid.getRunnerUi(), dockableGrid.getOriginalRunnerUi(), dockableGrid.getWindow()); } @Override public void dispose() {} }
apache-2.0
nevir/rubyspec
library/csv/reader/initialize_spec.rb
210
require File.expand_path('../../../../spec_helper', __FILE__) require 'csv' ruby_version_is "" ... "1.9" do describe "CSV::Reader#initialize" do it "needs to be reviewed for spec completeness" end end
mit
jenskastensson/openhab
bundles/binding/org.openhab.binding.fritzaha/src/main/java/org/openhab/binding/fritzaha/internal/hardware/callbacks/FritzahaReauthCallback.java
3121
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.fritzaha.internal.hardware.callbacks; import org.openhab.binding.fritzaha.internal.hardware.FritzahaWebInterface; /** * Callback implementation for reauthorization and retry * * @author Christian Brauers * @since 1.3.0 */ public class FritzahaReauthCallback implements FritzahaCallback { /** * Path to HTTP interface */ String path; /** * Arguments to use */ String args; /** * Web interface to use */ FritzahaWebInterface webIface; /** * HTTP Method for callback retries * * @author Projektgruppe Smart Home, Lehrstuhl KT, TU Dortmund * @since 1.3.0 */ public enum Method { POST, GET }; /** * Method used */ Method httpMethod; /** * Number of remaining retries */ int retries; /** * Whether the request returned a valid response */ boolean validRequest; /** * Callback to execute on next retry */ FritzahaCallback retryCallback; /** * Returns whether the request returned a valid response * * @return Validity of response */ public boolean isValidRequest() { return validRequest; } /** * Returns whether there will be another retry on an invalid response * * @return true if there will be no more retries, false otherwise */ public boolean isFinalAttempt() { return retries <= 0; } /** * Sets different Callback to use on retry (initial value: same callback * after decremented retry counter) * * @param newRetryCallback * Callback to retry with */ public void setRetryCallback(FritzahaCallback newRetryCallback) { retryCallback = newRetryCallback; } /** * {@inheritDoc} */ public void execute(int status, String response) { if (status != 200 || "".equals(response) || ".".equals(response)) { validRequest = false; if (retries >= 1) { webIface.authenticate(); retries--; if (httpMethod == Method.GET) { webIface.asyncGet(path, args, retryCallback); } else if (httpMethod == Method.POST) { webIface.asyncPost(path, args, retryCallback); } } } else validRequest = true; } /** * Constructor for retriable authentication * * @param path * Path to HTTP interface * @param args * Arguments to use * @param webIface * Web interface to use * @param httpMethod * Method used * @param retries * Number of retries */ public FritzahaReauthCallback(String path, String args, FritzahaWebInterface webIface, Method httpMethod, int retries) { this.path = path; this.args = args; this.webIface = webIface; this.httpMethod = httpMethod; this.retries = retries; retryCallback = this; } }
epl-1.0
endjin/tinymce
js/tinymce/classes/ui/Throbber.js
1791
/** * Throbber.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * This class enables you to display a Throbber for any element. * * @-x-less Throbber.less * @class tinymce.ui.Throbber */ define("tinymce/ui/Throbber", [ "tinymce/dom/DomQuery", "tinymce/ui/Control" ], function($, Control) { "use strict"; /** * Constructs a new throbber. * * @constructor * @param {Element} elm DOM Html element to display throbber in. * @param {Boolean} inline Optional true/false state if the throbber should be appended to end of element for infinite scroll. */ return function(elm, inline) { var self = this, state, classPrefix = Control.classPrefix; /** * Shows the throbber. * * @method show * @param {Number} [time] Time to wait before showing. * @param {function} [callback] Optional callback to execute when the throbber is shown. * @return {tinymce.ui.Throbber} Current throbber instance. */ self.show = function(time, callback) { self.hide(); state = true; window.setTimeout(function() { if (state) { $(elm).append( '<div class="' + classPrefix + 'throbber' + (inline ? ' ' + classPrefix + 'throbber-inline' : '') + '"></div>' ); if (callback) { callback(); } } }, time || 0); return self; }; /** * Hides the throbber. * * @method hide * @return {tinymce.ui.Throbber} Current throbber instance. */ self.hide = function() { var child = elm.lastChild; if (child && child.className.indexOf('throbber') != -1) { child.parentNode.removeChild(child); } state = false; return self; }; }; });
lgpl-2.1
iains/darwin-gcc-5
libstdc++-v3/include/ext/pb_ds/detail/list_update_map_/lu_map_.hpp
10393
// -*- C++ -*- // Copyright (C) 2005-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, 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 // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/lu_map_.hpp * Contains a list update map. */ #include <utility> #include <iterator> #include <ext/pb_ds/detail/cond_dealtor.hpp> #include <ext/pb_ds/tag_and_trait.hpp> #include <ext/pb_ds/detail/types_traits.hpp> #include <ext/pb_ds/detail/list_update_map_/entry_metadata_base.hpp> #include <ext/pb_ds/exception.hpp> #ifdef _GLIBCXX_DEBUG #include <ext/pb_ds/detail/debug_map_base.hpp> #endif #ifdef PB_DS_LU_MAP_TRACE_ #include <iostream> #endif #include <debug/debug.h> namespace __gnu_pbds { namespace detail { #ifdef PB_DS_DATA_TRUE_INDICATOR #define PB_DS_LU_NAME lu_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR #define PB_DS_LU_NAME lu_set #endif #define PB_DS_CLASS_T_DEC \ template<typename Key, typename Mapped, typename Eq_Fn, \ typename _Alloc, typename Update_Policy> #define PB_DS_CLASS_C_DEC \ PB_DS_LU_NAME<Key, Mapped, Eq_Fn, _Alloc, Update_Policy> #define PB_DS_LU_TRAITS_BASE \ types_traits<Key, Mapped, _Alloc, false> #ifdef _GLIBCXX_DEBUG #define PB_DS_DEBUG_MAP_BASE_C_DEC \ debug_map_base<Key, Eq_Fn, \ typename _Alloc::template rebind<Key>::other::const_reference> #endif /// list-based (with updates) associative container. /// Skip to the lu, my darling. template<typename Key, typename Mapped, typename Eq_Fn, typename _Alloc, typename Update_Policy> class PB_DS_LU_NAME : #ifdef _GLIBCXX_DEBUG protected PB_DS_DEBUG_MAP_BASE_C_DEC, #endif public PB_DS_LU_TRAITS_BASE { private: typedef PB_DS_LU_TRAITS_BASE traits_base; struct entry : public lu_map_entry_metadata_base<typename Update_Policy::metadata_type> { typename traits_base::value_type m_value; typename _Alloc::template rebind<entry>::other::pointer m_p_next; }; typedef typename _Alloc::template rebind<entry>::other entry_allocator; typedef typename entry_allocator::pointer entry_pointer; typedef typename entry_allocator::const_pointer const_entry_pointer; typedef typename entry_allocator::reference entry_reference; typedef typename entry_allocator::const_reference const_entry_reference; typedef typename _Alloc::template rebind<entry_pointer>::other entry_pointer_allocator; typedef typename entry_pointer_allocator::pointer entry_pointer_array; typedef typename traits_base::value_type value_type_; typedef typename traits_base::pointer pointer_; typedef typename traits_base::const_pointer const_pointer_; typedef typename traits_base::reference reference_; typedef typename traits_base::const_reference const_reference_; #define PB_DS_GEN_POS entry_pointer #include <ext/pb_ds/detail/unordered_iterator/point_const_iterator.hpp> #include <ext/pb_ds/detail/unordered_iterator/point_iterator.hpp> #include <ext/pb_ds/detail/unordered_iterator/const_iterator.hpp> #include <ext/pb_ds/detail/unordered_iterator/iterator.hpp> #undef PB_DS_GEN_POS #ifdef _GLIBCXX_DEBUG typedef PB_DS_DEBUG_MAP_BASE_C_DEC debug_base; #endif typedef cond_dealtor<entry, _Alloc> cond_dealtor_t; public: typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef Eq_Fn eq_fn; typedef Update_Policy update_policy; typedef typename Update_Policy::metadata_type update_metadata; typedef typename traits_base::key_type key_type; typedef typename traits_base::key_pointer key_pointer; typedef typename traits_base::key_const_pointer key_const_pointer; typedef typename traits_base::key_reference key_reference; typedef typename traits_base::key_const_reference key_const_reference; typedef typename traits_base::mapped_type mapped_type; typedef typename traits_base::mapped_pointer mapped_pointer; typedef typename traits_base::mapped_const_pointer mapped_const_pointer; typedef typename traits_base::mapped_reference mapped_reference; typedef typename traits_base::mapped_const_reference mapped_const_reference; typedef typename traits_base::value_type value_type; typedef typename traits_base::pointer pointer; typedef typename traits_base::const_pointer const_pointer; typedef typename traits_base::reference reference; typedef typename traits_base::const_reference const_reference; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef point_iterator_ point_iterator; #endif #ifdef PB_DS_DATA_FALSE_INDICATOR typedef point_const_iterator_ point_iterator; #endif typedef point_const_iterator_ point_const_iterator; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef iterator_ iterator; #endif #ifdef PB_DS_DATA_FALSE_INDICATOR typedef const_iterator_ iterator; #endif typedef const_iterator_ const_iterator; public: PB_DS_LU_NAME(); PB_DS_LU_NAME(const PB_DS_CLASS_C_DEC&); virtual ~PB_DS_LU_NAME(); template<typename It> PB_DS_LU_NAME(It, It); void swap(PB_DS_CLASS_C_DEC&); inline size_type size() const; inline size_type max_size() const; inline bool empty() const; inline mapped_reference operator[](key_const_reference r_key) { #ifdef PB_DS_DATA_TRUE_INDICATOR _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) return insert(std::make_pair(r_key, mapped_type())).first->second; #else insert(r_key); return traits_base::s_null_type; #endif } inline std::pair<point_iterator, bool> insert(const_reference); inline point_iterator find(key_const_reference r_key) { _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) entry_pointer p_e = find_imp(r_key); return point_iterator(p_e == 0 ? 0: &p_e->m_value); } inline point_const_iterator find(key_const_reference r_key) const { _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) entry_pointer p_e = find_imp(r_key); return point_const_iterator(p_e == 0 ? 0: &p_e->m_value); } inline bool erase(key_const_reference); template<typename Pred> inline size_type erase_if(Pred); void clear(); inline iterator begin(); inline const_iterator begin() const; inline iterator end(); inline const_iterator end() const; #ifdef _GLIBCXX_DEBUG void assert_valid(const char* file, int line) const; #endif #ifdef PB_DS_LU_MAP_TRACE_ void trace() const; #endif protected: template<typename It> void copy_from_range(It, It); private: #ifdef PB_DS_DATA_TRUE_INDICATOR friend class iterator_; #endif friend class const_iterator_; inline entry_pointer allocate_new_entry(const_reference, false_type); inline entry_pointer allocate_new_entry(const_reference, true_type); template<typename Metadata> inline static void init_entry_metadata(entry_pointer, type_to_type<Metadata>); inline static void init_entry_metadata(entry_pointer, type_to_type<null_type>); void deallocate_all(); void erase_next(entry_pointer); void actual_erase_entry(entry_pointer); void inc_it_state(const_pointer& r_p_value, entry_pointer& r_pos) const { r_pos = r_pos->m_p_next; r_p_value = (r_pos == 0) ? 0 : &r_pos->m_value; } template<typename Metadata> inline static bool apply_update(entry_pointer, type_to_type<Metadata>); inline static bool apply_update(entry_pointer, type_to_type<null_type>); inline entry_pointer find_imp(key_const_reference) const; static entry_allocator s_entry_allocator; static Eq_Fn s_eq_fn; static Update_Policy s_update_policy; static type_to_type<update_metadata> s_metadata_type_indicator; static null_type s_null_type; mutable entry_pointer m_p_l; }; #include <ext/pb_ds/detail/list_update_map_/constructor_destructor_fn_imps.hpp> #include <ext/pb_ds/detail/list_update_map_/info_fn_imps.hpp> #include <ext/pb_ds/detail/list_update_map_/debug_fn_imps.hpp> #include <ext/pb_ds/detail/list_update_map_/iterators_fn_imps.hpp> #include <ext/pb_ds/detail/list_update_map_/erase_fn_imps.hpp> #include <ext/pb_ds/detail/list_update_map_/find_fn_imps.hpp> #include <ext/pb_ds/detail/list_update_map_/insert_fn_imps.hpp> #include <ext/pb_ds/detail/list_update_map_/trace_fn_imps.hpp> #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_LU_TRAITS_BASE #undef PB_DS_DEBUG_MAP_BASE_C_DEC #undef PB_DS_LU_NAME } // namespace detail } // namespace __gnu_pbds
gpl-2.0
patricerandria/ccmgr-wp
ccmgr/wp-content/plugins/profile-builder/assets/lib/Mustache/Parser.php
6315
<?php /* * This file is part of Mustache.php. * * (c) 2012 Justin Hileman * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Mustache Parser class. * * This class is responsible for turning a set of Mustache tokens into a parse tree. */ class Mustache_Parser { private $lineNum; private $lineTokens; /** * Process an array of Mustache tokens and convert them into a parse tree. * * @param array $tokens Set of Mustache tokens * * @return array Mustache token parse tree */ public function parse(array $tokens = array()) { $this->lineNum = -1; $this->lineTokens = 0; return $this->buildTree($tokens); } /** * Helper method for recursively building a parse tree. * * @throws Mustache_Exception_SyntaxException when nesting errors or mismatched section tags are encountered. * * @param array &$tokens Set of Mustache tokens * @param array $parent Parent token (default: null) * * @return array Mustache Token parse tree */ private function buildTree(array &$tokens, array $parent = null) { $nodes = array(); while (!empty($tokens)) { $token = array_shift($tokens); if ($token[Mustache_Tokenizer::LINE] === $this->lineNum) { $this->lineTokens++; } else { $this->lineNum = $token[Mustache_Tokenizer::LINE]; $this->lineTokens = 0; } switch ($token[Mustache_Tokenizer::TYPE]) { case Mustache_Tokenizer::T_DELIM_CHANGE: $this->clearStandaloneLines($nodes, $tokens); break; case Mustache_Tokenizer::T_SECTION: case Mustache_Tokenizer::T_INVERTED: $this->clearStandaloneLines($nodes, $tokens); $nodes[] = $this->buildTree($tokens, $token); break; case Mustache_Tokenizer::T_END_SECTION: if (!isset($parent)) { $msg = sprintf('Unexpected closing tag: /%s', $token[Mustache_Tokenizer::NAME]); throw new Mustache_Exception_SyntaxException($msg, $token); } if ($token[Mustache_Tokenizer::NAME] !== $parent[Mustache_Tokenizer::NAME]) { $msg = sprintf('Nesting error: %s vs. %s', $parent[Mustache_Tokenizer::NAME], $token[Mustache_Tokenizer::NAME]); throw new Mustache_Exception_SyntaxException($msg, $token); } $this->clearStandaloneLines($nodes, $tokens); $parent[Mustache_Tokenizer::END] = $token[Mustache_Tokenizer::INDEX]; $parent[Mustache_Tokenizer::NODES] = $nodes; return $parent; break; case Mustache_Tokenizer::T_PARTIAL: case Mustache_Tokenizer::T_PARTIAL_2: // store the whitespace prefix for laters! if ($indent = $this->clearStandaloneLines($nodes, $tokens)) { $token[Mustache_Tokenizer::INDENT] = $indent[Mustache_Tokenizer::VALUE]; } $nodes[] = $token; break; case Mustache_Tokenizer::T_PRAGMA: case Mustache_Tokenizer::T_COMMENT: $this->clearStandaloneLines($nodes, $tokens); $nodes[] = $token; break; default: $nodes[] = $token; break; } } if (isset($parent)) { $msg = sprintf('Missing closing tag: %s', $parent[Mustache_Tokenizer::NAME]); throw new Mustache_Exception_SyntaxException($msg, $parent); } return $nodes; } /** * Clear standalone line tokens. * * Returns a whitespace token for indenting partials, if applicable. * * @param array $nodes Parsed nodes. * @param array $tokens Tokens to be parsed. * * @return array Resulting indent token, if any. */ private function clearStandaloneLines(array &$nodes, array &$tokens) { if ($this->lineTokens > 1) { // this is the third or later node on this line, so it can't be standalone return; } $prev = null; if ($this->lineTokens === 1) { // this is the second node on this line, so it can't be standalone // unless the previous node is whitespace. if ($prev = end($nodes)) { if (!$this->tokenIsWhitespace($prev)) { return; } } } $next = null; if ($next = reset($tokens)) { // If we're on a new line, bail. if ($next[Mustache_Tokenizer::LINE] !== $this->lineNum) { return; } // If the next token isn't whitespace, bail. if (!$this->tokenIsWhitespace($next)) { return; } if (count($tokens) !== 1) { // Unless it's the last token in the template, the next token // must end in newline for this to be standalone. if (substr($next[Mustache_Tokenizer::VALUE], -1) !== "\n") { return; } } // Discard the whitespace suffix array_shift($tokens); } if ($prev) { // Return the whitespace prefix, if any return array_pop($nodes); } } /** * Check whether token is a whitespace token. * * True if token type is T_TEXT and value is all whitespace characters. * * @param array $token * * @return boolean True if token is a whitespace token */ private function tokenIsWhitespace(array $token) { if ($token[Mustache_Tokenizer::TYPE] == Mustache_Tokenizer::T_TEXT) { return preg_match('/^\s*$/', $token[Mustache_Tokenizer::VALUE]); } return false; } }
gpl-2.0
twalpole/bower
test/commands/unregister.js
2408
var expect = require('expect.js'); var helpers = require('../helpers'); var fakeRepositoryFactory = function () { function FakeRepository() { } FakeRepository.prototype.getRegistryClient = function() { return { unregister: function (name, cb) { cb(null, { name: name }); } }; }; return FakeRepository; }; var unregister = helpers.command('unregister'); var unregisterFactory = function () { return helpers.command('unregister', { '../core/PackageRepository': fakeRepositoryFactory() }); }; describe('bower unregister', function () { it('correctly reads arguments', function() { expect(unregister.readOptions(['jquery'])) .to.eql(['jquery']); }); it('errors if name is not provided', function () { return helpers.run(unregister).fail(function(reason) { expect(reason.message).to.be('Usage: bower unregister <name> <url>'); expect(reason.code).to.be('EINVFORMAT'); }); }); it('should call registry client with name', function () { var unregister = unregisterFactory(); return helpers.run(unregister, ['some-name']) .spread(function(result) { expect(result).to.eql({ // Result from register action on stub name: 'some-name' }); }); }); it('should confirm in interactive mode', function () { var register = unregisterFactory(); var promise = helpers.run(register, ['some-name', { interactive: true, registry: { register: 'http://localhost' } }] ); return helpers.expectEvent(promise.logger, 'confirm') .spread(function(e) { expect(e.type).to.be('confirm'); expect(e.message).to.be('You are about to remove component "some-name" from the bower registry (http://localhost). It is generally considered bad behavior to remove versions of a library that others are depending on. Are you really sure?'); expect(e.default).to.be(false); }); }); it('should skip confirming when forcing', function () { var register = unregisterFactory(); return helpers.run(register, ['some-name', { interactive: true, force: true } ] ); }); });
mit
shakamunyi/kubernetes
pkg/kubelet/cm/node_container_manager_test.go
12421
// +build linux /* 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. */ package cm import ( "testing" "github.com/stretchr/testify/assert" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" evictionapi "k8s.io/kubernetes/pkg/kubelet/eviction/api" ) func TestNodeAllocatableReservationForScheduling(t *testing.T) { memoryEvictionThreshold := resource.MustParse("100Mi") cpuMemCases := []struct { kubeReserved v1.ResourceList systemReserved v1.ResourceList expected v1.ResourceList capacity v1.ResourceList hardThreshold evictionapi.ThresholdValue }{ { kubeReserved: getResourceList("100m", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), capacity: getResourceList("10", "10Gi"), expected: getResourceList("150m", "150Mi"), }, { kubeReserved: getResourceList("100m", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), hardThreshold: evictionapi.ThresholdValue{ Quantity: &memoryEvictionThreshold, }, capacity: getResourceList("10", "10Gi"), expected: getResourceList("150m", "250Mi"), }, { kubeReserved: getResourceList("100m", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), capacity: getResourceList("10", "10Gi"), hardThreshold: evictionapi.ThresholdValue{ Percentage: 0.05, }, expected: getResourceList("150m", "694157320"), }, { kubeReserved: v1.ResourceList{}, systemReserved: v1.ResourceList{}, capacity: getResourceList("10", "10Gi"), expected: getResourceList("", ""), }, { kubeReserved: getResourceList("", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), capacity: getResourceList("10", "10Gi"), expected: getResourceList("50m", "150Mi"), }, { kubeReserved: getResourceList("50m", "100Mi"), systemReserved: getResourceList("", "50Mi"), capacity: getResourceList("10", "10Gi"), expected: getResourceList("50m", "150Mi"), }, { kubeReserved: getResourceList("", "100Mi"), systemReserved: getResourceList("", "50Mi"), capacity: getResourceList("10", ""), expected: getResourceList("", "150Mi"), }, } for idx, tc := range cpuMemCases { nc := NodeConfig{ NodeAllocatableConfig: NodeAllocatableConfig{ KubeReserved: tc.kubeReserved, SystemReserved: tc.systemReserved, HardEvictionThresholds: []evictionapi.Threshold{ { Signal: evictionapi.SignalMemoryAvailable, Operator: evictionapi.OpLessThan, Value: tc.hardThreshold, }, }, }, } cm := &containerManagerImpl{ NodeConfig: nc, capacity: tc.capacity, } for k, v := range cm.GetNodeAllocatableReservation() { expected, exists := tc.expected[k] assert.True(t, exists, "test case %d expected resource %q", idx+1, k) assert.Equal(t, expected.MilliValue(), v.MilliValue(), "test case %d failed for resource %q", idx+1, k) } } ephemeralStorageEvictionThreshold := resource.MustParse("100Mi") ephemeralStorageTestCases := []struct { kubeReserved v1.ResourceList expected v1.ResourceList capacity v1.ResourceList hardThreshold evictionapi.ThresholdValue }{ { kubeReserved: getEphemeralStorageResourceList("100Mi"), capacity: getEphemeralStorageResourceList("10Gi"), expected: getEphemeralStorageResourceList("100Mi"), }, { kubeReserved: getEphemeralStorageResourceList("100Mi"), hardThreshold: evictionapi.ThresholdValue{ Quantity: &ephemeralStorageEvictionThreshold, }, capacity: getEphemeralStorageResourceList("10Gi"), expected: getEphemeralStorageResourceList("200Mi"), }, { kubeReserved: getEphemeralStorageResourceList("150Mi"), capacity: getEphemeralStorageResourceList("10Gi"), hardThreshold: evictionapi.ThresholdValue{ Percentage: 0.05, }, expected: getEphemeralStorageResourceList("694157320"), }, { kubeReserved: v1.ResourceList{}, capacity: getEphemeralStorageResourceList("10Gi"), expected: getEphemeralStorageResourceList(""), }, } for idx, tc := range ephemeralStorageTestCases { nc := NodeConfig{ NodeAllocatableConfig: NodeAllocatableConfig{ KubeReserved: tc.kubeReserved, HardEvictionThresholds: []evictionapi.Threshold{ { Signal: evictionapi.SignalNodeFsAvailable, Operator: evictionapi.OpLessThan, Value: tc.hardThreshold, }, }, }, } cm := &containerManagerImpl{ NodeConfig: nc, capacity: tc.capacity, } for k, v := range cm.GetNodeAllocatableReservation() { expected, exists := tc.expected[k] assert.True(t, exists, "test case %d expected resource %q", idx+1, k) assert.Equal(t, expected.MilliValue(), v.MilliValue(), "test case %d failed for resource %q", idx+1, k) } } } func TestNodeAllocatableForEnforcement(t *testing.T) { memoryEvictionThreshold := resource.MustParse("100Mi") testCases := []struct { kubeReserved v1.ResourceList systemReserved v1.ResourceList capacity v1.ResourceList expected v1.ResourceList hardThreshold evictionapi.ThresholdValue }{ { kubeReserved: getResourceList("100m", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), capacity: getResourceList("10", "10Gi"), expected: getResourceList("9850m", "10090Mi"), }, { kubeReserved: getResourceList("100m", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), hardThreshold: evictionapi.ThresholdValue{ Quantity: &memoryEvictionThreshold, }, capacity: getResourceList("10", "10Gi"), expected: getResourceList("9850m", "10090Mi"), }, { kubeReserved: getResourceList("100m", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), hardThreshold: evictionapi.ThresholdValue{ Percentage: 0.05, }, capacity: getResourceList("10", "10Gi"), expected: getResourceList("9850m", "10090Mi"), }, { kubeReserved: v1.ResourceList{}, systemReserved: v1.ResourceList{}, capacity: getResourceList("10", "10Gi"), expected: getResourceList("10", "10Gi"), }, { kubeReserved: getResourceList("", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), capacity: getResourceList("10", "10Gi"), expected: getResourceList("9950m", "10090Mi"), }, { kubeReserved: getResourceList("50m", "100Mi"), systemReserved: getResourceList("", "50Mi"), capacity: getResourceList("10", "10Gi"), expected: getResourceList("9950m", "10090Mi"), }, { kubeReserved: getResourceList("", "100Mi"), systemReserved: getResourceList("", "50Mi"), capacity: getResourceList("10", ""), expected: getResourceList("10", ""), }, } for idx, tc := range testCases { nc := NodeConfig{ NodeAllocatableConfig: NodeAllocatableConfig{ KubeReserved: tc.kubeReserved, SystemReserved: tc.systemReserved, HardEvictionThresholds: []evictionapi.Threshold{ { Signal: evictionapi.SignalMemoryAvailable, Operator: evictionapi.OpLessThan, Value: tc.hardThreshold, }, }, }, } cm := &containerManagerImpl{ NodeConfig: nc, capacity: tc.capacity, } for k, v := range cm.getNodeAllocatableAbsolute() { expected, exists := tc.expected[k] assert.True(t, exists) assert.Equal(t, expected.MilliValue(), v.MilliValue(), "test case %d failed for resource %q", idx+1, k) } } } func TestNodeAllocatableInputValidation(t *testing.T) { memoryEvictionThreshold := resource.MustParse("100Mi") highMemoryEvictionThreshold := resource.MustParse("2Gi") cpuMemTestCases := []struct { kubeReserved v1.ResourceList systemReserved v1.ResourceList capacity v1.ResourceList hardThreshold evictionapi.ThresholdValue invalidConfiguration bool }{ { kubeReserved: getResourceList("100m", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), capacity: getResourceList("10", "10Gi"), }, { kubeReserved: getResourceList("100m", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), hardThreshold: evictionapi.ThresholdValue{ Quantity: &memoryEvictionThreshold, }, capacity: getResourceList("10", "10Gi"), }, { kubeReserved: getResourceList("100m", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), hardThreshold: evictionapi.ThresholdValue{ Percentage: 0.05, }, capacity: getResourceList("10", "10Gi"), }, { kubeReserved: v1.ResourceList{}, systemReserved: v1.ResourceList{}, capacity: getResourceList("10", "10Gi"), }, { kubeReserved: getResourceList("", "100Mi"), systemReserved: getResourceList("50m", "50Mi"), capacity: getResourceList("10", "10Gi"), }, { kubeReserved: getResourceList("50m", "100Mi"), systemReserved: getResourceList("", "50Mi"), capacity: getResourceList("10", "10Gi"), }, { kubeReserved: getResourceList("", "100Mi"), systemReserved: getResourceList("", "50Mi"), capacity: getResourceList("10", ""), }, { kubeReserved: getResourceList("5", "10Gi"), systemReserved: getResourceList("5", "10Gi"), hardThreshold: evictionapi.ThresholdValue{ Quantity: &highMemoryEvictionThreshold, }, capacity: getResourceList("10", "11Gi"), invalidConfiguration: true, }, } for _, tc := range cpuMemTestCases { nc := NodeConfig{ NodeAllocatableConfig: NodeAllocatableConfig{ KubeReserved: tc.kubeReserved, SystemReserved: tc.systemReserved, HardEvictionThresholds: []evictionapi.Threshold{ { Signal: evictionapi.SignalMemoryAvailable, Operator: evictionapi.OpLessThan, Value: tc.hardThreshold, }, }, }, } cm := &containerManagerImpl{ NodeConfig: nc, capacity: tc.capacity, } err := cm.validateNodeAllocatable() if err == nil && tc.invalidConfiguration { t.Logf("Expected invalid node allocatable configuration") t.FailNow() } else if err != nil && !tc.invalidConfiguration { t.Logf("Expected valid node allocatable configuration: %v", err) t.FailNow() } } ephemeralStorageEvictionThreshold := resource.MustParse("100Mi") ephemeralStorageTestCases := []struct { kubeReserved v1.ResourceList capacity v1.ResourceList hardThreshold evictionapi.ThresholdValue invalidConfiguration bool }{ { kubeReserved: getEphemeralStorageResourceList("100Mi"), capacity: getEphemeralStorageResourceList("500Mi"), }, { kubeReserved: getEphemeralStorageResourceList("20Gi"), hardThreshold: evictionapi.ThresholdValue{ Quantity: &ephemeralStorageEvictionThreshold, }, capacity: getEphemeralStorageResourceList("20Gi"), invalidConfiguration: true, }, } for _, tc := range ephemeralStorageTestCases { nc := NodeConfig{ NodeAllocatableConfig: NodeAllocatableConfig{ KubeReserved: tc.kubeReserved, HardEvictionThresholds: []evictionapi.Threshold{ { Signal: evictionapi.SignalNodeFsAvailable, Operator: evictionapi.OpLessThan, Value: tc.hardThreshold, }, }, }, } cm := &containerManagerImpl{ NodeConfig: nc, capacity: tc.capacity, } err := cm.validateNodeAllocatable() if err == nil && tc.invalidConfiguration { t.Logf("Expected invalid node allocatable configuration") t.FailNow() } else if err != nil && !tc.invalidConfiguration { t.Logf("Expected valid node allocatable configuration: %v", err) t.FailNow() } } } // getEphemeralStorageResourceList returns a ResourceList with the // specified ephemeral storage resource values func getEphemeralStorageResourceList(storage string) v1.ResourceList { res := v1.ResourceList{} if storage != "" { res[v1.ResourceEphemeralStorage] = resource.MustParse(storage) } return res }
apache-2.0
Slaffka/moodel
question/behaviour/immediatefeedback/renderer.php
1417
<?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/>. /** * Defines the renderer for the immediate feedback behaviour. * * @package qbehaviour * @subpackage immediatefeedback * @copyright 2009 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Renderer for outputting parts of a question belonging to the immediate * feedback behaviour. * * @copyright 2009 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class qbehaviour_immediatefeedback_renderer extends qbehaviour_renderer { public function controls(question_attempt $qa, question_display_options $options) { return $this->submit_button($qa, $options); } }
gpl-3.0
tacrow/tacrow
node_modules/hapi/node_modules/vision/test/templates/valid/helpers/tools/lowercase.js
86
exports = module.exports = function (context) { return context.toLowerCase(); };
mit
bbcrd/vistatv_live_dashboard
public/components/d3/src/geom/hull.js
2688
/** * Computes the 2D convex hull of a set of points using Graham's scanning * algorithm. The algorithm has been implemented as described in Cormen, * Leiserson, and Rivest's Introduction to Algorithms. The running time of * this algorithm is O(n log n), where n is the number of input points. * * @param vertices [[x1, y1], [x2, y2], …] * @returns polygon [[x1, y1], [x2, y2], …] */ d3.geom.hull = function(vertices) { if (vertices.length < 3) return []; var len = vertices.length, plen = len - 1, points = [], stack = [], i, j, h = 0, x1, y1, x2, y2, u, v, a, sp; // find the starting ref point: leftmost point with the minimum y coord for (i=1; i<len; ++i) { if (vertices[i][1] < vertices[h][1]) { h = i; } else if (vertices[i][1] == vertices[h][1]) { h = (vertices[i][0] < vertices[h][0] ? i : h); } } // calculate polar angles from ref point and sort for (i=0; i<len; ++i) { if (i === h) continue; y1 = vertices[i][1] - vertices[h][1]; x1 = vertices[i][0] - vertices[h][0]; points.push({angle: Math.atan2(y1, x1), index: i}); } points.sort(function(a, b) { return a.angle - b.angle; }); // toss out duplicate angles a = points[0].angle; v = points[0].index; u = 0; for (i=1; i<plen; ++i) { j = points[i].index; if (a == points[i].angle) { // keep angle for point most distant from the reference x1 = vertices[v][0] - vertices[h][0]; y1 = vertices[v][1] - vertices[h][1]; x2 = vertices[j][0] - vertices[h][0]; y2 = vertices[j][1] - vertices[h][1]; if ((x1*x1 + y1*y1) >= (x2*x2 + y2*y2)) { points[i].index = -1; } else { points[u].index = -1; a = points[i].angle; u = i; v = j; } } else { a = points[i].angle; u = i; v = j; } } // initialize the stack stack.push(h); for (i=0, j=0; i<2; ++j) { if (points[j].index !== -1) { stack.push(points[j].index); i++; } } sp = stack.length; // do graham's scan for (; j<plen; ++j) { if (points[j].index === -1) continue; // skip tossed out points while (!d3_geom_hullCCW(stack[sp-2], stack[sp-1], points[j].index, vertices)) { --sp; } stack[sp++] = points[j].index; } // construct the hull var poly = []; for (i=0; i<sp; ++i) { poly.push(vertices[stack[i]]); } return poly; } // are three points in counter-clockwise order? function d3_geom_hullCCW(i1, i2, i3, v) { var t, a, b, c, d, e, f; t = v[i1]; a = t[0]; b = t[1]; t = v[i2]; c = t[0]; d = t[1]; t = v[i3]; e = t[0]; f = t[1]; return ((f-b)*(c-a) - (d-b)*(e-a)) > 0; }
apache-2.0
esi-mineset/spark
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/SerializedOffset.scala
1272
/* * 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.spark.sql.execution.streaming /** * Used when loading a JSON serialized offset from external storage. * We are currently not responsible for converting JSON serialized * data into an internal (i.e., object) representation. Sources should * define a factory method in their source Offset companion objects * that accepts a [[SerializedOffset]] for doing the conversion. */ case class SerializedOffset(override val json: String) extends Offset
apache-2.0
cdnjs/cdnjs
ajax/libs/react-native-web/0.0.0-bd62af4f4/cjs/hooks/useResponderEvents/index.js
4034
"use strict"; exports.__esModule = true; exports.default = useResponderEvents; var React = _interopRequireWildcard(require("react")); var ResponderSystem = _interopRequireWildcard(require("./ResponderSystem")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * Copyright (c) Nicolas Gallagher * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ /** * Hook for integrating the Responder System into React * * function SomeComponent({ onStartShouldSetResponder }) { * const ref = useRef(null); * useResponderEvents(ref, { onStartShouldSetResponder }); * return <div ref={ref} /> * } */ var emptyObject = {}; var idCounter = 0; function useStable(getInitialValue) { var ref = React.useRef(null); if (ref.current == null) { ref.current = getInitialValue(); } return ref.current; } function useResponderEvents(hostRef, config) { if (config === void 0) { config = emptyObject; } var id = useStable(function () { return idCounter++; }); var isAttachedRef = React.useRef(false); // This is a separate effects so it doesn't run when the config changes. // On initial mount, attach global listeners if needed. // On unmount, remove node potentially attached to the Responder System. React.useEffect(function () { ResponderSystem.attachListeners(); return function () { ResponderSystem.removeNode(id); }; }, [id]); // Register and unregister with the Responder System as necessary React.useEffect(function () { var _config = config, onMoveShouldSetResponder = _config.onMoveShouldSetResponder, onMoveShouldSetResponderCapture = _config.onMoveShouldSetResponderCapture, onScrollShouldSetResponder = _config.onScrollShouldSetResponder, onScrollShouldSetResponderCapture = _config.onScrollShouldSetResponderCapture, onSelectionChangeShouldSetResponder = _config.onSelectionChangeShouldSetResponder, onSelectionChangeShouldSetResponderCapture = _config.onSelectionChangeShouldSetResponderCapture, onStartShouldSetResponder = _config.onStartShouldSetResponder, onStartShouldSetResponderCapture = _config.onStartShouldSetResponderCapture; var requiresResponderSystem = onMoveShouldSetResponder != null || onMoveShouldSetResponderCapture != null || onScrollShouldSetResponder != null || onScrollShouldSetResponderCapture != null || onSelectionChangeShouldSetResponder != null || onSelectionChangeShouldSetResponderCapture != null || onStartShouldSetResponder != null || onStartShouldSetResponderCapture != null; var node = hostRef.current; if (requiresResponderSystem) { ResponderSystem.addNode(id, node, config); isAttachedRef.current = true; } else if (isAttachedRef.current) { ResponderSystem.removeNode(id); isAttachedRef.current = false; } }, [config, hostRef, id]); React.useDebugValue({ isResponder: hostRef.current === ResponderSystem.getResponderNode() }); React.useDebugValue(config); } module.exports = exports.default;
mit
michaelgallacher/intellij-community
java/java-tests/testData/codeInsight/template/postfix/completion/restartCompletionForExactMatch.java
94
public class Test { public static void main(String[] args) { Boolean.FALSE.<caret> } }
apache-2.0
SerCeMan/intellij-community
python/testData/mover/multiCompound.py
46
for item in range(1, 3): b = 2<caret>
apache-2.0
pwoodworth/intellij-community
java/java-tests/testData/inspection/dataFlow/fixture/ExceptionFromFinallyNesting.java
604
import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; class Foo { private void run(int port) throws Exception { Socket socket = new Socket("localhost", port); try { InputStream inputReader = socket.getInputStream(); try { OutputStream outputWriter = socket.getOutputStream(); try { while (true) { inputReader.read(); } } finally { outputWriter.close(); } } finally { inputReader.close(); } } finally { socket.close(); } } }
apache-2.0
StudentLifeMarketingAndDesign/uisg-OLDNOTUSED
sapphire/thirdparty/tinymce/plugins/media/langs/ms_dlg.js
2641
tinyMCE.addI18n('ms.media_dlg',{ title:"Masukkan / sunting media", general:"Am", advanced:"Lanjutan", file:"Fail/URL", list:"Senarai", size:"Dimensi", preview:"Pratonton", constrain_proportions:"Kadar tahanan", type:"Jenis", id:"Id", name:"Nama", class_name:"Kelas", vspace:"Ruangan-Tegak", hspace:"Ruangan-Datar", play:"Auto main", loop:"Gelung", menu:"Tunjuk menu", quality:"Kualiti", scale:"Ukuran", align:"Luruskan", salign:"SLuruskan", wmode:"WMod", bgcolor:"Latar belakang", base:"Dasar", flashvars:"Flashvars", liveconnect:"SWLiveConnect", autohref:"AutoHREF", cache:"Tempat menyembunyikan", hidden:"Tersorok", controller:"Kendali", kioskmode:"Mode toko", playeveryframe:"Main setiap bingkai", targetcache:"Sasaran tersembunyi", correction:"Tiada pembetulan", enablejavascript:"Bolehkan JavaScript", starttime:"Masa bermula", endtime:"Masa tamat", href:"Href", qtsrcchokespeed:"Kelajuan sumbatan", target:"Sasaran", volume:"Ketinggian suara", autostart:"Auto mula", enabled:"Dibolehkan", fullscreen:"Skrin penuh", invokeurls:"Panggil URL", mute:"Bisu", stretchtofit:"Bujurkan supaya sesuai", windowlessvideo:"Tetingkap tanpa video", balance:"Baki", baseurl:"URL dasar", captioningid:"Tajuk id", currentmarker:"Penanda semasa", currentposition:"Posisi semasa", defaultframe:"Bingkai asal", playcount:"Kira", rate:"Undi", uimode:"Mod Grafik", flash_options:"Flash", qt_options:"Quicktime", wmp_options:"Pemain Windows media", rmp_options:"Pemain Real media", shockwave_options:"Shockwave", autogotourl:"Auto pergi-ke URL", center:"Tengah", imagestatus:"Status imej", maintainaspect:"Pelihara aspek", nojava:"Java tidak dibenarkan", prefetch:"Preambilan", shuffle:"Merangkak", console:"Konsol", numloop:"Nombor gelungan", controls:"Kendali", scriptcallbacks:"Panggilan balik skrip", swstretchstyle:"Gaya bentangan", swstretchhalign:"Bentangan Selarian-Ufuk", swstretchvalign:"Stretch Selarian-Tegak", sound:"Sound", progress:"Progress", qtsrc:"QT Src", align_top:"Atas", align_right:"Kanan", align_bottom:"Bawah", align_left:"Kiri", align_center:"Tengah", align_top_left:"Kiri atas", align_top_right:"Kanan atas", align_bottom_left:"Bawah kiri", align_bottom_right:"Bawah kanan", flv_options:"Alatan flash video", flv_scalemode:"Skala mod", flv_buffer:"Buffer", flv_startimage:"Start imej", flv_starttime:"Masa mula", flv_defaultvolume:"Bunyi asal", flv_hiddengui:"GUI tersorok", flv_autostart:"Auto mula", flv_loop:"Gegelung", flv_showscalemodes:"Tunjuk skala mod", flv_smoothvideo:"Perlahankan video", flv_jscallback:"JS Callback" });
bsd-3-clause
BrennanConroy/corefx
src/System.Data.Odbc/tests/OdbcConnectionSchemaTests.cs
1192
// 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 Xunit; namespace System.Data.Odbc.Tests { public class OdbcConnectionSchemaTests { [CheckConnStrSetupFact] public void TestConnectionSchemaOnOpenConnection() { string connectionString = DataTestUtility.OdbcConnStr; using (OdbcConnection connection = new OdbcConnection(connectionString)) { connection.GetSchema(); connection.Open(); DataTable schema = connection.GetSchema(); Assert.NotNull(schema); DataTable tableSchema = connection.GetSchema("Tables"); Assert.NotNull(tableSchema); } } [Fact] public void TestConnectionSchemaOnNonOpenConnection() { using (OdbcConnection connection = new OdbcConnection(string.Empty)) { Assert.Throws<InvalidOperationException>(() => connection.GetSchema()); } } } }
mit
miguel250/vagrant
test/unit/vagrant/action/builtin/lock_test.rb
2601
require File.expand_path("../../../../base", __FILE__) describe Vagrant::Action::Builtin::Lock do let(:app) { lambda { |env| } } let(:env) { {} } let(:lock_path) do @__lock_path = Tempfile.new("vagrant-test-lock") @__lock_path.path.to_s end let(:options) do { exception: Class.new(StandardError), path: lock_path } end it "should require a path" do expect { described_class.new(app, env) }. to raise_error(ArgumentError) expect { described_class.new(app, env, path: "foo") }. to raise_error(ArgumentError) expect { described_class.new(app, env, exception: "foo") }. to raise_error(ArgumentError) expect { described_class.new(app, env, path: "bar", exception: "foo") }. to_not raise_error end it "should allow the path to be a proc" do inner_acquire = true app = lambda do |env| File.open(lock_path, "w+") do |f| inner_acquire = f.flock(File::LOCK_EX | File::LOCK_NB) end end options[:path] = lambda { |env| lock_path } instance = described_class.new(app, env, options) instance.call(env) expect(inner_acquire).to eq(false) end it "should allow the exception to be a proc" do exception = options[:exception] options[:exception] = lambda { |env| exception } File.open(lock_path, "w+") do |f| # Acquire lock expect(f.flock(File::LOCK_EX | File::LOCK_NB)).to eq(0) # Test! instance = described_class.new(app, env, options) expect { instance.call(env) }. to raise_error(exception) end end it "should call the middleware with the lock held" do inner_acquire = true app = lambda do |env| File.open(lock_path, "w+") do |f| inner_acquire = f.flock(File::LOCK_EX | File::LOCK_NB) end end instance = described_class.new(app, env, options) instance.call(env) expect(inner_acquire).to eq(false) end it "should raise an exception if the lock is already held" do File.open(lock_path, "w+") do |f| # Acquire lock expect(f.flock(File::LOCK_EX | File::LOCK_NB)).to eq(0) # Test! instance = described_class.new(app, env, options) expect { instance.call(env) }. to raise_error(options[:exception]) end end it "should allow nesting locks within the same middleware sequence" do called = false app = lambda { |env| called = true } inner = described_class.new(app, env, options) outer = described_class.new(inner, env, options) outer.call(env) expect(called).to eq(true) end end
mit
moodlerooms/moodle
mod/label/mod_form.php
1354
<?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/>. /** * Add label form * * @package mod * @subpackage label * @copyright 2006 Jamie Pratt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; require_once ($CFG->dirroot.'/course/moodleform_mod.php'); class mod_label_mod_form extends moodleform_mod { function definition() { $mform = $this->_form; $this->add_intro_editor(true, get_string('labeltext', 'label')); $this->standard_coursemodule_elements(); //------------------------------------------------------------------------------- // buttons $this->add_action_buttons(true, false, null); } }
gpl-3.0
alexmandujano/django
tests/i18n/patterns/urls/wrong.py
276
from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.utils.translation import ugettext_lazy as _ urlpatterns = i18n_patterns('', url(_(r'^account/'), include('i18n.patterns.urls.wrong_namespace', namespace='account')), )
bsd-3-clause
siscia/jsdelivr
files/parsleyjs/2.1.0-rc3/parsley.js
92310
/*! * Parsleyjs * Guillaume Potier - <[email protected]> * Version 2.1.0-rc3 - built Sun Mar 15 2015 17:50:03 * MIT Licensed * */ !(function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module depending on jQuery. define(['jquery'], factory); } else { // No AMD. Register plugin with global jQuery object. factory(jQuery); } }(function ($) { // small hack for requirejs if jquery is loaded through map and not path // see http://requirejs.org/docs/jquery.html if ('undefined' === typeof $ && 'undefined' !== typeof window.jQuery) $ = window.jQuery; var globalID = 1, pastWarnings = {}, // http://support.microsoft.com/kb/167820 // http://stackoverflow.com/questions/19999388/jquery-check-if-user-is-using-ie msie = (function () { var ua = window.navigator.userAgent, msie = ua.indexOf('MSIE '); if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); return 0; })() modern = !msie || msie >= 8; var ParsleyUtils = { // Parsley DOM-API // returns object from dom attributes and values attr: function ($element, namespace, obj) { var attribute, attributes, regex = new RegExp('^' + namespace, 'i'); if ('undefined' === typeof obj) obj = {}; else { // Clear all own properties. This won't affect prototype's values for (var i in obj) { if (obj.hasOwnProperty(i)) delete obj[i]; } } if ('undefined' === typeof $element || 'undefined' === typeof $element[0]) return obj; attributes = $element[0].attributes; for (var i = attributes.length; i--; ) { attribute = attributes[i]; if (attribute && (modern || attribute.specified) && regex.test(attribute.name)) { obj[this.camelize(attribute.name.slice(namespace.length))] = this.deserializeValue(attribute.value); } } return obj; }, checkAttr: function ($element, namespace, checkAttr) { return $element.is('[' + namespace + checkAttr + ']'); }, setAttr: function ($element, namespace, attr, value) { $element[0].setAttribute(this.dasherize(namespace + attr), String(value)); }, generateID: function () { return '' + globalID++; }, /** Third party functions **/ // Zepto deserialize function deserializeValue: function (value) { var num; try { return value ? value == "true" || (value == "false" ? false : value == "null" ? null : !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value) : value; } catch (e) { return value; } }, // Zepto camelize function camelize: function (str) { return str.replace(/-+(.)?/g, function (match, chr) { return chr ? chr.toUpperCase() : ''; }); }, // Zepto dasherize function dasherize: function (str) { return str.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/_/g, '-') .toLowerCase(); }, warn: function() { if (window.console && window.console.warn) window.console.warn.apply(window.console, arguments); }, warnOnce: function(msg) { if (!pastWarnings[msg]) { pastWarnings[msg] = true; this.warn.apply(this, arguments); } }, // Object.create polyfill, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill objectCreate: Object.create || (function () { var Object = function () {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype != 'object') { throw TypeError('Argument must be an object'); } Object.prototype = prototype; var result = new Object(); Object.prototype = null; return result; }; })() }; // All these options could be overriden and specified directly in DOM using // `data-parsley-` default DOM-API // eg: `inputs` can be set in DOM using `data-parsley-inputs="input, textarea"` // eg: `data-parsley-stop-on-first-failing-constraint="false"` var ParsleyDefaults = { // ### General // Default data-namespace for DOM API namespace: 'data-parsley-', // Supported inputs by default inputs: 'input, textarea, select', // Excluded inputs by default excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]', // Stop validating field on highest priority failing constraint priorityEnabled: true, // ### UI // Enable\Disable error messages uiEnabled: true, // Key events threshold before validation validationThreshold: 3, // Focused field on form validation error. 'fist'|'last'|'none' focus: 'first', // `$.Event()` that will trigger validation. eg: `keyup`, `change`... trigger: false, // Class that would be added on every failing validation Parsley field errorClass: 'parsley-error', // Same for success validation successClass: 'parsley-success', // Return the `$element` that will receive these above success or error classes // Could also be (and given directly from DOM) a valid selector like `'#div'` classHandler: function (ParsleyField) {}, // Return the `$element` where errors will be appended // Could also be (and given directly from DOM) a valid selector like `'#div'` errorsContainer: function (ParsleyField) {}, // ul elem that would receive errors' list errorsWrapper: '<ul class="parsley-errors-list"></ul>', // li elem that would receive error message errorTemplate: '<li></li>' }; var ParsleyAbstract = function () {}; ParsleyAbstract.prototype = { asyncSupport: false, actualizeOptions: function () { ParsleyUtils.attr(this.$element, this.options.namespace, this.domOptions); if (this.parent) this.parent.actualizeOptions(); return this; }, _resetOptions: function (initOptions) { var baseOptions = this.parent ? this.parent.options : window.ParsleyConfig; this.domOptions = ParsleyUtils.objectCreate(baseOptions); this.options = ParsleyUtils.objectCreate(this.domOptions); // Shallow copy of ownProperties of initOptions: for (var i in initOptions) { if (initOptions.hasOwnProperty(i)) this.options[i] = initOptions[i]; } this.actualizeOptions(); }, // ParsleyValidator validate proxy function . Could be replaced by third party scripts validateThroughValidator: function (value, constraints, priority) { return window.ParsleyValidator.validate(value, constraints, priority); }, // Deprecated. Use jQuery events subscribe: function (name, fn) { $.listenTo(this, name.toLowerCase(), fn); return this; }, // Deprecated. Use jQuery events unsubscribe: function (name) { $.unsubscribeTo(this, name.toLowerCase()); return this; }, // Reset UI reset: function () { // Field case: just emit a reset event for UI if ('ParsleyForm' !== this.__class__) return this._trigger('reset'); // Form case: emit a reset event for each field for (var i = 0; i < this.fields.length; i++) this.fields[i]._trigger('reset'); this._trigger('reset'); }, // Destroy Parsley instance (+ UI) destroy: function () { // Field case: emit destroy event to clean UI and then destroy stored instance if ('ParsleyForm' !== this.__class__) { this.$element.removeData('Parsley'); this.$element.removeData('ParsleyFieldMultiple'); this._trigger('destroy'); return; } // Form case: destroy all its fields and then destroy stored instance for (var i = 0; i < this.fields.length; i++) this.fields[i].destroy(); this.$element.removeData('Parsley'); this._trigger('destroy'); } }; /*! * validator.js * Guillaume Potier - <[email protected]> * Version 1.0.1 - built Mon Aug 25 2014 16:10:10 * MIT Licensed * */ var Validator = ( function ( ) { var exports = {}; /** * Validator */ var Validator = function ( options ) { this.__class__ = 'Validator'; this.__version__ = '1.0.1'; this.options = options || {}; this.bindingKey = this.options.bindingKey || '_validatorjsConstraint'; }; Validator.prototype = { constructor: Validator, /* * Validate string: validate( string, Assert, string ) || validate( string, [ Assert, Assert ], [ string, string ] ) * Validate object: validate( object, Constraint, string ) || validate( object, Constraint, [ string, string ] ) * Validate binded object: validate( object, string ) || validate( object, [ string, string ] ) */ validate: function ( objectOrString, AssertsOrConstraintOrGroup, group ) { if ( 'string' !== typeof objectOrString && 'object' !== typeof objectOrString ) throw new Error( 'You must validate an object or a string' ); // string / array validation if ( 'string' === typeof objectOrString || _isArray(objectOrString) ) return this._validateString( objectOrString, AssertsOrConstraintOrGroup, group ); // binded object validation if ( this.isBinded( objectOrString ) ) return this._validateBindedObject( objectOrString, AssertsOrConstraintOrGroup ); // regular object validation return this._validateObject( objectOrString, AssertsOrConstraintOrGroup, group ); }, bind: function ( object, constraint ) { if ( 'object' !== typeof object ) throw new Error( 'Must bind a Constraint to an object' ); object[ this.bindingKey ] = new Constraint( constraint ); return this; }, unbind: function ( object ) { if ( 'undefined' === typeof object._validatorjsConstraint ) return this; delete object[ this.bindingKey ]; return this; }, isBinded: function ( object ) { return 'undefined' !== typeof object[ this.bindingKey ]; }, getBinded: function ( object ) { return this.isBinded( object ) ? object[ this.bindingKey ] : null; }, _validateString: function ( string, assert, group ) { var result, failures = []; if ( !_isArray( assert ) ) assert = [ assert ]; for ( var i = 0; i < assert.length; i++ ) { if ( ! ( assert[ i ] instanceof Assert) ) throw new Error( 'You must give an Assert or an Asserts array to validate a string' ); result = assert[ i ].check( string, group ); if ( result instanceof Violation ) failures.push( result ); } return failures.length ? failures : true; }, _validateObject: function ( object, constraint, group ) { if ( 'object' !== typeof constraint ) throw new Error( 'You must give a constraint to validate an object' ); if ( constraint instanceof Constraint ) return constraint.check( object, group ); return new Constraint( constraint ).check( object, group ); }, _validateBindedObject: function ( object, group ) { return object[ this.bindingKey ].check( object, group ); } }; Validator.errorCode = { must_be_a_string: 'must_be_a_string', must_be_an_array: 'must_be_an_array', must_be_a_number: 'must_be_a_number', must_be_a_string_or_array: 'must_be_a_string_or_array' }; /** * Constraint */ var Constraint = function ( data, options ) { this.__class__ = 'Constraint'; this.options = options || {}; this.nodes = {}; if ( data ) { try { this._bootstrap( data ); } catch ( err ) { throw new Error( 'Should give a valid mapping object to Constraint', err, data ); } } }; Constraint.prototype = { constructor: Constraint, check: function ( object, group ) { var result, failures = {}; // check all constraint nodes. for ( var property in this.nodes ) { var isRequired = false; var constraint = this.get(property); var constraints = _isArray( constraint ) ? constraint : [constraint]; for (var i = constraints.length - 1; i >= 0; i--) { if ( 'Required' === constraints[i].__class__ ) { isRequired = constraints[i].requiresValidation( group ); continue; } } if ( ! this.has( property, object ) && ! this.options.strict && ! isRequired ) { continue; } try { if (! this.has( property, this.options.strict || isRequired ? object : undefined ) ) { // we trigger here a HaveProperty Assert violation to have uniform Violation object in the end new Assert().HaveProperty( property ).validate( object ); } result = this._check( property, object[ property ], group ); // check returned an array of Violations or an object mapping Violations if ( ( _isArray( result ) && result.length > 0 ) || ( !_isArray( result ) && !_isEmptyObject( result ) ) ) { failures[ property ] = result; } } catch ( violation ) { failures[ property ] = violation; } } return _isEmptyObject(failures) ? true : failures; }, add: function ( node, object ) { if ( object instanceof Assert || ( _isArray( object ) && object[ 0 ] instanceof Assert ) ) { this.nodes[ node ] = object; return this; } if ( 'object' === typeof object && !_isArray( object ) ) { this.nodes[ node ] = object instanceof Constraint ? object : new Constraint( object ); return this; } throw new Error( 'Should give an Assert, an Asserts array, a Constraint', object ); }, has: function ( node, nodes ) { nodes = 'undefined' !== typeof nodes ? nodes : this.nodes; return 'undefined' !== typeof nodes[ node ]; }, get: function ( node, placeholder ) { return this.has( node ) ? this.nodes[ node ] : placeholder || null; }, remove: function ( node ) { var _nodes = []; for ( var i in this.nodes ) if ( i !== node ) _nodes[ i ] = this.nodes[ i ]; this.nodes = _nodes; return this; }, _bootstrap: function ( data ) { if ( data instanceof Constraint ) return this.nodes = data.nodes; for ( var node in data ) this.add( node, data[ node ] ); }, _check: function ( node, value, group ) { // Assert if ( this.nodes[ node ] instanceof Assert ) return this._checkAsserts( value, [ this.nodes[ node ] ], group ); // Asserts if ( _isArray( this.nodes[ node ] ) ) return this._checkAsserts( value, this.nodes[ node ], group ); // Constraint -> check api if ( this.nodes[ node ] instanceof Constraint ) return this.nodes[ node ].check( value, group ); throw new Error( 'Invalid node', this.nodes[ node ] ); }, _checkAsserts: function ( value, asserts, group ) { var result, failures = []; for ( var i = 0; i < asserts.length; i++ ) { result = asserts[ i ].check( value, group ); if ( 'undefined' !== typeof result && true !== result ) failures.push( result ); // Some asserts (Collection for example) could return an object // if ( result && ! ( result instanceof Violation ) ) // return result; // // // Vast assert majority return Violation // if ( result instanceof Violation ) // failures.push( result ); } return failures; } }; /** * Violation */ var Violation = function ( assert, value, violation ) { this.__class__ = 'Violation'; if ( ! ( assert instanceof Assert ) ) throw new Error( 'Should give an assertion implementing the Assert interface' ); this.assert = assert; this.value = value; if ( 'undefined' !== typeof violation ) this.violation = violation; }; Violation.prototype = { show: function () { var show = { assert: this.assert.__class__, value: this.value }; if ( this.violation ) show.violation = this.violation; return show; }, __toString: function () { if ( 'undefined' !== typeof this.violation ) this.violation = '", ' + this.getViolation().constraint + ' expected was ' + this.getViolation().expected; return this.assert.__class__ + ' assert failed for "' + this.value + this.violation || ''; }, getViolation: function () { var constraint, expected; for ( constraint in this.violation ) expected = this.violation[ constraint ]; return { constraint: constraint, expected: expected }; } }; /** * Assert */ var Assert = function ( group ) { this.__class__ = 'Assert'; this.__parentClass__ = this.__class__; this.groups = []; if ( 'undefined' !== typeof group ) this.addGroup( group ); }; Assert.prototype = { construct: Assert, requiresValidation: function ( group ) { if ( group && !this.hasGroup( group ) ) return false; if ( !group && this.hasGroups() ) return false; return true; }, check: function ( value, group ) { if ( !this.requiresValidation( group ) ) return; try { return this.validate( value, group ); } catch ( violation ) { return violation; } }, hasGroup: function ( group ) { if ( _isArray( group ) ) return this.hasOneOf( group ); // All Asserts respond to "Any" group if ( 'Any' === group ) return true; // Asserts with no group also respond to "Default" group. Else return false if ( !this.hasGroups() ) return 'Default' === group; return -1 !== this.groups.indexOf( group ); }, hasOneOf: function ( groups ) { for ( var i = 0; i < groups.length; i++ ) if ( this.hasGroup( groups[ i ] ) ) return true; return false; }, hasGroups: function () { return this.groups.length > 0; }, addGroup: function ( group ) { if ( _isArray( group ) ) return this.addGroups( group ); if ( !this.hasGroup( group ) ) this.groups.push( group ); return this; }, removeGroup: function ( group ) { var _groups = []; for ( var i = 0; i < this.groups.length; i++ ) if ( group !== this.groups[ i ] ) _groups.push( this.groups[ i ] ); this.groups = _groups; return this; }, addGroups: function ( groups ) { for ( var i = 0; i < groups.length; i++ ) this.addGroup( groups[ i ] ); return this; }, /** * Asserts definitions */ HaveProperty: function ( node ) { this.__class__ = 'HaveProperty'; this.node = node; this.validate = function ( object ) { if ( 'undefined' === typeof object[ this.node ] ) throw new Violation( this, object, { value: this.node } ); return true; }; return this; }, Blank: function () { this.__class__ = 'Blank'; this.validate = function ( value ) { if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( '' !== value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) ) throw new Violation( this, value ); return true; }; return this; }, Callback: function ( fn ) { this.__class__ = 'Callback'; this.arguments = Array.prototype.slice.call( arguments ); if ( 1 === this.arguments.length ) this.arguments = []; else this.arguments.splice( 0, 1 ); if ( 'function' !== typeof fn ) throw new Error( 'Callback must be instanciated with a function' ); this.fn = fn; this.validate = function ( value ) { var result = this.fn.apply( this, [ value ].concat( this.arguments ) ); if ( true !== result ) throw new Violation( this, value, { result: result } ); return true; }; return this; }, Choice: function ( list ) { this.__class__ = 'Choice'; if ( !_isArray( list ) && 'function' !== typeof list ) throw new Error( 'Choice must be instanciated with an array or a function' ); this.list = list; this.validate = function ( value ) { var list = 'function' === typeof this.list ? this.list() : this.list; for ( var i = 0; i < list.length; i++ ) if ( value === list[ i ] ) return true; throw new Violation( this, value, { choices: list } ); }; return this; }, Collection: function ( assertOrConstraint ) { this.__class__ = 'Collection'; this.constraint = 'undefined' !== typeof assertOrConstraint ? (assertOrConstraint instanceof Assert ? assertOrConstraint : new Constraint( assertOrConstraint )) : false; this.validate = function ( collection, group ) { var result, validator = new Validator(), count = 0, failures = {}, groups = this.groups.length ? this.groups : group; if ( !_isArray( collection ) ) throw new Violation( this, collection, { value: Validator.errorCode.must_be_an_array } ); for ( var i = 0; i < collection.length; i++ ) { result = this.constraint ? validator.validate( collection[ i ], this.constraint, groups ) : validator.validate( collection[ i ], groups ); if ( !_isEmptyObject( result ) ) failures[ count ] = result; count++; } return !_isEmptyObject( failures ) ? failures : true; }; return this; }, Count: function ( count ) { this.__class__ = 'Count'; this.count = count; this.validate = function ( array ) { if ( !_isArray( array ) ) throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } ); var count = 'function' === typeof this.count ? this.count( array ) : this.count; if ( isNaN( Number( count ) ) ) throw new Error( 'Count must be a valid interger', count ); if ( count !== array.length ) throw new Violation( this, array, { count: count } ); return true; }; return this; }, Email: function () { this.__class__ = 'Email'; this.validate = function ( value ) { var regExp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( !regExp.test( value ) ) throw new Violation( this, value ); return true; }; return this; }, EqualTo: function ( reference ) { this.__class__ = 'EqualTo'; if ( 'undefined' === typeof reference ) throw new Error( 'EqualTo must be instanciated with a value or a function' ); this.reference = reference; this.validate = function ( value ) { var reference = 'function' === typeof this.reference ? this.reference( value ) : this.reference; if ( reference !== value ) throw new Violation( this, value, { value: reference } ); return true; }; return this; }, GreaterThan: function ( threshold ) { this.__class__ = 'GreaterThan'; if ( 'undefined' === typeof threshold ) throw new Error( 'Should give a threshold value' ); this.threshold = threshold; this.validate = function ( value ) { if ( '' === value || isNaN( Number( value ) ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } ); if ( this.threshold >= value ) throw new Violation( this, value, { threshold: this.threshold } ); return true; }; return this; }, GreaterThanOrEqual: function ( threshold ) { this.__class__ = 'GreaterThanOrEqual'; if ( 'undefined' === typeof threshold ) throw new Error( 'Should give a threshold value' ); this.threshold = threshold; this.validate = function ( value ) { if ( '' === value || isNaN( Number( value ) ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } ); if ( this.threshold > value ) throw new Violation( this, value, { threshold: this.threshold } ); return true; }; return this; }, InstanceOf: function ( classRef ) { this.__class__ = 'InstanceOf'; if ( 'undefined' === typeof classRef ) throw new Error( 'InstanceOf must be instanciated with a value' ); this.classRef = classRef; this.validate = function ( value ) { if ( true !== (value instanceof this.classRef) ) throw new Violation( this, value, { classRef: this.classRef } ); return true; }; return this; }, Length: function ( boundaries ) { this.__class__ = 'Length'; if ( !boundaries.min && !boundaries.max ) throw new Error( 'Lenth assert must be instanciated with a { min: x, max: y } object' ); this.min = boundaries.min; this.max = boundaries.max; this.validate = function ( value ) { if ( 'string' !== typeof value && !_isArray( value ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string_or_array } ); if ( 'undefined' !== typeof this.min && this.min === this.max && value.length !== this.min ) throw new Violation( this, value, { min: this.min, max: this.max } ); if ( 'undefined' !== typeof this.max && value.length > this.max ) throw new Violation( this, value, { max: this.max } ); if ( 'undefined' !== typeof this.min && value.length < this.min ) throw new Violation( this, value, { min: this.min } ); return true; }; return this; }, LessThan: function ( threshold ) { this.__class__ = 'LessThan'; if ( 'undefined' === typeof threshold ) throw new Error( 'Should give a threshold value' ); this.threshold = threshold; this.validate = function ( value ) { if ( '' === value || isNaN( Number( value ) ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } ); if ( this.threshold <= value ) throw new Violation( this, value, { threshold: this.threshold } ); return true; }; return this; }, LessThanOrEqual: function ( threshold ) { this.__class__ = 'LessThanOrEqual'; if ( 'undefined' === typeof threshold ) throw new Error( 'Should give a threshold value' ); this.threshold = threshold; this.validate = function ( value ) { if ( '' === value || isNaN( Number( value ) ) ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } ); if ( this.threshold < value ) throw new Violation( this, value, { threshold: this.threshold } ); return true; }; return this; }, NotNull: function () { this.__class__ = 'NotNull'; this.validate = function ( value ) { if ( null === value || 'undefined' === typeof value ) throw new Violation( this, value ); return true; }; return this; }, NotBlank: function () { this.__class__ = 'NotBlank'; this.validate = function ( value ) { if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( '' === value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) ) throw new Violation( this, value ); return true; }; return this; }, Null: function () { this.__class__ = 'Null'; this.validate = function ( value ) { if ( null !== value ) throw new Violation( this, value ); return true; }; return this; }, Range: function ( min, max ) { this.__class__ = 'Range'; if ( 'undefined' === typeof min || 'undefined' === typeof max ) throw new Error( 'Range assert expects min and max values' ); this.min = min; this.max = max; this.validate = function ( value ) { try { // validate strings and objects with their Length if ( ( 'string' === typeof value && isNaN( Number( value ) ) ) || _isArray( value ) ) new Assert().Length( { min: this.min, max: this.max } ).validate( value ); // validate numbers with their value else new Assert().GreaterThanOrEqual( this.min ).validate( value ) && new Assert().LessThanOrEqual( this.max ).validate( value ); return true; } catch ( violation ) { throw new Violation( this, value, violation.violation ); } return true; }; return this; }, Regexp: function ( regexp, flag ) { this.__class__ = 'Regexp'; if ( 'undefined' === typeof regexp ) throw new Error( 'You must give a regexp' ); this.regexp = regexp; this.flag = flag || ''; this.validate = function ( value ) { if ( 'string' !== typeof value ) throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } ); if ( !new RegExp( this.regexp, this.flag ).test( value ) ) throw new Violation( this, value, { regexp: this.regexp, flag: this.flag } ); return true; }; return this; }, Required: function () { this.__class__ = 'Required'; this.validate = function ( value ) { if ( 'undefined' === typeof value ) throw new Violation( this, value ); try { if ( 'string' === typeof value ) new Assert().NotNull().validate( value ) && new Assert().NotBlank().validate( value ); else if ( true === _isArray( value ) ) new Assert().Length( { min: 1 } ).validate( value ); } catch ( violation ) { throw new Violation( this, value ); } return true; }; return this; }, // Unique() or Unique ( { key: foo } ) Unique: function ( object ) { this.__class__ = 'Unique'; if ( 'object' === typeof object ) this.key = object.key; this.validate = function ( array ) { var value, store = []; if ( !_isArray( array ) ) throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } ); for ( var i = 0; i < array.length; i++ ) { value = 'object' === typeof array[ i ] ? array[ i ][ this.key ] : array[ i ]; if ( 'undefined' === typeof value ) continue; if ( -1 !== store.indexOf( value ) ) throw new Violation( this, array, { value: value } ); store.push( value ); } return true; }; return this; } }; // expose to the world these awesome classes exports.Assert = Assert; exports.Validator = Validator; exports.Violation = Violation; exports.Constraint = Constraint; /** * Some useful object prototypes / functions here */ // IE8<= compatibility // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { if (this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n !== 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; // Test if object is empty, useful for Constraint violations check var _isEmptyObject = function ( obj ) { for ( var property in obj ) return false; return true; }; var _isArray = function ( obj ) { return Object.prototype.toString.call( obj ) === '[object Array]'; }; // AMD export if ( typeof define === 'function' && define.amd ) { define( 'vendors/validator.js/dist/validator',[],function() { return exports; } ); // commonjs export } else if ( typeof module !== 'undefined' && module.exports ) { module.exports = exports; // browser } else { window[ 'undefined' !== typeof validatorjs_ns ? validatorjs_ns : 'Validator' ] = exports; } return exports; } )( ); // This is needed for Browserify usage that requires Validator.js through module.exports Validator = 'undefined' !== typeof Validator ? Validator : ('undefined' !== typeof module ? module.exports : null); var ParsleyValidator = function (validators, catalog) { this.__class__ = 'ParsleyValidator'; this.Validator = Validator; // Default Parsley locale is en this.locale = 'en'; this.init(validators || {}, catalog || {}); }; ParsleyValidator.prototype = { init: function (validators, catalog) { this.catalog = catalog; for (var name in validators) this.addValidator(name, validators[name].fn, validators[name].priority, validators[name].requirementsTransformer); $(document).trigger('parsley:validator:init'); }, // Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n setLocale: function (locale) { if ('undefined' === typeof this.catalog[locale]) throw new Error(locale + ' is not available in the catalog'); this.locale = locale; return this; }, // Add a new messages catalog for a given locale. Set locale for this catalog if set === `true` addCatalog: function (locale, messages, set) { if ('object' === typeof messages) this.catalog[locale] = messages; if (true === set) return this.setLocale(locale); return this; }, // Add a specific message for a given constraint in a given locale addMessage: function (locale, name, message) { if ('undefined' === typeof this.catalog[locale]) this.catalog[locale] = {}; this.catalog[locale][name.toLowerCase()] = message; return this; }, validate: function (value, constraints, priority) { return new this.Validator.Validator().validate.apply(new Validator.Validator(), arguments); }, // Add a new validator addValidator: function (name, fn, priority, requirementsTransformer) { this.validators[name] = function (requirements) { return $.extend(new Validator.Assert().Callback(fn, requirements), { priority: priority, requirementsTransformer: requirementsTransformer }); }; return this; }, updateValidator: function (name, fn, priority, requirementsTransformer) { return this.addValidator(name, fn, priority, requirementsTransformer); }, removeValidator: function (name) { delete this.validators[name]; return this; }, getErrorMessage: function (constraint) { var message; // Type constraints are a bit different, we have to match their requirements too to find right error message if ('type' === constraint.name) { var typeMessages = this.catalog[this.locale][constraint.name] || {}; message = typeMessages[constraint.requirements]; } else message = this.formatMessage(this.catalog[this.locale][constraint.name], constraint.requirements); return message || this.catalog[this.locale].defaultMessage || this.catalog.en.defaultMessage; }, // Kind of light `sprintf()` implementation formatMessage: function (string, parameters) { if ('object' === typeof parameters) { for (var i in parameters) string = this.formatMessage(string, parameters[i]); return string; } return 'string' === typeof string ? string.replace(new RegExp('%s', 'i'), parameters) : ''; }, // Here is the Parsley default validators list. // This is basically Validatorjs validators, with different API for some of them // and a Parsley priority set validators: { notblank: function () { return $.extend(new Validator.Assert().NotBlank(), { priority: 2 }); }, required: function () { return $.extend(new Validator.Assert().Required(), { priority: 512 }); }, type: function (type) { var assert; switch (type) { case 'email': assert = new Validator.Assert().Email(); break; // range type just ensure we have a number here case 'range': case 'number': assert = new Validator.Assert().Regexp('^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)?(?:\\.\\d+)?$'); break; case 'integer': assert = new Validator.Assert().Regexp('^-?\\d+$'); break; case 'digits': assert = new Validator.Assert().Regexp('^\\d+$'); break; case 'alphanum': assert = new Validator.Assert().Regexp('^\\w+$', 'i'); break; case 'url': // Thanks to https://gist.github.com/dperini/729294 // Voted best validator in https://mathiasbynens.be/demo/url-regex // Modified to make scheme optional and allow local IPs assert = new Validator.Assert().Regexp( "^" + // protocol identifier "(?:(?:https?|ftp)://)?" + // ** mod: make scheme optional // user:pass authentication "(?:\\S+(?::\\S*)?@)?" + "(?:" + // IP address exclusion // private & local networks // "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + // ** mod: allow local networks // "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks // "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks // IP address dotted notation octets // excludes loopback network 0.0.0.0 // excludes reserved space >= 224.0.0.0 // excludes network & broacast addresses // (first & last IP address of each class) "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + // host name "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + // domain name "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + // TLD identifier "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + ")" + // port number "(?::\\d{2,5})?" + // resource path "(?:/\\S*)?" + "$", 'i'); break; default: throw new Error('validator type `' + type + '` is not supported'); } return $.extend(assert, { priority: 256 }); }, pattern: function (regexp) { var flags = ''; // Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern if (!!(/^\/.*\/(?:[gimy]*)$/.test(regexp))) { // Replace the regexp literal string with the first match group: ([gimy]*) // If no flag is present, this will be a blank string flags = regexp.replace(/.*\/([gimy]*)$/, '$1'); // Again, replace the regexp literal string with the first match group: // everything excluding the opening and closing slashes and the flags regexp = regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1'); } return $.extend(new Validator.Assert().Regexp(regexp, flags), { priority: 64 }); }, minlength: function (value) { return $.extend(new Validator.Assert().Length({ min: value }), { priority: 30, requirementsTransformer: function () { return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value; } }); }, maxlength: function (value) { return $.extend(new Validator.Assert().Length({ max: value }), { priority: 30, requirementsTransformer: function () { return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value; } }); }, length: function (array) { return $.extend(new Validator.Assert().Length({ min: array[0], max: array[1] }), { priority: 32 }); }, mincheck: function (length) { return this.minlength(length); }, maxcheck: function (length) { return this.maxlength(length); }, check: function (array) { return this.length(array); }, min: function (value) { return $.extend(new Validator.Assert().GreaterThanOrEqual(value), { priority: 30, requirementsTransformer: function () { return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value; } }); }, max: function (value) { return $.extend(new Validator.Assert().LessThanOrEqual(value), { priority: 30, requirementsTransformer: function () { return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value; } }); }, range: function (array) { return $.extend(new Validator.Assert().Range(array[0], array[1]), { priority: 32, requirementsTransformer: function () { for (var i = 0; i < array.length; i++) array[i] = 'string' === typeof array[i] && !isNaN(array[i]) ? parseInt(array[i], 10) : array[i]; return array; } }); }, equalto: function (value) { return $.extend(new Validator.Assert().EqualTo(value), { priority: 256, requirementsTransformer: function () { return $(value).length ? $(value).val() : value; } }); } } }; var ParsleyUI = function (options) { this.__class__ = 'ParsleyUI'; }; ParsleyUI.prototype = { listen: function () { var that = this; $(document) .on('form:init.parsley', function (evt, field) { that.setupForm (field); } ) .on('field:init.parsley', function (evt, field) { that.setupField(field); } ) .on('field:validated.parsley', function (evt, field) { that.reflow (field); } ) .on('form:validated.parsley', function (evt, field) { that.focus (field); } ) .on('field:reset.parsley', function (evt, field) { that.reset (field); } ) .on('form:destroy.parsley', function (evt, field) { that.destroy (field); } ) .on('field:destroy.parsley', function (evt, field) { that.destroy (field); } ); return this; }, reflow: function (fieldInstance) { // If this field has not an active UI (case for multiples) don't bother doing something if ('undefined' === typeof fieldInstance._ui || false === fieldInstance._ui.active) return; // Diff between two validation results var diff = this._diff(fieldInstance.validationResult, fieldInstance._ui.lastValidationResult); // Then store current validation result for next reflow fieldInstance._ui.lastValidationResult = fieldInstance.validationResult; // Field have been validated at least once if here. Useful for binded key events... fieldInstance._ui.validatedOnce = true; // Handle valid / invalid / none field class this.manageStatusClass(fieldInstance); // Add, remove, updated errors messages this.manageErrorsMessages(fieldInstance, diff); // Triggers impl this.actualizeTriggers(fieldInstance); // If field is not valid for the first time, bind keyup trigger to ease UX and quickly inform user if ((diff.kept.length || diff.added.length) && true !== fieldInstance._ui.failedOnce) this.manageFailingFieldTrigger(fieldInstance); }, // Returns an array of field's error message(s) getErrorsMessages: function (fieldInstance) { // No error message, field is valid if (true === fieldInstance.validationResult) return []; var messages = []; for (var i = 0; i < fieldInstance.validationResult.length; i++) messages.push(this._getErrorMessage(fieldInstance, fieldInstance.validationResult[i].assert)); return messages; }, manageStatusClass: function (fieldInstance) { if (fieldInstance.hasConstraints() && fieldInstance.needsValidation() && true === fieldInstance.validationResult) this._successClass(fieldInstance); else if (fieldInstance.validationResult.length > 0) this._errorClass(fieldInstance); else this._resetClass(fieldInstance); }, manageErrorsMessages: function (fieldInstance, diff) { if ('undefined' !== typeof fieldInstance.options.errorsMessagesDisabled) return; // Case where we have errorMessage option that configure an unique field error message, regardless failing validators if ('undefined' !== typeof fieldInstance.options.errorMessage) { if ((diff.added.length || diff.kept.length)) { this._insertErrorWrapper(fieldInstance); if (0 === fieldInstance._ui.$errorsWrapper.find('.parsley-custom-error-message').length) fieldInstance._ui.$errorsWrapper .append( $(fieldInstance.options.errorTemplate) .addClass('parsley-custom-error-message') ); return fieldInstance._ui.$errorsWrapper .addClass('filled') .find('.parsley-custom-error-message') .html(fieldInstance.options.errorMessage); } return fieldInstance._ui.$errorsWrapper .removeClass('filled') .find('.parsley-custom-error-message') .remove(); } // Show, hide, update failing constraints messages for (var i = 0; i < diff.removed.length; i++) this.removeError(fieldInstance, diff.removed[i].assert.name, true); for (i = 0; i < diff.added.length; i++) this.addError(fieldInstance, diff.added[i].assert.name, undefined, diff.added[i].assert, true); for (i = 0; i < diff.kept.length; i++) this.updateError(fieldInstance, diff.kept[i].assert.name, undefined, diff.kept[i].assert, true); }, // TODO: strange API here, intuitive for manual usage with addError(pslyInstance, 'foo', 'bar') // but a little bit complex for above internal usage, with forced undefined parameter... addError: function (fieldInstance, name, message, assert, doNotUpdateClass) { this._insertErrorWrapper(fieldInstance); fieldInstance._ui.$errorsWrapper .addClass('filled') .append( $(fieldInstance.options.errorTemplate) .addClass('parsley-' + name) .html(message || this._getErrorMessage(fieldInstance, assert)) ); if (true !== doNotUpdateClass) this._errorClass(fieldInstance); }, // Same as above updateError: function (fieldInstance, name, message, assert, doNotUpdateClass) { fieldInstance._ui.$errorsWrapper .addClass('filled') .find('.parsley-' + name) .html(message || this._getErrorMessage(fieldInstance, assert)); if (true !== doNotUpdateClass) this._errorClass(fieldInstance); }, // Same as above twice removeError: function (fieldInstance, name, doNotUpdateClass) { fieldInstance._ui.$errorsWrapper .removeClass('filled') .find('.parsley-' + name) .remove(); // edge case possible here: remove a standard Parsley error that is still failing in fieldInstance.validationResult // but highly improbable cuz' manually removing a well Parsley handled error makes no sense. if (true !== doNotUpdateClass) this.manageStatusClass(fieldInstance); }, focus: function (formInstance) { if (true === formInstance.validationResult || 'none' === formInstance.options.focus) return formInstance._focusedField = null; formInstance._focusedField = null; for (var i = 0; i < formInstance.fields.length; i++) if (true !== formInstance.fields[i].validationResult && formInstance.fields[i].validationResult.length > 0 && 'undefined' === typeof formInstance.fields[i].options.noFocus) { if ('first' === formInstance.options.focus) { formInstance._focusedField = formInstance.fields[i].$element; return formInstance._focusedField.focus(); } formInstance._focusedField = formInstance.fields[i].$element; } if (null === formInstance._focusedField) return null; return formInstance._focusedField.focus(); }, _getErrorMessage: function (fieldInstance, constraint) { var customConstraintErrorMessage = constraint.name + 'Message'; if ('undefined' !== typeof fieldInstance.options[customConstraintErrorMessage]) return window.ParsleyValidator.formatMessage(fieldInstance.options[customConstraintErrorMessage], constraint.requirements); return window.ParsleyValidator.getErrorMessage(constraint); }, _diff: function (newResult, oldResult, deep) { var added = [], kept = []; for (var i = 0; i < newResult.length; i++) { var found = false; for (var j = 0; j < oldResult.length; j++) if (newResult[i].assert.name === oldResult[j].assert.name) { found = true; break; } if (found) kept.push(newResult[i]); else added.push(newResult[i]); } return { kept: kept, added: added, removed: !deep ? this._diff(oldResult, newResult, true).added : [] }; }, setupForm: function (formInstance) { formInstance.$element.on('submit.Parsley', false, $.proxy(formInstance.onSubmitValidate, formInstance)); // UI could be disabled if (false === formInstance.options.uiEnabled) return; formInstance.$element.attr('novalidate', ''); }, setupField: function (fieldInstance) { var _ui = { active: false }; // UI could be disabled if (false === fieldInstance.options.uiEnabled) return; _ui.active = true; // Give field its Parsley id in DOM fieldInstance.$element.attr(fieldInstance.options.namespace + 'id', fieldInstance.__id__); /** Generate important UI elements and store them in fieldInstance **/ // $errorClassHandler is the $element that woul have parsley-error and parsley-success classes _ui.$errorClassHandler = this._manageClassHandler(fieldInstance); // $errorsWrapper is a div that would contain the various field errors, it will be appended into $errorsContainer _ui.errorsWrapperId = 'parsley-id-' + ('undefined' !== typeof fieldInstance.options.multiple ? 'multiple-' + fieldInstance.options.multiple : fieldInstance.__id__); _ui.$errorsWrapper = $(fieldInstance.options.errorsWrapper).attr('id', _ui.errorsWrapperId); // ValidationResult UI storage to detect what have changed bwt two validations, and update DOM accordingly _ui.lastValidationResult = []; _ui.validatedOnce = false; _ui.validationInformationVisible = false; // Store it in fieldInstance for later fieldInstance._ui = _ui; // Bind triggers first time this.actualizeTriggers(fieldInstance); }, // Determine which element will have `parsley-error` and `parsley-success` classes _manageClassHandler: function (fieldInstance) { // An element selector could be passed through DOM with `data-parsley-class-handler=#foo` if ('string' === typeof fieldInstance.options.classHandler && $(fieldInstance.options.classHandler).length) return $(fieldInstance.options.classHandler); // Class handled could also be determined by function given in Parsley options var $handler = fieldInstance.options.classHandler(fieldInstance); // If this function returned a valid existing DOM element, go for it if ('undefined' !== typeof $handler && $handler.length) return $handler; // Otherwise, if simple element (input, texatrea, select...) it will perfectly host the classes if ('undefined' === typeof fieldInstance.options.multiple || fieldInstance.$element.is('select')) return fieldInstance.$element; // But if multiple element (radio, checkbox), that would be their parent return fieldInstance.$element.parent(); }, _insertErrorWrapper: function (fieldInstance) { var $errorsContainer; // Nothing to do if already inserted if (0 !== fieldInstance._ui.$errorsWrapper.parent().length) return fieldInstance._ui.$errorsWrapper.parent(); if ('string' === typeof fieldInstance.options.errorsContainer) { if ($(fieldInstance.options.errorsContainer).length) return $(fieldInstance.options.errorsContainer).append(fieldInstance._ui.$errorsWrapper); else ParsleyUtils.warn('The errors container `' + fieldInstance.options.errorsContainer + '` does not exist in DOM'); } else if ('function' === typeof fieldInstance.options.errorsContainer) $errorsContainer = fieldInstance.options.errorsContainer(fieldInstance); if ('undefined' !== typeof $errorsContainer && $errorsContainer.length) return $errorsContainer.append(fieldInstance._ui.$errorsWrapper); return 'undefined' === typeof fieldInstance.options.multiple ? fieldInstance.$element.after(fieldInstance._ui.$errorsWrapper) : fieldInstance.$element.parent().after(fieldInstance._ui.$errorsWrapper); }, actualizeTriggers: function (fieldInstance) { var $toBind = fieldInstance.$element; if (fieldInstance.options.multiple) $toBind = $('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]'); // Remove Parsley events already binded on this field $toBind.off('.Parsley'); // If no trigger is set, all good if (false === fieldInstance.options.trigger) return; var triggers = fieldInstance.options.trigger.replace(/^\s+/g , '').replace(/\s+$/g , ''); if ('' === triggers) return; // Bind fieldInstance.eventValidate if exists (for parsley.ajax for example), ParsleyUI.eventValidate otherwise $toBind.on( triggers.split(' ').join('.Parsley ') + '.Parsley', $.proxy('function' === typeof fieldInstance.eventValidate ? fieldInstance.eventValidate : this.eventValidate, fieldInstance)); }, // Called through $.proxy with fieldInstance. `this` context is ParsleyField eventValidate: function (event) { // For keyup, keypress, keydown... events that could be a little bit obstrusive // do not validate if val length < min threshold on first validation. Once field have been validated once and info // about success or failure have been displayed, always validate with this trigger to reflect every yalidation change. if (new RegExp('key').test(event.type)) if (!this._ui.validationInformationVisible && this.getValue().length <= this.options.validationThreshold) return; this._ui.validatedOnce = true; this.validate(); }, manageFailingFieldTrigger: function (fieldInstance) { fieldInstance._ui.failedOnce = true; // Radio and checkboxes fields must bind every field multiple if (fieldInstance.options.multiple) $('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () { if (!new RegExp('change', 'i').test($(this).parsley().options.trigger || '')) return $(this).on('change.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance)); }); // Select case if (fieldInstance.$element.is('select')) if (!new RegExp('change', 'i').test(fieldInstance.options.trigger || '')) return fieldInstance.$element.on('change.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance)); // All other inputs fields if (!new RegExp('keyup', 'i').test(fieldInstance.options.trigger || '')) return fieldInstance.$element.on('keyup.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance)); }, reset: function (parsleyInstance) { // Reset all event listeners parsleyInstance.$element.off('.Parsley'); parsleyInstance.$element.off('.ParsleyFailedOnce'); // Nothing to do if UI never initialized for this field if ('undefined' === typeof parsleyInstance._ui) return; if ('ParsleyForm' === parsleyInstance.__class__) return; // Reset all errors' li parsleyInstance._ui.$errorsWrapper .removeClass('filled') .children() .remove(); // Reset validation class this._resetClass(parsleyInstance); // Reset validation flags and last validation result parsleyInstance._ui.validatedOnce = false; parsleyInstance._ui.lastValidationResult = []; parsleyInstance._ui.validationInformationVisible = false; parsleyInstance._ui.failedOnce = false; }, destroy: function (parsleyInstance) { this.reset(parsleyInstance); if ('ParsleyForm' === parsleyInstance.__class__) return; if ('undefined' !== typeof parsleyInstance._ui) parsleyInstance._ui.$errorsWrapper.remove(); delete parsleyInstance._ui; }, _successClass: function (fieldInstance) { fieldInstance._ui.validationInformationVisible = true; fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.errorClass).addClass(fieldInstance.options.successClass); }, _errorClass: function (fieldInstance) { fieldInstance._ui.validationInformationVisible = true; fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.successClass).addClass(fieldInstance.options.errorClass); }, _resetClass: function (fieldInstance) { fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.successClass).removeClass(fieldInstance.options.errorClass); } }; var ParsleyForm = function (element, domOptions, options) { this.__class__ = 'ParsleyForm'; this.__id__ = ParsleyUtils.generateID(); this.$element = $(element); this.domOptions = domOptions; this.options = options; this.fields = []; this.validationResult = null; }; ParsleyForm.prototype = { onSubmitValidate: function (event) { this.validate(undefined, undefined, event); // prevent form submission if validation fails if ((false === this.validationResult || !this._trigger('submit')) && event instanceof $.Event) { event.stopImmediatePropagation(); event.preventDefault(); } return this; }, // @returns boolean validate: function (group, force, event) { this.submitEvent = event; this.validationResult = true; var fieldValidationResult = []; // fire validate event to eventually modify things before very validation this._trigger('validate'); // Refresh form DOM options and form's fields that could have changed this._refreshFields(); this._withoutReactualizingFormOptions(function(){ // loop through fields to validate them one by one for (var i = 0; i < this.fields.length; i++) { // do not validate a field if not the same as given validation group if (group && !this._isFieldInGroup(this.fields[i], group)) continue; fieldValidationResult = this.fields[i].validate(force); if (true !== fieldValidationResult && fieldValidationResult.length > 0 && this.validationResult) this.validationResult = false; } }); this._trigger(this.validationResult ? 'success' : 'error'); this._trigger('validated'); return this.validationResult; }, // Iterate over refreshed fields, and stop on first failure isValid: function (group, force) { this._refreshFields(); return this._withoutReactualizingFormOptions(function(){ for (var i = 0; i < this.fields.length; i++) { // do not validate a field if not the same as given validation group if (group && !this._isFieldInGroup(this.fields[i], group)) continue; if (false === this.fields[i].isValid(force)) return false; } return true; }); }, _isFieldInGroup: function (field, group) { if($.isArray(field.options.group)) return -1 !== $.inArray(group, field.options.group); return field.options.group === group; }, _refreshFields: function () { return this.actualizeOptions()._bindFields(); }, _bindFields: function () { var self = this, oldFields = this.fields; this.fields = []; this.fieldsMappedById = {}; this._withoutReactualizingFormOptions(function(){ this.$element.find(this.options.inputs).each(function () { var fieldInstance = new window.Parsley(this, {}, self); // Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && !fieldInstance.$element.is(fieldInstance.options.excluded)) if ('undefined' === typeof self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) { self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance; self.fields.push(fieldInstance); } }); $(oldFields).not(self.fields).each(function () { this._trigger('reset'); // If DOM element is detached or removed from the form, also trigger // at the form level: if (!jQuery.contains(self.$element[0], this.$element[0])) { self.$element.trigger('field:reset.parsley', [this]); } }); }); return this; }, // Internal only. // Looping on a form's fields to do validation or similar // will trigger reactualizing options on all of them, which // in turn will reactualize the form's options. // To avoid calling actualizeOptions so many times on the form // for nothing, _withoutReactualizingFormOptions temporarily disables // the method actualizeOptions on this form while `fn` is called. _withoutReactualizingFormOptions: function (fn) { var oldActualizeOptions = this.actualizeOptions; this.actualizeOptions = $.noop; var result = fn.call(this); // Keep the current `this`. this.actualizeOptions = oldActualizeOptions; return result; }, // Internal only. // Shortcut to trigger an event // Returns true iff event is not interrupted and default not prevented. _trigger: function (eventName) { var event = jQuery.Event('form:' + eventName + '.parsley'); this.$element.trigger(event, [this]); return !(event.isDefaultPrevented() || event.isImmediatePropagationStopped() || event.isPropagationStopped()); } }; var ConstraintFactory = function (parsleyField, name, requirements, priority, isDomConstraint) { var assert = {}; if (!new RegExp('ParsleyField').test(parsleyField.__class__)) throw new Error('ParsleyField or ParsleyFieldMultiple instance expected'); if ('function' === typeof window.ParsleyValidator.validators[name]) assert = window.ParsleyValidator.validators[name](requirements); if ('Assert' !== assert.__parentClass__) throw new Error('Valid validator expected'); var getPriority = function () { if ('undefined' !== typeof parsleyField.options[name + 'Priority']) return parsleyField.options[name + 'Priority']; return assert.priority || 2; }; priority = priority || getPriority(); // If validator have a requirementsTransformer, execute it if ('function' === typeof assert.requirementsTransformer) { requirements = assert.requirementsTransformer(); // rebuild assert with new requirements assert = window.ParsleyValidator.validators[name](requirements); } return $.extend(assert, { name: name, requirements: requirements, priority: priority, groups: [priority], isDomConstraint: isDomConstraint || ParsleyUtils.checkAttr(parsleyField.$element, parsleyField.options.namespace, name) }); }; var ParsleyField = function (field, domOptions, options, parsleyFormInstance) { this.__class__ = 'ParsleyField'; this.__id__ = ParsleyUtils.generateID(); this.$element = $(field); // Set parent if we have one if ('undefined' !== typeof parsleyFormInstance) { this.parent = parsleyFormInstance; } this.options = options; this.domOptions = domOptions; // Initialize some properties this.constraints = []; this.constraintsByName = {}; this.validationResult = []; // Bind constraints this._bindConstraints(); }; ParsleyField.prototype = { // # Public API // Validate field and trigger some events for mainly `ParsleyUI` // @returns validationResult: // - `true` if field valid // - `[Violation, [Violation...]]` if there were validation errors validate: function (force) { this.value = this.getValue(); // Field Validate event. `this.value` could be altered for custom needs this._trigger('validate'); this._trigger(this.isValid(force, this.value) ? 'success' : 'error'); // Field validated event. `this.validationResult` could be altered for custom needs too this._trigger('validated'); return this.validationResult; }, hasConstraints: function () { return 0 !== this.constraints.length; }, // An empty optional field does not need validation needsValidation: function (value) { if ('undefined' === typeof value) value = this.getValue(); // If a field is empty and not required, it is valid // Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators if (!value.length && !this._isRequired() && 'undefined' === typeof this.options.validateIfEmpty) return false; return true; }, // Just validate field. Do not trigger any event // - `false` if there are constraints and at least one of them failed // - `true` in all other cases isValid: function (force, value) { // Recompute options and rebind constraints to have latest changes this.refreshConstraints(); this.validationResult = true; // A field without constraint is valid if (!this.hasConstraints()) return true; // Value could be passed as argument, needed to add more power to 'parsley:field:validate' if ('undefined' === typeof value || null === value) value = this.getValue(); if (!this.needsValidation(value) && true !== force) return true; // If we want to validate field against all constraints, just call Validator and let it do the job if (false === this.options.priorityEnabled) return true === (this.validationResult = this.validateThroughValidator(value, this.constraints, 'Any')); // Sort priorities to validate more important first var priorities = this._getConstraintsSortedPriorities(); // Else, iterate over priorities one by one, and validate related asserts one by one for (var i = 0; i < priorities.length; i++) if (true !== (this.validationResult = this.validateThroughValidator(value, this.constraints, priorities[i]))) return false; return true; }, // @returns Parsley field computed value that could be overrided or configured in DOM getValue: function () { var value; // Value could be overriden in DOM or with explicit options if ('function' === typeof this.options.value) value = this.options.value(this); else if ('undefined' !== typeof this.options.value) value = this.options.value; else value = this.$element.val(); // Handle wrong DOM or configurations if ('undefined' === typeof value || null === value) return ''; // Use `data-parsley-trim-value="true"` to auto trim inputs entry if (true === this.options.trimValue) return value.replace(/^\s+|\s+$/g, ''); return value; }, // Actualize options that could have change since previous validation // Re-bind accordingly constraints (could be some new, removed or updated) refreshConstraints: function () { return this.actualizeOptions()._bindConstraints(); }, /** * Add a new constraint to a field * * @method addConstraint * @param {String} name * @param {Mixed} requirements optional * @param {Number} priority optional * @param {Boolean} isDomConstraint optional */ addConstraint: function (name, requirements, priority, isDomConstraint) { if ('function' === typeof window.ParsleyValidator.validators[name]) { var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint); // if constraint already exist, delete it and push new version if ('undefined' !== this.constraintsByName[constraint.name]) this.removeConstraint(constraint.name); this.constraints.push(constraint); this.constraintsByName[constraint.name] = constraint; } return this; }, // Remove a constraint removeConstraint: function (name) { for (var i = 0; i < this.constraints.length; i++) if (name === this.constraints[i].name) { this.constraints.splice(i, 1); break; } delete this.constraintsByName[name]; return this; }, // Update a constraint (Remove + re-add) updateConstraint: function (name, parameters, priority) { return this.removeConstraint(name) .addConstraint(name, parameters, priority); }, // # Internals // Internal only. // Bind constraints from config + options + DOM _bindConstraints: function () { var constraints = [], constraintsByName = {}; // clean all existing DOM constraints to only keep javascript user constraints for (var i = 0; i < this.constraints.length; i++) if (false === this.constraints[i].isDomConstraint) { constraints.push(this.constraints[i]); constraintsByName[this.constraints[i].name] = this.constraints[i]; } this.constraints = constraints; this.constraintsByName = constraintsByName; // then re-add Parsley DOM-API constraints for (var name in this.options) this.addConstraint(name, this.options[name]); // finally, bind special HTML5 constraints return this._bindHtml5Constraints(); }, // Internal only. // Bind specific HTML5 constraints to be HTML5 compliant _bindHtml5Constraints: function () { // html5 required if (this.$element.hasClass('required') || this.$element.attr('required')) this.addConstraint('required', true, undefined, true); // html5 pattern if ('string' === typeof this.$element.attr('pattern')) this.addConstraint('pattern', this.$element.attr('pattern'), undefined, true); // range if ('undefined' !== typeof this.$element.attr('min') && 'undefined' !== typeof this.$element.attr('max')) this.addConstraint('range', [this.$element.attr('min'), this.$element.attr('max')], undefined, true); // HTML5 min else if ('undefined' !== typeof this.$element.attr('min')) this.addConstraint('min', this.$element.attr('min'), undefined, true); // HTML5 max else if ('undefined' !== typeof this.$element.attr('max')) this.addConstraint('max', this.$element.attr('max'), undefined, true); // length if ('undefined' !== typeof this.$element.attr('minlength') && 'undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('length', [this.$element.attr('minlength'), this.$element.attr('maxlength')], undefined, true); // HTML5 minlength else if ('undefined' !== typeof this.$element.attr('minlength')) this.addConstraint('minlength', this.$element.attr('minlength'), undefined, true); // HTML5 maxlength else if ('undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('maxlength', this.$element.attr('maxlength'), undefined, true); // html5 types var type = this.$element.attr('type'); if ('undefined' === typeof type) return this; // Small special case here for HTML5 number: integer validator if step attribute is undefined or an integer value, number otherwise if ('number' === type) { if (('undefined' === typeof this.$element.attr('step')) || (0 === parseFloat(this.$element.attr('step')) % 1)) { return this.addConstraint('type', 'integer', undefined, true); } else { return this.addConstraint('type', 'number', undefined, true); } // Regular other HTML5 supported types } else if (new RegExp(type, 'i').test('email url range')) { return this.addConstraint('type', type, undefined, true); } return this; }, // Internal only. // Field is required if have required constraint without `false` value _isRequired: function () { if ('undefined' === typeof this.constraintsByName.required) return false; return false !== this.constraintsByName.required.requirements; }, // Internal only. // Shortcut to trigger an event _trigger: function (event) { this.$element.trigger('field:' + event + '.parsley', [this]); }, // Internal only. // Sort constraints by priority DESC _getConstraintsSortedPriorities: function () { var priorities = []; // Create array unique of priorities for (var i = 0; i < this.constraints.length; i++) if (-1 === priorities.indexOf(this.constraints[i].priority)) priorities.push(this.constraints[i].priority); // Sort them by priority DESC priorities.sort(function (a, b) { return b - a; }); return priorities; } }; var ParsleyMultiple = function () { this.__class__ = 'ParsleyFieldMultiple'; }; ParsleyMultiple.prototype = { // Add new `$element` sibling for multiple field addElement: function ($element) { this.$elements.push($element); return this; }, // See `ParsleyField.refreshConstraints()` refreshConstraints: function () { var fieldConstraints; this.constraints = []; // Select multiple special treatment if (this.$element.is('select')) { this.actualizeOptions()._bindConstraints(); return this; } // Gather all constraints for each input in the multiple group for (var i = 0; i < this.$elements.length; i++) { // Check if element have not been dynamically removed since last binding if (!$('html').has(this.$elements[i]).length) { this.$elements.splice(i, 1); continue; } fieldConstraints = this.$elements[i].data('ParsleyFieldMultiple').refreshConstraints().constraints; for (var j = 0; j < fieldConstraints.length; j++) this.addConstraint(fieldConstraints[j].name, fieldConstraints[j].requirements, fieldConstraints[j].priority, fieldConstraints[j].isDomConstraint); } return this; }, // See `ParsleyField.getValue()` getValue: function () { // Value could be overriden in DOM if ('undefined' !== typeof this.options.value) return this.options.value; // Radio input case if (this.$element.is('input[type=radio]')) return $('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]:checked').val() || ''; // checkbox input case if (this.$element.is('input[type=checkbox]')) { var values = []; $('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]:checked').each(function () { values.push($(this).val()); }); return values.length ? values : []; } // Select multiple case if (this.$element.is('select') && null === this.$element.val()) return []; // Default case that should never happen return this.$element.val(); }, _init: function (multiple) { this.$elements = [this.$element]; this.options.multiple = multiple; return this; } }; var o = $({}), deprecated = function () { ParsleyUtils.warnOnce("Parsley's pubsub module is deprecated; use the corresponding jQuery event method instead"); }; // Returns an event handler that calls `fn` with the arguments it expects function adapt(fn, context) { // Store to allow unbinding if (!fn.parsleyAdaptedCallback) { fn.parsleyAdaptedCallback = function (evt, parsley) { var args = Array.prototype.slice.call(arguments, 2); args.unshift(parsley); fn.apply(context || o, args); }; } return fn.parsleyAdaptedCallback; } var eventPrefix = 'parsley:'; // Converts 'parsley:form:validate' into 'form:validate.parsley' function eventName(name) { if (name.lastIndexOf(eventPrefix, 0) === 0) return name.substr(eventPrefix.length) + '.parsley'; return name; } // $.listen is deprecated. Use jQuery events instead. $.listen = function (name, callback) { var context; deprecated(); if ('object' === typeof arguments[1] && 'function' === typeof arguments[2]) { context = arguments[1]; callback = arguments[2]; } if ('function' !== typeof arguments[1]) throw new Error('Wrong parameters'); $(document).on(eventName(name), adapt(callback, context)); }; $.listenTo = function (instance, name, fn) { deprecated(); if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance'); if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong parameters'); $(instance.$element).on(eventName(name), adapt(fn)); }; $.unsubscribe = function (name, fn) { deprecated(); if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong arguments'); $(document).off(eventName(name), fn.parsleyAdaptedCallback); }; $.unsubscribeTo = function (instance, name) { deprecated(); if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance'); $(instance.$element).off(eventName(name)); }; $.unsubscribeAll = function (name) { deprecated(); $(document).off(eventName(name)); $('form,input').off(eventName(name)); }; // $.emit is deprecated. Use jQuery events instead. $.emit = function (name, instance) { var $target = $(document); deprecated(); if ((instance instanceof ParsleyField) || (instance instanceof ParsleyForm)) { $target = instance.$element; } $target.trigger(eventName(name), Array.prototype.slice.call(arguments, 1)); }; // ParsleyConfig definition if not already set window.ParsleyConfig = window.ParsleyConfig || {}; window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {}; // Define then the messages window.ParsleyConfig.i18n.en = $.extend(window.ParsleyConfig.i18n.en || {}, { defaultMessage: "This value seems to be invalid.", type: { email: "This value should be a valid email.", url: "This value should be a valid url.", number: "This value should be a valid number.", integer: "This value should be a valid integer.", digits: "This value should be digits.", alphanum: "This value should be alphanumeric." }, notblank: "This value should not be blank.", required: "This value is required.", pattern: "This value seems to be invalid.", min: "This value should be greater than or equal to %s.", max: "This value should be lower than or equal to %s.", range: "This value should be between %s and %s.", minlength: "This value is too short. It should have %s characters or more.", maxlength: "This value is too long. It should have %s characters or fewer.", length: "This value length is invalid. It should be between %s and %s characters long.", mincheck: "You must select at least %s choices.", maxcheck: "You must select %s choices or fewer.", check: "You must select between %s and %s choices.", equalto: "This value should be the same." }); // If file is loaded after Parsley main file, auto-load locale if ('undefined' !== typeof window.ParsleyValidator) window.ParsleyValidator.addCatalog('en', window.ParsleyConfig.i18n.en, true); // Parsley.js 2.1.0-rc3 // http://parsleyjs.org // (c) 2012-2015 Guillaume Potier, Wisembly // Parsley may be freely distributed under the MIT license. // ### Parsley factory var Parsley = function (element, options, parsleyFormInstance) { this.$element = $(element); // If element have already been binded, returns its saved Parsley instance var savedparsleyFormInstance = this.$element.data('Parsley'); if (savedparsleyFormInstance) { // If saved instance have been binded without a ParsleyForm parent and there is one given in this call, add it if ('undefined' !== typeof parsleyFormInstance && !savedparsleyFormInstance.parent) { savedparsleyFormInstance.parent = parsleyFormInstance; savedparsleyFormInstance._resetOptions(savedparsleyFormInstance.options); } return savedparsleyFormInstance; } // Parsley must be instantiated with a DOM element or jQuery $element if (!this.$element.length) throw new Error('You must bind Parsley on an existing element.'); if ('undefined' !== typeof parsleyFormInstance && 'ParsleyForm' !== parsleyFormInstance.__class__) throw new Error('Parent instance must be a ParsleyForm instance'); this.parent = parsleyFormInstance; return this.init(options); }; Parsley.prototype = { init: function (options) { this.__class__ = 'Parsley'; this.__version__ = '2.1.0-rc3'; this.__id__ = ParsleyUtils.generateID(); // Pre-compute options this._resetOptions(options); // A ParsleyForm instance is obviously a `<form>` elem but also every node that is not an input and have `data-parsley-validate` attribute if (this.$element.is('form') || (ParsleyUtils.checkAttr(this.$element, this.options.namespace, 'validate') && !this.$element.is(this.options.inputs))) return this.bind('parsleyForm'); // Every other element is binded as a `ParsleyField` or `ParsleyFieldMultiple` return this.isMultiple() ? this.handleMultiple() : this.bind('parsleyField'); }, isMultiple: function () { return (this.$element.is('input[type=radio], input[type=checkbox]')) || (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')); }, // Multiples fields are a real nightmare :( // Maybe some refacto would be appreciated here... handleMultiple: function () { var that = this, name, multiple, parsleyMultipleInstance; // Handle multiple name if (this.options.multiple) multiple = this.options.multiple; else if ('undefined' !== typeof this.$element.attr('name') && this.$element.attr('name').length) multiple = name = this.$element.attr('name'); else if ('undefined' !== typeof this.$element.attr('id') && this.$element.attr('id').length) multiple = this.$element.attr('id'); // Special select multiple input if (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')) { return this.bind('parsleyFieldMultiple', multiple || this.__id__); // Else for radio / checkboxes, we need a `name` or `data-parsley-multiple` to properly bind it } else if ('undefined' === typeof multiple) { ParsleyUtils.warn('To be binded by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.', this.$element); return this; } // Remove special chars multiple = multiple.replace(/(:|\.|\[|\]|\{|\}|\$)/g, ''); // Add proper `data-parsley-multiple` to siblings if we have a valid multiple name if ('undefined' !== typeof name) { $('input[name="' + name + '"]').each(function () { if ($(this).is('input[type=radio], input[type=checkbox]')) $(this).attr(that.options.namespace + 'multiple', multiple); }); } // Check here if we don't already have a related multiple instance saved if ($('[' + this.options.namespace + 'multiple=' + multiple +']').length) { for (var i = 0; i < $('[' + this.options.namespace + 'multiple=' + multiple +']').length; i++) { if ('undefined' !== typeof $($('[' + this.options.namespace + 'multiple=' + multiple +']').get(i)).data('Parsley')) { parsleyMultipleInstance = $($('[' + this.options.namespace + 'multiple=' + multiple +']').get(i)).data('Parsley'); if (!this.$element.data('ParsleyFieldMultiple')) { parsleyMultipleInstance.addElement(this.$element); this.$element.attr(this.options.namespace + 'id', parsleyMultipleInstance.__id__); } break; } } } // Create a secret ParsleyField instance for every multiple field. It would be stored in `data('ParsleyFieldMultiple')` // And would be useful later to access classic `ParsleyField` stuff while being in a `ParsleyFieldMultiple` instance this.bind('parsleyField', multiple, true); return parsleyMultipleInstance || this.bind('parsleyFieldMultiple', multiple); }, // Return proper `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple` bind: function (type, multiple, doNotStore) { var parsleyInstance; switch (type) { case 'parsleyForm': parsleyInstance = $.extend( new ParsleyForm(this.$element, this.domOptions, this.options), window.ParsleyExtend )._bindFields(); break; case 'parsleyField': parsleyInstance = $.extend( new ParsleyField(this.$element, this.domOptions, this.options, this.parent), window.ParsleyExtend ); break; case 'parsleyFieldMultiple': parsleyInstance = $.extend( new ParsleyField(this.$element, this.domOptions, this.options, this.parent), new ParsleyMultiple(), window.ParsleyExtend )._init(multiple); break; default: throw new Error(type + 'is not a supported Parsley type'); } if ('undefined' !== typeof multiple) ParsleyUtils.setAttr(this.$element, this.options.namespace, 'multiple', multiple); if ('undefined' !== typeof doNotStore) { this.$element.data('ParsleyFieldMultiple', parsleyInstance); return parsleyInstance; } // Store for later access the freshly binded instance in DOM element itself using jQuery `data()` this.$element.data('Parsley', parsleyInstance); // Tell the world we got a new ParsleyForm or ParsleyField instance! parsleyInstance._trigger('init'); return parsleyInstance; } }; // Supplement ParsleyField and Form with ParsleyAbstract // This way, the constructors will have access to those methods $.extend(ParsleyField.prototype, ParsleyAbstract.prototype); $.extend(ParsleyForm.prototype, ParsleyAbstract.prototype); // Inherit actualizeOptions and _resetOptions: $.extend(Parsley.prototype, ParsleyAbstract.prototype); // ### jQuery API // `$('.elem').parsley(options)` or `$('.elem').psly(options)` $.fn.parsley = $.fn.psly = function (options) { if (this.length > 1) { var instances = []; this.each(function () { instances.push($(this).parsley(options)); }); return instances; } // Return undefined if applied to non existing DOM element if (!$(this).length) { ParsleyUtils.warn('You must bind Parsley on an existing element.'); return; } return new Parsley(this, options); }; // ### ParsleyField and ParsleyForm extension // Ensure that defined if not already the case if ('undefined' === typeof window.ParsleyExtend) window.ParsleyExtend = {}; // ### ParsleyConfig // Inherit from ParsleyDefault, and copy over any existing values window.ParsleyConfig = $.extend(ParsleyUtils.objectCreate(ParsleyDefaults), window.ParsleyConfig); // ### ParsleyUI // UI is a class apart that only listen to some events and them modify DOM accordingly // Could be overriden by defining a `window.ParsleyConfig.ParsleyUI` appropriate class (with `listen()` method basically) window.ParsleyUI = 'function' === typeof window.ParsleyConfig.ParsleyUI ? new window.ParsleyConfig.ParsleyUI().listen() : new ParsleyUI().listen(); // ### Globals window.Parsley = window.psly = Parsley; window.ParsleyUtils = ParsleyUtils; window.ParsleyValidator = new ParsleyValidator(window.ParsleyConfig.validators, window.ParsleyConfig.i18n); // ### PARSLEY auto-binding // Prevent it by setting `ParsleyConfig.autoBind` to `false` if (false !== window.ParsleyConfig.autoBind) $(function () { // Works only on `data-parsley-validate`. if ($('[data-parsley-validate]').length) $('[data-parsley-validate]').parsley(); }); }));
mit
soovorov/d8intranet
drupal/core/modules/shortcut/shortcut.api.php
1344
<?php /** * @file * Hooks provided by the Shortcut module. */ /** * @addtogroup hooks * @{ */ /** * Return the name of a default shortcut set for the provided user account. * * This hook allows modules to define default shortcut sets for a particular * user that differ from the site-wide default (for example, a module may want * to define default shortcuts on a per-role basis). * * The default shortcut set is used only when the user does not have any other * shortcut set explicitly assigned to them. * * Note that only one default shortcut set can exist per user, so when multiple * modules implement this hook, the last (i.e., highest weighted) module which * returns a valid shortcut set name will prevail. * * @param $account * The user account whose default shortcut set is being requested. * @return * The name of the shortcut set that this module recommends for that user, if * there is one. */ function hook_shortcut_default_set($account) { // Use a special set of default shortcuts for administrators only. $roles = \Drupal::entityManager()->getStorage('user_role')->loadByProperties(['is_admin' => TRUE]); $user_admin_roles = array_intersect(array_keys($roles), $account->getRoles()); if ($user_admin_roles) { return 'admin-shortcuts'; } } /** * @} End of "addtogroup hooks". */
gpl-2.0
ahb0327/intellij-community
python/testData/copyPaste/Dictionary.dst.py
19
a = 1 <caret> b = 2
apache-2.0
paleozogt/cdnjs
ajax/libs/angular.js/1.2.12/i18n/angular-locale_hr.js
2256
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "nedjelja", "ponedjeljak", "utorak", "srijeda", "\u010detvrtak", "petak", "subota" ], "MONTH": [ "sije\u010dnja", "velja\u010de", "o\u017eujka", "travnja", "svibnja", "lipnja", "srpnja", "kolovoza", "rujna", "listopada", "studenoga", "prosinca" ], "SHORTDAY": [ "ned", "pon", "uto", "sri", "\u010det", "pet", "sub" ], "SHORTMONTH": [ "sij", "velj", "o\u017eu", "tra", "svi", "lip", "srp", "kol", "ruj", "lis", "stu", "pro" ], "fullDate": "EEEE, d. MMMM y.", "longDate": "d. MMMM y.", "medium": "d. M. y. HH:mm:ss", "mediumDate": "d. M. y.", "mediumTime": "HH:mm:ss", "short": "d.M.y. HH:mm", "shortDate": "d.M.y.", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "kn", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "hr", "pluralCat": function (n) { if (n % 10 == 1 && n % 100 != 11) { return PLURAL_CATEGORY.ONE; } if (n == (n | 0) && n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14)) { return PLURAL_CATEGORY.FEW; } if (n % 10 == 0 || n == (n | 0) && n % 10 >= 5 && n % 10 <= 9 || n == (n | 0) && n % 100 >= 11 && n % 100 <= 14) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;} }); }]);
mit
franciscofruiz/hc
lib/vendor/symfony/lib/user/sfBasicSecurityUser.class.php
7481
<?php /* * This file is part of the symfony package. * (c) 2004-2006 Fabien Potencier <[email protected]> * (c) 2004-2006 Sean Kerr <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfBasicSecurityUser will handle any type of data as a credential. * * @package symfony * @subpackage user * @author Fabien Potencier <[email protected]> * @author Sean Kerr <[email protected]> * @version SVN: $Id: sfBasicSecurityUser.class.php 33466 2012-05-30 07:33:03Z fabien $ */ class sfBasicSecurityUser extends sfUser implements sfSecurityUser { const LAST_REQUEST_NAMESPACE = 'symfony/user/sfUser/lastRequest'; const AUTH_NAMESPACE = 'symfony/user/sfUser/authenticated'; const CREDENTIAL_NAMESPACE = 'symfony/user/sfUser/credentials'; protected $lastRequest = null; protected $credentials = null; protected $authenticated = null; protected $timedout = false; /** * Clears all credentials. * */ public function clearCredentials() { $this->credentials = array(); } /** * Returns the current user's credentials. * * @return array */ public function getCredentials() { return $this->credentials; } /** * Removes a credential. * * @param mixed $credential credential */ public function removeCredential($credential) { if ($this->hasCredential($credential)) { foreach ($this->credentials as $key => $value) { if ($credential == $value) { if ($this->options['logging']) { $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Remove credential "%s"', $credential)))); } unset($this->credentials[$key]); $this->storage->regenerate(true); return; } } } } /** * Adds a credential. * * @param mixed $credential */ public function addCredential($credential) { $this->addCredentials(func_get_args()); } /** * Adds several credential at once. * * @param mixed array or list of credentials */ public function addCredentials() { if (func_num_args() == 0) return; // Add all credentials $credentials = (is_array(func_get_arg(0))) ? func_get_arg(0) : func_get_args(); if ($this->options['logging']) { $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Add credential(s) "%s"', implode(', ', $credentials))))); } $added = false; foreach ($credentials as $aCredential) { if (!in_array($aCredential, $this->credentials)) { $added = true; $this->credentials[] = $aCredential; } } if ($added) { $this->storage->regenerate(true); } } /** * Returns true if user has credential. * * @param mixed $credentials * @param bool $useAnd specify the mode, either AND or OR * @return bool * * @author Olivier Verdier <[email protected]> */ public function hasCredential($credentials, $useAnd = true) { if (null === $this->credentials) { return false; } if (!is_array($credentials)) { return in_array($credentials, $this->credentials); } // now we assume that $credentials is an array $test = false; foreach ($credentials as $credential) { // recursively check the credential with a switched AND/OR mode $test = $this->hasCredential($credential, $useAnd ? false : true); if ($useAnd) { $test = $test ? false : true; } if ($test) // either passed one in OR mode or failed one in AND mode { break; // the matter is settled } } if ($useAnd) // in AND mode we succeed if $test is false { $test = $test ? false : true; } return $test; } /** * Returns true if user is authenticated. * * @return boolean */ public function isAuthenticated() { return $this->authenticated; } /** * Sets authentication for user. * * @param bool $authenticated */ public function setAuthenticated($authenticated) { if ($this->options['logging']) { $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('User is %sauthenticated', $authenticated === true ? '' : 'not ')))); } if ((bool) $authenticated !== $this->authenticated) { if ($authenticated === true) { $this->authenticated = true; } else { $this->authenticated = false; $this->clearCredentials(); } $this->dispatcher->notify(new sfEvent($this, 'user.change_authentication', array('authenticated' => $this->authenticated))); $this->storage->regenerate(true); } } public function setTimedOut() { $this->timedout = true; } public function isTimedOut() { return $this->timedout; } /** * Returns the timestamp of the last user request. * * @return int */ public function getLastRequestTime() { return $this->lastRequest; } /** * Available options: * * * timeout: Timeout to automatically log out the user in seconds (1800 by default) * Set to false to disable * * @param sfEventDispatcher $dispatcher An sfEventDispatcher instance. * @param sfStorage $storage An sfStorage instance. * @param array $options An associative array of options. * * @see sfUser */ public function initialize(sfEventDispatcher $dispatcher, sfStorage $storage, $options = array()) { // initialize parent parent::initialize($dispatcher, $storage, $options); if (!array_key_exists('timeout', $this->options)) { $this->options['timeout'] = 1800; } // force the max lifetime for session garbage collector to be greater than timeout if (ini_get('session.gc_maxlifetime') < $this->options['timeout']) { ini_set('session.gc_maxlifetime', $this->options['timeout']); } // read data from storage $this->authenticated = $storage->read(self::AUTH_NAMESPACE); $this->credentials = $storage->read(self::CREDENTIAL_NAMESPACE); $this->lastRequest = $storage->read(self::LAST_REQUEST_NAMESPACE); if (null === $this->authenticated) { $this->authenticated = false; $this->credentials = array(); } else { // Automatic logout logged in user if no request within timeout parameter seconds $timeout = $this->options['timeout']; if (false !== $timeout && null !== $this->lastRequest && time() - $this->lastRequest >= $timeout) { if ($this->options['logging']) { $this->dispatcher->notify(new sfEvent($this, 'application.log', array('Automatic user logout due to timeout'))); } $this->setTimedOut(); $this->setAuthenticated(false); } } $this->lastRequest = time(); } public function shutdown() { // write the last request time to the storage $this->storage->write(self::LAST_REQUEST_NAMESPACE, $this->lastRequest); $this->storage->write(self::AUTH_NAMESPACE, $this->authenticated); $this->storage->write(self::CREDENTIAL_NAMESPACE, $this->credentials); // call the parent shutdown method parent::shutdown(); } }
mit
sufuf3/cdnjs
ajax/libs/URI.js/1.17.0/URITemplate.js
14811
/*! * URI.js - Mutating URLs * URI Template Support - http://tools.ietf.org/html/rfc6570 * * Version: 1.17.0 * * Author: Rodney Rehm * Web: http://medialize.github.io/URI.js/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license * GPL v3 http://opensource.org/licenses/GPL-3.0 * */ (function (root, factory) { 'use strict'; // https://github.com/umdjs/umd/blob/master/returnExports.js if (typeof exports === 'object') { // Node module.exports = factory(require('./URI')); } else if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['./URI'], factory); } else { // Browser globals (root is window) root.URITemplate = factory(root.URI, root); } }(this, function (URI, root) { 'use strict'; // FIXME: v2.0.0 renamce non-camelCase properties to uppercase /*jshint camelcase: false */ // save current URITemplate variable, if any var _URITemplate = root && root.URITemplate; var hasOwn = Object.prototype.hasOwnProperty; function URITemplate(expression) { // serve from cache where possible if (URITemplate._cache[expression]) { return URITemplate._cache[expression]; } // Allow instantiation without the 'new' keyword if (!(this instanceof URITemplate)) { return new URITemplate(expression); } this.expression = expression; URITemplate._cache[expression] = this; return this; } function Data(data) { this.data = data; this.cache = {}; } var p = URITemplate.prototype; // list of operators and their defined options var operators = { // Simple string expansion '' : { prefix: '', separator: ',', named: false, empty_name_separator: false, encode : 'encode' }, // Reserved character strings '+' : { prefix: '', separator: ',', named: false, empty_name_separator: false, encode : 'encodeReserved' }, // Fragment identifiers prefixed by '#' '#' : { prefix: '#', separator: ',', named: false, empty_name_separator: false, encode : 'encodeReserved' }, // Name labels or extensions prefixed by '.' '.' : { prefix: '.', separator: '.', named: false, empty_name_separator: false, encode : 'encode' }, // Path segments prefixed by '/' '/' : { prefix: '/', separator: '/', named: false, empty_name_separator: false, encode : 'encode' }, // Path parameter name or name=value pairs prefixed by ';' ';' : { prefix: ';', separator: ';', named: true, empty_name_separator: false, encode : 'encode' }, // Query component beginning with '?' and consisting // of name=value pairs separated by '&'; an '?' : { prefix: '?', separator: '&', named: true, empty_name_separator: true, encode : 'encode' }, // Continuation of query-style &name=value pairs // within a literal query component. '&' : { prefix: '&', separator: '&', named: true, empty_name_separator: true, encode : 'encode' } // The operator characters equals ("="), comma (","), exclamation ("!"), // at sign ("@"), and pipe ("|") are reserved for future extensions. }; // storage for already parsed templates URITemplate._cache = {}; // pattern to identify expressions [operator, variable-list] in template URITemplate.EXPRESSION_PATTERN = /\{([^a-zA-Z0-9%_]?)([^\}]+)(\}|$)/g; // pattern to identify variables [name, explode, maxlength] in variable-list URITemplate.VARIABLE_PATTERN = /^([^*:]+)((\*)|:(\d+))?$/; // pattern to verify variable name integrity URITemplate.VARIABLE_NAME_PATTERN = /[^a-zA-Z0-9%_]/; // expand parsed expression (expression, not template!) URITemplate.expand = function(expression, data) { // container for defined options for the given operator var options = operators[expression.operator]; // expansion type (include keys or not) var type = options.named ? 'Named' : 'Unnamed'; // list of variables within the expression var variables = expression.variables; // result buffer for evaluating the expression var buffer = []; var d, variable, i; for (i = 0; (variable = variables[i]); i++) { // fetch simplified data source d = data.get(variable.name); if (!d.val.length) { if (d.type) { // empty variables (empty string) // still lead to a separator being appended! buffer.push(''); } // no data, no action continue; } // expand the given variable buffer.push(URITemplate['expand' + type]( d, options, variable.explode, variable.explode && options.separator || ',', variable.maxlength, variable.name )); } if (buffer.length) { return options.prefix + buffer.join(options.separator); } else { // prefix is not prepended for empty expressions return ''; } }; // expand a named variable URITemplate.expandNamed = function(d, options, explode, separator, length, name) { // variable result buffer var result = ''; // peformance crap var encode = options.encode; var empty_name_separator = options.empty_name_separator; // flag noting if values are already encoded var _encode = !d[encode].length; // key for named expansion var _name = d.type === 2 ? '': URI[encode](name); var _value, i, l; // for each found value for (i = 0, l = d.val.length; i < l; i++) { if (length) { // maxlength must be determined before encoding can happen _value = URI[encode](d.val[i][1].substring(0, length)); if (d.type === 2) { // apply maxlength to keys of objects as well _name = URI[encode](d.val[i][0].substring(0, length)); } } else if (_encode) { // encode value _value = URI[encode](d.val[i][1]); if (d.type === 2) { // encode name and cache encoded value _name = URI[encode](d.val[i][0]); d[encode].push([_name, _value]); } else { // cache encoded value d[encode].push([undefined, _value]); } } else { // values are already encoded and can be pulled from cache _value = d[encode][i][1]; if (d.type === 2) { _name = d[encode][i][0]; } } if (result) { // unless we're the first value, prepend the separator result += separator; } if (!explode) { if (!i) { // first element, so prepend variable name result += URI[encode](name) + (empty_name_separator || _value ? '=' : ''); } if (d.type === 2) { // without explode-modifier, keys of objects are returned comma-separated result += _name + ','; } result += _value; } else { // only add the = if it is either default (?&) or there actually is a value (;) result += _name + (empty_name_separator || _value ? '=' : '') + _value; } } return result; }; // expand an unnamed variable URITemplate.expandUnnamed = function(d, options, explode, separator, length) { // variable result buffer var result = ''; // performance crap var encode = options.encode; var empty_name_separator = options.empty_name_separator; // flag noting if values are already encoded var _encode = !d[encode].length; var _name, _value, i, l; // for each found value for (i = 0, l = d.val.length; i < l; i++) { if (length) { // maxlength must be determined before encoding can happen _value = URI[encode](d.val[i][1].substring(0, length)); } else if (_encode) { // encode and cache value _value = URI[encode](d.val[i][1]); d[encode].push([ d.type === 2 ? URI[encode](d.val[i][0]) : undefined, _value ]); } else { // value already encoded, pull from cache _value = d[encode][i][1]; } if (result) { // unless we're the first value, prepend the separator result += separator; } if (d.type === 2) { if (length) { // maxlength also applies to keys of objects _name = URI[encode](d.val[i][0].substring(0, length)); } else { // at this point the name must already be encoded _name = d[encode][i][0]; } result += _name; if (explode) { // explode-modifier separates name and value by "=" result += (empty_name_separator || _value ? '=' : ''); } else { // no explode-modifier separates name and value by "," result += ','; } } result += _value; } return result; }; URITemplate.noConflict = function() { if (root.URITemplate === URITemplate) { root.URITemplate = _URITemplate; } return URITemplate; }; // expand template through given data map p.expand = function(data) { var result = ''; if (!this.parts || !this.parts.length) { // lazilyy parse the template this.parse(); } if (!(data instanceof Data)) { // make given data available through the // optimized data handling thingie data = new Data(data); } for (var i = 0, l = this.parts.length; i < l; i++) { /*jshint laxbreak: true */ result += typeof this.parts[i] === 'string' // literal string ? this.parts[i] // expression : URITemplate.expand(this.parts[i], data); /*jshint laxbreak: false */ } return result; }; // parse template into action tokens p.parse = function() { // performance crap var expression = this.expression; var ePattern = URITemplate.EXPRESSION_PATTERN; var vPattern = URITemplate.VARIABLE_PATTERN; var nPattern = URITemplate.VARIABLE_NAME_PATTERN; // token result buffer var parts = []; // position within source template var pos = 0; var variables, eMatch, vMatch; // RegExp is shared accross all templates, // which requires a manual reset ePattern.lastIndex = 0; // I don't like while(foo = bar()) loops, // to make things simpler I go while(true) and break when required while (true) { eMatch = ePattern.exec(expression); if (eMatch === null) { // push trailing literal parts.push(expression.substring(pos)); break; } else { // push leading literal parts.push(expression.substring(pos, eMatch.index)); pos = eMatch.index + eMatch[0].length; } if (!operators[eMatch[1]]) { throw new Error('Unknown Operator "' + eMatch[1] + '" in "' + eMatch[0] + '"'); } else if (!eMatch[3]) { throw new Error('Unclosed Expression "' + eMatch[0] + '"'); } // parse variable-list variables = eMatch[2].split(','); for (var i = 0, l = variables.length; i < l; i++) { vMatch = variables[i].match(vPattern); if (vMatch === null) { throw new Error('Invalid Variable "' + variables[i] + '" in "' + eMatch[0] + '"'); } else if (vMatch[1].match(nPattern)) { throw new Error('Invalid Variable Name "' + vMatch[1] + '" in "' + eMatch[0] + '"'); } variables[i] = { name: vMatch[1], explode: !!vMatch[3], maxlength: vMatch[4] && parseInt(vMatch[4], 10) }; } if (!variables.length) { throw new Error('Expression Missing Variable(s) "' + eMatch[0] + '"'); } parts.push({ expression: eMatch[0], operator: eMatch[1], variables: variables }); } if (!parts.length) { // template doesn't contain any expressions // so it is a simple literal string // this probably should fire a warning or something? parts.push(expression); } this.parts = parts; return this; }; // simplify data structures Data.prototype.get = function(key) { // performance crap var data = this.data; // cache for processed data-point var d = { // type of data 0: undefined/null, 1: string, 2: object, 3: array type: 0, // original values (except undefined/null) val: [], // cache for encoded values (only for non-maxlength expansion) encode: [], encodeReserved: [] }; var i, l, value; if (this.cache[key] !== undefined) { // we've already processed this key return this.cache[key]; } this.cache[key] = d; if (String(Object.prototype.toString.call(data)) === '[object Function]') { // data itself is a callback (global callback) value = data(key); } else if (String(Object.prototype.toString.call(data[key])) === '[object Function]') { // data is a map of callbacks (local callback) value = data[key](key); } else { // data is a map of data value = data[key]; } // generalize input into [ [name1, value1], [name2, value2], … ] // so expansion has to deal with a single data structure only if (value === undefined || value === null) { // undefined and null values are to be ignored completely return d; } else if (String(Object.prototype.toString.call(value)) === '[object Array]') { for (i = 0, l = value.length; i < l; i++) { if (value[i] !== undefined && value[i] !== null) { // arrays don't have names d.val.push([undefined, String(value[i])]); } } if (d.val.length) { // only treat non-empty arrays as arrays d.type = 3; // array } } else if (String(Object.prototype.toString.call(value)) === '[object Object]') { for (i in value) { if (hasOwn.call(value, i) && value[i] !== undefined && value[i] !== null) { // objects have keys, remember them for named expansion d.val.push([i, String(value[i])]); } } if (d.val.length) { // only treat non-empty objects as objects d.type = 2; // object } } else { d.type = 1; // primitive string (could've been string, number, boolean and objects with a toString()) // arrays don't have names d.val.push([undefined, String(value)]); } return d; }; // hook into URI for fluid access URI.expand = function(expression, data) { var template = new URITemplate(expression); var expansion = template.expand(data); return new URI(expansion); }; return URITemplate; }));
mit
huangzl233/zxing
core/src/main/java/com/google/zxing/client/result/ISBNResultParser.java
1443
/* * Copyright 2008 ZXing 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 com.google.zxing.client.result; import com.google.zxing.BarcodeFormat; import com.google.zxing.Result; /** * Parses strings of digits that represent a ISBN. * * @author [email protected] (Jeff Breidenbach) */ public final class ISBNResultParser extends ResultParser { /** * See <a href="http://www.bisg.org/isbn-13/for.dummies.html">ISBN-13 For Dummies</a> */ @Override public ISBNParsedResult parse(Result result) { BarcodeFormat format = result.getBarcodeFormat(); if (format != BarcodeFormat.EAN_13) { return null; } String rawText = getMassagedText(result); int length = rawText.length(); if (length != 13) { return null; } if (!rawText.startsWith("978") && !rawText.startsWith("979")) { return null; } return new ISBNParsedResult(rawText); } }
apache-2.0
upenn-acg/REMIX
jvm-remix/openjdk/jdk/src/share/classes/sun/awt/geom/ChainEnd.java
3804
/* * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.awt.geom; final class ChainEnd { CurveLink head; CurveLink tail; ChainEnd partner; int etag; public ChainEnd(CurveLink first, ChainEnd partner) { this.head = first; this.tail = first; this.partner = partner; this.etag = first.getEdgeTag(); } public CurveLink getChain() { return head; } public void setOtherEnd(ChainEnd partner) { this.partner = partner; } public ChainEnd getPartner() { return partner; } /* * Returns head of a complete chain to be added to subcurves * or null if the links did not complete such a chain. */ public CurveLink linkTo(ChainEnd that) { if (etag == AreaOp.ETAG_IGNORE || that.etag == AreaOp.ETAG_IGNORE) { throw new InternalError("ChainEnd linked more than once!"); } if (etag == that.etag) { throw new InternalError("Linking chains of the same type!"); } ChainEnd enter, exit; // assert(partner.etag != that.partner.etag); if (etag == AreaOp.ETAG_ENTER) { enter = this; exit = that; } else { enter = that; exit = this; } // Now make sure these ChainEnds are not linked to any others... etag = AreaOp.ETAG_IGNORE; that.etag = AreaOp.ETAG_IGNORE; // Now link everything up... enter.tail.setNext(exit.head); enter.tail = exit.tail; if (partner == that) { // Curve has closed on itself... return enter.head; } // Link this chain into one end of the chain formed by the partners ChainEnd otherenter = exit.partner; ChainEnd otherexit = enter.partner; otherenter.partner = otherexit; otherexit.partner = otherenter; if (enter.head.getYTop() < otherenter.head.getYTop()) { enter.tail.setNext(otherenter.head); otherenter.head = enter.head; } else { otherexit.tail.setNext(enter.head); otherexit.tail = enter.tail; } return null; } public void addLink(CurveLink newlink) { if (etag == AreaOp.ETAG_ENTER) { tail.setNext(newlink); tail = newlink; } else { newlink.setNext(head); head = newlink; } } public double getX() { if (etag == AreaOp.ETAG_ENTER) { return tail.getXBot(); } else { return head.getXBot(); } } }
gpl-2.0
junalmeida/Sick-Beard
lib/hachoir_core/cmd_line.py
1472
from optparse import OptionGroup from lib.hachoir_core.log import log from lib.hachoir_core.i18n import _, getTerminalCharset from lib.hachoir_core.tools import makePrintable import lib.hachoir_core.config as config def getHachoirOptions(parser): """ Create an option group (type optparse.OptionGroup) of Hachoir library options. """ def setLogFilename(*args): log.setFilename(args[2]) common = OptionGroup(parser, _("Hachoir library"), \ "Configure Hachoir library") common.add_option("--verbose", help=_("Verbose mode"), default=False, action="store_true") common.add_option("--log", help=_("Write log in a file"), type="string", action="callback", callback=setLogFilename) common.add_option("--quiet", help=_("Quiet mode (don't display warning)"), default=False, action="store_true") common.add_option("--debug", help=_("Debug mode"), default=False, action="store_true") return common def configureHachoir(option): # Configure Hachoir using "option" (value from optparse) if option.quiet: config.quiet = True if option.verbose: config.verbose = True if option.debug: config.debug = True def unicodeFilename(filename, charset=None): if not charset: charset = getTerminalCharset() try: return unicode(filename, charset) except UnicodeDecodeError: return makePrintable(filename, charset, to_unicode=True)
gpl-3.0
cdnjs/cdnjs
ajax/libs/react-native-web/0.13.10/cjs/exports/BackHandler/index.js
608
"use strict"; exports.__esModule = true; exports.default = void 0; /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ function emptyFunction() {} var BackHandler = { exitApp: emptyFunction, addEventListener: function addEventListener() { return { remove: emptyFunction }; }, removeEventListener: emptyFunction }; var _default = BackHandler; exports.default = _default; module.exports = exports.default;
mit
gcabrini/workshop-angular
api/node_modules/body-parser/node_modules/raw-body/index.js
6532
/*! * raw-body * Copyright(c) 2013-2014 Jonathan Ong * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module dependencies. * @private */ var bytes = require('bytes') var iconv = require('iconv-lite') var unpipe = require('unpipe') /** * Module exports. * @public */ module.exports = getRawBody /** * Get the decoder for a given encoding. * * @param {string} encoding * @private */ function getDecoder(encoding) { if (!encoding) return null try { return iconv.getDecoder(encoding) } catch (e) { throw createError(415, 'specified encoding unsupported', 'encoding.unsupported', { encoding: encoding }) } } /** * Get the raw body of a stream (typically HTTP). * * @param {object} stream * @param {object|string|function} [options] * @param {function} [callback] * @public */ function getRawBody(stream, options, callback) { var done = callback var opts = options || {} if (options === true || typeof options === 'string') { // short cut for encoding opts = { encoding: options } } if (typeof options === 'function') { done = options opts = {} } // validate callback is a function, if provided if (done !== undefined && typeof done !== 'function') { throw new TypeError('argument callback must be a function') } // require the callback without promises if (!done && !global.Promise) { throw new TypeError('argument callback is required') } // get encoding var encoding = opts.encoding !== true ? opts.encoding : 'utf-8' // convert the limit to an integer var limit = bytes.parse(opts.limit) // convert the expected length to an integer var length = opts.length != null && !isNaN(opts.length) ? parseInt(opts.length, 10) : null if (done) { // classic callback style return readStream(stream, encoding, length, limit, done) } return new Promise(function executor(resolve, reject) { readStream(stream, encoding, length, limit, function onRead(err, buf) { if (err) return reject(err) resolve(buf) }) }) } /** * Halt a stream. * * @param {Object} stream * @private */ function halt(stream) { // unpipe everything from the stream unpipe(stream) // pause stream if (typeof stream.pause === 'function') { stream.pause() } } /** * Make a serializable error object. * * To create serializable errors you must re-set message so * that it is enumerable and you must re configure the type * property so that is writable and enumerable. * * @param {number} status * @param {string} message * @param {string} type * @param {object} props * @private */ function createError(status, message, type, props) { var error = new Error() // capture stack trace Error.captureStackTrace(error, createError) // set free-form properties for (var prop in props) { error[prop] = props[prop] } // set message error.message = message // set status error.status = status error.statusCode = status // set type Object.defineProperty(error, 'type', { value: type, enumerable: true, writable: true, configurable: true }) return error } /** * Read the data from the stream. * * @param {object} stream * @param {string} encoding * @param {number} length * @param {number} limit * @param {function} callback * @public */ function readStream(stream, encoding, length, limit, callback) { var complete = false var sync = true // check the length and limit options. // note: we intentionally leave the stream paused, // so users should handle the stream themselves. if (limit !== null && length !== null && length > limit) { return done(createError(413, 'request entity too large', 'entity.too.large', { expected: length, length: length, limit: limit })) } // streams1: assert request encoding is buffer. // streams2+: assert the stream encoding is buffer. // stream._decoder: streams1 // state.encoding: streams2 // state.decoder: streams2, specifically < 0.10.6 var state = stream._readableState if (stream._decoder || (state && (state.encoding || state.decoder))) { // developer error return done(createError(500, 'stream encoding should not be set', 'stream.encoding.set')) } var received = 0 var decoder try { decoder = getDecoder(encoding) } catch (err) { return done(err) } var buffer = decoder ? '' : [] // attach listeners stream.on('aborted', onAborted) stream.on('close', cleanup) stream.on('data', onData) stream.on('end', onEnd) stream.on('error', onEnd) // mark sync section complete sync = false function done() { var args = new Array(arguments.length) // copy arguments for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } // mark complete complete = true if (sync) { process.nextTick(invokeCallback) } else { invokeCallback() } function invokeCallback() { cleanup() if (args[0]) { // halt the stream on error halt(stream) } callback.apply(null, args) } } function onAborted() { if (complete) return done(createError(400, 'request aborted', 'request.aborted', { code: 'ECONNABORTED', expected: length, length: length, received: received })) } function onData(chunk) { if (complete) return received += chunk.length decoder ? buffer += decoder.write(chunk) : buffer.push(chunk) if (limit !== null && received > limit) { done(createError(413, 'request entity too large', 'entity.too.large', { limit: limit, received: received })) } } function onEnd(err) { if (complete) return if (err) return done(err) if (length !== null && received !== length) { done(createError(400, 'request size did not match content length', 'request.size.invalid', { expected: length, length: length, received: received })) } else { var string = decoder ? buffer + (decoder.end() || '') : Buffer.concat(buffer) cleanup() done(null, string) } } function cleanup() { buffer = null stream.removeListener('aborted', onAborted) stream.removeListener('data', onData) stream.removeListener('end', onEnd) stream.removeListener('error', onEnd) stream.removeListener('close', cleanup) } }
mit
bakerfranke/code-dot-org
dashboard/public/apps-package/js/bs_ba/netsim_locale.js
5719
var appLocale = {lc:{"ar":function(n){ if (n === 0) { return 'zero'; } if (n == 1) { return 'one'; } if (n == 2) { return 'two'; } if ((n % 100) >= 3 && (n % 100) <= 10 && n == Math.floor(n)) { return 'few'; } if ((n % 100) >= 11 && (n % 100) <= 99 && n == Math.floor(n)) { return 'many'; } return 'other'; },"en":function(n){return n===1?"one":"other"},"bg":function(n){return n===1?"one":"other"},"bn":function(n){return n===1?"one":"other"},"ca":function(n){return n===1?"one":"other"},"cs":function(n){ if (n == 1) { return 'one'; } if (n == 2 || n == 3 || n == 4) { return 'few'; } return 'other'; },"da":function(n){return n===1?"one":"other"},"de":function(n){return n===1?"one":"other"},"el":function(n){return n===1?"one":"other"},"es":function(n){return n===1?"one":"other"},"et":function(n){return n===1?"one":"other"},"eu":function(n){return n===1?"one":"other"},"fa":function(n){return "other"},"fi":function(n){return n===1?"one":"other"},"fil":function(n){return n===0||n==1?"one":"other"},"fr":function(n){return Math.floor(n)===0||Math.floor(n)==1?"one":"other"},"gl":function(n){return n===1?"one":"other"},"he":function(n){return n===1?"one":"other"},"hi":function(n){return n===0||n==1?"one":"other"},"hr":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"hu":function(n){return "other"},"id":function(n){return "other"},"is":function(n){ return ((n%10) === 1 && (n%100) !== 11) ? 'one' : 'other'; },"it":function(n){return n===1?"one":"other"},"ja":function(n){return "other"},"ko":function(n){return "other"},"lt":function(n){ if ((n % 10) == 1 && ((n % 100) < 11 || (n % 100) > 19)) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 9 && ((n % 100) < 11 || (n % 100) > 19) && n == Math.floor(n)) { return 'few'; } return 'other'; },"lv":function(n){ if (n === 0) { return 'zero'; } if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } return 'other'; },"mk":function(n){return (n%10)==1&&n!=11?"one":"other"},"ms":function(n){return "other"},"mt":function(n){ if (n == 1) { return 'one'; } if (n === 0 || ((n % 100) >= 2 && (n % 100) <= 4 && n == Math.floor(n))) { return 'few'; } if ((n % 100) >= 11 && (n % 100) <= 19 && n == Math.floor(n)) { return 'many'; } return 'other'; },"nl":function(n){return n===1?"one":"other"},"no":function(n){return n===1?"one":"other"},"pl":function(n){ if (n == 1) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || n != 1 && (n % 10) == 1 || ((n % 10) >= 5 && (n % 10) <= 9 || (n % 100) >= 12 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"pt":function(n){return n===1?"one":"other"},"ro":function(n){ if (n == 1) { return 'one'; } if (n === 0 || n != 1 && (n % 100) >= 1 && (n % 100) <= 19 && n == Math.floor(n)) { return 'few'; } return 'other'; },"ru":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"sk":function(n){ if (n == 1) { return 'one'; } if (n == 2 || n == 3 || n == 4) { return 'few'; } return 'other'; },"sl":function(n){ if ((n % 100) == 1) { return 'one'; } if ((n % 100) == 2) { return 'two'; } if ((n % 100) == 3 || (n % 100) == 4) { return 'few'; } return 'other'; },"sq":function(n){return n===1?"one":"other"},"sr":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"sv":function(n){return n===1?"one":"other"},"ta":function(n){return n===1?"one":"other"},"th":function(n){return "other"},"tr":function(n){return n===1?"one":"other"},"uk":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"ur":function(n){return n===1?"one":"other"},"vi":function(n){return "other"},"zh":function(n){return "other"}}, c:function(d,k){if(!d)throw new Error("MessageFormat: Data required for '"+k+"'.")}, n:function(d,k,o){if(isNaN(d[k]))throw new Error("MessageFormat: '"+k+"' isn't a number.");return d[k]-(o||0)}, v:function(d,k){appLocale.c(d,k);return d[k]}, p:function(d,k,o,l,p){appLocale.c(d,k);return d[k] in p?p[d[k]]:(k=appLocale.lc[l](d[k]-o),k in p?p[k]:p.other)}, s:function(d,k,p){appLocale.c(d,k);return d[k] in p?p[d[k]]:p.other}}; (window.blockly = window.blockly || {}).appLocale = { "workspaceHeader":function(d){return "Internet Simulator"}};
apache-2.0
nagyistoce/TypeScript
tests/baselines/reference/parserErrorRecovery_ArgumentList4.js
184
//// [parserErrorRecovery_ArgumentList4.ts] function foo() { bar(a,b return; } //// [parserErrorRecovery_ArgumentList4.js] function foo() { bar(a, b); return; }
apache-2.0
joshloyal/scikit-learn
examples/svm/plot_weighted_samples.py
1943
""" ===================== SVM: Weighted samples ===================== Plot decision function of a weighted dataset, where the size of points is proportional to its weight. The sample weighting rescales the C parameter, which means that the classifier puts more emphasis on getting these points right. The effect might often be subtle. To emphasize the effect here, we particularly weight outliers, making the deformation of the decision boundary very visible. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm def plot_decision_function(classifier, sample_weight, axis, title): # plot the decision function xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500)) Z = classifier.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # plot the line, the points, and the nearest vectors to the plane axis.contourf(xx, yy, Z, alpha=0.75, cmap=plt.cm.bone) axis.scatter(X[:, 0], X[:, 1], c=y, s=100 * sample_weight, alpha=0.9, cmap=plt.cm.bone) axis.axis('off') axis.set_title(title) # we create 20 points np.random.seed(0) X = np.r_[np.random.randn(10, 2) + [1, 1], np.random.randn(10, 2)] y = [1] * 10 + [-1] * 10 sample_weight_last_ten = abs(np.random.randn(len(X))) sample_weight_constant = np.ones(len(X)) # and bigger weights to some outliers sample_weight_last_ten[15:] *= 5 sample_weight_last_ten[9] *= 15 # for reference, first fit without class weights # fit the model clf_weights = svm.SVC() clf_weights.fit(X, y, sample_weight=sample_weight_last_ten) clf_no_weights = svm.SVC() clf_no_weights.fit(X, y) fig, axes = plt.subplots(1, 2, figsize=(14, 6)) plot_decision_function(clf_no_weights, sample_weight_constant, axes[0], "Constant weights") plot_decision_function(clf_weights, sample_weight_last_ten, axes[1], "Modified weights") plt.show()
bsd-3-clause
him2him2/cdnjs
ajax/libs/element-ui/1.3.4/locale/el.js
3754
(function (global, factory) { if (typeof define === "function" && define.amd) { define('element/locale/el', ['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.el = 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: 'εβδομάδα', 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: 'Δεν βρέθηκαν αποτελέσματα', loading: 'Φόρτωση', placeholder: 'Επιλογή' }, pagination: { goto: 'Μετάβαση σε', pagesize: '/σελίδα', total: 'Σύνολο {total}', pageClassifier: '' }, messagebox: { title: 'Μήνυμα', confirm: 'OK', cancel: 'Ακύρωση', error: 'Άκυρη εισαγωγή' }, upload: { delete: 'Διαγραφή', preview: 'Προεπισκόπηση', continue: 'Συνέχεια' }, table: { emptyText: 'Χωρίς Δεδομένα', confirmFilter: 'Επιβεβαίωση', resetFilter: 'Επαναφορά', clearFilter: 'Όλα', sumText: 'Sum' // to be translated }, tree: { emptyText: 'Χωρίς Δεδομένα' }, transfer: { noMatch: 'Δεν βρέθηκαν αποτελέσματα', noData: 'Χωρίς δεδομένα', titles: ['List 1', 'List 2'], // to be translated filterPlaceholder: 'Enter keyword', // to be translated noCheckedFormat: '{total} items', // to be translated hasCheckedFormat: '{checked}/{total} checked' // to be translated } } }; module.exports = exports['default']; });
mit
rn0/babel
packages/babel/test/fixtures/transformation/es6.spec.block-scoping-fail/call-2.js
58
function b() { assert.equals(a, 1); } let a = 1; b();
mit
Jwing28/myBooks
node_modules/mongodb-core/lib/auth/mongocr.js
5595
"use strict"; var f = require('util').format , crypto = require('crypto') , Query = require('../connection/commands').Query , MongoError = require('../error'); var AuthSession = function(db, username, password) { this.db = db; this.username = username; this.password = password; } AuthSession.prototype.equal = function(session) { return session.db == this.db && session.username == this.username && session.password == this.password; } /** * Creates a new MongoCR authentication mechanism * @class * @return {MongoCR} A cursor instance */ var MongoCR = function(bson) { this.bson = bson; this.authStore = []; } // Add to store only if it does not exist var addAuthSession = function(authStore, session) { var found = false; for(var i = 0; i < authStore.length; i++) { if(authStore[i].equal(session)) { found = true; break; } } if(!found) authStore.push(session); } /** * Authenticate * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {string} db Name of the database * @param {string} username Username * @param {string} password Password * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ MongoCR.prototype.auth = function(server, connections, db, username, password, callback) { var self = this; // Total connections var count = connections.length; if(count == 0) return callback(null, null); // Valid connections var numberOfValidConnections = 0; var credentialsValid = false; var errorObject = null; // For each connection we need to authenticate while(connections.length > 0) { // Execute MongoCR var executeMongoCR = function(connection) { // Write the commmand on the connection server(connection, new Query(self.bson, f("%s.$cmd", db), { getnonce:1 }, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { var nonce = null; var key = null; // Adjust the number of connections left // Get nonce if(err == null) { nonce = r.result.nonce; // Use node md5 generator var md5 = crypto.createHash('md5'); // Generate keys used for authentication md5.update(username + ":mongo:" + password, 'utf8'); var hash_password = md5.digest('hex'); // Final key md5 = crypto.createHash('md5'); md5.update(nonce + username + hash_password, 'utf8'); key = md5.digest('hex'); } // Execute command // Write the commmand on the connection server(connection, new Query(self.bson, f("%s.$cmd", db), { authenticate: 1, user: username, nonce: nonce, key:key }, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { count = count - 1; // If we have an error if(err) { errorObject = err; } else if(r.result['$err']) { errorObject = r.result; } else if(r.result['errmsg']) { errorObject = r.result; } else { credentialsValid = true; numberOfValidConnections = numberOfValidConnections + 1; } // We have authenticated all connections if(count == 0 && numberOfValidConnections > 0) { // Store the auth details addAuthSession(self.authStore, new AuthSession(db, username, password)); // Return correct authentication callback(null, true); } else if(count == 0) { if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); callback(errorObject, false); } }); }); } var _execute = function(_connection) { process.nextTick(function() { executeMongoCR(_connection); }); } _execute(connections.shift()); } } /** * Remove authStore credentials * @method * @param {string} db Name of database we are removing authStore details about * @return {object} */ MongoCR.prototype.logout = function(dbName) { this.authStore = this.authStore.filter(function(x) { return x.db != dbName; }); } /** * Re authenticate pool * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ MongoCR.prototype.reauthenticate = function(server, connections, callback) { var authStore = this.authStore.slice(0); var err = null; var count = authStore.length; if(count == 0) return callback(null, null); // Iterate over all the auth details stored for(var i = 0; i < authStore.length; i++) { this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { if(err) err = err; count = count - 1; // Done re-authenticating if(count == 0) { callback(err, null); } }); } } /** * This is a result from a authentication strategy * * @callback authResultCallback * @param {error} error An error object. Set to null if no error present * @param {boolean} result The result of the authentication process */ module.exports = MongoCR;
mit
charliemaiors/golang-wol
vendor/golang.org/x/crypto/acme/autocert/renewal.go
3245
// Copyright 2016 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 autocert import ( "context" "crypto" "sync" "time" ) // renewJitter is the maximum deviation from Manager.RenewBefore. const renewJitter = time.Hour // domainRenewal tracks the state used by the periodic timers // renewing a single domain's cert. type domainRenewal struct { m *Manager domain string key crypto.Signer timerMu sync.Mutex timer *time.Timer } // start starts a cert renewal timer at the time // defined by the certificate expiration time exp. // // If the timer is already started, calling start is a noop. func (dr *domainRenewal) start(exp time.Time) { dr.timerMu.Lock() defer dr.timerMu.Unlock() if dr.timer != nil { return } dr.timer = time.AfterFunc(dr.next(exp), dr.renew) } // stop stops the cert renewal timer. // If the timer is already stopped, calling stop is a noop. func (dr *domainRenewal) stop() { dr.timerMu.Lock() defer dr.timerMu.Unlock() if dr.timer == nil { return } dr.timer.Stop() dr.timer = nil } // renew is called periodically by a timer. // The first renew call is kicked off by dr.start. func (dr *domainRenewal) renew() { dr.timerMu.Lock() defer dr.timerMu.Unlock() if dr.timer == nil { return } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) defer cancel() // TODO: rotate dr.key at some point? next, err := dr.do(ctx) if err != nil { next = renewJitter / 2 next += time.Duration(pseudoRand.int63n(int64(next))) } dr.timer = time.AfterFunc(next, dr.renew) testDidRenewLoop(next, err) } // do is similar to Manager.createCert but it doesn't lock a Manager.state item. // Instead, it requests a new certificate independently and, upon success, // replaces dr.m.state item with a new one and updates cache for the given domain. // // It may return immediately if the expiration date of the currently cached cert // is far enough in the future. // // The returned value is a time interval after which the renewal should occur again. func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) { // a race is likely unavoidable in a distributed environment // but we try nonetheless if tlscert, err := dr.m.cacheGet(ctx, dr.domain); err == nil { next := dr.next(tlscert.Leaf.NotAfter) if next > dr.m.renewBefore()+renewJitter { return next, nil } } der, leaf, err := dr.m.authorizedCert(ctx, dr.key, dr.domain) if err != nil { return 0, err } state := &certState{ key: dr.key, cert: der, leaf: leaf, } tlscert, err := state.tlscert() if err != nil { return 0, err } dr.m.cachePut(ctx, dr.domain, tlscert) dr.m.stateMu.Lock() defer dr.m.stateMu.Unlock() // m.state is guaranteed to be non-nil at this point dr.m.state[dr.domain] = state return dr.next(leaf.NotAfter), nil } func (dr *domainRenewal) next(expiry time.Time) time.Duration { d := expiry.Sub(timeNow()) - dr.m.renewBefore() // add a bit of randomness to renew deadline n := pseudoRand.int63n(int64(renewJitter)) d -= time.Duration(n) if d < 0 { return 0 } return d } var testDidRenewLoop = func(next time.Duration, err error) {}
mit
sreym/cdnjs
ajax/libs/prettydate/0.0.2/i18n/prettydate.pt-BR.min.js
606
!function(s){"function"==typeof define&&define.amd?define(["jquery"],s):s(jQuery)}(function(s){"use strict";s.fn.prettydate.setDefaults({afterSuffix:"depois",beforeSuffix:"atrás",dateFormat:"DD/MM/YYYY hh:mm:ss",messages:{second:"Agora",seconds:"%s segundos %s",minute:"Um minuto %s",minutes:"%s minutos %s",hour:"Uma hora %s",hours:"%s horas %s",day:"Um dia %s",days:"%s dias %s",week:"Uma semana %s",weeks:"%s semanas %s",month:"Um mês %s",months:"%s meses %s",year:"Um ano %s",years:"%s anos %s",yesterday:"Ontem",beforeYesterday:"Anteontem",tomorrow:"Amanhã",afterTomorrow:"Depois de amanhã"}})});
mit
aeste/binutils
gold/testsuite/icf_string_merge_test.cc
1564
// icf_string_merge_test.cc -- a test case for gold // Copyright 2010 Free Software Foundation, Inc. // Written by Sriraman Tallam <[email protected]>. // This file is part of gold. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, // MA 02110-1301, USA. // The goal of this program is to verify is strings are handled correctly // by ICF. ICF inlines strings that can be merged. In some cases, the // addend of the relocation pointing to a string merge section must be // ignored. This program has no pair of identical functions that can be // folded. However, if the addend is not ignored then get2 and get3 will // become identical. const char* const str1 = "aaaaaaaaaastr1"; const char* const str2 = "bbbbaaaaaastr1"; const char* const str3 = "cccccaaaaastr1"; const char* get1() { return str1; } const char* get2() { return str2; } const char* get3() { return str3; } int main() { return 0; }
gpl-2.0
openjdk/jdk7-hotspot
src/share/vm/ci/ciExceptionHandler.cpp
2648
/* * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "ci/ciExceptionHandler.hpp" #include "ci/ciUtilities.hpp" // ciExceptionHandler // // This class represents an exception handler for a method. // ------------------------------------------------------------------ // ciExceptionHandler::catch_klass // // Get the exception klass that this handler catches. ciInstanceKlass* ciExceptionHandler::catch_klass() { VM_ENTRY_MARK; assert(!is_catch_all(), "bad index"); if (_catch_klass == NULL) { bool will_link; assert(_loading_klass->get_instanceKlass()->is_linked(), "must be linked before accessing constant pool"); constantPoolHandle cpool(_loading_klass->get_instanceKlass()->constants()); ciKlass* k = CURRENT_ENV->get_klass_by_index(cpool, _catch_klass_index, will_link, _loading_klass); if (!will_link && k->is_loaded()) { GUARDED_VM_ENTRY( k = CURRENT_ENV->get_unloaded_klass(_loading_klass, k->name()); ) } _catch_klass = k->as_instance_klass(); } return _catch_klass; } // ------------------------------------------------------------------ // ciExceptionHandler::print() void ciExceptionHandler::print() { tty->print("<ciExceptionHandler start=%d limit=%d" " handler_bci=%d ex_klass_index=%d", start(), limit(), handler_bci(), catch_klass_index()); if (_catch_klass != NULL) { tty->print(" ex_klass="); _catch_klass->print(); } tty->print(">"); }
gpl-2.0
arisu1000/kubernetes
pkg/volume/git_repo/git_repo_test.go
4920
/* 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 git_repo import ( "io/ioutil" "os" "path" "reflect" "strings" "testing" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/empty_dir" ) func newTestHost(t *testing.T) volume.VolumeHost { tempDir, err := ioutil.TempDir("/tmp", "git_repo_test.") if err != nil { t.Fatalf("can't make a temp rootdir: %v", err) } return volume.NewFakeVolumeHost(tempDir, nil, empty_dir.ProbeVolumePlugins()) } func TestCanSupport(t *testing.T) { plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t)) plug, err := plugMgr.FindPluginByName("kubernetes.io/git-repo") if err != nil { t.Errorf("Can't find the plugin by name") } if plug.Name() != "kubernetes.io/git-repo" { t.Errorf("Wrong name: %s", plug.Name()) } if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{GitRepo: &api.GitRepoVolumeSource{}}}}) { t.Errorf("Expected true") } } func testSetUp(plug volume.VolumePlugin, builder volume.Builder, t *testing.T) { var fcmd exec.FakeCmd fcmd = exec.FakeCmd{ CombinedOutputScript: []exec.FakeCombinedOutputAction{ // git clone func() ([]byte, error) { os.MkdirAll(path.Join(fcmd.Dirs[0], "kubernetes"), 0750) return []byte{}, nil }, // git checkout func() ([]byte, error) { return []byte{}, nil }, // git reset func() ([]byte, error) { return []byte{}, nil }, }, } fake := exec.FakeExec{ CommandScript: []exec.FakeCommandAction{ func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, }, } g := builder.(*gitRepoVolumeBuilder) g.exec = &fake err := g.SetUp() if err != nil { t.Errorf("unexpected error: %v", err) } expectedCmds := [][]string{ {"git", "clone", g.source}, {"git", "checkout", g.revision}, {"git", "reset", "--hard"}, } if fake.CommandCalls != len(expectedCmds) { t.Errorf("unexpected command calls: expected 3, saw: %d", fake.CommandCalls) } if !reflect.DeepEqual(expectedCmds, fcmd.CombinedOutputLog) { t.Errorf("unexpected commands: %v, expected: %v", fcmd.CombinedOutputLog, expectedCmds) } expectedDirs := []string{g.GetPath(), g.GetPath() + "/kubernetes", g.GetPath() + "/kubernetes"} if len(fcmd.Dirs) != 3 || !reflect.DeepEqual(expectedDirs, fcmd.Dirs) { t.Errorf("unexpected directories: %v, expected: %v", fcmd.Dirs, expectedDirs) } } func TestPlugin(t *testing.T) { plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), newTestHost(t)) plug, err := plugMgr.FindPluginByName("kubernetes.io/git-repo") if err != nil { t.Errorf("Can't find the plugin by name") } spec := &api.Volume{ Name: "vol1", VolumeSource: api.VolumeSource{ GitRepo: &api.GitRepoVolumeSource{ Repository: "https://github.com/GoogleCloudPlatform/kubernetes.git", Revision: "2a30ce65c5ab586b98916d83385c5983edd353a1", }, }, } pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} builder, err := plug.NewBuilder(volume.NewSpecFromVolume(spec), pod, volume.VolumeOptions{RootContext: ""}) if err != nil { t.Errorf("Failed to make a new Builder: %v", err) } if builder == nil { t.Errorf("Got a nil Builder") } path := builder.GetPath() if !strings.HasSuffix(path, "pods/poduid/volumes/kubernetes.io~git-repo/vol1") { t.Errorf("Got unexpected path: %s", path) } testSetUp(plug, builder, t) if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, volume path not created: %s", path) } else { t.Errorf("SetUp() failed: %v", err) } } cleaner, err := plug.NewCleaner("vol1", types.UID("poduid")) if err != nil { t.Errorf("Failed to make a new Cleaner: %v", err) } if cleaner == nil { t.Errorf("Got a nil Cleaner") } if err := cleaner.TearDown(); err != nil { t.Errorf("Expected success, got: %v", err) } if _, err := os.Stat(path); err == nil { t.Errorf("TearDown() failed, volume path still exists: %s", path) } else if !os.IsNotExist(err) { t.Errorf("SetUp() failed: %v", err) } }
apache-2.0
nitro2010/moodle
filter/poodll/3rdparty/aws-v2/Aws/S3/Resources/s3-2006-03-01.php
234902
<?php /** * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ return array ( 'apiVersion' => '2006-03-01', 'endpointPrefix' => 's3', 'serviceFullName' => 'Amazon Simple Storage Service', 'serviceAbbreviation' => 'Amazon S3', 'serviceType' => 'rest-xml', 'timestampFormat' => 'rfc822', 'globalEndpoint' => 's3.amazonaws.com', 'signatureVersion' => 's3', 'namespace' => 'S3', 'regions' => array( 'us-east-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3.amazonaws.com', ), 'us-west-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-us-west-1.amazonaws.com', ), 'us-west-2' => array( 'http' => true, 'https' => true, 'hostname' => 's3-us-west-2.amazonaws.com', ), 'eu-west-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-eu-west-1.amazonaws.com', ), 'eu-central-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-eu-central-1.amazonaws.com', ), 'ap-northeast-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-ap-northeast-1.amazonaws.com', ), 'ap-southeast-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-ap-southeast-1.amazonaws.com', ), 'ap-southeast-2' => array( 'http' => true, 'https' => true, 'hostname' => 's3-ap-southeast-2.amazonaws.com', ), 'sa-east-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-sa-east-1.amazonaws.com', ), 'cn-north-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3.cn-north-1.amazonaws.com.cn', ), 'us-gov-west-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-us-gov-west-1.amazonaws.com', ), ), 'operations' => array( 'AbortMultipartUpload' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'AbortMultipartUploadOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadAbort.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), ), 'errorResponses' => array( array( 'reason' => 'The specified multipart upload does not exist.', 'class' => 'NoSuchUploadException', ), ), ), 'CompleteMultipartUpload' => array( 'httpMethod' => 'POST', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'CompleteMultipartUploadOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadComplete.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CompleteMultipartUpload', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Parts' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CompletedPart', 'type' => 'object', 'sentAs' => 'Part', 'properties' => array( 'ETag' => array( 'type' => 'string', ), 'PartNumber' => array( 'type' => 'numeric', ), ), ), ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'CopyObject' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'CopyObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectCOPY.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CopyObjectRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'CopySource' => array( 'required' => true, 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source', ), 'CopySourceIfMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-match', ), 'CopySourceIfModifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-modified-since', ), 'CopySourceIfNoneMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-none-match', ), 'CopySourceIfUnmodifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-unmodified-since', ), 'Expires' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'MetadataDirective' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-metadata-directive', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'StorageClass' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-storage-class', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'CopySourceSSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-algorithm', ), 'CopySourceSSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key', ), 'CopySourceSSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key-MD5', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), 'errorResponses' => array( array( 'reason' => 'The source object of the COPY operation is not in the active tier and is only stored in Amazon Glacier.', 'class' => 'ObjectNotInActiveTierErrorException', ), ), ), 'CreateBucket' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'CreateBucketOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUT.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CreateBucketConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'LocationConstraint' => array( 'type' => 'string', 'location' => 'xml', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWrite' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), ), 'errorResponses' => array( array( 'reason' => 'The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.', 'class' => 'BucketAlreadyExistsException', ), ), ), 'CreateMultipartUpload' => array( 'httpMethod' => 'POST', 'uri' => '/{Bucket}{/Key*}?uploads', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'CreateMultipartUploadOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadInitiate.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CreateMultipartUploadRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'Expires' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'StorageClass' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-storage-class', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'DeleteBucket' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETE.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketCors' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?cors', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketCorsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEcors.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketLifecycle' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?lifecycle', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketLifecycleOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETElifecycle.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketPolicy' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?policy', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketPolicyOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEpolicy.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketReplication' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?replication', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketReplicationOutput', 'responseType' => 'model', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketTagging' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?tagging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketTaggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEtagging.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketWebsite' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?website', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketWebsiteOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEwebsite.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteObject' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'MFA' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-mfa', ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), ), ), 'DeleteObjects' => array( 'httpMethod' => 'POST', 'uri' => '/{Bucket}?delete', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteObjectsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html', 'data' => array( 'xmlRoot' => array( 'name' => 'Delete', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'contentMd5' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Objects' => array( 'required' => true, 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ObjectIdentifier', 'type' => 'object', 'sentAs' => 'Object', 'properties' => array( 'Key' => array( 'required' => true, 'type' => 'string', 'minLength' => 1, ), 'VersionId' => array( 'type' => 'string', ), ), ), ), 'Quiet' => array( 'type' => 'boolean', 'format' => 'boolean-string', 'location' => 'xml', ), 'MFA' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-mfa', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketAcl' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?acl', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketAclOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETacl.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketCors' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?cors', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketCorsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETcors.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketLifecycle' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?lifecycle', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketLifecycleOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlifecycle.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketLifecycleConfiguration' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?lifecycle', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketLifecycleConfigurationOutput', 'responseType' => 'model', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketLocation' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?location', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketLocationOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'GetBucketLogging' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?logging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketLoggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlogging.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketNotification' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?notification', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'NotificationConfigurationDeprecated', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETnotification.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketNotificationConfiguration' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?notification', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'NotificationConfiguration', 'responseType' => 'model', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketPolicy' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?policy', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketPolicyOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETpolicy.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'GetBucketReplication' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?replication', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketReplicationOutput', 'responseType' => 'model', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketRequestPayment' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?requestPayment', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketRequestPaymentOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTrequestPaymentGET.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketTagging' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?tagging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketTaggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETtagging.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketVersioning' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?versioning', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketVersioningOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETversioningStatus.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketWebsite' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?website', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketWebsiteOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETwebsite.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetObject' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'IfMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'If-Match', ), 'IfModifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'If-Modified-Since', ), 'IfNoneMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'If-None-Match', ), 'IfUnmodifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'If-Unmodified-Since', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Range' => array( 'type' => 'string', 'location' => 'header', ), 'ResponseCacheControl' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-cache-control', ), 'ResponseContentDisposition' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-content-disposition', ), 'ResponseContentEncoding' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-content-encoding', ), 'ResponseContentLanguage' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-content-language', ), 'ResponseContentType' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-content-type', ), 'ResponseExpires' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'query', 'sentAs' => 'response-expires', ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'SaveAs' => array( 'location' => 'response_body', ), ), 'errorResponses' => array( array( 'reason' => 'The specified key does not exist.', 'class' => 'NoSuchKeyException', ), ), ), 'GetObjectAcl' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}{/Key*}?acl', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetObjectAclOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETacl.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), 'errorResponses' => array( array( 'reason' => 'The specified key does not exist.', 'class' => 'NoSuchKeyException', ), ), ), 'GetObjectTorrent' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}{/Key*}?torrent', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetObjectTorrentOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETtorrent.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), ), ), 'HeadBucket' => array( 'httpMethod' => 'HEAD', 'uri' => '/{Bucket}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'HeadBucketOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), 'errorResponses' => array( array( 'reason' => 'The specified bucket does not exist.', 'class' => 'NoSuchBucketException', ), ), ), 'HeadObject' => array( 'httpMethod' => 'HEAD', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'HeadObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'IfMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'If-Match', ), 'IfModifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'If-Modified-Since', ), 'IfNoneMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'If-None-Match', ), 'IfUnmodifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'If-Unmodified-Since', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Range' => array( 'type' => 'string', 'location' => 'header', ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), ), 'errorResponses' => array( array( 'reason' => 'The specified key does not exist.', 'class' => 'NoSuchKeyException', ), ), ), 'ListBuckets' => array( 'httpMethod' => 'GET', 'uri' => '/', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListBucketsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTServiceGET.html', 'parameters' => array( 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'ListMultipartUploads' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?uploads', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListMultipartUploadsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadListMPUpload.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'delimiter', ), 'EncodingType' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'encoding-type', ), 'KeyMarker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'key-marker', ), 'MaxUploads' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'max-uploads', ), 'Prefix' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'prefix', ), 'UploadIdMarker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'upload-id-marker', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'ListObjectVersions' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?versions', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListObjectVersionsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETVersion.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'delimiter', ), 'EncodingType' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'encoding-type', ), 'KeyMarker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'key-marker', ), 'MaxKeys' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'max-keys', ), 'Prefix' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'prefix', ), 'VersionIdMarker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'version-id-marker', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'ListObjects' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListObjectsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'delimiter', ), 'EncodingType' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'encoding-type', ), 'Marker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'marker', ), 'MaxKeys' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'max-keys', ), 'Prefix' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'prefix', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), 'errorResponses' => array( array( 'reason' => 'The specified bucket does not exist.', 'class' => 'NoSuchBucketException', ), ), ), 'ListParts' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListPartsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadListParts.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'MaxParts' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'max-parts', ), 'PartNumberMarker' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'part-number-marker', ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'PutBucketAcl' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?acl', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketAclOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html', 'data' => array( 'xmlRoot' => array( 'name' => 'AccessControlPolicy', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Grants' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'AccessControlList', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'required' => true, 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWrite' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), ), ), 'PutBucketCors' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?cors', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketCorsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTcors.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CORSConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'contentMd5' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CORSRules' => array( 'required' => true, 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CORSRule', 'type' => 'object', 'sentAs' => 'CORSRule', 'properties' => array( 'AllowedHeaders' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedHeader', 'type' => 'string', 'sentAs' => 'AllowedHeader', ), ), 'AllowedMethods' => array( 'required' => true, 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedMethod', 'type' => 'string', 'sentAs' => 'AllowedMethod', ), ), 'AllowedOrigins' => array( 'required' => true, 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedOrigin', 'type' => 'string', 'sentAs' => 'AllowedOrigin', ), ), 'ExposeHeaders' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ExposeHeader', 'type' => 'string', 'sentAs' => 'ExposeHeader', ), ), 'MaxAgeSeconds' => array( 'type' => 'numeric', ), ), ), ), ), ), 'PutBucketLifecycle' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?lifecycle', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketLifecycleOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html', 'data' => array( 'xmlRoot' => array( 'name' => 'LifecycleConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'contentMd5' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Rules' => array( 'required' => true, 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Rule', 'type' => 'object', 'sentAs' => 'Rule', 'properties' => array( 'Expiration' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time', ), 'Days' => array( 'type' => 'numeric', ), ), ), 'ID' => array( 'type' => 'string', ), 'Prefix' => array( 'required' => true, 'type' => 'string', ), 'Status' => array( 'required' => true, 'type' => 'string', ), 'Transition' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time', ), 'Days' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), 'NoncurrentVersionTransition' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), 'NoncurrentVersionExpiration' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), ), ), ), ), ), ), ), 'PutBucketLifecycleConfiguration' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?lifecycle', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketLifecycleConfigurationOutput', 'responseType' => 'model', 'data' => array( 'xmlRoot' => array( 'name' => 'LifecycleConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Rules' => array( 'required' => true, 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'LifecycleRule', 'type' => 'object', 'sentAs' => 'Rule', 'properties' => array( 'Expiration' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', ), 'Days' => array( 'type' => 'numeric', ), ), ), 'ID' => array( 'type' => 'string', ), 'Prefix' => array( 'required' => true, 'type' => 'string', ), 'Status' => array( 'required' => true, 'type' => 'string', ), 'Transitions' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Transition', 'type' => 'object', 'sentAs' => 'Transition', 'properties' => array( 'Date' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', ), 'Days' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), ), 'NoncurrentVersionTransitions' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'NoncurrentVersionTransition', 'type' => 'object', 'sentAs' => 'NoncurrentVersionTransition', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), ), 'NoncurrentVersionExpiration' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), ), ), ), ), ), ), ), 'PutBucketLogging' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?logging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketLoggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlogging.html', 'data' => array( 'xmlRoot' => array( 'name' => 'BucketLoggingStatus', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'xmlAllowEmpty' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'LoggingEnabled' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'TargetBucket' => array( 'type' => 'string', ), 'TargetGrants' => array( 'type' => 'array', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'required' => true, 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'TargetPrefix' => array( 'type' => 'string', ), ), ), ), ), 'PutBucketNotification' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?notification', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketNotificationOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTnotification.html', 'data' => array( 'xmlRoot' => array( 'name' => 'NotificationConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'xmlAllowEmpty' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'TopicConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', ), ), 'Event' => array( 'type' => 'string', ), 'Topic' => array( 'type' => 'string', ), ), ), 'QueueConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Event' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', ), ), 'Queue' => array( 'type' => 'string', ), ), ), 'CloudFunctionConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Event' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', ), ), 'CloudFunction' => array( 'type' => 'string', ), 'InvocationRole' => array( 'type' => 'string', ), ), ), ), ), 'PutBucketNotificationConfiguration' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?notification', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketNotificationConfigurationOutput', 'responseType' => 'model', 'data' => array( 'xmlRoot' => array( 'name' => 'NotificationConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'TopicConfigurations' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'TopicConfiguration', 'type' => 'object', 'sentAs' => 'TopicConfiguration', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'TopicArn' => array( 'required' => true, 'type' => 'string', 'sentAs' => 'Topic', ), 'Events' => array( 'required' => true, 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Filter' => array( 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'object', 'sentAs' => 'S3Key', 'properties' => array( 'FilterRules' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'FilterRule', 'type' => 'object', 'sentAs' => 'FilterRule', 'properties' => array( 'Name' => array( 'type' => 'string', ), 'Value' => array( 'type' => 'string', ), ), ), ), ), ), ), ), ), ), ), 'QueueConfigurations' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'QueueConfiguration', 'type' => 'object', 'sentAs' => 'QueueConfiguration', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'QueueArn' => array( 'required' => true, 'type' => 'string', 'sentAs' => 'Queue', ), 'Events' => array( 'required' => true, 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Filter' => array( 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'object', 'sentAs' => 'S3Key', 'properties' => array( 'FilterRules' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'FilterRule', 'type' => 'object', 'sentAs' => 'FilterRule', 'properties' => array( 'Name' => array( 'type' => 'string', ), 'Value' => array( 'type' => 'string', ), ), ), ), ), ), ), ), ), ), ), 'LambdaFunctionConfigurations' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'LambdaFunctionConfiguration', 'type' => 'object', 'sentAs' => 'CloudFunctionConfiguration', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'LambdaFunctionArn' => array( 'required' => true, 'type' => 'string', 'sentAs' => 'CloudFunction', ), 'Events' => array( 'required' => true, 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Filter' => array( 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'object', 'sentAs' => 'S3Key', 'properties' => array( 'FilterRules' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'FilterRule', 'type' => 'object', 'sentAs' => 'FilterRule', 'properties' => array( 'Name' => array( 'type' => 'string', ), 'Value' => array( 'type' => 'string', ), ), ), ), ), ), ), ), ), ), ), ), ), 'PutBucketPolicy' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?policy', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketPolicyOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTpolicy.html', 'data' => array( 'xmlRoot' => array( 'name' => 'PutBucketPolicyRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Policy' => array( 'required' => true, 'type' => array( 'string', 'object', ), 'location' => 'body', ), ), ), 'PutBucketReplication' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?replication', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketReplicationOutput', 'responseType' => 'model', 'data' => array( 'xmlRoot' => array( 'name' => 'ReplicationConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Role' => array( 'required' => true, 'type' => 'string', 'location' => 'xml', ), 'Rules' => array( 'required' => true, 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ReplicationRule', 'type' => 'object', 'sentAs' => 'Rule', 'properties' => array( 'ID' => array( 'type' => 'string', ), 'Prefix' => array( 'required' => true, 'type' => 'string', ), 'Status' => array( 'required' => true, 'type' => 'string', ), 'Destination' => array( 'required' => true, 'type' => 'object', 'properties' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', ), 'StorageClass' => array( 'type' => 'string', ), ), ), ), ), ), ), ), 'PutBucketRequestPayment' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?requestPayment', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketRequestPaymentOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTrequestPaymentPUT.html', 'data' => array( 'xmlRoot' => array( 'name' => 'RequestPaymentConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Payer' => array( 'required' => true, 'type' => 'string', 'location' => 'xml', ), ), ), 'PutBucketTagging' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?tagging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketTaggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTtagging.html', 'data' => array( 'xmlRoot' => array( 'name' => 'Tagging', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'contentMd5' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'TagSet' => array( 'required' => true, 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'Tag', 'type' => 'object', 'properties' => array( 'Key' => array( 'required' => true, 'type' => 'string', 'minLength' => 1, ), 'Value' => array( 'required' => true, 'type' => 'string', ), ), ), ), ), ), 'PutBucketVersioning' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?versioning', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketVersioningOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTVersioningStatus.html', 'data' => array( 'xmlRoot' => array( 'name' => 'VersioningConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'MFA' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-mfa', ), 'MFADelete' => array( 'type' => 'string', 'location' => 'xml', 'sentAs' => 'MfaDelete', ), 'Status' => array( 'type' => 'string', 'location' => 'xml', ), ), ), 'PutBucketWebsite' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?website', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketWebsiteOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTwebsite.html', 'data' => array( 'xmlRoot' => array( 'name' => 'WebsiteConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'xmlAllowEmpty' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'ErrorDocument' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Key' => array( 'required' => true, 'type' => 'string', 'minLength' => 1, ), ), ), 'IndexDocument' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Suffix' => array( 'required' => true, 'type' => 'string', ), ), ), 'RedirectAllRequestsTo' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'HostName' => array( 'required' => true, 'type' => 'string', ), 'Protocol' => array( 'type' => 'string', ), ), ), 'RoutingRules' => array( 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'RoutingRule', 'type' => 'object', 'properties' => array( 'Condition' => array( 'type' => 'object', 'properties' => array( 'HttpErrorCodeReturnedEquals' => array( 'type' => 'string', ), 'KeyPrefixEquals' => array( 'type' => 'string', ), ), ), 'Redirect' => array( 'required' => true, 'type' => 'object', 'properties' => array( 'HostName' => array( 'type' => 'string', ), 'HttpRedirectCode' => array( 'type' => 'string', ), 'Protocol' => array( 'type' => 'string', ), 'ReplaceKeyPrefixWith' => array( 'type' => 'string', ), 'ReplaceKeyWith' => array( 'type' => 'string', ), ), ), ), ), ), ), ), 'PutObject' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html', 'data' => array( 'xmlRoot' => array( 'name' => 'PutObjectRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Body' => array( 'type' => array( 'string', 'object', ), 'location' => 'body', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentLength' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'Content-Length', ), 'ContentMD5' => array( 'type' => array( 'string', 'boolean', ), 'location' => 'header', 'sentAs' => 'Content-MD5', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'Expires' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'StorageClass' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-storage-class', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), ), ), 'PutObjectAcl' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}?acl', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutObjectAclOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUTacl.html', 'data' => array( 'xmlRoot' => array( 'name' => 'AccessControlPolicy', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Grants' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'AccessControlList', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'required' => true, 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWrite' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), ), 'errorResponses' => array( array( 'reason' => 'The specified key does not exist.', 'class' => 'NoSuchKeyException', ), ), ), 'RestoreObject' => array( 'httpMethod' => 'POST', 'uri' => '/{Bucket}{/Key*}?restore', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'RestoreObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectRestore.html', 'data' => array( 'xmlRoot' => array( 'name' => 'RestoreRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), 'Days' => array( 'required' => true, 'type' => 'numeric', 'location' => 'xml', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), ), 'errorResponses' => array( array( 'reason' => 'This operation is not allowed against this storage tier', 'class' => 'ObjectAlreadyInActiveTierErrorException', ), ), ), 'UploadPart' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'UploadPartOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html', 'data' => array( 'xmlRoot' => array( 'name' => 'UploadPartRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Body' => array( 'type' => array( 'string', 'object', ), 'location' => 'body', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'ContentLength' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'Content-Length', ), 'ContentMD5' => array( 'type' => array( 'string', 'boolean', ), 'location' => 'header', 'sentAs' => 'Content-MD5', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'PartNumber' => array( 'required' => true, 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'partNumber', ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), ), ), 'UploadPartCopy' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'UploadPartCopyOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPartCopy.html', 'data' => array( 'xmlRoot' => array( 'name' => 'UploadPartCopyRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CopySource' => array( 'required' => true, 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source', ), 'CopySourceIfMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-match', ), 'CopySourceIfModifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-modified-since', ), 'CopySourceIfNoneMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-none-match', ), 'CopySourceIfUnmodifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-unmodified-since', ), 'CopySourceRange' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-range', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'minLength' => 1, 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'PartNumber' => array( 'required' => true, 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'partNumber', ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'CopySourceSSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-algorithm', ), 'CopySourceSSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key', ), 'CopySourceSSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key-MD5', ), 'RequestPayer' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-payer', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), ), 'models' => array( 'AbortMultipartUploadOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'CompleteMultipartUploadOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Location' => array( 'type' => 'string', 'location' => 'xml', ), 'Bucket' => array( 'type' => 'string', 'location' => 'xml', ), 'Key' => array( 'type' => 'string', 'location' => 'xml', ), 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'ETag' => array( 'type' => 'string', 'location' => 'xml', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'CopyObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'ETag' => array( 'type' => 'string', 'location' => 'xml', ), 'LastModified' => array( 'type' => 'string', 'location' => 'xml', ), 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'CopySourceVersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-version-id', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'CreateBucketOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Location' => array( 'type' => 'string', 'location' => 'header', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'CreateMultipartUploadOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Bucket' => array( 'type' => 'string', 'location' => 'xml', 'sentAs' => 'Bucket', ), 'Key' => array( 'type' => 'string', 'location' => 'xml', ), 'UploadId' => array( 'type' => 'string', 'location' => 'xml', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketCorsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketLifecycleOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketPolicyOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketReplicationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketTaggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketWebsiteOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'DeleteMarker' => array( 'type' => 'boolean', 'location' => 'header', 'sentAs' => 'x-amz-delete-marker', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteObjectsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Deleted' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'DeletedObject', 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'string', ), 'VersionId' => array( 'type' => 'string', ), 'DeleteMarker' => array( 'type' => 'boolean', ), 'DeleteMarkerVersionId' => array( 'type' => 'string', ), ), ), ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'Errors' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Error', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Error', 'type' => 'object', 'sentAs' => 'Error', 'properties' => array( 'Key' => array( 'type' => 'string', ), 'VersionId' => array( 'type' => 'string', ), 'Code' => array( 'type' => 'string', ), 'Message' => array( 'type' => 'string', ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketAclOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Grants' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'AccessControlList', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'sentAs' => 'Grant', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketCorsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'CORSRules' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'CORSRule', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CORSRule', 'type' => 'object', 'sentAs' => 'CORSRule', 'properties' => array( 'AllowedHeaders' => array( 'type' => 'array', 'sentAs' => 'AllowedHeader', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedHeader', 'type' => 'string', 'sentAs' => 'AllowedHeader', ), ), 'AllowedMethods' => array( 'type' => 'array', 'sentAs' => 'AllowedMethod', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedMethod', 'type' => 'string', 'sentAs' => 'AllowedMethod', ), ), 'AllowedOrigins' => array( 'type' => 'array', 'sentAs' => 'AllowedOrigin', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedOrigin', 'type' => 'string', 'sentAs' => 'AllowedOrigin', ), ), 'ExposeHeaders' => array( 'type' => 'array', 'sentAs' => 'ExposeHeader', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ExposeHeader', 'type' => 'string', 'sentAs' => 'ExposeHeader', ), ), 'MaxAgeSeconds' => array( 'type' => 'numeric', ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketLifecycleOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Rules' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Rule', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Rule', 'type' => 'object', 'sentAs' => 'Rule', 'properties' => array( 'Expiration' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => 'string', ), 'Days' => array( 'type' => 'numeric', ), ), ), 'ID' => array( 'type' => 'string', ), 'Prefix' => array( 'type' => 'string', ), 'Status' => array( 'type' => 'string', ), 'Transition' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => 'string', ), 'Days' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), 'NoncurrentVersionTransition' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), 'NoncurrentVersionExpiration' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), ), ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketLifecycleConfigurationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Rules' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Rule', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'LifecycleRule', 'type' => 'object', 'sentAs' => 'Rule', 'properties' => array( 'Expiration' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => 'string', ), 'Days' => array( 'type' => 'numeric', ), ), ), 'ID' => array( 'type' => 'string', ), 'Prefix' => array( 'type' => 'string', ), 'Status' => array( 'type' => 'string', ), 'Transitions' => array( 'type' => 'array', 'sentAs' => 'Transition', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Transition', 'type' => 'object', 'sentAs' => 'Transition', 'properties' => array( 'Date' => array( 'type' => 'string', ), 'Days' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), ), 'NoncurrentVersionTransitions' => array( 'type' => 'array', 'sentAs' => 'NoncurrentVersionTransition', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'NoncurrentVersionTransition', 'type' => 'object', 'sentAs' => 'NoncurrentVersionTransition', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), ), 'NoncurrentVersionExpiration' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), ), ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketLocationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Location' => array( 'type' => 'string', 'location' => 'body', 'filters' => array( 'strval', 'strip_tags', 'trim', ), ), ), ), 'GetBucketLoggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'LoggingEnabled' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'TargetBucket' => array( 'type' => 'string', ), 'TargetGrants' => array( 'type' => 'array', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'sentAs' => 'Grant', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'TargetPrefix' => array( 'type' => 'string', ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'NotificationConfigurationDeprecated' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'TopicConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'sentAs' => 'Event', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Event' => array( 'type' => 'string', ), 'Topic' => array( 'type' => 'string', ), ), ), 'QueueConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Event' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'sentAs' => 'Event', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Queue' => array( 'type' => 'string', ), ), ), 'CloudFunctionConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Event' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'sentAs' => 'Event', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'CloudFunction' => array( 'type' => 'string', ), 'InvocationRole' => array( 'type' => 'string', ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'NotificationConfiguration' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'TopicConfigurations' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'TopicConfiguration', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'TopicConfiguration', 'type' => 'object', 'sentAs' => 'TopicConfiguration', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'TopicArn' => array( 'type' => 'string', 'sentAs' => 'Topic', ), 'Events' => array( 'type' => 'array', 'sentAs' => 'Event', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Filter' => array( 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'object', 'sentAs' => 'S3Key', 'properties' => array( 'FilterRules' => array( 'type' => 'array', 'sentAs' => 'FilterRule', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'FilterRule', 'type' => 'object', 'sentAs' => 'FilterRule', 'properties' => array( 'Name' => array( 'type' => 'string', ), 'Value' => array( 'type' => 'string', ), ), ), ), ), ), ), ), ), ), ), 'QueueConfigurations' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'QueueConfiguration', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'QueueConfiguration', 'type' => 'object', 'sentAs' => 'QueueConfiguration', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'QueueArn' => array( 'type' => 'string', 'sentAs' => 'Queue', ), 'Events' => array( 'type' => 'array', 'sentAs' => 'Event', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Filter' => array( 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'object', 'sentAs' => 'S3Key', 'properties' => array( 'FilterRules' => array( 'type' => 'array', 'sentAs' => 'FilterRule', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'FilterRule', 'type' => 'object', 'sentAs' => 'FilterRule', 'properties' => array( 'Name' => array( 'type' => 'string', ), 'Value' => array( 'type' => 'string', ), ), ), ), ), ), ), ), ), ), ), 'LambdaFunctionConfigurations' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'CloudFunctionConfiguration', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'LambdaFunctionConfiguration', 'type' => 'object', 'sentAs' => 'CloudFunctionConfiguration', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'LambdaFunctionArn' => array( 'type' => 'string', 'sentAs' => 'CloudFunction', ), 'Events' => array( 'type' => 'array', 'sentAs' => 'Event', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Filter' => array( 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'object', 'sentAs' => 'S3Key', 'properties' => array( 'FilterRules' => array( 'type' => 'array', 'sentAs' => 'FilterRule', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'FilterRule', 'type' => 'object', 'sentAs' => 'FilterRule', 'properties' => array( 'Name' => array( 'type' => 'string', ), 'Value' => array( 'type' => 'string', ), ), ), ), ), ), ), ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketPolicyOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Policy' => array( 'type' => 'string', 'instanceOf' => 'Guzzle\\Http\\EntityBody', 'location' => 'body', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketReplicationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Role' => array( 'type' => 'string', 'location' => 'xml', ), 'Rules' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Rule', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ReplicationRule', 'type' => 'object', 'sentAs' => 'Rule', 'properties' => array( 'ID' => array( 'type' => 'string', ), 'Prefix' => array( 'type' => 'string', ), 'Status' => array( 'type' => 'string', ), 'Destination' => array( 'type' => 'object', 'properties' => array( 'Bucket' => array( 'type' => 'string', ), 'StorageClass' => array( 'type' => 'string', ), ), ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketRequestPaymentOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Payer' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketTaggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'TagSet' => array( 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'Tag', 'type' => 'object', 'sentAs' => 'Tag', 'properties' => array( 'Key' => array( 'type' => 'string', ), 'Value' => array( 'type' => 'string', ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketVersioningOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Status' => array( 'type' => 'string', 'location' => 'xml', ), 'MFADelete' => array( 'type' => 'string', 'location' => 'xml', 'sentAs' => 'MfaDelete', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketWebsiteOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RedirectAllRequestsTo' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'HostName' => array( 'type' => 'string', ), 'Protocol' => array( 'type' => 'string', ), ), ), 'IndexDocument' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Suffix' => array( 'type' => 'string', ), ), ), 'ErrorDocument' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Key' => array( 'type' => 'string', ), ), ), 'RoutingRules' => array( 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'RoutingRule', 'type' => 'object', 'sentAs' => 'RoutingRule', 'properties' => array( 'Condition' => array( 'type' => 'object', 'properties' => array( 'HttpErrorCodeReturnedEquals' => array( 'type' => 'string', ), 'KeyPrefixEquals' => array( 'type' => 'string', ), ), ), 'Redirect' => array( 'type' => 'object', 'properties' => array( 'HostName' => array( 'type' => 'string', ), 'HttpRedirectCode' => array( 'type' => 'string', ), 'Protocol' => array( 'type' => 'string', ), 'ReplaceKeyPrefixWith' => array( 'type' => 'string', ), 'ReplaceKeyWith' => array( 'type' => 'string', ), ), ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Body' => array( 'type' => 'string', 'instanceOf' => 'Guzzle\\Http\\EntityBody', 'location' => 'body', ), 'DeleteMarker' => array( 'type' => 'boolean', 'location' => 'header', 'sentAs' => 'x-amz-delete-marker', ), 'AcceptRanges' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'accept-ranges', ), 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'Restore' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-restore', ), 'LastModified' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Last-Modified', ), 'ContentLength' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'Content-Length', ), 'ETag' => array( 'type' => 'string', 'location' => 'header', ), 'MissingMeta' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'x-amz-missing-meta', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentRange' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Range', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'Expires' => array( 'type' => 'string', 'location' => 'header', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'StorageClass' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-storage-class', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'ReplicationStatus' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-replication-status', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetObjectAclOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Grants' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'AccessControlList', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'sentAs' => 'Grant', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetObjectTorrentOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Body' => array( 'type' => 'string', 'instanceOf' => 'Guzzle\\Http\\EntityBody', 'location' => 'body', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'HeadBucketOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'HeadObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'DeleteMarker' => array( 'type' => 'boolean', 'location' => 'header', 'sentAs' => 'x-amz-delete-marker', ), 'AcceptRanges' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'accept-ranges', ), 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'Restore' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-restore', ), 'LastModified' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Last-Modified', ), 'ContentLength' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'Content-Length', ), 'ETag' => array( 'type' => 'string', 'location' => 'header', ), 'MissingMeta' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'x-amz-missing-meta', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'Expires' => array( 'type' => 'string', 'location' => 'header', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'StorageClass' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-storage-class', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'ReplicationStatus' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-replication-status', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListBucketsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Buckets' => array( 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'Bucket', 'type' => 'object', 'sentAs' => 'Bucket', 'properties' => array( 'Name' => array( 'type' => 'string', ), 'CreationDate' => array( 'type' => 'string', ), ), ), ), 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListMultipartUploadsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Bucket' => array( 'type' => 'string', 'location' => 'xml', ), 'KeyMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'UploadIdMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'NextKeyMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'Prefix' => array( 'type' => 'string', 'location' => 'xml', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'xml', ), 'NextUploadIdMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'MaxUploads' => array( 'type' => 'numeric', 'location' => 'xml', ), 'IsTruncated' => array( 'type' => 'boolean', 'location' => 'xml', ), 'Uploads' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Upload', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'MultipartUpload', 'type' => 'object', 'sentAs' => 'Upload', 'properties' => array( 'UploadId' => array( 'type' => 'string', ), 'Key' => array( 'type' => 'string', ), 'Initiated' => array( 'type' => 'string', ), 'StorageClass' => array( 'type' => 'string', ), 'Owner' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Initiator' => array( 'type' => 'object', 'properties' => array( 'ID' => array( 'type' => 'string', ), 'DisplayName' => array( 'type' => 'string', ), ), ), ), ), ), 'CommonPrefixes' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CommonPrefix', 'type' => 'object', 'properties' => array( 'Prefix' => array( 'type' => 'string', ), ), ), ), 'EncodingType' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListObjectVersionsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'IsTruncated' => array( 'type' => 'boolean', 'location' => 'xml', ), 'KeyMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'VersionIdMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'NextKeyMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'NextVersionIdMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'Versions' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Version', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ObjectVersion', 'type' => 'object', 'sentAs' => 'Version', 'properties' => array( 'ETag' => array( 'type' => 'string', ), 'Size' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), 'Key' => array( 'type' => 'string', ), 'VersionId' => array( 'type' => 'string', ), 'IsLatest' => array( 'type' => 'boolean', ), 'LastModified' => array( 'type' => 'string', ), 'Owner' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), ), ), ), 'DeleteMarkers' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'DeleteMarker', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'DeleteMarkerEntry', 'type' => 'object', 'sentAs' => 'DeleteMarker', 'properties' => array( 'Owner' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Key' => array( 'type' => 'string', ), 'VersionId' => array( 'type' => 'string', ), 'IsLatest' => array( 'type' => 'boolean', ), 'LastModified' => array( 'type' => 'string', ), ), ), ), 'Name' => array( 'type' => 'string', 'location' => 'xml', ), 'Prefix' => array( 'type' => 'string', 'location' => 'xml', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'xml', ), 'MaxKeys' => array( 'type' => 'numeric', 'location' => 'xml', ), 'CommonPrefixes' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CommonPrefix', 'type' => 'object', 'properties' => array( 'Prefix' => array( 'type' => 'string', ), ), ), ), 'EncodingType' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListObjectsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'IsTruncated' => array( 'type' => 'boolean', 'location' => 'xml', ), 'Marker' => array( 'type' => 'string', 'location' => 'xml', ), 'NextMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'Contents' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Object', 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'string', ), 'LastModified' => array( 'type' => 'string', ), 'ETag' => array( 'type' => 'string', ), 'Size' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), 'Owner' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), ), ), ), 'Name' => array( 'type' => 'string', 'location' => 'xml', ), 'Prefix' => array( 'type' => 'string', 'location' => 'xml', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'xml', ), 'MaxKeys' => array( 'type' => 'numeric', 'location' => 'xml', ), 'CommonPrefixes' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CommonPrefix', 'type' => 'object', 'properties' => array( 'Prefix' => array( 'type' => 'string', ), ), ), ), 'EncodingType' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListPartsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Bucket' => array( 'type' => 'string', 'location' => 'xml', ), 'Key' => array( 'type' => 'string', 'location' => 'xml', ), 'UploadId' => array( 'type' => 'string', 'location' => 'xml', ), 'PartNumberMarker' => array( 'type' => 'numeric', 'location' => 'xml', ), 'NextPartNumberMarker' => array( 'type' => 'numeric', 'location' => 'xml', ), 'MaxParts' => array( 'type' => 'numeric', 'location' => 'xml', ), 'IsTruncated' => array( 'type' => 'boolean', 'location' => 'xml', ), 'Parts' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Part', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Part', 'type' => 'object', 'sentAs' => 'Part', 'properties' => array( 'PartNumber' => array( 'type' => 'numeric', ), 'LastModified' => array( 'type' => 'string', ), 'ETag' => array( 'type' => 'string', ), 'Size' => array( 'type' => 'numeric', ), ), ), ), 'Initiator' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'ID' => array( 'type' => 'string', ), 'DisplayName' => array( 'type' => 'string', ), ), ), 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'StorageClass' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketAclOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketCorsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketLifecycleOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketLifecycleConfigurationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketLoggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketNotificationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketNotificationConfigurationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketPolicyOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketReplicationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketRequestPaymentOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketTaggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketVersioningOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketWebsiteOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'ETag' => array( 'type' => 'string', 'location' => 'header', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), 'ObjectURL' => array( ), ), ), 'PutObjectAclOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'RestoreObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'UploadPartOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'ETag' => array( 'type' => 'string', 'location' => 'header', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'UploadPartCopyOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'CopySourceVersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-version-id', ), 'ETag' => array( 'type' => 'string', 'location' => 'xml', ), 'LastModified' => array( 'type' => 'string', 'location' => 'xml', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestCharged' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-request-charged', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), ), 'iterators' => array( 'ListBuckets' => array( 'result_key' => 'Buckets', ), 'ListMultipartUploads' => array( 'limit_key' => 'MaxUploads', 'more_results' => 'IsTruncated', 'output_token' => array( 'NextKeyMarker', 'NextUploadIdMarker', ), 'input_token' => array( 'KeyMarker', 'UploadIdMarker', ), 'result_key' => array( 'Uploads', 'CommonPrefixes', ), ), 'ListObjectVersions' => array( 'more_results' => 'IsTruncated', 'limit_key' => 'MaxKeys', 'output_token' => array( 'NextKeyMarker', 'NextVersionIdMarker', ), 'input_token' => array( 'KeyMarker', 'VersionIdMarker', ), 'result_key' => array( 'Versions', 'DeleteMarkers', 'CommonPrefixes', ), ), 'ListObjects' => array( 'more_results' => 'IsTruncated', 'limit_key' => 'MaxKeys', 'output_token' => 'NextMarker', 'input_token' => 'Marker', 'result_key' => array( 'Contents', 'CommonPrefixes', ), ), 'ListParts' => array( 'more_results' => 'IsTruncated', 'limit_key' => 'MaxParts', 'output_token' => 'NextPartNumberMarker', 'input_token' => 'PartNumberMarker', 'result_key' => 'Parts', ), ), 'waiters' => array( '__default__' => array( 'interval' => 5, 'max_attempts' => 20, ), 'BucketExists' => array( 'operation' => 'HeadBucket', 'success.type' => 'output', 'ignore_errors' => array( 'NoSuchBucket', ), ), 'BucketNotExists' => array( 'operation' => 'HeadBucket', 'success.type' => 'error', 'success.value' => 'NoSuchBucket', ), 'ObjectExists' => array( 'operation' => 'HeadObject', 'success.type' => 'output', 'ignore_errors' => array( 'NoSuchKey', ), ), 'ObjectNotExists' => array( 'operation' => 'HeadObject', 'success.type' => 'error', 'success.value' => 'NoSuchKey' ), ), );
gpl-3.0
gndpig/hadoop
src/core/org/apache/hadoop/record/compiler/JMap.java
9152
/** * 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.record.compiler; import java.util.Map; /** */ public class JMap extends JCompType { static private int level = 0; static private String getLevel() { return Integer.toString(level); } static private void incrLevel() { level++; } static private void decrLevel() { level--; } static private String getId(String id) { return id+getLevel(); } private JType keyType; private JType valueType; class JavaMap extends JavaCompType { JType.JavaType key; JType.JavaType value; JavaMap(JType.JavaType key, JType.JavaType value) { super("java.util.TreeMap<"+key.getWrapperType()+","+value.getWrapperType()+">", "Map", "java.util.TreeMap<"+key.getWrapperType()+","+value.getWrapperType()+">", "TypeID.RIOType.MAP"); this.key = key; this.value = value; } String getTypeIDObjectString() { return "new org.apache.hadoop.record.meta.MapTypeID(" + key.getTypeIDObjectString() + ", " + value.getTypeIDObjectString() + ")"; } void genSetRTIFilter(CodeBuffer cb, Map<String, Integer> nestedStructMap) { key.genSetRTIFilter(cb, nestedStructMap); value.genSetRTIFilter(cb, nestedStructMap); } void genCompareTo(CodeBuffer cb, String fname, String other) { String setType = "java.util.Set<"+key.getWrapperType()+"> "; String iterType = "java.util.Iterator<"+key.getWrapperType()+"> "; cb.append("{\n"); cb.append(setType+getId(Consts.RIO_PREFIX + "set1")+" = "+ fname+".keySet();\n"); cb.append(setType+getId(Consts.RIO_PREFIX + "set2")+" = "+ other+".keySet();\n"); cb.append(iterType+getId(Consts.RIO_PREFIX + "miter1")+" = "+ getId(Consts.RIO_PREFIX + "set1")+".iterator();\n"); cb.append(iterType+getId(Consts.RIO_PREFIX + "miter2")+" = "+ getId(Consts.RIO_PREFIX + "set2")+".iterator();\n"); cb.append("for(; "+getId(Consts.RIO_PREFIX + "miter1")+".hasNext() && "+ getId(Consts.RIO_PREFIX + "miter2")+".hasNext();) {\n"); cb.append(key.getType()+" "+getId(Consts.RIO_PREFIX + "k1")+ " = "+getId(Consts.RIO_PREFIX + "miter1")+".next();\n"); cb.append(key.getType()+" "+getId(Consts.RIO_PREFIX + "k2")+ " = "+getId(Consts.RIO_PREFIX + "miter2")+".next();\n"); key.genCompareTo(cb, getId(Consts.RIO_PREFIX + "k1"), getId(Consts.RIO_PREFIX + "k2")); cb.append("if (" + Consts.RIO_PREFIX + "ret != 0) { return " + Consts.RIO_PREFIX + "ret; }\n"); cb.append("}\n"); cb.append(Consts.RIO_PREFIX + "ret = ("+getId(Consts.RIO_PREFIX + "set1")+ ".size() - "+getId(Consts.RIO_PREFIX + "set2")+".size());\n"); cb.append("}\n"); } void genReadMethod(CodeBuffer cb, String fname, String tag, boolean decl) { if (decl) { cb.append(getType()+" "+fname+";\n"); } cb.append("{\n"); incrLevel(); cb.append("org.apache.hadoop.record.Index " + getId(Consts.RIO_PREFIX + "midx")+" = " + Consts.RECORD_INPUT + ".startMap(\""+tag+"\");\n"); cb.append(fname+"=new "+getType()+"();\n"); cb.append("for (; !"+getId(Consts.RIO_PREFIX + "midx")+".done(); "+ getId(Consts.RIO_PREFIX + "midx")+".incr()) {\n"); key.genReadMethod(cb, getId(Consts.RIO_PREFIX + "k"), getId(Consts.RIO_PREFIX + "k"), true); value.genReadMethod(cb, getId(Consts.RIO_PREFIX + "v"), getId(Consts.RIO_PREFIX + "v"), true); cb.append(fname+".put("+getId(Consts.RIO_PREFIX + "k")+","+ getId(Consts.RIO_PREFIX + "v")+");\n"); cb.append("}\n"); cb.append(Consts.RECORD_INPUT + ".endMap(\""+tag+"\");\n"); decrLevel(); cb.append("}\n"); } void genWriteMethod(CodeBuffer cb, String fname, String tag) { String setType = "java.util.Set<java.util.Map.Entry<"+ key.getWrapperType()+","+value.getWrapperType()+">> "; String entryType = "java.util.Map.Entry<"+ key.getWrapperType()+","+value.getWrapperType()+"> "; String iterType = "java.util.Iterator<java.util.Map.Entry<"+ key.getWrapperType()+","+value.getWrapperType()+">> "; cb.append("{\n"); incrLevel(); cb.append(Consts.RECORD_OUTPUT + ".startMap("+fname+",\""+tag+"\");\n"); cb.append(setType+getId(Consts.RIO_PREFIX + "es")+" = "+ fname+".entrySet();\n"); cb.append("for("+iterType+getId(Consts.RIO_PREFIX + "midx")+" = "+ getId(Consts.RIO_PREFIX + "es")+".iterator(); "+ getId(Consts.RIO_PREFIX + "midx")+".hasNext();) {\n"); cb.append(entryType+getId(Consts.RIO_PREFIX + "me")+" = "+ getId(Consts.RIO_PREFIX + "midx")+".next();\n"); cb.append(key.getType()+" "+getId(Consts.RIO_PREFIX + "k")+" = "+ getId(Consts.RIO_PREFIX + "me")+".getKey();\n"); cb.append(value.getType()+" "+getId(Consts.RIO_PREFIX + "v")+" = "+ getId(Consts.RIO_PREFIX + "me")+".getValue();\n"); key.genWriteMethod(cb, getId(Consts.RIO_PREFIX + "k"), getId(Consts.RIO_PREFIX + "k")); value.genWriteMethod(cb, getId(Consts.RIO_PREFIX + "v"), getId(Consts.RIO_PREFIX + "v")); cb.append("}\n"); cb.append(Consts.RECORD_OUTPUT + ".endMap("+fname+",\""+tag+"\");\n"); cb.append("}\n"); decrLevel(); } void genSlurpBytes(CodeBuffer cb, String b, String s, String l) { cb.append("{\n"); incrLevel(); cb.append("int "+getId("mi")+ " = org.apache.hadoop.record.Utils.readVInt("+b+", "+s+");\n"); cb.append("int "+getId("mz")+ " = org.apache.hadoop.record.Utils.getVIntSize("+getId("mi")+");\n"); cb.append(s+"+="+getId("mz")+"; "+l+"-="+getId("mz")+";\n"); cb.append("for (int "+getId("midx")+" = 0; "+getId("midx")+ " < "+getId("mi")+"; "+getId("midx")+"++) {"); key.genSlurpBytes(cb, b, s, l); value.genSlurpBytes(cb, b, s, l); cb.append("}\n"); decrLevel(); cb.append("}\n"); } void genCompareBytes(CodeBuffer cb) { cb.append("{\n"); incrLevel(); cb.append("int "+getId("mi1")+ " = org.apache.hadoop.record.Utils.readVInt(b1, s1);\n"); cb.append("int "+getId("mi2")+ " = org.apache.hadoop.record.Utils.readVInt(b2, s2);\n"); cb.append("int "+getId("mz1")+ " = org.apache.hadoop.record.Utils.getVIntSize("+getId("mi1")+");\n"); cb.append("int "+getId("mz2")+ " = org.apache.hadoop.record.Utils.getVIntSize("+getId("mi2")+");\n"); cb.append("s1+="+getId("mz1")+"; s2+="+getId("mz2")+ "; l1-="+getId("mz1")+"; l2-="+getId("mz2")+";\n"); cb.append("for (int "+getId("midx")+" = 0; "+getId("midx")+ " < "+getId("mi1")+" && "+getId("midx")+" < "+getId("mi2")+ "; "+getId("midx")+"++) {"); key.genCompareBytes(cb); value.genSlurpBytes(cb, "b1", "s1", "l1"); value.genSlurpBytes(cb, "b2", "s2", "l2"); cb.append("}\n"); cb.append("if ("+getId("mi1")+" != "+getId("mi2")+ ") { return ("+getId("mi1")+"<"+getId("mi2")+")?-1:0; }\n"); decrLevel(); cb.append("}\n"); } } class CppMap extends CppCompType { JType.CppType key; JType.CppType value; CppMap(JType.CppType key, JType.CppType value) { super("::std::map< "+key.getType()+", "+ value.getType()+" >"); this.key = key; this.value = value; } String getTypeIDObjectString() { return "new ::hadoop::MapTypeID(" + key.getTypeIDObjectString() + ", " + value.getTypeIDObjectString() + ")"; } void genSetRTIFilter(CodeBuffer cb) { key.genSetRTIFilter(cb); value.genSetRTIFilter(cb); } } /** Creates a new instance of JMap */ public JMap(JType t1, JType t2) { setJavaType(new JavaMap(t1.getJavaType(), t2.getJavaType())); setCppType(new CppMap(t1.getCppType(), t2.getCppType())); setCType(new CType()); keyType = t1; valueType = t2; } String getSignature() { return "{" + keyType.getSignature() + valueType.getSignature() +"}"; } }
apache-2.0
ashwinr/DefinitelyTyped
types/oracledb/oracledb-tests.ts
1273
import * as OracleDB from 'oracledb'; OracleDB.getConnection( { user: "hr", password: "welcome", connectString: "localhost/XE" }, function(err, connection) { if (err) { console.error(err.message); return; } connection.execute( "SELECT department_id, department_name " + "FROM departments " + "WHERE manager_id < :id", [110], // bind value for :id function(err, result) { if (err) { console.error(err.message); } else { console.log(result.rows); console.log(result.rows[0].department_id); // when outFormet is OBJECT console.log(result.metaData[0].name); } connection.release(); } ); } ); OracleDB.getConnection( { user: "hr", password: "welcome", connectString: "localhost/XE" } ).then((connection: OracleDB.IConnection) => { return connection.execute( "SELECT department_id, department_name " + "FROM departments " + "WHERE manager_id < :id", [110] ).then(result => { console.log(result.rows); console.log(result.rows[0].department_id); // when outFormet is OBJECT console.log(result.metaData[0].name); }).catch((err: any) => { console.error(err.message); }).then(() => { return connection.release(); }); }).catch((err: any) => { console.error(err.message); });
mit
lichuqiang/kubernetes
pkg/apis/node/zz_generated.deepcopy.go
4082
// +build !ignore_autogenerated /* Copyright 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package node import ( runtime "k8s.io/apimachinery/pkg/runtime" core "k8s.io/kubernetes/pkg/apis/core" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Overhead) DeepCopyInto(out *Overhead) { *out = *in if in.PodFixed != nil { in, out := &in.PodFixed, &out.PodFixed *out = make(core.ResourceList, len(*in)) for key, val := range *in { (*out)[key] = val.DeepCopy() } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Overhead. func (in *Overhead) DeepCopy() *Overhead { if in == nil { return nil } out := new(Overhead) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuntimeClass) DeepCopyInto(out *RuntimeClass) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) if in.Overhead != nil { in, out := &in.Overhead, &out.Overhead *out = new(Overhead) (*in).DeepCopyInto(*out) } if in.Scheduling != nil { in, out := &in.Scheduling, &out.Scheduling *out = new(Scheduling) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuntimeClass. func (in *RuntimeClass) DeepCopy() *RuntimeClass { if in == nil { return nil } out := new(RuntimeClass) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *RuntimeClass) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RuntimeClassList) DeepCopyInto(out *RuntimeClassList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]RuntimeClass, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuntimeClassList. func (in *RuntimeClassList) DeepCopy() *RuntimeClassList { if in == nil { return nil } out := new(RuntimeClassList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *RuntimeClassList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Scheduling) DeepCopyInto(out *Scheduling) { *out = *in if in.NodeSelector != nil { in, out := &in.NodeSelector, &out.NodeSelector *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Tolerations != nil { in, out := &in.Tolerations, &out.Tolerations *out = make([]core.Toleration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Scheduling. func (in *Scheduling) DeepCopy() *Scheduling { if in == nil { return nil } out := new(Scheduling) in.DeepCopyInto(out) return out }
apache-2.0
savaki/gocd
tools/jruby-1.7.11/lib/ruby/shared/rubygems/commands/sources_command.rb
5310
require 'rubygems/command' require 'rubygems/remote_fetcher' require 'rubygems/spec_fetcher' require 'rubygems/local_remote_options' class Gem::Commands::SourcesCommand < Gem::Command include Gem::LocalRemoteOptions def initialize require 'fileutils' super 'sources', 'Manage the sources and cache file RubyGems uses to search for gems' add_option '-a', '--add SOURCE_URI', 'Add source' do |value, options| options[:add] = value end add_option '-l', '--list', 'List sources' do |value, options| options[:list] = value end add_option '-r', '--remove SOURCE_URI', 'Remove source' do |value, options| options[:remove] = value end add_option '-c', '--clear-all', 'Remove all sources (clear the cache)' do |value, options| options[:clear_all] = value end add_option '-u', '--update', 'Update source cache' do |value, options| options[:update] = value end add_proxy_option end def add_source source_uri # :nodoc: check_rubygems_https source_uri source = Gem::Source.new source_uri begin if Gem.sources.include? source_uri then say "source #{source_uri} already present in the cache" else source.load_specs :released Gem.sources << source Gem.configuration.write say "#{source_uri} added to sources" end rescue URI::Error, ArgumentError say "#{source_uri} is not a URI" terminate_interaction 1 rescue Gem::RemoteFetcher::FetchError => e say "Error fetching #{source_uri}:\n\t#{e.message}" terminate_interaction 1 end end def check_rubygems_https source_uri # :nodoc: uri = URI source_uri if uri.scheme and uri.scheme.downcase == 'http' and uri.host.downcase == 'rubygems.org' then question = <<-QUESTION.chomp https://rubygems.org is recommended for security over #{uri} Do you want to add this insecure source? QUESTION terminate_interaction 1 unless ask_yes_no question end end def clear_all # :nodoc: path = Gem.spec_cache_dir FileUtils.rm_rf path unless File.exist? path then say "*** Removed specs cache ***" else unless File.writable? path then say "*** Unable to remove source cache (write protected) ***" else say "*** Unable to remove source cache ***" end terminate_interaction 1 end end def defaults_str # :nodoc: '--list' end def description # :nodoc: <<-EOF RubyGems fetches gems from the sources you have configured (stored in your ~/.gemrc). The default source is https://rubygems.org, but you may have older sources configured. This guide will help you update your sources or configure yourself to use your own gem server. Without any arguments the sources lists your currently configured sources: $ gem sources *** CURRENT SOURCES *** https://rubygems.org This may list multiple sources or non-rubygems sources. You probably configured them before or have an old `~/.gemrc`. If you have sources you do not recognize you should remove them. RubyGems has been configured to serve gems via the following URLs through its history: * http://gems.rubyforge.org (RubyGems 1.3.6 and earlier) * http://rubygems.org (RubyGems 1.3.7 through 1.8.25) * https://rubygems.org (RubyGems 2.0.1 and newer) Since all of these sources point to the same set of gems you only need one of them in your list. https://rubygems.org is recommended as it brings the protections of an SSL connection to gem downloads. To add a source use the --add argument: $ gem sources --add https://rubygems.org https://rubygems.org added to sources RubyGems will check to see if gems can be installed from the source given before it is added. To remove a source use the --remove argument: $ gem sources --remove http://rubygems.org http://rubygems.org removed from sources EOF end def list # :nodoc: say "*** CURRENT SOURCES ***" say Gem.sources.each do |src| say src end end def list? # :nodoc: !(options[:add] || options[:clear_all] || options[:remove] || options[:update]) end def execute clear_all if options[:clear_all] source_uri = options[:add] add_source source_uri if source_uri source_uri = options[:remove] remove_source source_uri if source_uri update if options[:update] list if list? end def remove_source source_uri # :nodoc: unless Gem.sources.include? source_uri then say "source #{source_uri} not present in cache" else Gem.sources.delete source_uri Gem.configuration.write say "#{source_uri} removed from sources" end end def update # :nodoc: Gem.sources.each_source do |src| src.load_specs :released src.load_specs :latest end say "source cache successfully updated" end def remove_cache_file desc, path # :nodoc: FileUtils.rm_rf path if not File.exist?(path) then say "*** Removed #{desc} source cache ***" elsif not File.writable?(path) then say "*** Unable to remove #{desc} source cache (write protected) ***" else say "*** Unable to remove #{desc} source cache ***" end end end
apache-2.0
jkorab/camel
camel-core/src/test/java/org/apache/camel/component/bean/BeanInvocationSerializeTest.java
2697
/** * 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.bean; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Method; import org.apache.camel.TestSupport; /** * @version */ public class BeanInvocationSerializeTest extends TestSupport { public void testSerialize() throws Exception { Method method = getClass().getMethod("cheese", String.class, String.class); BeanInvocation invocation = new BeanInvocation(method, new Object[] {"a", "b"}); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(invocation); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object object = in.readObject(); BeanInvocation actual = assertIsInstanceOf(BeanInvocation.class, object); log.debug("Received " + actual); } public void testSerializeCtr() throws Exception { Method method = getClass().getMethod("cheese", String.class, String.class); BeanInvocation invocation = new BeanInvocation(); invocation.setArgs(new Object[] {"a", "b"}); invocation.setMethod(method); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(invocation); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object object = in.readObject(); BeanInvocation actual = assertIsInstanceOf(BeanInvocation.class, object); log.debug("Received " + actual); } public void cheese(String a, String b) { log.debug("Called with a: " + a + " b: " + b); } }
apache-2.0
Graulf/LIA_wordpress
wp-content/plugins/jetpack/modules/shortcodes/googleplus.php
1188
<?php /** * Google+ embeds */ define( 'JETPACK_GOOGLEPLUS_EMBED_REGEX', '#^https?://plus\.(sandbox\.)?google\.com/(u/\d+/)?([^/]+)/posts/([^/]+)$#' ); // Example URL: https://plus.google.com/114986219448604314131/posts/LgHkesWCmJo // Alternate example: https://plus.google.com/u/0/100004581596612508203/posts/2UKwN67MBQs (note the /u/0/) wp_embed_register_handler( 'googleplus', JETPACK_GOOGLEPLUS_EMBED_REGEX, 'jetpack_googleplus_embed_handler' ); function jetpack_googleplus_embed_handler( $matches, $attr, $url ) { static $did_script; if ( ! $did_script ) { $did_script = true; add_action( 'wp_footer', 'jetpack_googleplus_add_script' ); } return sprintf( '<div class="g-post" data-href="%s"></div>', esc_url( $url ) ); } function jetpack_googleplus_add_script() { ?> <script src="https://apis.google.com/js/plusone.js"></script> <?php } add_shortcode( 'googleplus', 'jetpack_googleplus_shortcode_handler' ); function jetpack_googleplus_shortcode_handler( $atts ) { global $wp_embed; if ( empty( $atts['url'] ) ) return; if ( ! preg_match( JETPACK_GOOGLEPLUS_EMBED_REGEX, $atts['url'] ) ) return; return $wp_embed->shortcode( $atts, $atts['url'] ); }
gpl-2.0
gitromand/phantomjs
src/qt/qtwebkit/Source/WebCore/inspector/front-end/ElementsTreeOutline.js
81536
/* * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2008 Matt Lilek <[email protected]> * Copyright (C) 2009 Joseph Pecoraro * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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. */ /** * @constructor * @extends {TreeOutline} * @param {boolean=} omitRootDOMNode * @param {boolean=} selectEnabled * @param {boolean=} showInElementsPanelEnabled * @param {function(WebInspector.ContextMenu, WebInspector.DOMNode)=} contextMenuCallback * @param {function(DOMAgent.NodeId, string, boolean)=} setPseudoClassCallback */ WebInspector.ElementsTreeOutline = function(omitRootDOMNode, selectEnabled, showInElementsPanelEnabled, contextMenuCallback, setPseudoClassCallback) { this.element = document.createElement("ol"); this.element.addEventListener("mousedown", this._onmousedown.bind(this), false); this.element.addEventListener("mousemove", this._onmousemove.bind(this), false); this.element.addEventListener("mouseout", this._onmouseout.bind(this), false); this.element.addEventListener("dragstart", this._ondragstart.bind(this), false); this.element.addEventListener("dragover", this._ondragover.bind(this), false); this.element.addEventListener("dragleave", this._ondragleave.bind(this), false); this.element.addEventListener("drop", this._ondrop.bind(this), false); this.element.addEventListener("dragend", this._ondragend.bind(this), false); this.element.addEventListener("keydown", this._onkeydown.bind(this), false); TreeOutline.call(this, this.element); this._includeRootDOMNode = !omitRootDOMNode; this._selectEnabled = selectEnabled; this._showInElementsPanelEnabled = showInElementsPanelEnabled; this._rootDOMNode = null; this._selectDOMNode = null; this._eventSupport = new WebInspector.Object(); this._visible = false; this.element.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), true); this._contextMenuCallback = contextMenuCallback; this._setPseudoClassCallback = setPseudoClassCallback; this._createNodeDecorators(); } WebInspector.ElementsTreeOutline.Events = { SelectedNodeChanged: "SelectedNodeChanged" } WebInspector.ElementsTreeOutline.MappedCharToEntity = { "\u00a0": "nbsp", "\u2002": "ensp", "\u2003": "emsp", "\u2009": "thinsp", "\u200b": "#8203", // ZWSP "\u200c": "zwnj", "\u200d": "zwj", "\u200e": "lrm", "\u200f": "rlm", "\u202a": "#8234", // LRE "\u202b": "#8235", // RLE "\u202c": "#8236", // PDF "\u202d": "#8237", // LRO "\u202e": "#8238" // RLO } WebInspector.ElementsTreeOutline.prototype = { _createNodeDecorators: function() { this._nodeDecorators = []; this._nodeDecorators.push(new WebInspector.ElementsTreeOutline.PseudoStateDecorator()); }, wireToDomAgent: function() { this._elementsTreeUpdater = new WebInspector.ElementsTreeUpdater(this); }, setVisible: function(visible) { this._visible = visible; if (!this._visible) return; this._updateModifiedNodes(); if (this._selectedDOMNode) this._revealAndSelectNode(this._selectedDOMNode, false); }, addEventListener: function(eventType, listener, thisObject) { this._eventSupport.addEventListener(eventType, listener, thisObject); }, removeEventListener: function(eventType, listener, thisObject) { this._eventSupport.removeEventListener(eventType, listener, thisObject); }, get rootDOMNode() { return this._rootDOMNode; }, set rootDOMNode(x) { if (this._rootDOMNode === x) return; this._rootDOMNode = x; this._isXMLMimeType = x && x.isXMLNode(); this.update(); }, get isXMLMimeType() { return this._isXMLMimeType; }, selectedDOMNode: function() { return this._selectedDOMNode; }, selectDOMNode: function(node, focus) { if (this._selectedDOMNode === node) { this._revealAndSelectNode(node, !focus); return; } this._selectedDOMNode = node; this._revealAndSelectNode(node, !focus); // The _revealAndSelectNode() method might find a different element if there is inlined text, // and the select() call would change the selectedDOMNode and reenter this setter. So to // avoid calling _selectedNodeChanged() twice, first check if _selectedDOMNode is the same // node as the one passed in. if (this._selectedDOMNode === node) this._selectedNodeChanged(); }, /** * @return {boolean} */ editing: function() { var node = this.selectedDOMNode(); if (!node) return false; var treeElement = this.findTreeElement(node); if (!treeElement) return false; return treeElement._editing || false; }, update: function() { var selectedNode = this.selectedTreeElement ? this.selectedTreeElement.representedObject : null; this.removeChildren(); if (!this.rootDOMNode) return; var treeElement; if (this._includeRootDOMNode) { treeElement = new WebInspector.ElementsTreeElement(this.rootDOMNode); treeElement.selectable = this._selectEnabled; this.appendChild(treeElement); } else { // FIXME: this could use findTreeElement to reuse a tree element if it already exists var node = this.rootDOMNode.firstChild; while (node) { treeElement = new WebInspector.ElementsTreeElement(node); treeElement.selectable = this._selectEnabled; this.appendChild(treeElement); node = node.nextSibling; } } if (selectedNode) this._revealAndSelectNode(selectedNode, true); }, updateSelection: function() { if (!this.selectedTreeElement) return; var element = this.treeOutline.selectedTreeElement; element.updateSelection(); }, /** * @param {WebInspector.DOMNode} node */ updateOpenCloseTags: function(node) { var treeElement = this.findTreeElement(node); if (treeElement) treeElement.updateTitle(); var children = treeElement.children; var closingTagElement = children[children.length - 1]; if (closingTagElement && closingTagElement._elementCloseTag) closingTagElement.updateTitle(); }, _selectedNodeChanged: function() { this._eventSupport.dispatchEventToListeners(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, this._selectedDOMNode); }, /** * @param {WebInspector.DOMNode} node */ findTreeElement: function(node) { function isAncestorNode(ancestor, node) { return ancestor.isAncestor(node); } function parentNode(node) { return node.parentNode; } var treeElement = TreeOutline.prototype.findTreeElement.call(this, node, isAncestorNode, parentNode); if (!treeElement && node.nodeType() === Node.TEXT_NODE) { // The text node might have been inlined if it was short, so try to find the parent element. treeElement = TreeOutline.prototype.findTreeElement.call(this, node.parentNode, isAncestorNode, parentNode); } return treeElement; }, /** * @param {WebInspector.DOMNode} node */ createTreeElementFor: function(node) { var treeElement = this.findTreeElement(node); if (treeElement) return treeElement; if (!node.parentNode) return null; treeElement = this.createTreeElementFor(node.parentNode); if (treeElement && treeElement.showChild(node.index)) return treeElement.children[node.index]; return null; }, set suppressRevealAndSelect(x) { if (this._suppressRevealAndSelect === x) return; this._suppressRevealAndSelect = x; }, _revealAndSelectNode: function(node, omitFocus) { if (!node || this._suppressRevealAndSelect) return; var treeElement = this.createTreeElementFor(node); if (!treeElement) return; treeElement.revealAndSelect(omitFocus); }, _treeElementFromEvent: function(event) { var scrollContainer = this.element.parentElement; // We choose this X coordinate based on the knowledge that our list // items extend at least to the right edge of the outer <ol> container. // In the no-word-wrap mode the outer <ol> may be wider than the tree container // (and partially hidden), in which case we are left to use only its right boundary. var x = scrollContainer.totalOffsetLeft() + scrollContainer.offsetWidth - 36; var y = event.pageY; // Our list items have 1-pixel cracks between them vertically. We avoid // the cracks by checking slightly above and slightly below the mouse // and seeing if we hit the same element each time. var elementUnderMouse = this.treeElementFromPoint(x, y); var elementAboveMouse = this.treeElementFromPoint(x, y - 2); var element; if (elementUnderMouse === elementAboveMouse) element = elementUnderMouse; else element = this.treeElementFromPoint(x, y + 2); return element; }, _onmousedown: function(event) { var element = this._treeElementFromEvent(event); if (!element || element.isEventWithinDisclosureTriangle(event)) return; element.select(); }, _onmousemove: function(event) { var element = this._treeElementFromEvent(event); if (element && this._previousHoveredElement === element) return; if (this._previousHoveredElement) { this._previousHoveredElement.hovered = false; delete this._previousHoveredElement; } if (element) { element.hovered = true; this._previousHoveredElement = element; } WebInspector.domAgent.highlightDOMNode(element ? element.representedObject.id : 0); }, _onmouseout: function(event) { var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY); if (nodeUnderMouse && nodeUnderMouse.isDescendant(this.element)) return; if (this._previousHoveredElement) { this._previousHoveredElement.hovered = false; delete this._previousHoveredElement; } WebInspector.domAgent.hideDOMNodeHighlight(); }, _ondragstart: function(event) { if (!window.getSelection().isCollapsed) return false; if (event.target.nodeName === "A") return false; var treeElement = this._treeElementFromEvent(event); if (!treeElement) return false; if (!this._isValidDragSourceOrTarget(treeElement)) return false; if (treeElement.representedObject.nodeName() === "BODY" || treeElement.representedObject.nodeName() === "HEAD") return false; event.dataTransfer.setData("text/plain", treeElement.listItemElement.textContent); event.dataTransfer.effectAllowed = "copyMove"; this._treeElementBeingDragged = treeElement; WebInspector.domAgent.hideDOMNodeHighlight(); return true; }, _ondragover: function(event) { if (!this._treeElementBeingDragged) return false; var treeElement = this._treeElementFromEvent(event); if (!this._isValidDragSourceOrTarget(treeElement)) return false; var node = treeElement.representedObject; while (node) { if (node === this._treeElementBeingDragged.representedObject) return false; node = node.parentNode; } treeElement.updateSelection(); treeElement.listItemElement.addStyleClass("elements-drag-over"); this._dragOverTreeElement = treeElement; event.preventDefault(); event.dataTransfer.dropEffect = 'move'; return false; }, _ondragleave: function(event) { this._clearDragOverTreeElementMarker(); event.preventDefault(); return false; }, _isValidDragSourceOrTarget: function(treeElement) { if (!treeElement) return false; var node = treeElement.representedObject; if (!(node instanceof WebInspector.DOMNode)) return false; if (!node.parentNode || node.parentNode.nodeType() !== Node.ELEMENT_NODE) return false; return true; }, _ondrop: function(event) { event.preventDefault(); var treeElement = this._treeElementFromEvent(event); if (treeElement) this._doMove(treeElement); }, _doMove: function(treeElement) { if (!this._treeElementBeingDragged) return; var parentNode; var anchorNode; if (treeElement._elementCloseTag) { // Drop onto closing tag -> insert as last child. parentNode = treeElement.representedObject; } else { var dragTargetNode = treeElement.representedObject; parentNode = dragTargetNode.parentNode; anchorNode = dragTargetNode; } var wasExpanded = this._treeElementBeingDragged.expanded; this._treeElementBeingDragged.representedObject.moveTo(parentNode, anchorNode, this._selectNodeAfterEdit.bind(this, null, wasExpanded)); delete this._treeElementBeingDragged; }, _ondragend: function(event) { event.preventDefault(); this._clearDragOverTreeElementMarker(); delete this._treeElementBeingDragged; }, _clearDragOverTreeElementMarker: function() { if (this._dragOverTreeElement) { this._dragOverTreeElement.updateSelection(); this._dragOverTreeElement.listItemElement.removeStyleClass("elements-drag-over"); delete this._dragOverTreeElement; } }, /** * @param {Event} event */ _onkeydown: function(event) { var keyboardEvent = /** @type {KeyboardEvent} */ (event); var node = this.selectedDOMNode(); var treeElement = this.getCachedTreeElement(node); if (!treeElement) return; if (!treeElement._editing && WebInspector.KeyboardShortcut.hasNoModifiers(keyboardEvent) && keyboardEvent.keyCode === WebInspector.KeyboardShortcut.Keys.H.code) { this._toggleHideShortcut(node); event.consume(true); return; } }, _contextMenuEventFired: function(event) { if (!this._showInElementsPanelEnabled) return; var treeElement = this._treeElementFromEvent(event); if (!treeElement) return; function focusElement() { // Force elements module load. WebInspector.showPanel("elements"); WebInspector.domAgent.inspectElement(treeElement.representedObject.id); } var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Reveal in Elements panel" : "Reveal in Elements Panel"), focusElement.bind(this)); contextMenu.show(); }, populateContextMenu: function(contextMenu, event) { var treeElement = this._treeElementFromEvent(event); if (!treeElement) return; var isTag = treeElement.representedObject.nodeType() === Node.ELEMENT_NODE; var textNode = event.target.enclosingNodeOrSelfWithClass("webkit-html-text-node"); if (textNode && textNode.hasStyleClass("bogus")) textNode = null; var commentNode = event.target.enclosingNodeOrSelfWithClass("webkit-html-comment"); contextMenu.appendApplicableItems(event.target); if (textNode) { contextMenu.appendSeparator(); treeElement._populateTextContextMenu(contextMenu, textNode); } else if (isTag) { contextMenu.appendSeparator(); treeElement._populateTagContextMenu(contextMenu, event); } else if (commentNode) { contextMenu.appendSeparator(); treeElement._populateNodeContextMenu(contextMenu, textNode); } }, adjustCollapsedRange: function() { }, _updateModifiedNodes: function() { if (this._elementsTreeUpdater) this._elementsTreeUpdater._updateModifiedNodes(); }, _populateContextMenu: function(contextMenu, node) { if (this._contextMenuCallback) this._contextMenuCallback(contextMenu, node); }, handleShortcut: function(event) { var node = this.selectedDOMNode(); var treeElement = this.getCachedTreeElement(node); if (!node || !treeElement) return; if (event.keyIdentifier === "F2") { this._toggleEditAsHTML(node); event.handled = true; return; } if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event) && node.parentNode) { if (event.keyIdentifier === "Up" && node.previousSibling) { node.moveTo(node.parentNode, node.previousSibling, this._selectNodeAfterEdit.bind(this, null, treeElement.expanded)); event.handled = true; return; } if (event.keyIdentifier === "Down" && node.nextSibling) { node.moveTo(node.parentNode, node.nextSibling.nextSibling, this._selectNodeAfterEdit.bind(this, null, treeElement.expanded)); event.handled = true; return; } } }, _toggleEditAsHTML: function(node) { var treeElement = this.getCachedTreeElement(node); if (!treeElement) return; if (treeElement._editing && treeElement._htmlEditElement && WebInspector.isBeingEdited(treeElement._htmlEditElement)) treeElement._editing.commit(); else treeElement._editAsHTML(); }, _selectNodeAfterEdit: function(fallbackNode, wasExpanded, error, nodeId) { if (error) return; // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date. this._updateModifiedNodes(); var newNode = WebInspector.domAgent.nodeForId(nodeId) || fallbackNode; if (!newNode) return; this.selectDOMNode(newNode, true); var newTreeItem = this.findTreeElement(newNode); if (wasExpanded) { if (newTreeItem) newTreeItem.expand(); } return newTreeItem; }, /** * Runs a script on the node's remote object that toggles a class name on * the node and injects a stylesheet into the head of the node's document * containing a rule to set "visibility: hidden" on the class and all it's * ancestors. * * @param {WebInspector.DOMNode} node * @param {function(?WebInspector.RemoteObject)=} userCallback */ _toggleHideShortcut: function(node, userCallback) { function resolvedNode(object) { if (!object) return; function toggleClassAndInjectStyleRule() { const className = "__web-inspector-hide-shortcut__"; const styleTagId = "__web-inspector-hide-shortcut-style__"; const styleRule = ".__web-inspector-hide-shortcut__, .__web-inspector-hide-shortcut__ * { visibility: hidden !important; }"; this.classList.toggle(className); var style = document.head.querySelector("style#" + styleTagId); if (style) return; style = document.createElement("style"); style.id = styleTagId; style.type = "text/css"; style.innerHTML = styleRule; document.head.appendChild(style); } object.callFunction(toggleClassAndInjectStyleRule, undefined, userCallback); object.release(); } WebInspector.RemoteObject.resolveNode(node, "", resolvedNode); }, __proto__: TreeOutline.prototype } /** * @interface */ WebInspector.ElementsTreeOutline.ElementDecorator = function() { } WebInspector.ElementsTreeOutline.ElementDecorator.prototype = { /** * @param {WebInspector.DOMNode} node */ decorate: function(node) { }, /** * @param {WebInspector.DOMNode} node */ decorateAncestor: function(node) { } } /** * @constructor * @implements {WebInspector.ElementsTreeOutline.ElementDecorator} */ WebInspector.ElementsTreeOutline.PseudoStateDecorator = function() { WebInspector.ElementsTreeOutline.ElementDecorator.call(this); } WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName = "pseudoState"; WebInspector.ElementsTreeOutline.PseudoStateDecorator.prototype = { decorate: function(node) { if (node.nodeType() !== Node.ELEMENT_NODE) return null; var propertyValue = node.getUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName); if (!propertyValue) return null; return WebInspector.UIString("Element state: %s", ":" + propertyValue.join(", :")); }, decorateAncestor: function(node) { if (node.nodeType() !== Node.ELEMENT_NODE) return null; var descendantCount = node.descendantUserPropertyCount(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName); if (!descendantCount) return null; if (descendantCount === 1) return WebInspector.UIString("%d descendant with forced state", descendantCount); return WebInspector.UIString("%d descendants with forced state", descendantCount); }, __proto__: WebInspector.ElementsTreeOutline.ElementDecorator.prototype } /** * @constructor * @extends {TreeElement} * @param {boolean=} elementCloseTag */ WebInspector.ElementsTreeElement = function(node, elementCloseTag) { this._elementCloseTag = elementCloseTag; var hasChildrenOverride = !elementCloseTag && node.hasChildNodes() && !this._showInlineText(node); // The title will be updated in onattach. TreeElement.call(this, "", node, hasChildrenOverride); if (this.representedObject.nodeType() == Node.ELEMENT_NODE && !elementCloseTag) this._canAddAttributes = true; this._searchQuery = null; this._expandedChildrenLimit = WebInspector.ElementsTreeElement.InitialChildrenLimit; } WebInspector.ElementsTreeElement.InitialChildrenLimit = 500; // A union of HTML4 and HTML5-Draft elements that explicitly // or implicitly (for HTML5) forbid the closing tag. // FIXME: Revise once HTML5 Final is published. WebInspector.ElementsTreeElement.ForbiddenClosingTagElements = [ "area", "base", "basefont", "br", "canvas", "col", "command", "embed", "frame", "hr", "img", "input", "isindex", "keygen", "link", "meta", "param", "source" ].keySet(); // These tags we do not allow editing their tag name. WebInspector.ElementsTreeElement.EditTagBlacklist = [ "html", "head", "body" ].keySet(); WebInspector.ElementsTreeElement.prototype = { highlightSearchResults: function(searchQuery) { if (this._searchQuery !== searchQuery) { this._updateSearchHighlight(false); delete this._highlightResult; // A new search query. } this._searchQuery = searchQuery; this._searchHighlightsVisible = true; this.updateTitle(true); }, hideSearchHighlights: function() { delete this._searchHighlightsVisible; this._updateSearchHighlight(false); }, _updateSearchHighlight: function(show) { if (!this._highlightResult) return; function updateEntryShow(entry) { switch (entry.type) { case "added": entry.parent.insertBefore(entry.node, entry.nextSibling); break; case "changed": entry.node.textContent = entry.newText; break; } } function updateEntryHide(entry) { switch (entry.type) { case "added": if (entry.node.parentElement) entry.node.parentElement.removeChild(entry.node); break; case "changed": entry.node.textContent = entry.oldText; break; } } // Preserve the semantic of node by following the order of updates for hide and show. if (show) { for (var i = 0, size = this._highlightResult.length; i < size; ++i) updateEntryShow(this._highlightResult[i]); } else { for (var i = (this._highlightResult.length - 1); i >= 0; --i) updateEntryHide(this._highlightResult[i]); } }, get hovered() { return this._hovered; }, set hovered(x) { if (this._hovered === x) return; this._hovered = x; if (this.listItemElement) { if (x) { this.updateSelection(); this.listItemElement.addStyleClass("hovered"); } else { this.listItemElement.removeStyleClass("hovered"); } } }, get expandedChildrenLimit() { return this._expandedChildrenLimit; }, set expandedChildrenLimit(x) { if (this._expandedChildrenLimit === x) return; this._expandedChildrenLimit = x; if (this.treeOutline && !this._updateChildrenInProgress) this._updateChildren(true); }, get expandedChildCount() { var count = this.children.length; if (count && this.children[count - 1]._elementCloseTag) count--; if (count && this.children[count - 1].expandAllButton) count--; return count; }, showChild: function(index) { if (this._elementCloseTag) return; if (index >= this.expandedChildrenLimit) { this._expandedChildrenLimit = index + 1; this._updateChildren(true); } // Whether index-th child is visible in the children tree return this.expandedChildCount > index; }, updateSelection: function() { var listItemElement = this.listItemElement; if (!listItemElement) return; if (!this._readyToUpdateSelection) { if (document.body.offsetWidth > 0) this._readyToUpdateSelection = true; else { // The stylesheet hasn't loaded yet or the window is closed, // so we can't calculate what we need. Return early. return; } } if (!this.selectionElement) { this.selectionElement = document.createElement("div"); this.selectionElement.className = "selection selected"; listItemElement.insertBefore(this.selectionElement, listItemElement.firstChild); } this.selectionElement.style.height = listItemElement.offsetHeight + "px"; }, onattach: function() { if (this._hovered) { this.updateSelection(); this.listItemElement.addStyleClass("hovered"); } this.updateTitle(); this._preventFollowingLinksOnDoubleClick(); this.listItemElement.draggable = true; }, _preventFollowingLinksOnDoubleClick: function() { var links = this.listItemElement.querySelectorAll("li > .webkit-html-tag > .webkit-html-attribute > .webkit-html-external-link, li > .webkit-html-tag > .webkit-html-attribute > .webkit-html-resource-link"); if (!links) return; for (var i = 0; i < links.length; ++i) links[i].preventFollowOnDoubleClick = true; }, onpopulate: function() { if (this.children.length || this._showInlineText(this.representedObject) || this._elementCloseTag) return; this.updateChildren(); }, /** * @param {boolean=} fullRefresh */ updateChildren: function(fullRefresh) { if (this._elementCloseTag) return; this.representedObject.getChildNodes(this._updateChildren.bind(this, fullRefresh)); }, /** * @param {boolean=} closingTag */ insertChildElement: function(child, index, closingTag) { var newElement = new WebInspector.ElementsTreeElement(child, closingTag); newElement.selectable = this.treeOutline._selectEnabled; this.insertChild(newElement, index); return newElement; }, moveChild: function(child, targetIndex) { var wasSelected = child.selected; this.removeChild(child); this.insertChild(child, targetIndex); if (wasSelected) child.select(); }, /** * @param {boolean=} fullRefresh */ _updateChildren: function(fullRefresh) { if (this._updateChildrenInProgress || !this.treeOutline._visible) return; this._updateChildrenInProgress = true; var selectedNode = this.treeOutline.selectedDOMNode(); var originalScrollTop = 0; if (fullRefresh) { var treeOutlineContainerElement = this.treeOutline.element.parentNode; originalScrollTop = treeOutlineContainerElement.scrollTop; var selectedTreeElement = this.treeOutline.selectedTreeElement; if (selectedTreeElement && selectedTreeElement.hasAncestor(this)) this.select(); this.removeChildren(); } var treeElement = this; var treeChildIndex = 0; var elementToSelect; function updateChildrenOfNode(node) { var treeOutline = treeElement.treeOutline; var child = node.firstChild; while (child) { var currentTreeElement = treeElement.children[treeChildIndex]; if (!currentTreeElement || currentTreeElement.representedObject !== child) { // Find any existing element that is later in the children list. var existingTreeElement = null; for (var i = (treeChildIndex + 1), size = treeElement.expandedChildCount; i < size; ++i) { if (treeElement.children[i].representedObject === child) { existingTreeElement = treeElement.children[i]; break; } } if (existingTreeElement && existingTreeElement.parent === treeElement) { // If an existing element was found and it has the same parent, just move it. treeElement.moveChild(existingTreeElement, treeChildIndex); } else { // No existing element found, insert a new element. if (treeChildIndex < treeElement.expandedChildrenLimit) { var newElement = treeElement.insertChildElement(child, treeChildIndex); if (child === selectedNode) elementToSelect = newElement; if (treeElement.expandedChildCount > treeElement.expandedChildrenLimit) treeElement.expandedChildrenLimit++; } } } child = child.nextSibling; ++treeChildIndex; } } // Remove any tree elements that no longer have this node (or this node's contentDocument) as their parent. for (var i = (this.children.length - 1); i >= 0; --i) { var currentChild = this.children[i]; var currentNode = currentChild.representedObject; var currentParentNode = currentNode.parentNode; if (currentParentNode === this.representedObject) continue; var selectedTreeElement = this.treeOutline.selectedTreeElement; if (selectedTreeElement && (selectedTreeElement === currentChild || selectedTreeElement.hasAncestor(currentChild))) this.select(); this.removeChildAtIndex(i); } updateChildrenOfNode(this.representedObject); this.adjustCollapsedRange(); var lastChild = this.children[this.children.length - 1]; if (this.representedObject.nodeType() == Node.ELEMENT_NODE && (!lastChild || !lastChild._elementCloseTag)) this.insertChildElement(this.representedObject, this.children.length, true); // We want to restore the original selection and tree scroll position after a full refresh, if possible. if (fullRefresh && elementToSelect) { elementToSelect.select(); if (treeOutlineContainerElement && originalScrollTop <= treeOutlineContainerElement.scrollHeight) treeOutlineContainerElement.scrollTop = originalScrollTop; } delete this._updateChildrenInProgress; }, adjustCollapsedRange: function() { // Ensure precondition: only the tree elements for node children are found in the tree // (not the Expand All button or the closing tag). if (this.expandAllButtonElement && this.expandAllButtonElement.__treeElement.parent) this.removeChild(this.expandAllButtonElement.__treeElement); const node = this.representedObject; if (!node.children) return; const childNodeCount = node.children.length; // In case some nodes from the expanded range were removed, pull some nodes from the collapsed range into the expanded range at the bottom. for (var i = this.expandedChildCount, limit = Math.min(this.expandedChildrenLimit, childNodeCount); i < limit; ++i) this.insertChildElement(node.children[i], i); const expandedChildCount = this.expandedChildCount; if (childNodeCount > this.expandedChildCount) { var targetButtonIndex = expandedChildCount; if (!this.expandAllButtonElement) { var button = document.createElement("button"); button.className = "show-all-nodes"; button.value = ""; var item = new TreeElement(button, null, false); item.selectable = false; item.expandAllButton = true; this.insertChild(item, targetButtonIndex); this.expandAllButtonElement = item.listItemElement.firstChild; this.expandAllButtonElement.__treeElement = item; this.expandAllButtonElement.addEventListener("click", this.handleLoadAllChildren.bind(this), false); } else if (!this.expandAllButtonElement.__treeElement.parent) this.insertChild(this.expandAllButtonElement.__treeElement, targetButtonIndex); this.expandAllButtonElement.textContent = WebInspector.UIString("Show All Nodes (%d More)", childNodeCount - expandedChildCount); } else if (this.expandAllButtonElement) delete this.expandAllButtonElement; }, handleLoadAllChildren: function() { this.expandedChildrenLimit = Math.max(this.representedObject._childNodeCount, this.expandedChildrenLimit + WebInspector.ElementsTreeElement.InitialChildrenLimit); }, expandRecursively: function() { function callback() { TreeElement.prototype.expandRecursively.call(this, Number.MAX_VALUE); } this.representedObject.getSubtree(-1, callback.bind(this)); }, onexpand: function() { if (this._elementCloseTag) return; this.updateTitle(); this.treeOutline.updateSelection(); }, oncollapse: function() { if (this._elementCloseTag) return; this.updateTitle(); this.treeOutline.updateSelection(); }, onreveal: function() { if (this.listItemElement) { var tagSpans = this.listItemElement.getElementsByClassName("webkit-html-tag-name"); if (tagSpans.length) tagSpans[0].scrollIntoViewIfNeeded(false); else this.listItemElement.scrollIntoViewIfNeeded(false); } }, onselect: function(selectedByUser) { this.treeOutline.suppressRevealAndSelect = true; this.treeOutline.selectDOMNode(this.representedObject, selectedByUser); if (selectedByUser) WebInspector.domAgent.highlightDOMNode(this.representedObject.id); this.updateSelection(); this.treeOutline.suppressRevealAndSelect = false; return true; }, ondelete: function() { var startTagTreeElement = this.treeOutline.findTreeElement(this.representedObject); startTagTreeElement ? startTagTreeElement.remove() : this.remove(); return true; }, onenter: function() { // On Enter or Return start editing the first attribute // or create a new attribute on the selected element. if (this._editing) return false; this._startEditing(); // prevent a newline from being immediately inserted return true; }, selectOnMouseDown: function(event) { TreeElement.prototype.selectOnMouseDown.call(this, event); if (this._editing) return; if (this.treeOutline._showInElementsPanelEnabled) { WebInspector.showPanel("elements"); this.treeOutline.selectDOMNode(this.representedObject, true); } // Prevent selecting the nearest word on double click. if (event.detail >= 2) event.preventDefault(); }, ondblclick: function(event) { if (this._editing || this._elementCloseTag) return; if (this._startEditingTarget(event.target)) return; if (this.hasChildren && !this.expanded) this.expand(); }, _insertInLastAttributePosition: function(tag, node) { if (tag.getElementsByClassName("webkit-html-attribute").length > 0) tag.insertBefore(node, tag.lastChild); else { var nodeName = tag.textContent.match(/^<(.*?)>$/)[1]; tag.textContent = ''; tag.appendChild(document.createTextNode('<'+nodeName)); tag.appendChild(node); tag.appendChild(document.createTextNode('>')); } this.updateSelection(); }, _startEditingTarget: function(eventTarget) { if (this.treeOutline.selectedDOMNode() != this.representedObject) return; if (this.representedObject.nodeType() != Node.ELEMENT_NODE && this.representedObject.nodeType() != Node.TEXT_NODE) return false; var textNode = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-text-node"); if (textNode) return this._startEditingTextNode(textNode); var attribute = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-attribute"); if (attribute) return this._startEditingAttribute(attribute, eventTarget); var tagName = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-tag-name"); if (tagName) return this._startEditingTagName(tagName); var newAttribute = eventTarget.enclosingNodeOrSelfWithClass("add-attribute"); if (newAttribute) return this._addNewAttribute(); return false; }, _populateTagContextMenu: function(contextMenu, event) { var attribute = event.target.enclosingNodeOrSelfWithClass("webkit-html-attribute"); var newAttribute = event.target.enclosingNodeOrSelfWithClass("add-attribute"); // Add attribute-related actions. var treeElement = this._elementCloseTag ? this.treeOutline.findTreeElement(this.representedObject) : this; contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Add attribute" : "Add Attribute"), this._addNewAttribute.bind(treeElement)); if (attribute && !newAttribute) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Edit attribute" : "Edit Attribute"), this._startEditingAttribute.bind(this, attribute, event.target)); contextMenu.appendSeparator(); if (this.treeOutline._setPseudoClassCallback) { var pseudoSubMenu = contextMenu.appendSubMenuItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Force element state" : "Force Element State")); this._populateForcedPseudoStateItems(pseudoSubMenu); contextMenu.appendSeparator(); } this._populateNodeContextMenu(contextMenu); this.treeOutline._populateContextMenu(contextMenu, this.representedObject); contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Scroll into view" : "Scroll into View"), this._scrollIntoView.bind(this)); }, _populateForcedPseudoStateItems: function(subMenu) { const pseudoClasses = ["active", "hover", "focus", "visited"]; var node = this.representedObject; var forcedPseudoState = (node ? node.getUserProperty("pseudoState") : null) || []; for (var i = 0; i < pseudoClasses.length; ++i) { var pseudoClassForced = forcedPseudoState.indexOf(pseudoClasses[i]) >= 0; subMenu.appendCheckboxItem(":" + pseudoClasses[i], this.treeOutline._setPseudoClassCallback.bind(null, node.id, pseudoClasses[i], !pseudoClassForced), pseudoClassForced, false); } }, _populateTextContextMenu: function(contextMenu, textNode) { contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Edit text" : "Edit Text"), this._startEditingTextNode.bind(this, textNode)); this._populateNodeContextMenu(contextMenu); }, _populateNodeContextMenu: function(contextMenu) { // Add free-form node-related actions. contextMenu.appendItem(WebInspector.UIString("Edit as HTML"), this._editAsHTML.bind(this)); contextMenu.appendItem(WebInspector.UIString("Copy as HTML"), this._copyHTML.bind(this)); contextMenu.appendItem(WebInspector.UIString("Copy XPath"), this._copyXPath.bind(this)); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Delete node" : "Delete Node"), this.remove.bind(this)); }, _startEditing: function() { if (this.treeOutline.selectedDOMNode() !== this.representedObject) return; var listItem = this._listItemNode; if (this._canAddAttributes) { var attribute = listItem.getElementsByClassName("webkit-html-attribute")[0]; if (attribute) return this._startEditingAttribute(attribute, attribute.getElementsByClassName("webkit-html-attribute-value")[0]); return this._addNewAttribute(); } if (this.representedObject.nodeType() === Node.TEXT_NODE) { var textNode = listItem.getElementsByClassName("webkit-html-text-node")[0]; if (textNode) return this._startEditingTextNode(textNode); return; } }, _addNewAttribute: function() { // Cannot just convert the textual html into an element without // a parent node. Use a temporary span container for the HTML. var container = document.createElement("span"); this._buildAttributeDOM(container, " ", ""); var attr = container.firstChild; attr.style.marginLeft = "2px"; // overrides the .editing margin rule attr.style.marginRight = "2px"; // overrides the .editing margin rule var tag = this.listItemElement.getElementsByClassName("webkit-html-tag")[0]; this._insertInLastAttributePosition(tag, attr); attr.scrollIntoViewIfNeeded(true); return this._startEditingAttribute(attr, attr); }, _triggerEditAttribute: function(attributeName) { var attributeElements = this.listItemElement.getElementsByClassName("webkit-html-attribute-name"); for (var i = 0, len = attributeElements.length; i < len; ++i) { if (attributeElements[i].textContent === attributeName) { for (var elem = attributeElements[i].nextSibling; elem; elem = elem.nextSibling) { if (elem.nodeType !== Node.ELEMENT_NODE) continue; if (elem.hasStyleClass("webkit-html-attribute-value")) return this._startEditingAttribute(elem.parentNode, elem); } } } }, _startEditingAttribute: function(attribute, elementForSelection) { if (WebInspector.isBeingEdited(attribute)) return true; var attributeNameElement = attribute.getElementsByClassName("webkit-html-attribute-name")[0]; if (!attributeNameElement) return false; var attributeName = attributeNameElement.textContent; function removeZeroWidthSpaceRecursive(node) { if (node.nodeType === Node.TEXT_NODE) { node.nodeValue = node.nodeValue.replace(/\u200B/g, ""); return; } if (node.nodeType !== Node.ELEMENT_NODE) return; for (var child = node.firstChild; child; child = child.nextSibling) removeZeroWidthSpaceRecursive(child); } // Remove zero-width spaces that were added by nodeTitleInfo. removeZeroWidthSpaceRecursive(attribute); var config = new WebInspector.EditingConfig(this._attributeEditingCommitted.bind(this), this._editingCancelled.bind(this), attributeName); function handleKeyDownEvents(event) { var isMetaOrCtrl = WebInspector.isMac() ? event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey : event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey; if (isEnterKey(event) && (event.isMetaOrCtrlForTest || !config.multiline || isMetaOrCtrl)) return "commit"; else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code || event.keyIdentifier === "U+001B") return "cancel"; else if (event.keyIdentifier === "U+0009") // Tab key return "move-" + (event.shiftKey ? "backward" : "forward"); else { WebInspector.handleElementValueModifications(event, attribute); return ""; } } config.customFinishHandler = handleKeyDownEvents.bind(this); this._editing = WebInspector.startEditing(attribute, config); window.getSelection().setBaseAndExtent(elementForSelection, 0, elementForSelection, 1); return true; }, /** * @param {Element} textNodeElement */ _startEditingTextNode: function(textNodeElement) { if (WebInspector.isBeingEdited(textNodeElement)) return true; var textNode = this.representedObject; // We only show text nodes inline in elements if the element only // has a single child, and that child is a text node. if (textNode.nodeType() === Node.ELEMENT_NODE && textNode.firstChild) textNode = textNode.firstChild; var container = textNodeElement.enclosingNodeOrSelfWithClass("webkit-html-text-node"); if (container) container.textContent = textNode.nodeValue(); // Strip the CSS or JS highlighting if present. var config = new WebInspector.EditingConfig(this._textNodeEditingCommitted.bind(this, textNode), this._editingCancelled.bind(this)); this._editing = WebInspector.startEditing(textNodeElement, config); window.getSelection().setBaseAndExtent(textNodeElement, 0, textNodeElement, 1); return true; }, /** * @param {Element=} tagNameElement */ _startEditingTagName: function(tagNameElement) { if (!tagNameElement) { tagNameElement = this.listItemElement.getElementsByClassName("webkit-html-tag-name")[0]; if (!tagNameElement) return false; } var tagName = tagNameElement.textContent; if (WebInspector.ElementsTreeElement.EditTagBlacklist[tagName.toLowerCase()]) return false; if (WebInspector.isBeingEdited(tagNameElement)) return true; var closingTagElement = this._distinctClosingTagElement(); function keyupListener(event) { if (closingTagElement) closingTagElement.textContent = "</" + tagNameElement.textContent + ">"; } function editingComitted(element, newTagName) { tagNameElement.removeEventListener('keyup', keyupListener, false); this._tagNameEditingCommitted.apply(this, arguments); } function editingCancelled() { tagNameElement.removeEventListener('keyup', keyupListener, false); this._editingCancelled.apply(this, arguments); } tagNameElement.addEventListener('keyup', keyupListener, false); var config = new WebInspector.EditingConfig(editingComitted.bind(this), editingCancelled.bind(this), tagName); this._editing = WebInspector.startEditing(tagNameElement, config); window.getSelection().setBaseAndExtent(tagNameElement, 0, tagNameElement, 1); return true; }, _startEditingAsHTML: function(commitCallback, error, initialValue) { if (error) return; if (this._editing) return; function consume(event) { if (event.eventPhase === Event.AT_TARGET) event.consume(true); } initialValue = this._convertWhitespaceToEntities(initialValue); this._htmlEditElement = document.createElement("div"); this._htmlEditElement.className = "source-code elements-tree-editor"; // Hide header items. var child = this.listItemElement.firstChild; while (child) { child.style.display = "none"; child = child.nextSibling; } // Hide children item. if (this._childrenListNode) this._childrenListNode.style.display = "none"; // Append editor. this.listItemElement.appendChild(this._htmlEditElement); this.treeOutline.childrenListElement.parentElement.addEventListener("mousedown", consume, false); this.updateSelection(); /** * @param {Element} element * @param {string} newValue */ function commit(element, newValue) { commitCallback(initialValue, newValue); dispose.call(this); } function dispose() { delete this._editing; // Remove editor. this.listItemElement.removeChild(this._htmlEditElement); delete this._htmlEditElement; // Unhide children item. if (this._childrenListNode) this._childrenListNode.style.removeProperty("display"); // Unhide header items. var child = this.listItemElement.firstChild; while (child) { child.style.removeProperty("display"); child = child.nextSibling; } this.treeOutline.childrenListElement.parentElement.removeEventListener("mousedown", consume, false); this.updateSelection(); } var config = new WebInspector.EditingConfig(commit.bind(this), dispose.bind(this)); config.setMultilineOptions(initialValue, { name: "xml", htmlMode: true }, "web-inspector-html", true, true); this._editing = WebInspector.startEditing(this._htmlEditElement, config); }, _attributeEditingCommitted: function(element, newText, oldText, attributeName, moveDirection) { delete this._editing; var treeOutline = this.treeOutline; /** * @param {Protocol.Error=} error */ function moveToNextAttributeIfNeeded(error) { if (error) this._editingCancelled(element, attributeName); if (!moveDirection) return; treeOutline._updateModifiedNodes(); // Search for the attribute's position, and then decide where to move to. var attributes = this.representedObject.attributes(); for (var i = 0; i < attributes.length; ++i) { if (attributes[i].name !== attributeName) continue; if (moveDirection === "backward") { if (i === 0) this._startEditingTagName(); else this._triggerEditAttribute(attributes[i - 1].name); } else { if (i === attributes.length - 1) this._addNewAttribute(); else this._triggerEditAttribute(attributes[i + 1].name); } return; } // Moving From the "New Attribute" position. if (moveDirection === "backward") { if (newText === " ") { // Moving from "New Attribute" that was not edited if (attributes.length > 0) this._triggerEditAttribute(attributes[attributes.length - 1].name); } else { // Moving from "New Attribute" that holds new value if (attributes.length > 1) this._triggerEditAttribute(attributes[attributes.length - 2].name); } } else if (moveDirection === "forward") { if (!/^\s*$/.test(newText)) this._addNewAttribute(); else this._startEditingTagName(); } } if (oldText !== newText) this.representedObject.setAttribute(attributeName, newText, moveToNextAttributeIfNeeded.bind(this)); else moveToNextAttributeIfNeeded.call(this); }, _tagNameEditingCommitted: function(element, newText, oldText, tagName, moveDirection) { delete this._editing; var self = this; function cancel() { var closingTagElement = self._distinctClosingTagElement(); if (closingTagElement) closingTagElement.textContent = "</" + tagName + ">"; self._editingCancelled(element, tagName); moveToNextAttributeIfNeeded.call(self); } function moveToNextAttributeIfNeeded() { if (moveDirection !== "forward") { this._addNewAttribute(); return; } var attributes = this.representedObject.attributes(); if (attributes.length > 0) this._triggerEditAttribute(attributes[0].name); else this._addNewAttribute(); } newText = newText.trim(); if (newText === oldText) { cancel(); return; } var treeOutline = this.treeOutline; var wasExpanded = this.expanded; function changeTagNameCallback(error, nodeId) { if (error || !nodeId) { cancel(); return; } var newTreeItem = treeOutline._selectNodeAfterEdit(null, wasExpanded, error, nodeId); moveToNextAttributeIfNeeded.call(newTreeItem); } this.representedObject.setNodeName(newText, changeTagNameCallback); }, /** * @param {WebInspector.DOMNode} textNode * @param {Element} element * @param {string} newText */ _textNodeEditingCommitted: function(textNode, element, newText) { delete this._editing; function callback() { this.updateTitle(); } textNode.setNodeValue(newText, callback.bind(this)); }, /** * @param {Element} element * @param {*} context */ _editingCancelled: function(element, context) { delete this._editing; // Need to restore attributes structure. this.updateTitle(); }, _distinctClosingTagElement: function() { // FIXME: Improve the Tree Element / Outline Abstraction to prevent crawling the DOM // For an expanded element, it will be the last element with class "close" // in the child element list. if (this.expanded) { var closers = this._childrenListNode.querySelectorAll(".close"); return closers[closers.length-1]; } // Remaining cases are single line non-expanded elements with a closing // tag, or HTML elements without a closing tag (such as <br>). Return // null in the case where there isn't a closing tag. var tags = this.listItemElement.getElementsByClassName("webkit-html-tag"); return (tags.length === 1 ? null : tags[tags.length-1]); }, /** * @param {boolean=} onlySearchQueryChanged */ updateTitle: function(onlySearchQueryChanged) { // If we are editing, return early to prevent canceling the edit. // After editing is committed updateTitle will be called. if (this._editing) return; if (onlySearchQueryChanged) { if (this._highlightResult) this._updateSearchHighlight(false); } else { var highlightElement = document.createElement("span"); highlightElement.className = "highlight"; highlightElement.appendChild(this._nodeTitleInfo(WebInspector.linkifyURLAsNode).titleDOM); this.title = highlightElement; this._updateDecorations(); delete this._highlightResult; } delete this.selectionElement; if (this.selected) this.updateSelection(); this._preventFollowingLinksOnDoubleClick(); this._highlightSearchResults(); }, _createDecoratorElement: function() { var node = this.representedObject; var decoratorMessages = []; var parentDecoratorMessages = []; for (var i = 0; i < this.treeOutline._nodeDecorators.length; ++i) { var decorator = this.treeOutline._nodeDecorators[i]; var message = decorator.decorate(node); if (message) { decoratorMessages.push(message); continue; } if (this.expanded || this._elementCloseTag) continue; message = decorator.decorateAncestor(node); if (message) parentDecoratorMessages.push(message) } if (!decoratorMessages.length && !parentDecoratorMessages.length) return null; var decoratorElement = document.createElement("div"); decoratorElement.addStyleClass("elements-gutter-decoration"); if (!decoratorMessages.length) decoratorElement.addStyleClass("elements-has-decorated-children"); decoratorElement.title = decoratorMessages.concat(parentDecoratorMessages).join("\n"); return decoratorElement; }, _updateDecorations: function() { if (this._decoratorElement && this._decoratorElement.parentElement) this._decoratorElement.parentElement.removeChild(this._decoratorElement); this._decoratorElement = this._createDecoratorElement(); if (this._decoratorElement && this.listItemElement) this.listItemElement.insertBefore(this._decoratorElement, this.listItemElement.firstChild); }, /** * @param {WebInspector.DOMNode=} node * @param {function(string, string, string, boolean=, string=)=} linkify */ _buildAttributeDOM: function(parentElement, name, value, node, linkify) { var hasText = (value.length > 0); var attrSpanElement = parentElement.createChild("span", "webkit-html-attribute"); var attrNameElement = attrSpanElement.createChild("span", "webkit-html-attribute-name"); attrNameElement.textContent = name; if (hasText) attrSpanElement.appendChild(document.createTextNode("=\u200B\"")); if (linkify && (name === "src" || name === "href")) { var rewrittenHref = node.resolveURL(value); value = value.replace(/([\/;:\)\]\}])/g, "$1\u200B"); if (rewrittenHref === null) { var attrValueElement = attrSpanElement.createChild("span", "webkit-html-attribute-value"); attrValueElement.textContent = value; } else { if (value.startsWith("data:")) value = value.centerEllipsizedToLength(60); attrSpanElement.appendChild(linkify(rewrittenHref, value, "webkit-html-attribute-value", node.nodeName().toLowerCase() === "a")); } } else { value = value.replace(/([\/;:\)\]\}])/g, "$1\u200B"); var attrValueElement = attrSpanElement.createChild("span", "webkit-html-attribute-value"); attrValueElement.textContent = value; } if (hasText) attrSpanElement.appendChild(document.createTextNode("\"")); }, /** * @param {function(string, string, string, boolean=, string=)=} linkify */ _buildTagDOM: function(parentElement, tagName, isClosingTag, isDistinctTreeElement, linkify) { var node = /** @type WebInspector.DOMNode */ (this.representedObject); var classes = [ "webkit-html-tag" ]; if (isClosingTag && isDistinctTreeElement) classes.push("close"); if (node.isInShadowTree()) classes.push("shadow"); var tagElement = parentElement.createChild("span", classes.join(" ")); tagElement.appendChild(document.createTextNode("<")); var tagNameElement = tagElement.createChild("span", isClosingTag ? "" : "webkit-html-tag-name"); tagNameElement.textContent = (isClosingTag ? "/" : "") + tagName; if (!isClosingTag && node.hasAttributes()) { var attributes = node.attributes(); for (var i = 0; i < attributes.length; ++i) { var attr = attributes[i]; tagElement.appendChild(document.createTextNode(" ")); this._buildAttributeDOM(tagElement, attr.name, attr.value, node, linkify); } } tagElement.appendChild(document.createTextNode(">")); parentElement.appendChild(document.createTextNode("\u200B")); }, _convertWhitespaceToEntities: function(text) { var result = ""; var lastIndexAfterEntity = 0; var charToEntity = WebInspector.ElementsTreeOutline.MappedCharToEntity; for (var i = 0, size = text.length; i < size; ++i) { var char = text.charAt(i); if (charToEntity[char]) { result += text.substring(lastIndexAfterEntity, i) + "&" + charToEntity[char] + ";"; lastIndexAfterEntity = i + 1; } } if (result) { result += text.substring(lastIndexAfterEntity); return result; } return text; }, _nodeTitleInfo: function(linkify) { var node = this.representedObject; var info = {titleDOM: document.createDocumentFragment(), hasChildren: this.hasChildren}; switch (node.nodeType()) { case Node.ATTRIBUTE_NODE: var value = node.value || "\u200B"; // Zero width space to force showing an empty value. this._buildAttributeDOM(info.titleDOM, node.name, value); break; case Node.ELEMENT_NODE: var tagName = node.nodeNameInCorrectCase(); if (this._elementCloseTag) { this._buildTagDOM(info.titleDOM, tagName, true, true); info.hasChildren = false; break; } this._buildTagDOM(info.titleDOM, tagName, false, false, linkify); var textChild = this._singleTextChild(node); var showInlineText = textChild && textChild.nodeValue().length < Preferences.maxInlineTextChildLength && !this.hasChildren; if (!this.expanded && (!showInlineText && (this.treeOutline.isXMLMimeType || !WebInspector.ElementsTreeElement.ForbiddenClosingTagElements[tagName]))) { if (this.hasChildren) { var textNodeElement = info.titleDOM.createChild("span", "webkit-html-text-node bogus"); textNodeElement.textContent = "\u2026"; info.titleDOM.appendChild(document.createTextNode("\u200B")); } this._buildTagDOM(info.titleDOM, tagName, true, false); } // If this element only has a single child that is a text node, // just show that text and the closing tag inline rather than // create a subtree for them if (showInlineText) { var textNodeElement = info.titleDOM.createChild("span", "webkit-html-text-node"); textNodeElement.textContent = this._convertWhitespaceToEntities(textChild.nodeValue()); info.titleDOM.appendChild(document.createTextNode("\u200B")); this._buildTagDOM(info.titleDOM, tagName, true, false); info.hasChildren = false; } break; case Node.TEXT_NODE: if (node.parentNode && node.parentNode.nodeName().toLowerCase() === "script") { var newNode = info.titleDOM.createChild("span", "webkit-html-text-node webkit-html-js-node"); newNode.textContent = node.nodeValue(); var javascriptSyntaxHighlighter = new WebInspector.DOMSyntaxHighlighter("text/javascript", true); javascriptSyntaxHighlighter.syntaxHighlightNode(newNode); } else if (node.parentNode && node.parentNode.nodeName().toLowerCase() === "style") { var newNode = info.titleDOM.createChild("span", "webkit-html-text-node webkit-html-css-node"); newNode.textContent = node.nodeValue(); var cssSyntaxHighlighter = new WebInspector.DOMSyntaxHighlighter("text/css", true); cssSyntaxHighlighter.syntaxHighlightNode(newNode); } else { info.titleDOM.appendChild(document.createTextNode("\"")); var textNodeElement = info.titleDOM.createChild("span", "webkit-html-text-node"); textNodeElement.textContent = this._convertWhitespaceToEntities(node.nodeValue()); info.titleDOM.appendChild(document.createTextNode("\"")); } break; case Node.COMMENT_NODE: var commentElement = info.titleDOM.createChild("span", "webkit-html-comment"); commentElement.appendChild(document.createTextNode("<!--" + node.nodeValue() + "-->")); break; case Node.DOCUMENT_TYPE_NODE: var docTypeElement = info.titleDOM.createChild("span", "webkit-html-doctype"); docTypeElement.appendChild(document.createTextNode("<!DOCTYPE " + node.nodeName())); if (node.publicId) { docTypeElement.appendChild(document.createTextNode(" PUBLIC \"" + node.publicId + "\"")); if (node.systemId) docTypeElement.appendChild(document.createTextNode(" \"" + node.systemId + "\"")); } else if (node.systemId) docTypeElement.appendChild(document.createTextNode(" SYSTEM \"" + node.systemId + "\"")); if (node.internalSubset) docTypeElement.appendChild(document.createTextNode(" [" + node.internalSubset + "]")); docTypeElement.appendChild(document.createTextNode(">")); break; case Node.CDATA_SECTION_NODE: var cdataElement = info.titleDOM.createChild("span", "webkit-html-text-node"); cdataElement.appendChild(document.createTextNode("<![CDATA[" + node.nodeValue() + "]]>")); break; case Node.DOCUMENT_FRAGMENT_NODE: var fragmentElement = info.titleDOM.createChild("span", "webkit-html-fragment"); fragmentElement.textContent = node.nodeNameInCorrectCase().collapseWhitespace(); if (node.isInShadowTree()) fragmentElement.addStyleClass("shadow"); break; default: info.titleDOM.appendChild(document.createTextNode(node.nodeNameInCorrectCase().collapseWhitespace())); } return info; }, _singleTextChild: function(node) { if (!node) return null; var firstChild = node.firstChild; if (!firstChild || firstChild.nodeType() !== Node.TEXT_NODE) return null; if (node.hasShadowRoots()) return null; var sibling = firstChild.nextSibling; return sibling ? null : firstChild; }, _showInlineText: function(node) { if (node.nodeType() === Node.ELEMENT_NODE) { var textChild = this._singleTextChild(node); if (textChild && textChild.nodeValue().length < Preferences.maxInlineTextChildLength) return true; } return false; }, remove: function() { var parentElement = this.parent; if (!parentElement) return; var self = this; function removeNodeCallback(error, removedNodeId) { if (error) return; parentElement.removeChild(self); parentElement.adjustCollapsedRange(); } if (!this.representedObject.parentNode || this.representedObject.parentNode.nodeType() === Node.DOCUMENT_NODE) return; this.representedObject.removeNode(removeNodeCallback); }, _editAsHTML: function() { var treeOutline = this.treeOutline; var node = this.representedObject; var parentNode = node.parentNode; var index = node.index; var wasExpanded = this.expanded; function selectNode(error, nodeId) { if (error) return; // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date. treeOutline._updateModifiedNodes(); var newNode = parentNode ? parentNode.children[index] || parentNode : null; if (!newNode) return; treeOutline.selectDOMNode(newNode, true); if (wasExpanded) { var newTreeItem = treeOutline.findTreeElement(newNode); if (newTreeItem) newTreeItem.expand(); } } function commitChange(initialValue, value) { if (initialValue !== value) node.setOuterHTML(value, selectNode); else return; } node.getOuterHTML(this._startEditingAsHTML.bind(this, commitChange)); }, _copyHTML: function() { this.representedObject.copyNode(); }, _copyXPath: function() { this.representedObject.copyXPath(true); }, _highlightSearchResults: function() { if (!this._searchQuery || !this._searchHighlightsVisible) return; if (this._highlightResult) { this._updateSearchHighlight(true); return; } var text = this.listItemElement.textContent; var regexObject = createPlainTextSearchRegex(this._searchQuery, "gi"); var offset = 0; var match = regexObject.exec(text); var matchRanges = []; while (match) { matchRanges.push({ offset: match.index, length: match[0].length }); match = regexObject.exec(text); } // Fall back for XPath, etc. matches. if (!matchRanges.length) matchRanges.push({ offset: 0, length: text.length }); this._highlightResult = []; WebInspector.highlightSearchResults(this.listItemElement, matchRanges, this._highlightResult); }, _scrollIntoView: function() { function scrollIntoViewCallback(object) { function scrollIntoView() { this.scrollIntoViewIfNeeded(true); } if (object) object.callFunction(scrollIntoView); } var node = /** @type {WebInspector.DOMNode} */ (this.representedObject); WebInspector.RemoteObject.resolveNode(node, "", scrollIntoViewCallback); }, __proto__: TreeElement.prototype } /** * @constructor */ WebInspector.ElementsTreeUpdater = function(treeOutline) { WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.NodeInserted, this._nodeInserted, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.NodeRemoved, this._nodeRemoved, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrModified, this._attributesUpdated, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrRemoved, this._attributesUpdated, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.CharacterDataModified, this._characterDataModified, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.DocumentUpdated, this._documentUpdated, this); WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.ChildNodeCountUpdated, this._childNodeCountUpdated, this); this._treeOutline = treeOutline; this._recentlyModifiedNodes = new Map(); } WebInspector.ElementsTreeUpdater.prototype = { /** * @param {!WebInspector.DOMNode} node * @param {boolean} isUpdated * @param {WebInspector.DOMNode=} parentNode */ _nodeModified: function(node, isUpdated, parentNode) { if (this._treeOutline._visible) this._updateModifiedNodesSoon(); var entry = /** @type {WebInspector.ElementsTreeUpdater.UpdateEntry} */ (this._recentlyModifiedNodes.get(node)); if (!entry) { entry = new WebInspector.ElementsTreeUpdater.UpdateEntry(isUpdated, parentNode); this._recentlyModifiedNodes.put(node, entry); return; } entry.isUpdated |= isUpdated; if (parentNode) entry.parent = parentNode; }, _documentUpdated: function(event) { var inspectedRootDocument = event.data; this._reset(); if (!inspectedRootDocument) return; this._treeOutline.rootDOMNode = inspectedRootDocument; }, _attributesUpdated: function(event) { this._nodeModified(event.data.node, true); }, _characterDataModified: function(event) { this._nodeModified(event.data, true); }, _nodeInserted: function(event) { this._nodeModified(event.data, false, event.data.parentNode); }, _nodeRemoved: function(event) { this._nodeModified(event.data.node, false, event.data.parent); }, _childNodeCountUpdated: function(event) { var treeElement = this._treeOutline.findTreeElement(event.data); if (treeElement) treeElement.hasChildren = event.data.hasChildNodes(); }, _updateModifiedNodesSoon: function() { if (this._updateModifiedNodesTimeout) return; this._updateModifiedNodesTimeout = setTimeout(this._updateModifiedNodes.bind(this), 50); }, _updateModifiedNodes: function() { if (this._updateModifiedNodesTimeout) { clearTimeout(this._updateModifiedNodesTimeout); delete this._updateModifiedNodesTimeout; } var updatedParentTreeElements = []; var hidePanelWhileUpdating = this._recentlyModifiedNodes.size() > 10; if (hidePanelWhileUpdating) { var treeOutlineContainerElement = this._treeOutline.element.parentNode; this._treeOutline.element.addStyleClass("hidden"); var originalScrollTop = treeOutlineContainerElement ? treeOutlineContainerElement.scrollTop : 0; } var keys = this._recentlyModifiedNodes.keys(); for (var i = 0, size = keys.length; i < size; ++i) { var node = keys[i]; var entry = this._recentlyModifiedNodes.get(node); var parent = entry.parent; if (parent === this._treeOutline._rootDOMNode) { // Document's children have changed, perform total update. this._treeOutline.update(); this._treeOutline.element.removeStyleClass("hidden"); return; } if (entry.isUpdated) { var nodeItem = this._treeOutline.findTreeElement(node); if (nodeItem) nodeItem.updateTitle(); } if (!parent) continue; var parentNodeItem = this._treeOutline.findTreeElement(parent); if (parentNodeItem && !parentNodeItem.alreadyUpdatedChildren) { parentNodeItem.updateChildren(); parentNodeItem.alreadyUpdatedChildren = true; updatedParentTreeElements.push(parentNodeItem); } } for (var i = 0; i < updatedParentTreeElements.length; ++i) delete updatedParentTreeElements[i].alreadyUpdatedChildren; if (hidePanelWhileUpdating) { this._treeOutline.element.removeStyleClass("hidden"); if (originalScrollTop) treeOutlineContainerElement.scrollTop = originalScrollTop; this._treeOutline.updateSelection(); } this._recentlyModifiedNodes.clear(); }, _reset: function() { this._treeOutline.rootDOMNode = null; this._treeOutline.selectDOMNode(null, false); WebInspector.domAgent.hideDOMNodeHighlight(); this._recentlyModifiedNodes.clear(); } } /** * @constructor * @param {boolean} isUpdated * @param {WebInspector.DOMNode=} parent */ WebInspector.ElementsTreeUpdater.UpdateEntry = function(isUpdated, parent) { this.isUpdated = isUpdated; if (parent) this.parent = parent; }
bsd-3-clause
rprata/boost
boost/atomic/detail/ops_gcc_x86_dcas.hpp
11618
/* * 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) * * Copyright (c) 2009 Helge Bahmann * Copyright (c) 2012 Tim Blechmann * Copyright (c) 2014 Andrey Semashev */ /*! * \file atomic/detail/ops_gcc_x86_dcas.hpp * * This header contains implementation of the double-width CAS primitive for x86. */ #ifndef BOOST_ATOMIC_DETAIL_OPS_GCC_X86_DCAS_HPP_INCLUDED_ #define BOOST_ATOMIC_DETAIL_OPS_GCC_X86_DCAS_HPP_INCLUDED_ #include <boost/cstdint.hpp> #include <boost/memory_order.hpp> #include <boost/atomic/detail/config.hpp> #include <boost/atomic/detail/storage_type.hpp> #include <boost/atomic/capabilities.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { namespace atomics { namespace detail { #if defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG8B) template< bool Signed > struct gcc_dcas_x86 { typedef typename make_storage_type< 8u, Signed >::type storage_type; static BOOST_FORCEINLINE void store(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { if ((((uint32_t)&storage) & 0x00000007) == 0) { #if defined(__SSE2__) __asm__ __volatile__ ( #if defined(__AVX__) "vmovq %1, %%xmm4\n\t" "vmovq %%xmm4, %0\n\t" #else "movq %1, %%xmm4\n\t" "movq %%xmm4, %0\n\t" #endif : "=m" (storage) : "m" (v) : "memory", "xmm4" ); #else __asm__ __volatile__ ( "fildll %1\n\t" "fistpll %0\n\t" : "=m" (storage) : "m" (v) : "memory" ); #endif } else { #if defined(__PIC__) uint32_t scratch; __asm__ __volatile__ ( "movl %%ebx, %[scratch]\n\t" "movl %[value_lo], %%ebx\n\t" "movl 0(%[dest]), %%eax\n\t" "movl 4(%[dest]), %%edx\n\t" ".align 16\n\t" "1: lock; cmpxchg8b 0(%[dest])\n\t" "jne 1b\n\t" "movl %[scratch], %%ebx" #if !defined(BOOST_ATOMIC_DETAIL_NO_ASM_CONSTRAINT_ALTERNATIVES) : [scratch] "=m,m" (scratch) : [value_lo] "a,a" ((uint32_t)v), "c,c" ((uint32_t)(v >> 32)), [dest] "D,S" (&storage) #else : [scratch] "=m" (scratch) : [value_lo] "a" ((uint32_t)v), "c" ((uint32_t)(v >> 32)), [dest] "D" (&storage) #endif : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "edx", "memory" ); #else __asm__ __volatile__ ( "movl 0(%[dest]), %%eax\n\t" "movl 4(%[dest]), %%edx\n\t" ".align 16\n\t" "1: lock; cmpxchg8b 0(%[dest])\n\t" "jne 1b\n\t" : #if !defined(BOOST_ATOMIC_DETAIL_NO_ASM_CONSTRAINT_ALTERNATIVES) : [value_lo] "b,b" ((uint32_t)v), "c,c" ((uint32_t)(v >> 32)), [dest] "D,S" (&storage) #else : [value_lo] "b" ((uint32_t)v), "c" ((uint32_t)(v >> 32)), [dest] "D" (&storage) #endif : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "eax", "edx", "memory" ); #endif } } static BOOST_FORCEINLINE storage_type load(storage_type const volatile& storage, memory_order) BOOST_NOEXCEPT { storage_type value; if ((((uint32_t)&storage) & 0x00000007) == 0) { #if defined(__SSE2__) __asm__ __volatile__ ( #if defined(__AVX__) "vmovq %1, %%xmm4\n\t" "vmovq %%xmm4, %0\n\t" #else "movq %1, %%xmm4\n\t" "movq %%xmm4, %0\n\t" #endif : "=m" (value) : "m" (storage) : "memory", "xmm4" ); #else __asm__ __volatile__ ( "fildll %1\n\t" "fistpll %0\n\t" : "=m" (value) : "m" (storage) : "memory" ); #endif } else { #if defined(__clang__) // Clang cannot allocate eax:edx register pairs but it has sync intrinsics value = __sync_val_compare_and_swap(&storage, (storage_type)0, (storage_type)0); #else // We don't care for comparison result here; the previous value will be stored into value anyway. // Also we don't care for ebx and ecx values, they just have to be equal to eax and edx before cmpxchg8b. __asm__ __volatile__ ( "movl %%ebx, %%eax\n\t" "movl %%ecx, %%edx\n\t" "lock; cmpxchg8b %[storage]" : "=&A" (value) : [storage] "m" (storage) : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); #endif } return value; } static BOOST_FORCEINLINE bool compare_exchange_strong( storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order, memory_order) BOOST_NOEXCEPT { #if defined(__clang__) // Clang cannot allocate eax:edx register pairs but it has sync intrinsics storage_type old_expected = expected; expected = __sync_val_compare_and_swap(&storage, old_expected, desired); return expected == old_expected; #elif defined(__PIC__) // Make sure ebx is saved and restored properly in case // of position independent code. To make this work // setup register constraints such that ebx can not be // used by accident e.g. as base address for the variable // to be modified. Accessing "scratch" should always be okay, // as it can only be placed on the stack (and therefore // accessed through ebp or esp only). // // In theory, could push/pop ebx onto/off the stack, but movs // to a prepared stack slot turn out to be faster. uint32_t scratch; bool success; __asm__ __volatile__ ( "movl %%ebx, %[scratch]\n\t" "movl %[desired_lo], %%ebx\n\t" "lock; cmpxchg8b %[dest]\n\t" "movl %[scratch], %%ebx\n\t" "sete %[success]" #if !defined(BOOST_ATOMIC_DETAIL_NO_ASM_CONSTRAINT_ALTERNATIVES) : "+A,A,A,A,A,A" (expected), [dest] "+m,m,m,m,m,m" (storage), [scratch] "=m,m,m,m,m,m" (scratch), [success] "=q,m,q,m,q,m" (success) : [desired_lo] "S,S,D,D,m,m" ((uint32_t)desired), "c,c,c,c,c,c" ((uint32_t)(desired >> 32)) #else : "+A" (expected), [dest] "+m" (storage), [scratch] "=m" (scratch), [success] "=q" (success) : [desired_lo] "S" ((uint32_t)desired), "c" ((uint32_t)(desired >> 32)) #endif : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); return success; #else bool success; __asm__ __volatile__ ( "lock; cmpxchg8b %[dest]\n\t" "sete %[success]" #if !defined(BOOST_ATOMIC_DETAIL_NO_ASM_CONSTRAINT_ALTERNATIVES) : "+A,A" (expected), [dest] "+m,m" (storage), [success] "=q,m" (success) : "b,b" ((uint32_t)desired), "c,c" ((uint32_t)(desired >> 32)) #else : "+A" (expected), [dest] "+m" (storage), [success] "=q" (success) : "b" ((uint32_t)desired), "c" ((uint32_t)(desired >> 32)) #endif : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); return success; #endif } static BOOST_FORCEINLINE bool compare_exchange_weak( storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order success_order, memory_order failure_order) BOOST_NOEXCEPT { return compare_exchange_strong(storage, expected, desired, success_order, failure_order); } static BOOST_FORCEINLINE bool is_lock_free(storage_type const volatile&) BOOST_NOEXCEPT { return true; } }; #endif // defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG8B) #if defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG16B) template< bool Signed > struct gcc_dcas_x86_64 { typedef typename make_storage_type< 16u, Signed >::type storage_type; static BOOST_FORCEINLINE void store(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { uint64_t const* p_value = (uint64_t const*)&v; __asm__ __volatile__ ( "movq 0(%[dest]), %%rax\n\t" "movq 8(%[dest]), %%rdx\n\t" ".align 16\n\t" "1: lock; cmpxchg16b 0(%[dest])\n\t" "jne 1b" : : "b" (p_value[0]), "c" (p_value[1]), [dest] "r" (&storage) : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "rax", "rdx", "memory" ); } static BOOST_FORCEINLINE storage_type load(storage_type const volatile& storage, memory_order) BOOST_NOEXCEPT { #if defined(__clang__) // Clang cannot allocate rax:rdx register pairs but it has sync intrinsics storage_type value = storage_type(); return __sync_val_compare_and_swap(&storage, value, value); #else storage_type value; // We don't care for comparison result here; the previous value will be stored into value anyway. // Also we don't care for rbx and rcx values, they just have to be equal to rax and rdx before cmpxchg16b. __asm__ __volatile__ ( "movq %%rbx, %%rax\n\t" "movq %%rcx, %%rdx\n\t" "lock; cmpxchg16b %[storage]" : "=&A" (value) : [storage] "m" (storage) : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); return value; #endif } static BOOST_FORCEINLINE bool compare_exchange_strong( storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order, memory_order) BOOST_NOEXCEPT { #if defined(__clang__) // Clang cannot allocate rax:rdx register pairs but it has sync intrinsics storage_type old_expected = expected; expected = __sync_val_compare_and_swap(&storage, old_expected, desired); return expected == old_expected; #else uint64_t const* p_desired = (uint64_t const*)&desired; bool success; __asm__ __volatile__ ( "lock; cmpxchg16b %[dest]\n\t" "sete %[success]" #if !defined(BOOST_ATOMIC_DETAIL_NO_ASM_CONSTRAINT_ALTERNATIVES) : "+A,A" (expected), [dest] "+m,m" (storage), [success] "=q,m" (success) : "b,b" (p_desired[0]), "c,c" (p_desired[1]) #else : "+A" (expected), [dest] "+m" (storage), [success] "=q" (success) : "b" (p_desired[0]), "c" (p_desired[1]) #endif : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); return success; #endif } static BOOST_FORCEINLINE bool compare_exchange_weak( storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order success_order, memory_order failure_order) BOOST_NOEXCEPT { return compare_exchange_strong(storage, expected, desired, success_order, failure_order); } static BOOST_FORCEINLINE bool is_lock_free(storage_type const volatile&) BOOST_NOEXCEPT { return true; } }; #endif // defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG16B) } // namespace detail } // namespace atomics } // namespace boost #endif // BOOST_ATOMIC_DETAIL_OPS_GCC_X86_DCAS_HPP_INCLUDED_
gpl-2.0
iivic/BoiseStateX
common/djangoapps/student/cookies.py
5305
""" Utility functions for setting "logged in" cookies used by subdomains. """ import time import json from django.utils.http import cookie_date from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch def set_logged_in_cookies(request, response, user): """ Set cookies indicating that the user is logged in. Some installations have an external marketing site configured that displays a different UI when the user is logged in (e.g. a link to the student dashboard instead of to the login page) Currently, two cookies are set: * EDXMKTG_LOGGED_IN_COOKIE_NAME: Set to 'true' if the user is logged in. * EDXMKTG_USER_INFO_COOKIE_VERSION: JSON-encoded dictionary with user information (see below). The user info cookie has the following format: { "version": 1, "username": "test-user", "email": "[email protected]", "header_urls": { "account_settings": "https://example.com/account/settings", "learner_profile": "https://example.com/u/test-user", "logout": "https://example.com/logout" } } Arguments: request (HttpRequest): The request to the view, used to calculate the cookie's expiration date based on the session expiration date. response (HttpResponse): The response on which the cookie will be set. user (User): The currently logged in user. Returns: HttpResponse """ if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = cookie_date(expires_time) cookie_settings = { 'max_age': max_age, 'expires': expires, 'domain': settings.SESSION_COOKIE_DOMAIN, 'path': '/', 'httponly': None, } # Backwards compatibility: set the cookie indicating that the user # is logged in. This is just a boolean value, so it's not very useful. # In the future, we should be able to replace this with the "user info" # cookie set below. response.set_cookie( settings.EDXMKTG_LOGGED_IN_COOKIE_NAME.encode('utf-8'), 'true', secure=None, **cookie_settings ) # Set a cookie with user info. This can be used by external sites # to customize content based on user information. Currently, # we include information that's used to customize the "account" # links in the header of subdomain sites (such as the marketing site). header_urls = {'logout': reverse('logout')} # Unfortunately, this app is currently used by both the LMS and Studio login pages. # If we're in Studio, we won't be able to reverse the account/profile URLs. # To handle this, we don't add the URLs if we can't reverse them. # External sites will need to have fallback mechanisms to handle this case # (most likely just hiding the links). try: header_urls['account_settings'] = reverse('account_settings') header_urls['learner_profile'] = reverse('learner_profile', kwargs={'username': user.username}) except NoReverseMatch: pass # Convert relative URL paths to absolute URIs for url_name, url_path in header_urls.iteritems(): header_urls[url_name] = request.build_absolute_uri(url_path) user_info = { 'version': settings.EDXMKTG_USER_INFO_COOKIE_VERSION, 'username': user.username, 'email': user.email, 'header_urls': header_urls, } # In production, TLS should be enabled so that this cookie is encrypted # when we send it. We also need to set "secure" to True so that the browser # will transmit it only over secure connections. # # In non-production environments (acceptance tests, devstack, and sandboxes), # we still want to set this cookie. However, we do NOT want to set it to "secure" # because the browser won't send it back to us. This can cause an infinite redirect # loop in the third-party auth flow, which calls `is_logged_in_cookie_set` to determine # whether it needs to set the cookie or continue to the next pipeline stage. user_info_cookie_is_secure = request.is_secure() response.set_cookie( settings.EDXMKTG_USER_INFO_COOKIE_NAME.encode('utf-8'), json.dumps(user_info), secure=user_info_cookie_is_secure, **cookie_settings ) return response def delete_logged_in_cookies(response): """ Delete cookies indicating that the user is logged in. Arguments: response (HttpResponse): The response sent to the client. Returns: HttpResponse """ for cookie_name in [settings.EDXMKTG_LOGGED_IN_COOKIE_NAME, settings.EDXMKTG_USER_INFO_COOKIE_NAME]: response.delete_cookie( cookie_name.encode('utf-8'), path='/', domain=settings.SESSION_COOKIE_DOMAIN ) return response def is_logged_in_cookie_set(request): """Check whether the request has logged in cookies set. """ return ( settings.EDXMKTG_LOGGED_IN_COOKIE_NAME in request.COOKIES and settings.EDXMKTG_USER_INFO_COOKIE_NAME in request.COOKIES )
agpl-3.0
sfluo/mrbot
crypto/pycrypto-2.6/build/lib.macosx-10.7-intel-2.7/Crypto/SelfTest/Random/Fortuna/test_FortunaAccumulator.py
8612
# -*- coding: utf-8 -*- # # SelfTest/Random/Fortuna/test_FortunaAccumulator.py: Self-test for the FortunaAccumulator module # # Written in 2008 by Dwayne C. Litzenberger <[email protected]> # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== """Self-tests for Crypto.Random.Fortuna.FortunaAccumulator""" __revision__ = "$Id$" import sys if sys.version_info[0] == 2 and sys.version_info[1] == 1: from Crypto.Util.py21compat import * from Crypto.Util.py3compat import * import unittest from binascii import b2a_hex class FortunaAccumulatorTests(unittest.TestCase): def setUp(self): global FortunaAccumulator from Crypto.Random.Fortuna import FortunaAccumulator def test_FortunaPool(self): """FortunaAccumulator.FortunaPool""" pool = FortunaAccumulator.FortunaPool() self.assertEqual(0, pool.length) self.assertEqual("5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456", pool.hexdigest()) pool.append(b('abc')) self.assertEqual(3, pool.length) self.assertEqual("4f8b42c22dd3729b519ba6f68d2da7cc5b2d606d05daed5ad5128cc03e6c6358", pool.hexdigest()) pool.append(b("dbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")) self.assertEqual(56, pool.length) self.assertEqual(b('0cffe17f68954dac3a84fb1458bd5ec99209449749b2b308b7cb55812f9563af'), b2a_hex(pool.digest())) pool.reset() self.assertEqual(0, pool.length) pool.append(b('a') * 10**6) self.assertEqual(10**6, pool.length) self.assertEqual(b('80d1189477563e1b5206b2749f1afe4807e5705e8bd77887a60187a712156688'), b2a_hex(pool.digest())) def test_which_pools(self): """FortunaAccumulator.which_pools""" # which_pools(0) should fail self.assertRaises(AssertionError, FortunaAccumulator.which_pools, 0) self.assertEqual(FortunaAccumulator.which_pools(1), [0]) self.assertEqual(FortunaAccumulator.which_pools(2), [0, 1]) self.assertEqual(FortunaAccumulator.which_pools(3), [0]) self.assertEqual(FortunaAccumulator.which_pools(4), [0, 1, 2]) self.assertEqual(FortunaAccumulator.which_pools(5), [0]) self.assertEqual(FortunaAccumulator.which_pools(6), [0, 1]) self.assertEqual(FortunaAccumulator.which_pools(7), [0]) self.assertEqual(FortunaAccumulator.which_pools(8), [0, 1, 2, 3]) for i in range(1, 32): self.assertEqual(FortunaAccumulator.which_pools(2L**i-1), [0]) self.assertEqual(FortunaAccumulator.which_pools(2L**i), range(i+1)) self.assertEqual(FortunaAccumulator.which_pools(2L**i+1), [0]) self.assertEqual(FortunaAccumulator.which_pools(2L**31), range(32)) self.assertEqual(FortunaAccumulator.which_pools(2L**32), range(32)) self.assertEqual(FortunaAccumulator.which_pools(2L**33), range(32)) self.assertEqual(FortunaAccumulator.which_pools(2L**34), range(32)) self.assertEqual(FortunaAccumulator.which_pools(2L**35), range(32)) self.assertEqual(FortunaAccumulator.which_pools(2L**36), range(32)) self.assertEqual(FortunaAccumulator.which_pools(2L**64), range(32)) self.assertEqual(FortunaAccumulator.which_pools(2L**128), range(32)) def test_accumulator(self): """FortunaAccumulator.FortunaAccumulator""" fa = FortunaAccumulator.FortunaAccumulator() # This should fail, because we haven't seeded the PRNG yet self.assertRaises(AssertionError, fa.random_data, 1) # Spread some test data across the pools (source number 42) # This would be horribly insecure in a real system. for p in range(32): fa.add_random_event(42, p, b("X") * 32) self.assertEqual(32+2, fa.pools[p].length) # This should still fail, because we haven't seeded the PRNG with 64 bytes yet self.assertRaises(AssertionError, fa.random_data, 1) # Add more data for p in range(32): fa.add_random_event(42, p, b("X") * 32) self.assertEqual((32+2)*2, fa.pools[p].length) # The underlying RandomGenerator should get seeded with Pool 0 # s = SHAd256(chr(42) + chr(32) + "X"*32 + chr(42) + chr(32) + "X"*32) # = SHA256(h'edd546f057b389155a31c32e3975e736c1dec030ddebb137014ecbfb32ed8c6f') # = h'aef42a5dcbddab67e8efa118e1b47fde5d697f89beb971b99e6e8e5e89fbf064' # The counter and the key before reseeding is: # C_0 = 0 # K_0 = "\x00" * 32 # The counter after reseeding is 1, and the new key after reseeding is # C_1 = 1 # K_1 = SHAd256(K_0 || s) # = SHA256(h'0eae3e401389fab86640327ac919ecfcb067359d95469e18995ca889abc119a6') # = h'aafe9d0409fbaaafeb0a1f2ef2014a20953349d3c1c6e6e3b962953bea6184dd' # The first block of random data, therefore, is # r_1 = AES-256(K_1, 1) # = AES-256(K_1, h'01000000000000000000000000000000') # = h'b7b86bd9a27d96d7bb4add1b6b10d157' # The second block of random data is # r_2 = AES-256(K_1, 2) # = AES-256(K_1, h'02000000000000000000000000000000') # = h'2350b1c61253db2f8da233be726dc15f' # The third and fourth blocks of random data (which become the new key) are # r_3 = AES-256(K_1, 3) # = AES-256(K_1, h'03000000000000000000000000000000') # = h'f23ad749f33066ff53d307914fbf5b21' # r_4 = AES-256(K_1, 4) # = AES-256(K_1, h'04000000000000000000000000000000') # = h'da9667c7e86ba247655c9490e9d94a7c' # K_2 = r_3 || r_4 # = h'f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c' # The final counter value is 5. self.assertEqual("aef42a5dcbddab67e8efa118e1b47fde5d697f89beb971b99e6e8e5e89fbf064", fa.pools[0].hexdigest()) self.assertEqual(None, fa.generator.key) self.assertEqual(0, fa.generator.counter.next_value()) result = fa.random_data(32) self.assertEqual(b("b7b86bd9a27d96d7bb4add1b6b10d157" "2350b1c61253db2f8da233be726dc15f"), b2a_hex(result)) self.assertEqual(b("f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c"), b2a_hex(fa.generator.key)) self.assertEqual(5, fa.generator.counter.next_value()) def test_accumulator_pool_length(self): """FortunaAccumulator.FortunaAccumulator minimum pool length""" fa = FortunaAccumulator.FortunaAccumulator() # This test case is hard-coded to assume that FortunaAccumulator.min_pool_size is 64. self.assertEqual(fa.min_pool_size, 64) # The PRNG should not allow us to get random data from it yet self.assertRaises(AssertionError, fa.random_data, 1) # Add 60 bytes, 4 at a time (2 header + 2 payload) to each of the 32 pools for i in range(15): for p in range(32): # Add the bytes to the pool fa.add_random_event(2, p, b("XX")) # The PRNG should not allow us to get random data from it yet self.assertRaises(AssertionError, fa.random_data, 1) # Add 4 more bytes to pool 0 fa.add_random_event(2, 0, b("XX")) # We should now be able to get data from the accumulator fa.random_data(1) def get_tests(config={}): from Crypto.SelfTest.st_common import list_test_cases return list_test_cases(FortunaAccumulatorTests) if __name__ == '__main__': suite = lambda: unittest.TestSuite(get_tests()) unittest.main(defaultTest='suite') # vim:set ts=4 sw=4 sts=4 expandtab:
bsd-3-clause
jleonhard/angular2-webpack-jquery-bootstrap
node_modules/tslint/lib/formatters.d.ts
716
/** * @license * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export * from "./language/formatter/abstractFormatter"; export * from "./formatters/index";
mit
diegopacheco/scala-playground
caliban-graphql-fun/src/main/resources/gateway/node_modules/core-js/modules/es.string.ends-with.js
1549
'use strict'; var $ = require('../internals/export'); var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; var toLength = require('../internals/to-length'); var notARegExp = require('../internals/not-a-regexp'); var requireObjectCoercible = require('../internals/require-object-coercible'); var correctIsRegExpLogic = require('../internals/correct-is-regexp-logic'); var IS_PURE = require('../internals/is-pure'); var nativeEndsWith = ''.endsWith; var min = Math.min; var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('endsWith'); // https://github.com/zloirock/core-js/pull/702 var MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () { var descriptor = getOwnPropertyDescriptor(String.prototype, 'endsWith'); return descriptor && !descriptor.writable; }(); // `String.prototype.endsWith` method // https://tc39.github.io/ecma262/#sec-string.prototype.endswith $({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, { endsWith: function endsWith(searchString /* , endPosition = @length */) { var that = String(requireObjectCoercible(this)); notARegExp(searchString); var endPosition = arguments.length > 1 ? arguments[1] : undefined; var len = toLength(that.length); var end = endPosition === undefined ? len : min(toLength(endPosition), len); var search = String(searchString); return nativeEndsWith ? nativeEndsWith.call(that, search, end) : that.slice(end - search.length, end) === search; } });
unlicense
Dokaponteam/ITF_Project
php/pear/adodb/session/adodb-encrypt-md5.php
751
<?php /* V5.18 3 Sep 2012 (c) 2000-2012 John Lim (jlim#natsoft.com). All rights reserved. Contributed by Ross Smith ([email protected]). Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. Set tabs to 4 for best viewing. */ // security - hide paths if (!defined('ADODB_SESSION')) die(); include_once ADODB_SESSION . '/crypt.inc.php'; /** */ class ADODB_Encrypt_MD5 { /** */ function write($data, $key) { $md5crypt = new MD5Crypt(); return $md5crypt->encrypt($data, $key); } /** */ function read($data, $key) { $md5crypt = new MD5Crypt(); return $md5crypt->decrypt($data, $key); } } return 1; ?>
mit
SirWellington/thrift
lib/nodejs/lib/thrift/binary.js
3661
/* * 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. */ var POW_8 = Math.pow(2, 8); var POW_16 = Math.pow(2, 16); var POW_24 = Math.pow(2, 24); var POW_32 = Math.pow(2, 32); var POW_40 = Math.pow(2, 40); var POW_48 = Math.pow(2, 48); var POW_52 = Math.pow(2, 52); var POW_1022 = Math.pow(2, 1022); exports.readByte = function(b){ return b > 127 ? b-256 : b; }; exports.readI16 = function(buff, off) { off = off || 0; var v = buff[off + 1]; v += buff[off] << 8; if (buff[off] & 128) { v -= POW_16; } return v; }; exports.readI32 = function(buff, off) { off = off || 0; var v = buff[off + 3]; v += buff[off + 2] << 8; v += buff[off + 1] << 16; v += buff[off] * POW_24; if (buff[off] & 0x80) { v -= POW_32; } return v; }; exports.writeI16 = function(buff, v) { buff[1] = v & 0xff; v >>= 8; buff[0] = v & 0xff; return buff; }; exports.writeI32 = function(buff, v) { buff[3] = v & 0xff; v >>= 8; buff[2] = v & 0xff; v >>= 8; buff[1] = v & 0xff; v >>= 8; buff[0] = v & 0xff; return buff; }; exports.readDouble = function(buff, off) { off = off || 0; var signed = buff[off] & 0x80; var e = (buff[off+1] & 0xF0) >> 4; e += (buff[off] & 0x7F) << 4; var m = buff[off+7]; m += buff[off+6] << 8; m += buff[off+5] << 16; m += buff[off+4] * POW_24; m += buff[off+3] * POW_32; m += buff[off+2] * POW_40; m += (buff[off+1] & 0x0F) * POW_48; switch (e) { case 0: e = -1022; break; case 2047: return m ? NaN : (signed ? -Infinity : Infinity); default: m += POW_52; e -= 1023; } if (signed) { m *= -1; } return m * Math.pow(2, e - 52); }; /* * Based on code from the jspack module: * http://code.google.com/p/jspack/ */ exports.writeDouble = function(buff, v) { var m, e, c; buff[0] = (v < 0 ? 0x80 : 0x00); v = Math.abs(v); if (v !== v) { // NaN, use QNaN IEEE format m = 2251799813685248; e = 2047; } else if (v === Infinity) { m = 0; e = 2047; } else { e = Math.floor(Math.log(v) / Math.LN2); c = Math.pow(2, -e); if (v * c < 1) { e--; c *= 2; } if (e + 1023 >= 2047) { // Overflow m = 0; e = 2047; } else if (e + 1023 >= 1) { // Normalized - term order matters, as Math.pow(2, 52-e) and v*Math.pow(2, 52) can overflow m = (v*c-1) * POW_52; e += 1023; } else { // Denormalized - also catches the '0' case, somewhat by chance m = (v * POW_1022) * POW_52; e = 0; } } buff[1] = (e << 4) & 0xf0; buff[0] |= (e >> 4) & 0x7f; buff[7] = m & 0xff; m = Math.floor(m / POW_8); buff[6] = m & 0xff; m = Math.floor(m / POW_8); buff[5] = m & 0xff; m = Math.floor(m / POW_8); buff[4] = m & 0xff; m >>= 8; buff[3] = m & 0xff; m >>= 8; buff[2] = m & 0xff; m >>= 8; buff[1] |= m & 0x0f; return buff; };
apache-2.0
emarchak/symfony2_training
vendor/jms/di-extra-bundle/JMS/DiExtraBundle/Tests/DependencyInjection/Compiler/LazyServiceSequencePassTest.php
1360
<?php namespace JMS\DiExtraBundle\Tests\DependencyInjection\Compiler; use JMS\DiExtraBundle\DependencyInjection\Compiler\LazyServiceSequencePass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; class LazyServiceSequencePassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { $called = false; $self = $this; $pass = new LazyServiceSequencePass('tag', function(ContainerBuilder $container, Definition $def) use (&$called, $self) { $self->assertFalse($called); $called = true; $self->assertEquals(new Reference('service_container'), $def->getArgument(0)); $self->assertEquals(array('foo', 'bar'), $def->getArgument(1)); }); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder') ->disableOriginalConstructor() ->setMethods(array('findTaggedServiceIds')) ->getMock(); $container->expects($this->once()) ->method('findTaggedServiceIds') ->with('tag') ->will($this->returnValue(array('foo' => array(), 'bar' => array()))); $pass->process($container); $this->assertTrue($called); } }
mit
jkburges/phantomjs
src/qt/qtwebkit/Source/WebCore/Modules/mediasource/MediaSourceRegistry.cpp
2754
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "MediaSourceRegistry.h" #if ENABLE(MEDIA_SOURCE) #include "KURL.h" #include "MediaSource.h" #include <wtf/MainThread.h> namespace WebCore { MediaSourceRegistry& MediaSourceRegistry::registry() { ASSERT(isMainThread()); DEFINE_STATIC_LOCAL(MediaSourceRegistry, instance, ()); return instance; } void MediaSourceRegistry::registerMediaSourceURL(const KURL& url, PassRefPtr<MediaSource> source) { ASSERT(isMainThread()); source->setPendingActivity(source.get()); m_mediaSources.set(url.string(), source); } void MediaSourceRegistry::unregisterMediaSourceURL(const KURL& url) { ASSERT(isMainThread()); HashMap<String, RefPtr<MediaSource> >::iterator iter = m_mediaSources.find(url.string()); if (iter == m_mediaSources.end()) return; RefPtr<MediaSource> source = iter->value; m_mediaSources.remove(iter); // Remove the pending activity added in registerMediaSourceURL(). source->unsetPendingActivity(source.get()); } MediaSource* MediaSourceRegistry::lookupMediaSource(const String& url) { ASSERT(isMainThread()); return m_mediaSources.get(url).get(); } } // namespace WebCore #endif
bsd-3-clause
Magik3a/PatientManagement_Admin
PatientManagement.Reservation/PatientManagement.Reservation.Web.Mvc/wwwroot/lib/jquery-sparkline/src/chart-discrete.js
2837
/** * Discrete charts */ $.fn.sparkline.discrete = discrete = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'discrete', init: function (el, values, options, width, height) { discrete._super.init.call(this, el, values, options, width, height); this.regionShapes = {}; this.values = values = $.map(values, Number); this.min = Math.min.apply(Math, values); this.max = Math.max.apply(Math, values); this.range = this.max - this.min; this.width = width = options.get('width') === 'auto' ? values.length * 2 : this.width; this.interval = Math.floor(width / values.length); this.itemWidth = width / values.length; if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.min)) { this.min = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.max)) { this.max = options.get('chartRangeMax'); } this.initTarget(); if (this.target) { this.lineHeight = options.get('lineHeight') === 'auto' ? Math.round(this.canvasHeight * 0.3) : options.get('lineHeight'); } }, getRegion: function (el, x, y) { return Math.floor(x / this.itemWidth); }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], offset: currentRegion }; }, renderRegion: function (valuenum, highlight) { var values = this.values, options = this.options, min = this.min, max = this.max, range = this.range, interval = this.interval, target = this.target, canvasHeight = this.canvasHeight, lineHeight = this.lineHeight, pheight = canvasHeight - lineHeight, ytop, val, color, x; val = clipval(values[valuenum], min, max); x = valuenum * interval; ytop = Math.round(pheight - pheight * ((val - min) / range)); color = (options.get('thresholdColor') && val < options.get('thresholdValue')) ? options.get('thresholdColor') : options.get('lineColor'); if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawLine(x, ytop, x, ytop + lineHeight, color); } });
mit
cunningt/camel
components/camel-spark-rest/src/test/java/org/apache/camel/component/sparkrest/UserService.java
1220
/** * 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.sparkrest; public class UserService { public CountryPojo livesWhere(UserPojo user) { CountryPojo answer = new CountryPojo(); if (user.getId() < 500) { answer.setIso("EN"); answer.setCountry("England"); } else { answer.setIso("SE"); answer.setCountry("Sweden"); } return answer; } }
apache-2.0
sleepinglion/sleepinglion
node_modules/core-js/features/weak-map/of.js
417
'use strict'; require('../../modules/es.string.iterator'); require('../../modules/es.weak-map'); require('../../modules/esnext.weak-map.of'); require('../../modules/web.dom-collections.iterator'); var path = require('../../internals/path'); var WeakMap = path.WeakMap; var weakMapOf = WeakMap.of; module.exports = function of() { return weakMapOf.apply(typeof this === 'function' ? this : WeakMap, arguments); };
mit
hqstevenson/camel
camel-core/src/test/java/org/apache/camel/processor/TryProcessorHandleWrappedExceptionTest.java
2919
/** * 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.processor; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; /** * Unit test for try .. handle routing where it should handle wrapped exceptions as well. */ public class TryProcessorHandleWrappedExceptionTest extends ContextTestSupport { private boolean handled; public void testTryCatchFinally() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); getMockEndpoint("mock:finally").expectedMessageCount(1); sendBody("direct:start", "<test>Hello World!</test>"); assertTrue("Should have been handled", handled); assertMockEndpointsSatisfied(); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start") .doTry() .process(new ProcessorFail()) .to("mock:result") .doCatch(IllegalStateException.class) .process(new ProcessorHandle()) .doFinally() .to("mock:finally") .end(); } }; } private class ProcessorFail implements Processor { public void process(Exchange exchange) throws Exception { throw new IllegalStateException("Force to fail"); } } private class ProcessorHandle implements Processor { public void process(Exchange exchange) throws Exception { handled = true; assertEquals("Should not be marked as failed", false, exchange.isFailed()); Exception e = (Exception)exchange.getProperty(Exchange.EXCEPTION_CAUGHT); assertNotNull("There should be an exception", e); assertTrue(e instanceof IllegalStateException); assertEquals("Force to fail", e.getMessage()); } } }
apache-2.0
alnahian/government
src/Orchard.Web/Modules/Orchard.Recipes/Services/RecipeStepQueue.cs
3676
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Orchard.FileSystems.AppData; using Orchard.Localization; using Orchard.Logging; using Orchard.Recipes.Models; namespace Orchard.Recipes.Services { public class RecipeStepQueue : IRecipeStepQueue { private readonly IAppDataFolder _appDataFolder; private readonly string _recipeQueueFolder = "RecipeQueue" + Path.DirectorySeparatorChar; public RecipeStepQueue(IAppDataFolder appDataFolder) { _appDataFolder = appDataFolder; Logger = NullLogger.Instance; T = NullLocalizer.Instance; } public Localizer T { get; set; } public ILogger Logger { get; set; } public void Enqueue(string executionId, RecipeStep step) { var recipeStepElement = new XElement("RecipeStep"); recipeStepElement.Add(new XElement("Name", step.Name)); recipeStepElement.Add(step.Step); if (_appDataFolder.DirectoryExists(Path.Combine(_recipeQueueFolder, executionId))) { int stepIndex = GetLastStepIndex(executionId) + 1; _appDataFolder.CreateFile(Path.Combine(_recipeQueueFolder, executionId + Path.DirectorySeparatorChar + stepIndex), recipeStepElement.ToString()); } else { _appDataFolder.CreateFile( Path.Combine(_recipeQueueFolder, executionId + Path.DirectorySeparatorChar + "0"), recipeStepElement.ToString()); } } public RecipeStep Dequeue(string executionId) { if (!_appDataFolder.DirectoryExists(Path.Combine(_recipeQueueFolder, executionId))) { return null; } RecipeStep recipeStep = null; int stepIndex = GetFirstStepIndex(executionId); if (stepIndex >= 0) { var stepPath = Path.Combine(_recipeQueueFolder, executionId + Path.DirectorySeparatorChar + stepIndex); // string to xelement var stepElement = XElement.Parse(_appDataFolder.ReadFile(stepPath)); var stepName = stepElement.Element("Name").Value; recipeStep = new RecipeStep { Name = stepName, Step = stepElement.Element(stepName) }; _appDataFolder.DeleteFile(stepPath); } if (stepIndex < 1) { _appDataFolder.DeleteFile(Path.Combine(_recipeQueueFolder, executionId)); } return recipeStep; } private int GetFirstStepIndex(string executionId) { var stepFiles = new List<string>(_appDataFolder.ListFiles(Path.Combine(_recipeQueueFolder, executionId))); if (stepFiles.Count == 0) return -1; var currentSteps = stepFiles.Select(stepFile => Int32.Parse(stepFile.Substring(stepFile.LastIndexOf('/') + 1))).ToList(); currentSteps.Sort(); return currentSteps[0]; } private int GetLastStepIndex(string executionId) { int lastIndex = -1; var stepFiles = _appDataFolder.ListFiles(Path.Combine(_recipeQueueFolder, executionId)); // we always have only a handful of steps. foreach (var stepFile in stepFiles) { int stepOrder = Int32.Parse(stepFile.Substring(stepFile.LastIndexOf('/') + 1)); if (stepOrder > lastIndex) lastIndex = stepOrder; } return lastIndex; } } }
bsd-3-clause
AlexGhiondea/coreclr
tests/src/Loader/classloader/generics/Layout/Specific/Negative004.cs
1354
// 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; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Auto)] public class GenBase<T> { T t; T Dummy(T t) { this.t = t; return t;} } [StructLayout(LayoutKind.Sequential)] public class GenInt : GenBase<int> { } public class GenTest { private GenInt InternalTest() { return new GenInt(); } private void IndirectTest() { InternalTest(); } public bool Test() { try { IndirectTest(); Console.WriteLine("Test did not throw expected TypeLoadException"); return false; } catch(TypeLoadException) { return true; } catch(Exception E) { Console.WriteLine("Test caught unexpected Exception " + E); return false; } } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Eval(new GenTest().Test()); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
mit
chai2/Midterm
node_modules/webpack/lib/DllModuleFactory.js
498
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; var Tapable = require("tapable"); var DllModule = require("./DllModule"); class DllModuleFactory extends Tapable { constructor() { super(); } create(data, callback) { const dependency = data.dependencies[0]; callback(null, new DllModule(data.context, dependency.dependencies, dependency.name, dependency.type)); } } module.exports = DllModuleFactory;
mit
pablopalillo/radio.tm
wp-content/plugins/better-wp-security/core/js/tracking.js
3380
if ( typeof itsec_tracking_vars != 'undefined' ) { href = location.href; (function () { var ga = document.createElement( 'script' ); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName( 'script' )[0]; s.parentNode.insertBefore( ga, s ); })(); var _gaq = _gaq || []; _gaq.push( ['_setAccount', 'UA-47645120-1'] ); function itsec_get_vars( type, values ) { var data = { action: 'itsec_tracking_ajax', type : type, nonce : itsec_tracking_vars.nonce }; if ( type != 'receive' ) { data.values = values; } jQuery.post( ajaxurl, data, function ( response ) { if ( response == 'false' ) { return false; } else { return true; } } ); } jQuery( document ).ready( function () { var tracking_settings = itsec_tracking_vars.vars; var track_it = new Array(); var timestamp = new Date().getTime(); jQuery( '.itsec-settings-form' ).submit( function ( event ) { var values = jQuery( this ).serializeArray(); jQuery.each( values, function ( name, value ) { var section = value.name.substring( 0, value.name.indexOf( '[' ) ); var setting = value.name.substring( value.name.indexOf( '[' ) + 1, value.name.indexOf( ']' ) ); if ( typeof tracking_settings[section] != 'undefined' && typeof tracking_settings[section][setting] != 'undefined' ) { var setting_value = tracking_settings[section][setting]; var value_array = setting_value.split( ':' ); var default_type = value_array[1]; if ( default_type == 'b' && value.value == 1 ) { var saved_value = 'true'; } else { if ( default_type == 'b' ) { var saved_value = 'false'; } else { var saved_value = value.value; } } delete tracking_settings[section][setting]; var item = new Object(); item.section = section; item.setting = setting; item.value = saved_value; track_it.push( item ); } } ); jQuery.each( tracking_settings, function ( section, settings ) { var section = section; jQuery.each( tracking_settings[section], function ( setting, value ) { var value_array = value.split( ':' ); var default_type = value_array[1]; var default_value = value_array[0]; if ( default_type == 'b' && default_value == 0 ) { var saved_value = 'false'; } else if ( default_type == 'b' ) { var saved_value = 'true'; } else { var saved_value = default_value; } var item = new Object(); item.section = section; item.setting = setting; item.value = saved_value; track_it.push( item ); } ); } ); var group_size = Math.ceil( track_it.length / 9 ); var group_count = 1; var count = 0; var saved_values = ''; jQuery.each( track_it, function ( setting, value ) { saved_value = ( value.section + '[' + value.setting + '] = ' + value.value + '; ') saved_values = saved_values.concat( saved_value ); if ( count === group_size - 1 ) { _gaq.push( ['_trackEvent', 'ITSEC', 'Group ' + ( group_count ), saved_values, timestamp, true] ); saved_values = ''; count = 0; group_count ++; } else { count ++; } } ); } ); } ); }
gpl-2.0
jeremyepling/TypeScript
tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve/main.ts
168
import * as ng from "angular2/core"; declare function foo(...args: any[]); @foo export class MyClass1 { constructor(private _elementRef: ng.ElementRef){} }
apache-2.0
klas/joomla-cms
administrator/components/com_login/views/login/view.html.php
390
<?php /** * @package Joomla.Administrator * @subpackage com_login * * @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** * HTML View class for the Login component * * @since 1.6 */ class LoginViewLogin extends JViewLegacy { }
gpl-2.0
lvdongr/spark
python/pyspark/mllib/stat/distribution.py
1263
# # 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. # from collections import namedtuple __all__ = ['MultivariateGaussian'] class MultivariateGaussian(namedtuple('MultivariateGaussian', ['mu', 'sigma'])): """Represents a (mu, sigma) tuple >>> m = MultivariateGaussian(Vectors.dense([11,12]),DenseMatrix(2, 2, (1.0, 3.0, 5.0, 2.0))) >>> (m.mu, m.sigma.toArray()) (DenseVector([11.0, 12.0]), array([[ 1., 5.],[ 3., 2.]])) >>> (m[0], m[1]) (DenseVector([11.0, 12.0]), array([[ 1., 5.],[ 3., 2.]])) """
apache-2.0
zachgersh/terraform
builtin/providers/aws/import_aws_ebs_volume_test.go
524
package aws import ( "testing" "github.com/hashicorp/terraform/helper/resource" ) func TestAccAWSEBSVolume_importBasic(t *testing.T) { resourceName := "aws_ebs_volume.test" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccAwsEbsVolumeConfig, }, resource.TestStep{ ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) }
mpl-2.0
subutai/nupic.core
external/common/include/boost/move/detail/meta_utils_core.hpp
3225
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2015-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) // // See http://www.boost.org/libs/move for documentation. // ////////////////////////////////////////////////////////////////////////////// //! \file #ifndef BOOST_MOVE_DETAIL_META_UTILS_CORE_HPP #define BOOST_MOVE_DETAIL_META_UTILS_CORE_HPP #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif # #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif //Small meta-typetraits to support move namespace boost { namespace move_detail { ////////////////////////////////////// // if_c ////////////////////////////////////// template<bool C, typename T1, typename T2> struct if_c { typedef T1 type; }; template<typename T1, typename T2> struct if_c<false,T1,T2> { typedef T2 type; }; ////////////////////////////////////// // if_ ////////////////////////////////////// template<typename T1, typename T2, typename T3> struct if_ : if_c<0 != T1::value, T2, T3> {}; ////////////////////////////////////// // enable_if_c ////////////////////////////////////// template <bool B, class T = void> struct enable_if_c { typedef T type; }; template <class T> struct enable_if_c<false, T> {}; ////////////////////////////////////// // enable_if ////////////////////////////////////// template <class Cond, class T = void> struct enable_if : enable_if_c<Cond::value, T> {}; ////////////////////////////////////// // disable_if_c ////////////////////////////////////// template <bool B, class T = void> struct disable_if_c : enable_if_c<!B, T> {}; ////////////////////////////////////// // disable_if ////////////////////////////////////// template <class Cond, class T = void> struct disable_if : enable_if_c<!Cond::value, T> {}; ////////////////////////////////////// // integral_constant ////////////////////////////////////// template<class T, T v> struct integral_constant { static const T value = v; typedef T value_type; typedef integral_constant<T, v> type; operator T() const { return value; } T operator()() const { return value; } }; typedef integral_constant<bool, true > true_type; typedef integral_constant<bool, false > false_type; ////////////////////////////////////// // is_same ////////////////////////////////////// template<class T, class U> struct is_same { static const bool value = false; }; template<class T> struct is_same<T, T> { static const bool value = true; }; ////////////////////////////////////// // enable_if_same ////////////////////////////////////// template <class T, class U, class R = void> struct enable_if_same : enable_if<is_same<T, U>, R> {}; ////////////////////////////////////// // disable_if_same ////////////////////////////////////// template <class T, class U, class R = void> struct disable_if_same : disable_if<is_same<T, U>, R> {}; } //namespace move_detail { } //namespace boost { #endif //#ifndef BOOST_MOVE_DETAIL_META_UTILS_CORE_HPP
agpl-3.0
Endika/omim
3party/boost/boost/phoenix/bind/preprocessed/bind_function_object_10.hpp
5185
/*============================================================================= Copyright (c) 2001-2007 Joel de Guzman 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) ==============================================================================*/ template < typename F , typename A0 > inline typename detail::expression::function_eval< F , A0 >::type const bind(F f, A0 const& a0) { return detail::expression::function_eval<F, A0>::make( f , a0 ); } template < typename F , typename A0 , typename A1 > inline typename detail::expression::function_eval< F , A0 , A1 >::type const bind(F f, A0 const& a0 , A1 const& a1) { return detail::expression::function_eval<F, A0 , A1>::make( f , a0 , a1 ); } template < typename F , typename A0 , typename A1 , typename A2 > inline typename detail::expression::function_eval< F , A0 , A1 , A2 >::type const bind(F f, A0 const& a0 , A1 const& a1 , A2 const& a2) { return detail::expression::function_eval<F, A0 , A1 , A2>::make( f , a0 , a1 , a2 ); } template < typename F , typename A0 , typename A1 , typename A2 , typename A3 > inline typename detail::expression::function_eval< F , A0 , A1 , A2 , A3 >::type const bind(F f, A0 const& a0 , A1 const& a1 , A2 const& a2 , A3 const& a3) { return detail::expression::function_eval<F, A0 , A1 , A2 , A3>::make( f , a0 , a1 , a2 , a3 ); } template < typename F , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > inline typename detail::expression::function_eval< F , A0 , A1 , A2 , A3 , A4 >::type const bind(F f, A0 const& a0 , A1 const& a1 , A2 const& a2 , A3 const& a3 , A4 const& a4) { return detail::expression::function_eval<F, A0 , A1 , A2 , A3 , A4>::make( f , a0 , a1 , a2 , a3 , a4 ); } template < typename F , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > inline typename detail::expression::function_eval< F , A0 , A1 , A2 , A3 , A4 , A5 >::type const bind(F f, A0 const& a0 , A1 const& a1 , A2 const& a2 , A3 const& a3 , A4 const& a4 , A5 const& a5) { return detail::expression::function_eval<F, A0 , A1 , A2 , A3 , A4 , A5>::make( f , a0 , a1 , a2 , a3 , a4 , a5 ); } template < typename F , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > inline typename detail::expression::function_eval< F , A0 , A1 , A2 , A3 , A4 , A5 , A6 >::type const bind(F f, A0 const& a0 , A1 const& a1 , A2 const& a2 , A3 const& a3 , A4 const& a4 , A5 const& a5 , A6 const& a6) { return detail::expression::function_eval<F, A0 , A1 , A2 , A3 , A4 , A5 , A6>::make( f , a0 , a1 , a2 , a3 , a4 , a5 , a6 ); } template < typename F , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > inline typename detail::expression::function_eval< F , A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 >::type const bind(F f, A0 const& a0 , A1 const& a1 , A2 const& a2 , A3 const& a3 , A4 const& a4 , A5 const& a5 , A6 const& a6 , A7 const& a7) { return detail::expression::function_eval<F, A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7>::make( f , a0 , a1 , a2 , a3 , a4 , a5 , a6 , a7 ); } template < typename F , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > inline typename detail::expression::function_eval< F , A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 >::type const bind(F f, A0 const& a0 , A1 const& a1 , A2 const& a2 , A3 const& a3 , A4 const& a4 , A5 const& a5 , A6 const& a6 , A7 const& a7 , A8 const& a8) { return detail::expression::function_eval<F, A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8>::make( f , a0 , a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 ); }
apache-2.0
washcycle/Windows-universal-samples
Samples/FileSearch/js/js/sample-configuration.js
414
//// Copyright (c) Microsoft Corporation. All rights reserved (function () { "use strict"; var sampleTitle = "File search JS sample"; var scenarios = [ { url: "/html/scenario1.html", title: "Obtain all files that match a search query" } ]; WinJS.Namespace.define("SdkSample", { sampleTitle: sampleTitle, scenarios: new WinJS.Binding.List(scenarios) }); })();
mit
shahid-pk/coreclr
tests/src/JIT/jit64/valuetypes/nullable/castclass/null/castclass-null006.cs
979
// 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; using System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((ValueType)(object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)(object)(ValueType)o) == null; } private static bool BoxUnboxToNQ(object o) { return ((ValueType)o) == null; } private static bool BoxUnboxToQ(object o) { return ((ushort?)(ValueType)o) == null; } private static int Main() { ushort? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
mit
How2ForFree/development
wp-content/plugins/wordfence.5.1.4/wordfence/lib/whois/whois.gtld.godaddy.php
1850
<?php /* Whois.php PHP classes to conduct whois queries Copyright (C)1999,2005 easyDNS Technologies Inc. & Mark Jeftovic Maintained by David Saez For the most recent version of this package visit: http://www.phpwhois.org This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ if (!defined('__GODADDY_HANDLER__')) define('__GODADDY_HANDLER__', 1); require_once('whois.parser.php'); class godaddy_handler { function parse($data_str, $query) { $items = array( 'owner' => 'Registrant:', 'admin' => 'Administrative Contact', 'tech' => 'Technical Contact', 'domain.name' => 'Domain Name:', 'domain.nserver.' => 'Domain servers in listed order:', 'domain.created' => 'Created on:', 'domain.expires' => 'Expires on:', 'domain.changed' => 'Last Updated on:', 'domain.sponsor' => 'Registered through:' ); $r = get_blocks($data_str, $items); $r['owner'] = get_contact($r['owner']); $r['admin'] = get_contact($r['admin'],false,true); $r['tech'] = get_contact($r['tech'],false,true); return format_dates($r, 'dmy'); } } ?>
gpl-2.0
BrennanConroy/corefx
src/System.Reflection.Metadata/tests/TestUtilities/TestMetadataStringDecoder.cs
790
// 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.Text; namespace System.Reflection.Metadata.Tests { public unsafe delegate string GetString(byte* bytes, int count); public sealed class TestMetadataStringDecoder : MetadataStringDecoder { private readonly GetString _getString; public TestMetadataStringDecoder(Encoding encoding, GetString getString) : base(encoding) { _getString = getString; } public override unsafe string GetString(byte* bytes, int byteCount) { return _getString(bytes, byteCount); } } }
mit
AbdulBasitBashir/learn-typescript
step36_decorators/node_modules/reflect-metadata/temp/test/reflect/reflect-getmetadatakeys.js
5365
// Reflect.getMetadataKeys ( target [, propertyKey] ) // - https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#reflectgetmetadatakeys--target--propertykey- require("../../Reflect"); var assert = require("assert"); function ReflectGetMetadataKeysInvalidTarget() { // 1. If Type(target) is not Object, throw a TypeError exception. assert.throws(function () { return Reflect.getMetadataKeys(undefined, undefined); }, TypeError); } exports.ReflectGetMetadataKeysInvalidTarget = ReflectGetMetadataKeysInvalidTarget; function ReflectGetMetadataKeysWithoutTargetKeyWhenNotDefined() { var obj = {}; var result = Reflect.getMetadataKeys(obj, undefined); assert.deepEqual(result, []); } exports.ReflectGetMetadataKeysWithoutTargetKeyWhenNotDefined = ReflectGetMetadataKeysWithoutTargetKeyWhenNotDefined; function ReflectGetMetadataKeysWithoutTargetKeyWhenDefined() { var obj = {}; Reflect.defineMetadata("key", "value", obj, undefined); var result = Reflect.getMetadataKeys(obj, undefined); assert.deepEqual(result, ["key"]); } exports.ReflectGetMetadataKeysWithoutTargetKeyWhenDefined = ReflectGetMetadataKeysWithoutTargetKeyWhenDefined; function ReflectGetMetadataKeysWithoutTargetKeyWhenDefinedOnPrototype() { var prototype = {}; var obj = Object.create(prototype); Reflect.defineMetadata("key", "value", prototype, undefined); var result = Reflect.getMetadataKeys(obj, undefined); assert.deepEqual(result, ["key"]); } exports.ReflectGetMetadataKeysWithoutTargetKeyWhenDefinedOnPrototype = ReflectGetMetadataKeysWithoutTargetKeyWhenDefinedOnPrototype; function ReflectGetMetadataKeysOrderWithoutTargetKey() { var obj = {}; Reflect.defineMetadata("key1", "value", obj, undefined); Reflect.defineMetadata("key0", "value", obj, undefined); var result = Reflect.getMetadataKeys(obj, undefined); assert.deepEqual(result, ["key1", "key0"]); } exports.ReflectGetMetadataKeysOrderWithoutTargetKey = ReflectGetMetadataKeysOrderWithoutTargetKey; function ReflectGetMetadataKeysOrderAfterRedefineWithoutTargetKey() { var obj = {}; Reflect.defineMetadata("key1", "value", obj, undefined); Reflect.defineMetadata("key0", "value", obj, undefined); Reflect.defineMetadata("key1", "value", obj, undefined); var result = Reflect.getMetadataKeys(obj, undefined); assert.deepEqual(result, ["key1", "key0"]); } exports.ReflectGetMetadataKeysOrderAfterRedefineWithoutTargetKey = ReflectGetMetadataKeysOrderAfterRedefineWithoutTargetKey; function ReflectGetMetadataKeysOrderWithoutTargetKeyWhenDefinedOnPrototype() { var prototype = {}; Reflect.defineMetadata("key2", "value", prototype, undefined); var obj = Object.create(prototype); Reflect.defineMetadata("key1", "value", obj, undefined); Reflect.defineMetadata("key0", "value", obj, undefined); var result = Reflect.getMetadataKeys(obj, undefined); assert.deepEqual(result, ["key1", "key0", "key2"]); } exports.ReflectGetMetadataKeysOrderWithoutTargetKeyWhenDefinedOnPrototype = ReflectGetMetadataKeysOrderWithoutTargetKeyWhenDefinedOnPrototype; function ReflectGetMetadataKeysWithTargetKeyWhenNotDefined() { var obj = {}; var result = Reflect.getMetadataKeys(obj, "name"); assert.deepEqual(result, []); } exports.ReflectGetMetadataKeysWithTargetKeyWhenNotDefined = ReflectGetMetadataKeysWithTargetKeyWhenNotDefined; function ReflectGetMetadataKeysWithTargetKeyWhenDefined() { var obj = {}; Reflect.defineMetadata("key", "value", obj, "name"); var result = Reflect.getMetadataKeys(obj, "name"); assert.deepEqual(result, ["key"]); } exports.ReflectGetMetadataKeysWithTargetKeyWhenDefined = ReflectGetMetadataKeysWithTargetKeyWhenDefined; function ReflectGetMetadataKeysWithTargetKeyWhenDefinedOnPrototype() { var prototype = {}; var obj = Object.create(prototype); Reflect.defineMetadata("key", "value", prototype, "name"); var result = Reflect.getMetadataKeys(obj, "name"); assert.deepEqual(result, ["key"]); } exports.ReflectGetMetadataKeysWithTargetKeyWhenDefinedOnPrototype = ReflectGetMetadataKeysWithTargetKeyWhenDefinedOnPrototype; function ReflectGetMetadataKeysOrderAfterRedefineWithTargetKey() { var obj = {}; Reflect.defineMetadata("key1", "value", obj, "name"); Reflect.defineMetadata("key0", "value", obj, "name"); Reflect.defineMetadata("key1", "value", obj, "name"); var result = Reflect.getMetadataKeys(obj, "name"); assert.deepEqual(result, ["key1", "key0"]); } exports.ReflectGetMetadataKeysOrderAfterRedefineWithTargetKey = ReflectGetMetadataKeysOrderAfterRedefineWithTargetKey; function ReflectGetMetadataKeysOrderWithTargetKeyWhenDefinedOnPrototype() { var prototype = {}; Reflect.defineMetadata("key2", "value", prototype, "name"); var obj = Object.create(prototype); Reflect.defineMetadata("key1", "value", obj, "name"); Reflect.defineMetadata("key0", "value", obj, "name"); var result = Reflect.getMetadataKeys(obj, "name"); assert.deepEqual(result, ["key1", "key0", "key2"]); } exports.ReflectGetMetadataKeysOrderWithTargetKeyWhenDefinedOnPrototype = ReflectGetMetadataKeysOrderWithTargetKeyWhenDefinedOnPrototype; //# sourceMappingURL=reflect-getmetadatakeys.js.map
mit
menglifei/zxing
zxing.appspot.com/src/main/java/com/google/zxing/web/generator/client/Validators.java
1991
/* * Copyright (C) 2008 ZXing 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 com.google.zxing.web.generator.client; /** * Helpers methods to check for phone numbers, email addresses, and URL. Other * general purpose check methods should go here as well. * * @author Yohann Coppel */ final class Validators { private Validators() { } static String filterNumber(String number) { return number.replaceAll("[ \\.,\\-\\(\\)]", ""); } static void validateNumber(String number) throws GeneratorException { if (!number.matches("\\+?[0-9]+")) { throw new GeneratorException("Phone number must be digits only."); } } static void validateUrl(String url) throws GeneratorException { if (!isBasicallyValidURI(url)) { throw new GeneratorException("URL is not valid."); } } private static boolean isBasicallyValidURI(String uri) { if (uri == null || uri.indexOf(' ') >= 0 || uri.indexOf('\n') >= 0) { return false; } int period = uri.indexOf('.'); // Look for period in a domain but followed by at least a two-char TLD return period < uri.length() - 2 && (period >= 0 || uri.indexOf(':') >= 0); } static void validateEmail(String email) throws GeneratorException { //FIXME: we can have a better check for email here. if (!email.matches("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$")) { throw new GeneratorException("Email is not valid."); } } }
apache-2.0