code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* Copyright 2018 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 genericclioptions import ( "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/printers" ) // KubeTemplatePrintFlags composes print flags that provide both a JSONPath and a go-template printer. // This is necessary if dealing with cases that require support both both printers, since both sets of flags // require overlapping flags. type KubeTemplatePrintFlags struct { GoTemplatePrintFlags *GoTemplatePrintFlags JSONPathPrintFlags *JSONPathPrintFlags AllowMissingKeys *bool TemplateArgument *string } func (f *KubeTemplatePrintFlags) AllowedFormats() []string { if f == nil { return []string{} } return append(f.GoTemplatePrintFlags.AllowedFormats(), f.JSONPathPrintFlags.AllowedFormats()...) } func (f *KubeTemplatePrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) { if f == nil { return nil, NoCompatiblePrinterError{} } if p, err := f.JSONPathPrintFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) { return p, err } return f.GoTemplatePrintFlags.ToPrinter(outputFormat) } // AddFlags receives a *cobra.Command reference and binds // flags related to template printing to it func (f *KubeTemplatePrintFlags) AddFlags(c *cobra.Command) { if f == nil { return } if f.TemplateArgument != nil { c.Flags().StringVar(f.TemplateArgument, "template", *f.TemplateArgument, "Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].") c.MarkFlagFilename("template") } if f.AllowMissingKeys != nil { c.Flags().BoolVar(f.AllowMissingKeys, "allow-missing-template-keys", *f.AllowMissingKeys, "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.") } } // NewKubeTemplatePrintFlags returns flags associated with // --template printing, with default values set. func NewKubeTemplatePrintFlags() *KubeTemplatePrintFlags { allowMissingKeysPtr := true templateArgPtr := "" return &KubeTemplatePrintFlags{ GoTemplatePrintFlags: &GoTemplatePrintFlags{ TemplateArgument: &templateArgPtr, AllowMissingKeys: &allowMissingKeysPtr, }, JSONPathPrintFlags: &JSONPathPrintFlags{ TemplateArgument: &templateArgPtr, AllowMissingKeys: &allowMissingKeysPtr, }, TemplateArgument: &templateArgPtr, AllowMissingKeys: &allowMissingKeysPtr, } }
pweil-/origin
vendor/k8s.io/kubernetes/staging/src/k8s.io/cli-runtime/pkg/genericclioptions/kube_template_flags.go
GO
apache-2.0
3,020
// 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.Runtime.InteropServices.WindowsRuntime.Tests { public class DefaultInterfaceAttributeTests { [Theory] [InlineData(null)] [InlineData(typeof(int))] public void Ctor_DefaultInterface(Type defaultInterface) { var attribute = new ComDefaultInterfaceAttribute(defaultInterface); Assert.Equal(defaultInterface, attribute.Value); } } }
BrennanConroy/corefx
src/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/DefaultInterfaceAttributeTests.cs
C#
mit
648
/* Package pagination contains utilities and convenience structs that implement common pagination idioms within OpenStack APIs. */ package pagination
kgrygiel/autoscaler
vertical-pod-autoscaler/vendor/github.com/gophercloud/gophercloud/pagination/pkg.go
GO
apache-2.0
150
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Dom * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** Zend_Exception */ require_once 'Zend/Exception.php'; /** * Zend_Dom Exceptions * * @category Zend * @package Zend_Dom * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Dom_Exception extends Zend_Exception { }
angusty/symfony-study
vendor/Zend/Dom/Exception.php
PHP
mit
1,050
# test equality for classes/instances to other types class A: pass class B: pass class C(A): pass print(A == None) print(None == A) print(A == A) print(A() == A) print(A() == A()) print(A == B) print(A() == B) print(A() == B()) print(A == C) print(A() == C) print(A() == C())
mhoffma/micropython
tests/basics/equal_class.py
Python
mit
295
/** * 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.interceptor; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.AdviceWithRouteBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.seda.SedaEndpoint; /** * @version */ public class AdviceWithMockEndpointsWithSkipTest extends ContextTestSupport { // START SNIPPET: e1 public void testAdvisedMockEndpointsWithSkip() throws Exception { // advice the first route using the inlined AdviceWith route builder // which has extended capabilities than the regular route builder context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { // mock sending to direct:foo and skip send to it mockEndpointsAndSkip("direct:foo"); } }); getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:direct:foo").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // the message was not send to the direct:foo route and thus not sent to the seda endpoint SedaEndpoint seda = context.getEndpoint("seda:foo", SedaEndpoint.class); assertEquals(0, seda.getCurrentQueueSize()); } // END SNIPPET: e1 // START SNIPPET: route @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("direct:foo").to("mock:result"); from("direct:foo").transform(constant("Bye World")).to("seda:foo"); } }; } // END SNIPPET: route }
YMartsynkevych/camel
camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithMockEndpointsWithSkipTest.java
Java
apache-2.0
2,666
/** * 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.jackson; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class JacksonIncludeDefaultTest extends CamelTestSupport { @Test public void testMmarshalPojo() throws Exception { MockEndpoint mock = getMockEndpoint("mock:marshal"); mock.expectedMessageCount(1); mock.message(0).body(String.class).isEqualTo("{\"name\":\"Camel\",\"country\":null}"); TestOtherPojo pojo = new TestOtherPojo(); pojo.setName("Camel"); template.sendBody("direct:marshal", pojo); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { JacksonDataFormat format = new JacksonDataFormat(); from("direct:marshal").marshal(format).to("mock:marshal"); } }; } }
YMartsynkevych/camel
components/camel-jackson/src/test/java/org/apache/camel/component/jackson/JacksonIncludeDefaultTest.java
Java
apache-2.0
1,906
export declare var __core_private_testing_placeholder__: string;
ice3x2/Clreball
web/lib/@angular/core/testing/testing.d.ts
TypeScript
gpl-3.0
65
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.LanguageServices.Implementation.RQName.SimpleTree; namespace Microsoft.VisualStudio.LanguageServices.Implementation.RQName.Nodes { internal class RQPointerType : RQArrayOrPointerType { public RQPointerType(RQType elementType) : base(elementType) { } public override SimpleTreeNode ToSimpleTree() { return new SimpleGroupNode(RQNameStrings.Pointer, ElementType.ToSimpleTree()); } } }
JohnHamby/roslyn
src/VisualStudio/Core/Def/Implementation/RQName/Nodes/RQPointerType.cs
C#
apache-2.0
632
#include <com.badlogic.gdx.physics.box2d.joints.PrismaticJoint.h> //@line:28 #include <Box2D/Box2D.h> JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetLocalAnchorA(JNIEnv* env, jobject object, jlong addr, jfloatArray obj_anchor) { float* anchor = (float*)env->GetPrimitiveArrayCritical(obj_anchor, 0); //@line:47 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; anchor[0] = joint->GetLocalAnchorA().x; anchor[1] = joint->GetLocalAnchorA().y; env->ReleasePrimitiveArrayCritical(obj_anchor, anchor, 0); } JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetLocalAnchorB(JNIEnv* env, jobject object, jlong addr, jfloatArray obj_anchor) { float* anchor = (float*)env->GetPrimitiveArrayCritical(obj_anchor, 0); //@line:59 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; anchor[0] = joint->GetLocalAnchorB().x; anchor[1] = joint->GetLocalAnchorB().y; env->ReleasePrimitiveArrayCritical(obj_anchor, anchor, 0); } JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetLocalAxisA(JNIEnv* env, jobject object, jlong addr, jfloatArray obj_anchor) { float* anchor = (float*)env->GetPrimitiveArrayCritical(obj_anchor, 0); //@line:71 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; anchor[0] = joint->GetLocalAxisA().x; anchor[1] = joint->GetLocalAxisA().y; env->ReleasePrimitiveArrayCritical(obj_anchor, anchor, 0); } JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetJointTranslation(JNIEnv* env, jobject object, jlong addr) { //@line:82 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->GetJointTranslation(); } JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetJointSpeed(JNIEnv* env, jobject object, jlong addr) { //@line:92 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->GetJointSpeed(); } JNIEXPORT jboolean JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniIsLimitEnabled(JNIEnv* env, jobject object, jlong addr) { //@line:102 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->IsLimitEnabled(); } JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniEnableLimit(JNIEnv* env, jobject object, jlong addr, jboolean flag) { //@line:112 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; joint->EnableLimit(flag); } JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetLowerLimit(JNIEnv* env, jobject object, jlong addr) { //@line:122 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->GetLowerLimit(); } JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetUpperLimit(JNIEnv* env, jobject object, jlong addr) { //@line:132 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->GetUpperLimit(); } JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniSetLimits(JNIEnv* env, jobject object, jlong addr, jfloat lower, jfloat upper) { //@line:142 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; joint->SetLimits(lower, upper ); } JNIEXPORT jboolean JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniIsMotorEnabled(JNIEnv* env, jobject object, jlong addr) { //@line:152 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->IsMotorEnabled(); } JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniEnableMotor(JNIEnv* env, jobject object, jlong addr, jboolean flag) { //@line:162 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; joint->EnableMotor(flag); } JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniSetMotorSpeed(JNIEnv* env, jobject object, jlong addr, jfloat speed) { //@line:172 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; joint->SetMotorSpeed(speed); } JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetMotorSpeed(JNIEnv* env, jobject object, jlong addr) { //@line:182 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->GetMotorSpeed(); } JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniSetMaxMotorForce(JNIEnv* env, jobject object, jlong addr, jfloat force) { //@line:192 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; joint->SetMaxMotorForce(force); } JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetMotorForce(JNIEnv* env, jobject object, jlong addr, jfloat invDt) { //@line:202 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->GetMotorForce(invDt); } JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetMaxMotorForce(JNIEnv* env, jobject object, jlong addr) { //@line:212 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->GetMaxMotorForce(); } JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetReferenceAngle(JNIEnv* env, jobject object, jlong addr) { //@line:222 b2PrismaticJoint* joint = (b2PrismaticJoint*)addr; return joint->GetReferenceAngle(); }
GreenLightning/libgdx
extensions/gdx-box2d/gdx-box2d/jni/com.badlogic.gdx.physics.box2d.joints.PrismaticJoint.cpp
C++
apache-2.0
5,331
// Bug: We weren't doing the normal replacement of array with pointer // for deduction in the context of a call because of the initializer list. // { dg-do compile { target c++11 } } #include <initializer_list> struct string { string (const char *); }; template <class T> struct vector { template <class U> vector (std::initializer_list<U>); }; vector<string> v = { "a", "b", "c" };
selmentdev/selment-toolchain
source/gcc-latest/gcc/testsuite/g++.dg/cpp0x/initlist14.C
C++
gpl-3.0
393
/* * DOM event listener abstraction layer * @module event * @submodule event-base */ (function() { // Unlike most of the library, this code has to be executed as soon as it is // introduced into the page -- and it should only be executed one time // regardless of the number of instances that use it. var stateChangeListener, GLOBAL_ENV = YUI.Env, config = YUI.config, doc = config.doc, docElement = doc.documentElement, doScrollCap = docElement.doScroll, add = YUI.Env.add, remove = YUI.Env.remove, targetEvent = (doScrollCap) ? 'onreadystatechange' : 'DOMContentLoaded', pollInterval = config.pollInterval || 40, _ready = function(e) { GLOBAL_ENV._ready(); }; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { if (!GLOBAL_ENV.DOMReady) { GLOBAL_ENV.DOMReady = true; remove(doc, targetEvent, _ready); // remove DOMContentLoaded listener } }; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the doScroll() method on the root element. This isolates what // appears to be a safe moment to manipulate the DOM prior to when the document's readyState // suggests it is safe to do so. if (doScrollCap) { if (self !== self.top) { stateChangeListener = function() { if (doc.readyState == 'complete') { remove(doc, targetEvent, stateChangeListener); // remove onreadystatechange listener _ready(); } }; add(doc, targetEvent, stateChangeListener); // add onreadystatechange listener } else { GLOBAL_ENV._dri = setInterval(function() { try { docElement.doScroll('left'); clearInterval(GLOBAL_ENV._dri); GLOBAL_ENV._dri = null; _ready(); } catch (domNotReady) { } }, pollInterval); } } else { // FireFox, Opera, Safari 3+ provide an event for this moment. add(doc, targetEvent, _ready); // add DOMContentLoaded listener } } })(); YUI.add('event-base', function(Y) { (function() { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ var GLOBAL_ENV = YUI.Env, yready = function() { Y.fire('domready'); }; /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true }); if (GLOBAL_ENV.DOMReady) { // console.log('DOMReady already fired', 'info', 'event'); yready(); } else { // console.log('setting up before listener', 'info', 'event'); // console.log('env: ' + YUI.Env.windowLoaded, 'info', 'event'); Y.before(yready, GLOBAL_ENV, "_ready"); } })(); (function() { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ /* * @TODO constants? LEFTBUTTON, MIDDLEBUTTON, RIGHTBUTTON, keys */ /* var whitelist = { altKey : 1, // "button" : 1, // we supply // "bubbles" : 1, // needed? // "cancelable" : 1, // needed? // "charCode" : 1, // we supply cancelBubble : 1, // "currentTarget" : 1, // we supply ctrlKey : 1, clientX : 1, // needed? clientY : 1, // needed? detail : 1, // not fully implemented // "fromElement" : 1, keyCode : 1, // "height" : 1, // needed? // "initEvent" : 1, // need the init events? // "initMouseEvent" : 1, // "initUIEvent" : 1, // "layerX" : 1, // needed? // "layerY" : 1, // needed? metaKey : 1, // "modifiers" : 1, // needed? // "offsetX" : 1, // needed? // "offsetY" : 1, // needed? // "preventDefault" : 1, // we supply // "reason" : 1, // IE proprietary // "relatedTarget" : 1, // "returnValue" : 1, // needed? shiftKey : 1, // "srcUrn" : 1, // IE proprietary // "srcElement" : 1, // "srcFilter" : 1, IE proprietary // "stopPropagation" : 1, // we supply // "target" : 1, // "timeStamp" : 1, // needed? // "toElement" : 1, type : 1, // "view" : 1, // "which" : 1, // we supply // "width" : 1, // needed? x : 1, y : 1 }, */ var ua = Y.UA, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }; // provide a single event with browser abstractions resolved // // include all properties for both browers? // include only DOM2 spec properties? // provide browser-specific facade? Y.DOMEventFacade = function(ev, currentTarget, wrapper) { wrapper = wrapper || {}; var e = ev, ot = currentTarget, d = Y.config.doc, b = d.body, x = e.pageX, y = e.pageY, c, t, overrides = wrapper.overrides || {}; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = overrides.type || e.type; this.clientX = e.clientX; this.clientY = e.clientY; ////////////////////////////////////////////////////// if (!x && 0 !== x) { x = e.clientX || 0; y = e.clientY || 0; if (ua.ie) { x += Math.max(d.documentElement.scrollLeft, b.scrollLeft); y += Math.max(d.documentElement.scrollTop, b.scrollTop); } } this._yuifacade = true; /** * The native event * @property _event */ this._event = e; /** * The X location of the event on the page (including scroll) * @property pageX * @type int */ this.pageX = x; /** * The Y location of the event on the page (including scroll) * @property pageY * @type int */ this.pageY = y; ////////////////////////////////////////////////////// c = e.keyCode || e.charCode || 0; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type int */ this.keyCode = c; /** * The charCode for key events. Same as keyCode * @property charCode * @type int */ this.charCode = c; ////////////////////////////////////////////////////// /** * The button that was pushed. * @property button * @type int */ this.button = e.which || e.button; /** * The button that was pushed. Same as button. * @property which * @type int */ this.which = this.button; ////////////////////////////////////////////////////// /** * Node reference for the targeted element * @propery target * @type Node */ this.target = resolve(e.target || e.srcElement); /** * Node reference for the element that the listener was attached to. * @propery currentTarget * @type Node */ this.currentTarget = resolve(ot); t = e.relatedTarget; if (!t) { if (e.type == "mouseout") { t = e.toElement; } else if (e.type == "mouseover") { t = e.fromElement; } } /** * Node reference to the relatedTarget * @propery relatedTarget * @type Node */ this.relatedTarget = resolve(t); /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type int */ if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } ////////////////////////////////////////////////////// // methods /** * Stops the propagation to the next bubble target * @method stopPropagation */ this.stopPropagation = function() { if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; } wrapper.stopped = 1; }; /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ this.stopImmediatePropagation = function() { if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } wrapper.stopped = 2; }; /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ this.preventDefault = function(returnValue) { if (e.preventDefault) { e.preventDefault(); } e.returnValue = returnValue || false; wrapper.prevented = 1; }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ this.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; }; })(); (function() { /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var _eventenv = Y.Env.evt, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(window, "load", onLoad); }, onUnload = function() { Y.Event._unload(); remove(window, "unload", onUnload); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !o.alert); } catch(ex) { Y.log("collection check failure", "warn", "event"); return false; } }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Y.bind(Event._poll, Event), Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; // Y.log('onAvailable registered for: ' + id); for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Y.bind(Event._poll, Event), 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, p_obj, p_override, compat) { return this.onAvailable(id, fn, p_obj, p_override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == Y.config.win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, config) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || Y.config.win, facade = config && config.facade, capture = config && config.capture, overrides = config && config.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; // trimmedArgs.pop(); } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); Y.log(type + " attach call failed, invalid callback", "error", "event"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args, config)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = Y.DOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, config); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { // Y.log(el + ' not found'); ret = this.onAvailable(el, function() { // Y.log('lazy attach: ' + args); ret.handle = Event._attach(args, config); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { Y.log("unable to attach event " + type, "warn", "event"); return false; } if (Y.Node && el instanceof Y.Node) { el = Y.Node.getDOMNode(el); } cewrapper = this._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == Y.config.win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = Y.DOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return this.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || window.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { // Y.log('Load Complete', 'info', 'event'); _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (this.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. this.startInterval(); return; } this.locked = true; // Y.log.debug("poll"); // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // Y.log('avail: ' + el); executeItem(el, item); _avail[i] = null; } else { // Y.log('NOT avail: ' + el); notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here this.startInterval(); } else { clearInterval(this._interval); this._interval = null; } this.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = this.getListeners(oEl, type), i, len, props, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); i = 0; len = children.length; for (; i < len; ++i) { child = this.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { i = 0; len = lis.length; for (; i < len; ++i) { props = lis[i]; props.detachAll(); remove(props.el, props.type, props.fn, props.capture); delete _wrappers[props.key]; delete _el_events[props.domkey][props.key]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {Y.Custom.Event} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null; if (!evts) { return null; } if (key) { if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { v.detachAll(); remove(v.el, v.type, v.fn, v.capture); delete _wrappers[k]; delete _el_events[v.domkey][k]; }); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (Y.config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(window, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll, Event, true); } Y.on("unload", onUnload); Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); })(); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string|HTMLElement|collection} the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : []; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available) * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string|HTMLElement|collection} the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : []; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('event-delegate', function(Y) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var Event = Y.Event, Lang = Y.Lang, delegates = {}, specialTypes = { mouseenter: "mouseover", mouseleave: "mouseout" }, resolveTextNode = function(n) { try { if (n && 3 == n.nodeType) { return n.parentNode; } } catch(e) { } return n; }, delegateHandler = function(delegateKey, e, el) { var target = resolveTextNode((e.target || e.srcElement)), tests = delegates[delegateKey], spec, ename, matched, fn, ev; var getMatch = function(el, selector, container) { var returnVal; if (!el || el === container) { returnVal = false; } else { returnVal = Y.Selector.test(el, selector, container) ? el: getMatch(el.parentNode, selector, container); } return returnVal; }; for (spec in tests) { if (tests.hasOwnProperty(spec)) { ename = tests[spec]; fn = tests.fn; matched = null; if (Y.Selector.test(target, spec, el)) { matched = target; } else if (Y.Selector.test(target, ((spec.replace(/,/gi, " *,")) + " *"), el)) { // The target is a descendant of an element matching // the selector, so crawl up to find the ancestor that // matches the selector matched = getMatch(target, spec, el); } if (matched) { if (!ev) { ev = new Y.DOMEventFacade(e, el); ev.container = ev.currentTarget; } ev.currentTarget = Y.one(matched); Y.publish(ename, { contextFn: function() { return ev.currentTarget; } }); if (fn) { fn(ev, ename); } else { Y.fire(ename, ev); } } } } }, attach = function (type, key, element) { var focusMethods = { focus: Event._attachFocus, blur: Event._attachBlur }, attachFn = focusMethods[type], args = [type, function (e) { delegateHandler(key, (e || window.event), element); }, element]; if (attachFn) { return attachFn(args, { capture: true, facade: false }); } else { return Event._attach(args, { facade: false }); } }, sanitize = Y.cached(function(str) { return str.replace(/[|,:]/g, '~'); }); /** * Sets up event delegation on a container element. The delegated event * will use a supplied selector to test if the target or one of the * descendants of the target match it. The supplied callback function * will only be executed if a match was encountered, and, in fact, * will be executed for each element that matches if you supply an * ambiguous selector. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the delegation specifcation. 'container' is * set to the element that the listener is bound to (this normally would * be the 'currentTarget'). * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param spec {string} a selector that must match the target of the * event. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Event.delegate = function (type, fn, el, spec) { if (!spec) { Y.log('delegate: no spec, nothing to do', 'warn', 'event'); return false; } var args = Y.Array(arguments, 0, true), element = el, // HTML element serving as the delegation container availHandle; if (Lang.isString(el)) { // Y.Selector.query returns an array of matches unless specified // to return just the first match. Since the primary use case for // event delegation is to use a single event handler on a container, // Y.delegate doesn't currently support being able to bind a // single listener to multiple containers. element = Y.Selector.query(el, null, true); if (!element) { // Not found, check using onAvailable availHandle = Event.onAvailable(el, function() { availHandle.handle = Event.delegate.apply(Event, args); }, Event, true, false); return availHandle; } } element = Y.Node.getDOMNode(element); var guid = Y.stamp(element), // The Custom Event for the delegation spec ename = 'delegate:' + guid + type + sanitize(spec), // The key to the listener for the event type and container delegateKey = type + guid, delegate = delegates[delegateKey], domEventHandle, ceHandle, listeners; if (!delegate) { delegate = {}; if (specialTypes[type]) { if (!Event._fireMouseEnter) { Y.log("Delegating a " + type + " event requires the event-mouseenter submodule.", "error", "Event"); return false; } type = specialTypes[type]; delegate.fn = Event._fireMouseEnter; } // Create the DOM Event wrapper that will fire the Custom Event domEventHandle = attach(type, delegateKey, element); // Hook into the _delete method for the Custom Event wrapper of this // DOM Event in order to clean up the 'delegates' map and unsubscribe // the associated Custom Event listeners fired by this DOM event // listener if/when the user calls "purgeElement" OR removes all // listeners of the Custom Event. Y.after(function (sub) { if (domEventHandle.sub == sub) { // Delete this event from the map of known delegates delete delegates[delegateKey]; Y.log("DOM event listener associated with the " + ename + " Custom Event removed. Removing all " + ename + " listeners.", "info", "Event"); // Unsubscribe all listeners of the Custom Event fired // by this DOM event. Y.detachAll(ename); } }, domEventHandle.evt, "_delete"); delegate.handle = domEventHandle; delegates[delegateKey] = delegate; } listeners = delegate.listeners; delegate.listeners = listeners ? (listeners + 1) : 1; delegate[spec] = ename; args[0] = ename; // Remove element, delegation spec args.splice(2, 2); // Subscribe to the Custom Event for the delegation spec ceHandle = Y.on.apply(Y, args); // Hook into the detach method of the handle in order to clean up the // 'delegates' map and remove the associated DOM event handler // responsible for firing this Custom Event if all listener for this // event have been removed. Y.after(function () { delegate.listeners = (delegate.listeners - 1); if (delegate.listeners === 0) { Y.log("No more listeners for the " + ename + " Custom Event. Removing its associated DOM event listener.", "info", "Event"); delegate.handle.detach(); } }, ceHandle, "detach"); return ceHandle; }; Y.delegate = Event.delegate; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-mousewheel', function(Y) { /** * Adds mousewheel event support * @module event * @submodule event-mousewheel */ var DOM_MOUSE_SCROLL = 'DOMMouseScroll', fixArgs = function(args) { var a = Y.Array(args, 0, true), target; if (Y.UA.gecko) { a[0] = DOM_MOUSE_SCROLL; target = Y.config.win; } else { target = Y.config.doc; } if (a.length < 3) { a[2] = target; } else { a.splice(2, 0, target); } return a; }; /** * Mousewheel event. This listener is automatically attached to the * correct target, so one should not be supplied. Mouse wheel * direction and velocity is stored in the 'mouseDelta' field. * @event mousewheel * @param type {string} 'mousewheel' * @param fn {function} the callback to execute * @param context optional context object * @param args 0..n additional arguments to provide to the listener. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.mousewheel = { on: function() { return Y.Event._attach(fixArgs(arguments)); }, detach: function() { return Y.Event.detach.apply(Y.Event, fixArgs(arguments)); } }; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-mouseenter', function(Y) { /** * Adds support for mouseenter/mouseleave events * @module event * @submodule event-mouseenter */ var Event = Y.Event, Lang = Y.Lang, plugins = Y.Env.evt.plugins, listeners = {}, eventConfig = { on: function(type, fn, el) { var args = Y.Array(arguments, 0, true), element = el, availHandle; if (Lang.isString(el)) { // Need to use Y.all because if el is a string it could be a // selector that returns a NodeList element = Y.all(el); if (element.size() === 0) { // Not found, check using onAvailable availHandle = Event.onAvailable(el, function() { availHandle.handle = Y.on.apply(Y, args); }, Event, true, false); return availHandle; } } var sDOMEvent = (type === "mouseenter") ? "mouseover" : "mouseout", // The name of the custom event sEventName = type + ":" + Y.stamp(element) + sDOMEvent, listener = listeners[sEventName], domEventHandle, ceHandle, nListeners; // Bind an actual DOM event listener that will call the // the custom event if (!listener) { domEventHandle = Y.on(sDOMEvent, Y.rbind(Event._fireMouseEnter, Y, sEventName), element); // Hook into the _delete method for the Custom Event wrapper of this // DOM Event in order to clean up the 'listeners' map and unsubscribe // the associated Custom Event listeners fired by this DOM event // listener if/when the user calls "purgeElement" OR removes all // listeners of the Custom Event. Y.after(function (sub) { if (domEventHandle.sub == sub) { // Delete this event from the map of known mouseenter // and mouseleave listeners delete listeners[sEventName]; Y.log("DOM event listener associated with the " + sEventName + " Custom Event removed. Removing all " + sEventName + " listeners.", "info", "Event"); // Unsubscribe all listeners of the Custom Event fired // by this DOM event. Y.detachAll(sEventName); } }, domEventHandle.evt, "_delete"); listener = {}; listener.handle = domEventHandle; listeners[sEventName] = listener; } nListeners = listener.count; listener.count = nListeners ? (nListeners + 1) : 1; args[0] = sEventName; // Remove the element from the args args.splice(2, 1); // Subscribe to the custom event ceHandle = Y.on.apply(Y, args); // Hook into the detach method of the handle in order to clean up the // 'listeners' map and remove the associated DOM event handler // responsible for firing this Custom Event if all listener for this // event have been removed. Y.after(function () { listener.count = (listener.count - 1); if (listener.count === 0) { Y.log("No more listeners for the " + sEventName + " Custom Event. Removing its associated DOM event listener.", "info", "Event"); listener.handle.detach(); } }, ceHandle, "detach"); return ceHandle; } }; Event._fireMouseEnter = function (e, eventName) { var relatedTarget = e.relatedTarget, currentTarget = e.currentTarget; if (currentTarget !== relatedTarget && !currentTarget.contains(relatedTarget)) { Y.publish(eventName, { contextFn: function() { return currentTarget; } }); Y.fire(eventName, e); } }; /** * Sets up a "mouseenter" listener&#151;a listener that is called the first time * the user's mouse enters the specified element(s). * * @event mouseenter * @param type {string} "mouseenter" * @param fn {function} The method the event invokes. * @param el {string|node} The element(s) to assign the listener to. * @param spec {string} Optional. String representing a selector that must * match the target of the event in order for the listener to be called. * @return {EventHandle} the detach handle * @for YUI */ plugins.mouseenter = eventConfig; /** * Sets up a "mouseleave" listener&#151;a listener that is called the first time * the user's mouse leaves the specified element(s). * * @event mouseleave * @param type {string} "mouseleave" * @param fn {function} The method the event invokes. * @param el {string|node} The element(s) to assign the listener to. * @param spec {string} Optional. String representing a selector that must * match the target of the event in order for the listener to be called. * @return {EventHandle} the detach handle * @for YUI */ plugins.mouseleave = eventConfig; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-key', function(Y) { /** * Functionality to listen for one or more specific key combinations. * @module event * @submodule event-key */ /** * Add a key listener. The listener will only be notified if the * keystroke detected meets the supplied specification. The * spec consists of the key event type, followed by a colon, * followed by zero or more comma separated key codes, followed * by zero or more modifiers delimited by a plus sign. Ex: * press:12,65+shift+ctrl * @event key * @for YUI * @param type {string} 'key' * @param fn {function} the function to execute * @param id {string|HTMLElement|collection} the element(s) to bind * @param spec {string} the keyCode and modifier specification * @param o optional context object * @param args 0..n additional arguments to provide to the listener. * @return {Event.Handle} the detach handle */ Y.Env.evt.plugins.key = { on: function(type, fn, id, spec, o) { var a = Y.Array(arguments, 0, true), parsed, etype, criteria, ename; parsed = spec && spec.split(':'); if (!spec || spec.indexOf(':') == -1 || !parsed[1]) { Y.log('Illegal key spec, creating a regular keypress listener instead.', 'info', 'event'); a[0] = 'key' + ((parsed && parsed[0]) || 'press'); return Y.on.apply(Y, a); } // key event type: 'down', 'up', or 'press' etype = parsed[0]; // list of key codes optionally followed by modifiers criteria = (parsed[1]) ? parsed[1].split(/,|\+/) : null; // the name of the custom event that will be created for the spec ename = (Y.Lang.isString(id) ? id : Y.stamp(id)) + spec; ename = ename.replace(/,/g, '_'); if (!Y.getEvent(ename)) { // subscribe spec validator to the DOM event Y.on(type + etype, function(e) { // Y.log('keylistener: ' + e.keyCode); var passed = false, failed = false, i, crit, critInt; for (i=0; i<criteria.length; i=i+1) { crit = criteria[i]; critInt = parseInt(crit, 10); // pass this section if any supplied keyCode // is found if (Y.Lang.isNumber(critInt)) { if (e.charCode === critInt) { // Y.log('passed: ' + crit); passed = true; } else { failed = true; // Y.log('failed: ' + crit); } // only check modifier if no keyCode was specified // or the keyCode check was successful. pass only // if every modifier passes } else if (passed || !failed) { passed = (e[crit + 'Key']); failed = !passed; // Y.log(crit + ": " + passed); } } // fire spec custom event if spec if met if (passed) { Y.fire(ename, e); } }, id); } // subscribe supplied listener to custom event for spec validator // remove element and spec. a.splice(2, 2); a[0] = ename; return Y.on.apply(Y, a); } }; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-focus', function(Y) { /** * Adds focus and blur event listener support. These events normally * do not bubble, so this adds support for that so these events * can be used in event delegation scenarios. * * @module event * @submodule event-focus */ (function() { var UA = Y.UA, Event = Y.Event, plugins = Y.Env.evt.plugins, ie = UA.ie, bUseMutation = (UA.opera || UA.webkit), eventNames = { focus: (ie ? 'focusin' : (bUseMutation ? 'DOMFocusIn' : 'focus')), blur: (ie ? 'focusout' : (bUseMutation ? 'DOMFocusOut' : 'blur')) }, // Only need to use capture phase for Gecko since it doesn't support // focusin, focusout, DOMFocusIn, or DOMFocusOut CAPTURE_CONFIG = { capture: (UA.gecko ? true : false) }, attach = function (args, config) { var a = Y.Array(args, 0, true), el = args[2]; config.overrides = config.overrides || {}; config.overrides.type = args[0]; if (el) { if (Y.DOM.isWindow(el)) { config.capture = false; } else { a[0] = eventNames[a[0]]; } } return Event._attach(a, config); }, eventAdapter = { on: function () { return attach(arguments, CAPTURE_CONFIG); } }; Event._attachFocus = attach; Event._attachBlur = attach; /** * Adds a DOM focus listener. Uses the focusin event in IE, * DOMFocusIn for Opera and Webkit, and the capture phase for Gecko so that * the event propagates in a way that enables event delegation. * * @for YUI * @event focus * @param type {string} 'focus' * @param fn {function} the callback function to execute * @param o {string|HTMLElement|collection} the element(s) to bind * @param context optional context object * @param args 0..n additional arguments to provide to the listener. * @return {EventHandle} the detach handle */ plugins.focus = eventAdapter; /** * Adds a DOM blur listener. Uses the focusout event in IE, * DOMFocusOut for Opera and Webkit, and the capture phase for Gecko so that * the event propagates in a way that enables event delegation. * * @for YUI * @event blur * @param type {string} 'blur' * @param fn {function} the callback function to execute * @param o {string|HTMLElement|collection} the element(s) to bind * @param context optional context object * @param args 0..n additional arguments to provide to the listener. * @return {EventHandle} the detach handle */ plugins.blur = eventAdapter; })(); }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-resize', function(Y) { /** * Adds a window resize event that has its behavior normalized to fire at the * end of the resize rather than constantly during the resize. * @module event * @submodule event-resize */ (function() { var detachHandle, timerHandle, CE_NAME = 'window:resize', handler = function(e) { if (Y.UA.gecko) { Y.fire(CE_NAME, e); } else { if (timerHandle) { timerHandle.cancel(); } timerHandle = Y.later(Y.config.windowResizeDelay || 40, Y, function() { Y.fire(CE_NAME, e); }); } }; /** * Firefox fires the window resize event once when the resize action * finishes, other browsers fire the event periodically during the * resize. This code uses timeout logic to simulate the Firefox * behavior in other browsers. * @event windowresize * @for YUI */ Y.Env.evt.plugins.windowresize = { on: function(type, fn) { // check for single window listener and add if needed if (!detachHandle) { detachHandle = Y.Event._attach(['resize', handler]); } var a = Y.Array(arguments, 0, true); a[0] = CE_NAME; return Y.on.apply(Y, a); } }; })(); }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event', function(Y){}, '@VERSION@' ,{use:['event-base', 'event-delegate', 'event-mousewheel', 'event-mouseenter', 'event-key', 'event-focus', 'event-resize']});
pcarrier/cdnjs
ajax/libs/yui/3.1.0pr2/event/event-debug.js
JavaScript
mit
64,193
/** * 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.jmx; /** * Reports a problem formatting the Notification. This will be a JAXB related issue. */ public class NotificationFormatException extends Exception { private static final long serialVersionUID = -3460338958670572299L; public NotificationFormatException(Exception aCausedBy) { super(aCausedBy); } }
YMartsynkevych/camel
components/camel-jmx/src/main/java/org/apache/camel/component/jmx/NotificationFormatException.java
Java
apache-2.0
1,170
<?php namespace Guzzle\Tests\Common; use Guzzle\Common\Event; class EventTest extends \Guzzle\Tests\GuzzleTestCase { /** * @return Event */ private function getEvent() { return new Event(array( 'test' => '123', 'other' => '456', 'event' => 'test.notify' )); } /** * @covers Guzzle\Common\Event::__construct */ public function testAllowsParameterInjection() { $event = new Event(array( 'test' => '123' )); $this->assertEquals('123', $event['test']); } /** * @covers Guzzle\Common\Event::offsetGet * @covers Guzzle\Common\Event::offsetSet * @covers Guzzle\Common\Event::offsetUnset * @covers Guzzle\Common\Event::offsetExists */ public function testImplementsArrayAccess() { $event = $this->getEvent(); $this->assertEquals('123', $event['test']); $this->assertNull($event['foobar']); $this->assertTrue($event->offsetExists('test')); $this->assertFalse($event->offsetExists('foobar')); unset($event['test']); $this->assertFalse($event->offsetExists('test')); $event['test'] = 'new'; $this->assertEquals('new', $event['test']); } /** * @covers Guzzle\Common\Event::getIterator */ public function testImplementsIteratorAggregate() { $event = $this->getEvent(); $this->assertInstanceOf('ArrayIterator', $event->getIterator()); } /** * @covers Guzzle\Common\Event::toArray */ public function testConvertsToArray() { $this->assertEquals(array( 'test' => '123', 'other' => '456', 'event' => 'test.notify' ), $this->getEvent()->toArray()); } }
LenLamberg/LenEntire_June_5
winkler/profiles/commerce_kickstart/libraries/yotpo-php/vendor/guzzle/http/Guzzle/Http/tests/Guzzle/Tests/Common/EventTest.php
PHP
gpl-2.0
1,819
/* 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 v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/client-go/pkg/api/v1" ) func addDefaultingFuncs(scheme *runtime.Scheme) error { return RegisterDefaults(scheme) } func SetDefaults_DaemonSet(obj *DaemonSet) { labels := obj.Spec.Template.Labels // TODO: support templates defined elsewhere when we support them in the API if labels != nil { if obj.Spec.Selector == nil { obj.Spec.Selector = &metav1.LabelSelector{ MatchLabels: labels, } } if len(obj.Labels) == 0 { obj.Labels = labels } } updateStrategy := &obj.Spec.UpdateStrategy if updateStrategy.Type == "" { updateStrategy.Type = OnDeleteDaemonSetStrategyType } if updateStrategy.Type == RollingUpdateDaemonSetStrategyType { if updateStrategy.RollingUpdate == nil { rollingUpdate := RollingUpdateDaemonSet{} updateStrategy.RollingUpdate = &rollingUpdate } if updateStrategy.RollingUpdate.MaxUnavailable == nil { // Set default MaxUnavailable as 1 by default. maxUnavailable := intstr.FromInt(1) updateStrategy.RollingUpdate.MaxUnavailable = &maxUnavailable } } if obj.Spec.RevisionHistoryLimit == nil { obj.Spec.RevisionHistoryLimit = new(int32) *obj.Spec.RevisionHistoryLimit = 10 } } func SetDefaults_Deployment(obj *Deployment) { // Default labels and selector to labels from pod template spec. labels := obj.Spec.Template.Labels if labels != nil { if obj.Spec.Selector == nil { obj.Spec.Selector = &metav1.LabelSelector{MatchLabels: labels} } if len(obj.Labels) == 0 { obj.Labels = labels } } // Set DeploymentSpec.Replicas to 1 if it is not set. if obj.Spec.Replicas == nil { obj.Spec.Replicas = new(int32) *obj.Spec.Replicas = 1 } strategy := &obj.Spec.Strategy // Set default DeploymentStrategyType as RollingUpdate. if strategy.Type == "" { strategy.Type = RollingUpdateDeploymentStrategyType } if strategy.Type == RollingUpdateDeploymentStrategyType || strategy.RollingUpdate != nil { if strategy.RollingUpdate == nil { rollingUpdate := RollingUpdateDeployment{} strategy.RollingUpdate = &rollingUpdate } if strategy.RollingUpdate.MaxUnavailable == nil { // Set default MaxUnavailable as 1 by default. maxUnavailable := intstr.FromInt(1) strategy.RollingUpdate.MaxUnavailable = &maxUnavailable } if strategy.RollingUpdate.MaxSurge == nil { // Set default MaxSurge as 1 by default. maxSurge := intstr.FromInt(1) strategy.RollingUpdate.MaxSurge = &maxSurge } } } func SetDefaults_ReplicaSet(obj *ReplicaSet) { labels := obj.Spec.Template.Labels // TODO: support templates defined elsewhere when we support them in the API if labels != nil { if obj.Spec.Selector == nil { obj.Spec.Selector = &metav1.LabelSelector{ MatchLabels: labels, } } if len(obj.Labels) == 0 { obj.Labels = labels } } if obj.Spec.Replicas == nil { obj.Spec.Replicas = new(int32) *obj.Spec.Replicas = 1 } } func SetDefaults_NetworkPolicy(obj *NetworkPolicy) { // Default any undefined Protocol fields to TCP. for _, i := range obj.Spec.Ingress { for _, p := range i.Ports { if p.Protocol == nil { proto := v1.ProtocolTCP p.Protocol = &proto } } } }
cdrage/kedge
vendor/k8s.io/kubernetes/staging/src/k8s.io/client-go/pkg/apis/extensions/v1beta1/defaults.go
GO
apache-2.0
3,848
class Openjpeg < Formula desc "Library for JPEG-2000 image manipulation" homepage "http://www.openjpeg.org" url "https://mirrors.ocf.berkeley.edu/debian/pool/main/o/openjpeg/openjpeg_1.5.2.orig.tar.gz" mirror "https://mirrorservice.org/sites/ftp.debian.org/debian/pool/main/o/openjpeg/openjpeg_1.5.2.orig.tar.gz" sha256 "aef498a293b4e75fa1ca8e367c3f32ed08e028d3557b069bf8584d0c1346026d" revision 1 head "https://github.com/uclouvain/openjpeg.git", :branch => "openjpeg-1.5" bottle do cellar :any sha256 "50be982ed3846844ac93a34ebd159c680bed484f96b6c0ea274c2e88cc5501de" => :el_capitan sha256 "c9cc5b4f37fdf8b8fc1b043597ab6ac4aa30bfa8fde94b7b0d67a30f03a3cb1b" => :yosemite sha256 "92badbf4968bfda26318855b28940f564e60c701fe3b4e29bc4f173748da7476" => :mavericks sha256 "a30aa5b0a7ebcc1daba910671183084d69afb1d30cb85bfeb8b213f8e7a617d7" => :mountain_lion end depends_on "cmake" => :build depends_on "little-cms2" depends_on "libtiff" depends_on "libpng" def install system "cmake", ".", *std_cmake_args system "make", "install" # https://github.com/uclouvain/openjpeg/issues/562 (lib/"pkgconfig").install_symlink lib/"pkgconfig/libopenjpeg1.pc" => "libopenjpeg.pc" end test do (testpath/"test.c").write <<-EOS.undent #include <openjpeg.h> int main () { opj_image_cmptparm_t cmptparm; const OPJ_COLOR_SPACE color_space = CLRSPC_GRAY; opj_image_t *image; image = opj_image_create(1, &cmptparm, color_space); opj_image_destroy(image); return 0; } EOS system ENV.cc, "-I#{include}/openjpeg-1.5", "-L#{lib}", "-lopenjpeg", testpath/"test.c", "-o", "test" system "./test" end end
rokn/Count_Words_2015
fetched_code/ruby/openjpeg.rb
Ruby
mit
1,743
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kuberuntime import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/kubernetes/pkg/api/v1" runtimeapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" ) // TestCreatePodSandbox tests creating sandbox and its corresponding pod log directory. func TestCreatePodSandbox(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "foo", Image: "busybox", ImagePullPolicy: v1.PullIfNotPresent, }, }, }, } fakeOS := m.osInterface.(*containertest.FakeOS) fakeOS.MkdirAllFn = func(path string, perm os.FileMode) error { // Check pod logs root directory is created. assert.Equal(t, filepath.Join(podLogsRootDirectory, "12345678"), path) assert.Equal(t, os.FileMode(0755), perm) return nil } id, _, err := m.createPodSandbox(pod, 1) assert.NoError(t, err) fakeRuntime.AssertCalls([]string{"RunPodSandbox"}) sandboxes, err := fakeRuntime.ListPodSandbox(&runtimeapi.PodSandboxFilter{Id: id}) assert.NoError(t, err) assert.Equal(t, len(sandboxes), 1) // TODO Check pod sandbox configuration }
wanghaoran1988/origin
vendor/k8s.io/kubernetes/pkg/kubelet/kuberuntime/kuberuntime_sandbox_test.go
GO
apache-2.0
1,975
/* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ (function (root, $, _, Backbone) { "use strict"; /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ var window = root; var Backgrid = root.Backgrid = { VERSION: "0.1.3", Extension: {} }; // Copyright 2009, 2010 Kristopher Michael Kowal // https://github.com/kriskowal/es5-shim // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { if (this === undefined || this === null) { throw new TypeError("can't convert " + this + " to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); }; } function capitalize(s) { return String.fromCharCode(s.charCodeAt(0) - 32) + s.slice(1); } function lpad(str, length, padstr) { var paddingLen = length - (str + '').length; paddingLen = paddingLen < 0 ? 0 : paddingLen; var padding = ''; for (var i = 0; i < paddingLen; i++) { padding = padding + padstr; } return padding + str; } function requireOptions(options, requireOptionKeys) { for (var i = 0; i < requireOptionKeys.length; i++) { var key = requireOptionKeys[i]; if (_.isUndefined(options[key])) { throw new TypeError("'" + key + "' is required"); } } } function resolveNameToClass(name, suffix) { if (_.isString(name)) { var key = capitalize(name) + suffix; var klass = Backgrid[key] || Backgrid.Extension[key]; if (_.isUndefined(klass)) { throw new ReferenceError("Class '" + key + "' not found"); } return klass; } return name; } /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Just a convenient class for interested parties to subclass. The default Cell classes don't require the formatter to be a subclass of Formatter as long as the fromRaw(rawData) and toRaw(formattedData) methods are defined. @abstract @class Backgrid.CellFormatter @constructor */ var CellFormatter = Backgrid.CellFormatter = function () {}; _.extend(CellFormatter.prototype, { /** Takes a raw value from a model and returns a formatted string for display. @member Backgrid.CellFormatter @param {*} rawData @return {string} */ fromRaw: function (rawData) { return rawData; }, /** Takes a formatted string, usually from user input, and returns a appropriately typed value for persistence in the model. If the user input is invalid or unable to be converted to a raw value suitable for persistence in the model, toRaw must return `undefined`. @member Backgrid.CellFormatter @param {string} formattedData @return {*|undefined} */ toRaw: function (formattedData) { return formattedData; } }); /** A floating point number formatter. Doesn't understand notation at the moment. @class Backgrid.NumberFormatter @extends Backgrid.CellFormatter @constructor @throws {RangeError} If decimals < 0 or > 20. */ var NumberFormatter = Backgrid.NumberFormatter = function (options) { options = options ? _.clone(options) : {}; _.extend(this, this.defaults, options); if (this.decimals < 0 || this.decimals > 20) { throw new RangeError("decimals must be between 0 and 20"); } }; NumberFormatter.prototype = new CellFormatter; _.extend(NumberFormatter.prototype, { /** @member Backgrid.NumberFormatter @cfg {Object} options @cfg {number} [options.decimals=2] Number of decimals to display. Must be an integer. @cfg {string} [options.decimalSeparator='.'] The separator to use when displaying decimals. @cfg {string} [options.orderSeparator=','] The separator to use to separator thousands. May be an empty string. */ defaults: { decimals: 2, decimalSeparator: '.', orderSeparator: ',' }, HUMANIZED_NUM_RE: /(\d)(?=(?:\d{3})+$)/g, /** Takes a floating point number and convert it to a formatted string where every thousand is separated by `orderSeparator`, with a `decimal` number of decimals separated by `decimalSeparator`. The number returned is rounded the usual way. @member Backgrid.NumberFormatter @param {number} number @return {string} */ fromRaw: function (number) { if (isNaN(number) || number === null) return ''; number = number.toFixed(~~this.decimals); var parts = number.split('.'); var integerPart = parts[0]; var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : ''; return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart; }, /** Takes a string, possibly formatted with `orderSeparator` and/or `decimalSeparator`, and convert it back to a number. @member Backgrid.NumberFormatter @param {string} formattedData @return {number|undefined} Undefined if the string cannot be converted to a number. */ toRaw: function (formattedData) { var rawData = ''; var thousands = formattedData.trim().split(this.orderSeparator); for (var i = 0; i < thousands.length; i++) { rawData += thousands[i]; } var decimalParts = rawData.split(this.decimalSeparator); rawData = ''; for (var i = 0; i < decimalParts.length; i++) { rawData = rawData + decimalParts[i] + '.'; } if (rawData[rawData.length - 1] === '.') { rawData = rawData.slice(0, rawData.length - 1); } var result = (rawData * 1).toFixed(~~this.decimals) * 1; if (_.isNumber(result) && !_.isNaN(result)) return result; } }); /** Formatter to converts between various datetime string formats. This class only understands ISO-8601 formatted datetime strings. See Backgrid.Extension.MomentFormatter if you need a much more flexible datetime formatter. @class Backgrid.DatetimeFormatter @extends Backgrid.CellFormatter @constructor @throws {Error} If both `includeDate` and `includeTime` are false. */ var DatetimeFormatter = Backgrid.DatetimeFormatter = function (options) { options = options ? _.clone(options) : {}; _.extend(this, this.defaults, options); if (!this.includeDate && !this.includeTime) { throw new Error("Either includeDate or includeTime must be true"); } }; DatetimeFormatter.prototype = new CellFormatter; _.extend(DatetimeFormatter.prototype, { /** @member Backgrid.DatetimeFormatter @cfg {Object} options @cfg {boolean} [options.includeDate=true] Whether the values include the date part. @cfg {boolean} [options.includeTime=true] Whether the values include the time part. @cfg {boolean} [options.includeMilli=false] If `includeTime` is true, whether to include the millisecond part, if it exists. */ defaults: { includeDate: true, includeTime: true, includeMilli: false }, DATE_RE: /^([+\-]?\d{4})-(\d{2})-(\d{2})$/, TIME_RE: /^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/, ISO_SPLITTER_RE: /T|Z| +/, _convert: function (data, validate) { if (_.isNull(data) || _.isUndefined(data)) return data; data = data.trim(); var parts = data.split(this.ISO_SPLITTER_RE) || []; var date = this.DATE_RE.test(parts[0]) ? parts[0] : ''; var time = date && parts[1] ? parts[1] : this.TIME_RE.test(parts[0]) ? parts[0] : ''; var YYYYMMDD = this.DATE_RE.exec(date) || []; var HHmmssSSS = this.TIME_RE.exec(time) || []; if (validate) { if (this.includeDate && _.isUndefined(YYYYMMDD[0])) return; if (this.includeTime && _.isUndefined(HHmmssSSS[0])) return; if (!this.includeDate && date) return; if (!this.includeTime && time) return; } var jsDate = new Date(Date.UTC(YYYYMMDD[1] * 1 || 0, YYYYMMDD[2] * 1 - 1 || 0, YYYYMMDD[3] * 1 || 0, HHmmssSSS[1] * 1 || null, HHmmssSSS[2] * 1 || null, HHmmssSSS[3] * 1 || null, HHmmssSSS[5] * 1 || null)); var result = ''; if (this.includeDate) { result = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0); } if (this.includeTime) { result = result + (this.includeDate ? 'T' : '') + lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0); if (this.includeMilli) { result = result + '.' + lpad(jsDate.getUTCMilliseconds(), 3, 0); } } if (this.includeDate && this.includeTime) { result += "Z"; } return result; }, /** Converts an ISO-8601 formatted datetime string to a datetime string, date string or a time string. The timezone is ignored if supplied. @member Backgrid.DatetimeFormatter @param {string} rawData @return {string|null|undefined} ISO-8601 string in UTC. Null and undefined values are returned as is. */ fromRaw: function (rawData) { return this._convert(rawData); }, /** Converts an ISO-8601 formatted datetime string to a datetime string, date string or a time string. The timezone is ignored if supplied. This method parses the input values exactly the same way as Backgrid.Extension.MomentFormatter#fromRaw(), in addition to doing some sanity checks. @member Backgrid.DatetimeFormatter @param {string} formattedData @return {string|undefined} ISO-8601 string in UTC. Undefined if a date is found `includeDate` is false, or a time is found if `includeTime` is false, or if `includeDate` is true and a date is not found, or if `includeTime` is true and a time is not found. */ toRaw: function (formattedData) { return this._convert(formattedData, true); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Generic cell editor base class. Only defines an initializer for a number of required parameters. @abstract @class Backgrid.CellEditor @extends Backbone.View */ var CellEditor = Backgrid.CellEditor = Backbone.View.extend({ /** Initializer. @param {Object} options @param {*} options.parent @param {Backgrid.CellFormatter} options.formatter @param {Backgrid.Column} options.column @param {Backbone.Model} options.model @throws {TypeError} If `formatter` is not a formatter instance, or when `model` or `column` are undefined. */ initialize: function (options) { requireOptions(options, ["formatter", "column", "model"]); this.parent = options.parent; this.formatter = options.formatter; this.column = options.column; if (!(this.column instanceof Column)) { this.column = new Column(this.column); } if (this.parent && _.isFunction(this.parent.on)) { this.listenTo(this.parent, "editing", this.postRender); } }, /** Post-rendering setup and initialization. Focuses the cell editor's `el` in this default implementation. **Should** be called by Cell classes after calling Backgrid.CellEditor#render. */ postRender: function () { this.$el.focus(); return this; } }); /** InputCellEditor the cell editor type used by most core cell types. This cell editor renders a text input box as its editor. The input will render a placeholder if the value is empty on supported browsers. @class Backgrid.InputCellEditor @extends Backgrid.CellEditor */ var InputCellEditor = Backgrid.InputCellEditor = CellEditor.extend({ /** @property */ tagName: "input", /** @property */ attributes: { type: "text" }, /** @property */ events: { "blur": "saveOrCancel", "keydown": "saveOrCancel" }, /** Initializer. Removes this `el` from the DOM when a `done` event is triggered. @param {Object} options @param {Backgrid.CellFormatter} options.formatter @param {Backgrid.Column} options.column @param {Backbone.Model} options.model @param {string} [options.placeholder] */ initialize: function (options) { CellEditor.prototype.initialize.apply(this, arguments); if (options.placeholder) { this.$el.attr("placeholder", options.placeholder); } this.listenTo(this, "done", this.remove); }, /** Renders a text input with the cell value formatted for display, if it exists. */ render: function () { this.$el.val(this.formatter.fromRaw(this.model.get(this.column.get("name")))); return this; }, /** If the key pressed is `enter` or `tab`, converts the value in the editor to a raw value for the model using the formatter. If the key pressed is `esc` the changes are undone. If the editor's value was changed and goes out of focus (`blur`), the event is intercepted, cancelled so the cell remains in focus pending for further action. Triggers a Backbone `done` event when successful. `error` if the value cannot be converted. Classes listening to the `error` event, usually the Cell classes, should respond appropriately, usually by rendering some kind of error feedback. @param {Event} e */ saveOrCancel: function (e) { if (e.type === "keydown") { // enter or tab if (e.keyCode === 13 || e.keyCode === 9) { e.preventDefault(); var valueToSet = this.formatter.toRaw(this.$el.val()); if (_.isUndefined(valueToSet) || !this.model.set(this.column.get("name"), valueToSet, {validate: true})) { this.trigger("error"); } else { this.trigger("done"); } } // esc else if (e.keyCode === 27) { // undo e.stopPropagation(); this.trigger("done"); } } else if (e.type === "blur") { if (this.formatter.fromRaw(this.model.get(this.column.get("name"))) === this.$el.val()) { this.trigger("done"); } else { var self = this; var timeout = window.setTimeout(function () { self.$el.focus(); window.clearTimeout(timeout); }, 1); } } }, postRender: function () { // move the cursor to the end on firefox if text is right aligned if (this.$el.css("text-align") === "right") { var val = this.$el.val(); this.$el.focus().val(null).val(val); } else { this.$el.focus(); } return this; } }); /** The super-class for all Cell types. By default, this class renders a plain table cell with the model value converted to a string using the formatter. The table cell is clickable, upon which the cell will go into editor mode, which is rendered by a Backgrid.InputCellEditor instance by default. Upon any formatting errors, this class will add a `error` CSS class to the table cell. @abstract @class Backgrid.Cell @extends Backbone.View */ var Cell = Backgrid.Cell = Backbone.View.extend({ /** @property */ tagName: "td", /** @property {Backgrid.CellFormatter|Object|string} [formatter=new CellFormatter()] */ formatter: new CellFormatter(), /** @property {Backgrid.CellEditor} [editor=Backgrid.InputCellEditor] The default editor for all cell instances of this class. This value must be a class, it will be automatically instantiated upon entering edit mode. See Backgrid.CellEditor */ editor: InputCellEditor, /** @property */ events: { "click": "enterEditMode" }, /** Initializer. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column @throws {ReferenceError} If formatter is a string but a formatter class of said name cannot be found in the Backgrid module. */ initialize: function (options) { requireOptions(options, ["model", "column"]); this.column = options.column; if (!(this.column instanceof Column)) { this.column = new Column(this.column); } this.formatter = resolveNameToClass(this.formatter, "Formatter"); this.editor = resolveNameToClass(this.editor, "CellEditor"); this.listenTo(this.model, "change:" + this.column.get("name"), function () { if (!this.$el.hasClass("editor")) this.render(); }); }, /** Render a text string in a table cell. The text is converted from the model's raw value for this cell's column. */ render: function () { this.$el.empty().text(this.formatter.fromRaw(this.model.get(this.column.get("name")))); return this; }, /** If this column is editable, a new CellEditor instance is instantiated with its required parameters and listens on the editor's `done` and `error` events. When the editor is `done`, edit mode is exited. When the editor triggers an `error` event, it means the editor is unable to convert the current user input to an apprpriate value for the model's column. An `editor` CSS class is added to the cell upon entering edit mode. */ enterEditMode: function (e) { if (this.column.get("editable")) { this.currentEditor = new this.editor({ parent: this, column: this.column, model: this.model, formatter: this.formatter }); /** Backbone Event. Fired when a cell is entering edit mode and an editor instance has been constructed, but before it is rendered and inserted into the DOM. @event edit @param {Backgrid.Cell} cell This cell instance. @param {Backgrid.CellEditor} editor The cell editor constructed. */ this.trigger("edit", this, this.currentEditor); this.listenTo(this.currentEditor, "done", this.exitEditMode); this.listenTo(this.currentEditor, "error", this.renderError); this.$el.empty(); this.undelegateEvents(); this.$el.append(this.currentEditor.$el); this.currentEditor.render(); this.$el.addClass("editor"); /** Backbone Event. Fired when a cell has finished switching to edit mode. @event editing @param {Backgrid.Cell} cell This cell instance. @param {Backgrid.CellEditor} editor The cell editor constructed. */ this.trigger("editing", this, this.currentEditor); } }, /** Put an `error` CSS class on the table cell. */ renderError: function () { this.$el.addClass("error"); }, /** Removes the editor and re-render in display mode. */ exitEditMode: function () { this.$el.removeClass("error"); this.currentEditor.off(null, null, this); this.currentEditor.remove(); delete this.currentEditor; this.$el.removeClass("editor"); this.render(); this.delegateEvents(); }, /** Clean up this cell. @chainable */ remove: function () { if (this.currentEditor) { this.currentEditor.remove.apply(this, arguments); delete this.currentEditor; } return Backbone.View.prototype.remove.apply(this, arguments); } }); /** StringCell displays HTML escaped strings and accepts anything typed in. @class Backgrid.StringCell @extends Backgrid.Cell */ var StringCell = Backgrid.StringCell = Cell.extend({ /** @property */ className: "string-cell" // No formatter needed. Strings call auto-escaped by jQuery on insertion. }); /** UriCell renders an HTML `<a>` anchor for the value and accepts URIs as user input values. A URI input is URI encoded using `encodeURI()` before writing to the underlying model. @class Backgrid.UriCell @extends Backgrid.Cell */ var UriCell = Backgrid.UriCell = Cell.extend({ /** @property */ className: "uri-cell", formatter: { fromRaw: function (rawData) { return rawData; }, toRaw: function (formattedData) { var result = encodeURI(formattedData); return result === "undefined" ? undefined : result; } }, render: function () { this.$el.empty(); var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name"))); this.$el.append($("<a>", { href: formattedValue, title: formattedValue, target: "_blank" }).text(formattedValue)); return this; } }); /** Like Backgrid.UriCell, EmailCell renders an HTML `<a>` anchor for the value. The `href` in the anchor is prefixed with `mailto:`. EmailCell will complain if the user enters a string that doesn't contain the `@` sign. @class Backgrid.EmailCell @extends Backgrid.Cell */ var EmailCell = Backgrid.EmailCell = Cell.extend({ /** @property */ className: "email-cell", formatter: { fromRaw: function (rawData) { return rawData; }, toRaw: function (formattedData) { var parts = formattedData.split("@"); if (parts.length === 2 && _.all(parts)) { return formattedData; } } }, render: function () { this.$el.empty(); var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name"))); this.$el.append($("<a>", { href: "mailto:" + formattedValue, title: formattedValue }).text(formattedValue)); return this; } }); /** NumberCell is a generic cell that renders all numbers. Numbers are formatted using a Backgrid.NumberFormatter. @class Backgrid.NumberCell @extends Backgrid.Cell */ var NumberCell = Backgrid.NumberCell = Cell.extend({ /** @property */ className: "number-cell", /** @property {number} [decimals=2] Must be an integer. */ decimals: NumberFormatter.prototype.defaults.decimals, /** @property {string} [decimalSeparator='.'] */ decimalSeparator: NumberFormatter.prototype.defaults.decimalSeparator, /** @property {string} [orderSeparator=','] */ orderSeparator: NumberFormatter.prototype.defaults.orderSeparator, /** @property {Backgrid.CellFormatter} [formatter=Backgrid.NumberFormatter] */ formatter: NumberFormatter, /** Initializes this cell and the number formatter. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column */ initialize: function (options) { Cell.prototype.initialize.apply(this, arguments); this.formatter = new this.formatter({ decimals: this.decimals, decimalSeparator: this.decimalSeparator, orderSeparator: this.orderSeparator }); } }); /** An IntegerCell is just a Backgrid.NumberCell with 0 decimals. If a floating point number is supplied, the number is simply rounded the usual way when displayed. @class Backgrid.IntegerCell @extends Backgrid.NumberCell */ var IntegerCell = Backgrid.IntegerCell = NumberCell.extend({ /** @property */ className: "integer-cell", /** @property {number} decimals Must be an integer. */ decimals: 0 }); /** DatetimeCell is a basic cell that accepts datetime string values in RFC-2822 or W3C's subset of ISO-8601 and displays them in ISO-8601 format. For a much more sophisticated date time cell with better datetime formatting, take a look at the Backgrid.Extension.MomentCell extension. @class Backgrid.DatetimeCell @extends Backgrid.Cell See: - Backgrid.Extension.MomentCell - Backgrid.DatetimeFormatter */ var DatetimeCell = Backgrid.DatetimeCell = Cell.extend({ /** @property */ className: "datetime-cell", /** @property {boolean} [includeDate=true] */ includeDate: DatetimeFormatter.prototype.defaults.includeDate, /** @property {boolean} [includeTime=true] */ includeTime: DatetimeFormatter.prototype.defaults.includeTime, /** @property {boolean} [includeMilli=false] */ includeMilli: DatetimeFormatter.prototype.defaults.includeMilli, /** @property {Backgrid.CellFormatter} [formatter=Backgrid.DatetimeFormatter] */ formatter: DatetimeFormatter, /** Initializes this cell and the datetime formatter. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column */ initialize: function (options) { Cell.prototype.initialize.apply(this, arguments); this.formatter = new this.formatter({ includeDate: this.includeDate, includeTime: this.includeTime, includeMilli: this.includeMilli }); var placeholder = this.includeDate ? "YYYY-MM-DD" : ""; placeholder += (this.includeDate && this.includeTime) ? "T" : ""; placeholder += this.includeTime ? "HH:mm:ss" : ""; placeholder += (this.includeTime && this.includeMilli) ? ".SSS" : ""; this.editor = this.editor.extend({ attributes: _.extend({}, this.editor.prototype.attributes, this.editor.attributes, { placeholder: placeholder }) }); } }); /** DateCell is a Backgrid.DatetimeCell without the time part. @class Backgrid.DateCell @extends Backgrid.DatetimeCell */ var DateCell = Backgrid.DateCell = DatetimeCell.extend({ /** @property */ className: "date-cell", /** @property */ includeTime: false }); /** TimeCell is a Backgrid.DatetimeCell without the date part. @class Backgrid.TimeCell @extends Backgrid.DatetimeCell */ var TimeCell = Backgrid.TimeCell = DatetimeCell.extend({ /** @property */ className: "time-cell", /** @property */ includeDate: false }); /** BooleanCell is a different kind of cell in that there's no difference between display mode and edit mode and this cell type always renders a checkbox for selection. @class Backgrid.BooleanCell @extends Backgrid.Cell */ var BooleanCell = Backgrid.BooleanCell = Cell.extend({ /** @property */ className: "boolean-cell", /** BooleanCell simple uses a default HTML checkbox template instead of a CellEditor instance. @property {function(Object, ?Object=): string} editor The Underscore.js template to render the editor. */ editor: _.template("<input type='checkbox'<%= checked ? checked='checked' : '' %> />'"), /** Since the editor is not an instance of a CellEditor subclass, more things need to be done in BooleanCell class to listen to editor mode events. */ events: { "click": "enterEditMode", "blur input[type=checkbox]": "exitEditMode", "change input[type=checkbox]": "save" }, /** Renders a checkbox and check it if the model value of this column is true, uncheck otherwise. */ render: function () { this.$el.empty(); this.currentEditor = $(this.editor({ checked: this.formatter.fromRaw(this.model.get(this.column.get("name"))) })); this.$el.append(this.currentEditor); return this; }, /** Simple focuses the checkbox and add an `editor` CSS class to the cell. */ enterEditMode: function (e) { this.$el.addClass("editor"); this.currentEditor.focus(); }, /** Removed the `editor` CSS class from the cell. */ exitEditMode: function (e) { this.$el.removeClass("editor"); }, /** Set true to the model attribute if the checkbox is checked, false otherwise. */ save: function (e) { var val = this.formatter.toRaw(this.currentEditor.prop("checked")); this.model.set(this.column.get("name"), val); } }); /** SelectCellEditor renders an HTML `<select>` fragment as the editor. @class Backgrid.SelectCellEditor @extends Backgrid.CellEditor */ var SelectCellEditor = Backgrid.SelectCellEditor = CellEditor.extend({ /** @property */ tagName: "select", /** @property */ events: { "change": "save", "blur": "save" }, /** @property {function(Object, ?Object=): string} template */ template: _.template('<option value="<%- value %>" <%= selected ? \'selected="selected"\' : "" %>><%- text %></option>'), setOptionValues: function (optionValues) { this.optionValues = optionValues; }, _renderOptions: function (nvps, currentValue) { var options = ''; for (var i = 0; i < nvps.length; i++) { options = options + this.template({ text: nvps[i][0], value: nvps[i][1], selected: currentValue == nvps[i][1] }); } return options; }, /** Renders the options if `optionValues` is a list of name-value pairs. The options are contained inside option groups if `optionValues` is a list of object hashes. The name is rendered at the option text and the value is the option value. If `optionValues` is a function, it is called without a parameter. */ render: function () { this.$el.empty(); var optionValues = _.result(this, "optionValues"); var currentValue = this.model.get(this.column.get("name")); if (!_.isArray(optionValues)) throw TypeError("optionValues must be an array"); var optionValue = null; var optionText = null; var optionValue = null; var optgroupName = null; var optgroup = null; for (var i = 0; i < optionValues.length; i++) { var optionValue = optionValues[i]; if (_.isArray(optionValue)) { optionText = optionValue[0]; optionValue = optionValue[1]; this.$el.append(this.template({ text: optionText, value: optionValue, selected: optionValue == currentValue })); } else if (_.isObject(optionValue)) { optgroupName = optionValue.name; optgroup = $("<optgroup></optgroup>", { label: optgroupName }); optgroup.append(this._renderOptions(optionValue.values, currentValue)); this.$el.append(optgroup); } else { throw TypeError("optionValues elements must be a name-value pair or an object hash of { name: 'optgroup label', value: [option name-value pairs] }"); } } return this; }, /** Saves the value of the selected option to the model attribute. Triggers a `done` Backbone event. */ save: function (e) { this.model.set(this.column.get("name"), this.formatter.toRaw(this.$el.val())); this.trigger("done"); } }); /** SelectCell is also a different kind of cell in that upon going into edit mode the cell renders a list of options for to pick from, as opposed to an input box. SelectCell cannot be referenced by its string name when used in a column definition because requires an `optionValues` class attribute to be defined. `optionValues` can either be a list of name-value pairs, to be rendered as options, or a list of object hashes which consist of a key *name* which is the option group name, and a key *values* which is a list of name-value pairs to be rendered as options under that option group. In addition, `optionValues` can also be a parameter-less function that returns one of the above. If the options are static, it is recommended the returned values to be memoized. _.memoize() is a good function to help with that. @class Backgrid.SelectCell @extends Backgrid.Cell */ var SelectCell = Backgrid.SelectCell = Cell.extend({ /** @property */ className: "select-cell", /** @property */ editor: SelectCellEditor, /** @property {Array.<Array>|Array.<{name: string, values: Array.<Array>}>} optionValues */ optionValues: undefined, /** Initializer. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column @throws {TypeError} If `optionsValues` is undefined. */ initialize: function (options) { Cell.prototype.initialize.apply(this, arguments); requireOptions(this, ["optionValues"]); this.optionValues = _.result(this, "optionValues"); this.listenTo(this, "edit", this.setOptionValues); }, setOptionValues: function (cell, editor) { editor.setOptionValues(this.optionValues); }, /** Renders the label using the raw value as key to look up from `optionValues`. @throws {TypeError} If `optionValues` is malformed. */ render: function () { this.$el.empty(); var optionValues = this.optionValues; var rawData = this.formatter.fromRaw(this.model.get(this.column.get("name"))); try { if (!_.isArray(optionValues) || _.isEmpty(optionValues)) throw new TypeError; for (var i = 0; i < optionValues.length; i++) { var optionValue = optionValues[i]; if (_.isArray(optionValue)) { var optionText = optionValue[0]; var optionValue = optionValue[1]; if (optionValue == rawData) { this.$el.append(optionText); break; } } else if (_.isObject(optionValue)) { var optionGroupValues = optionValue.values; for (var j = 0; j < optionGroupValues.length; j++) { var optionGroupValue = optionGroupValues[j]; if (optionGroupValue[1] == rawData) { this.$el.append(optionGroupValue[0]); break; } } } else { throw new TypeError; } } } catch (ex) { if (ex instanceof TypeError) { throw TypeError("'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}"); } throw ex; } return this; } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** A Column is a placeholder for column metadata. You usually don't need to create an instance of this class yourself as a collection of column instances will be created for you from a list of column attributes in the Backgrid.js view class constructors. @class Backgrid.Column @extends Backbone.Model */ var Column = Backgrid.Column = Backbone.Model.extend({ defaults: { name: undefined, label: undefined, sortable: true, editable: true, renderable: true, formatter: undefined, cell: undefined, headerCell: undefined }, /** Initializes this Column instance. @param {Object} attrs Column attributes. @param {string} attrs.name The name of the model attribute. @param {string|Backgrid.Cell} attrs.cell The cell type. If this is a string, the capitalized form will be used to look up a cell class in Backbone, i.e.: string => StringCell. If a Cell subclass is supplied, it is initialized with a hash of parameters. If a Cell instance is supplied, it is used directly. @param {string|Backgrid.HeaderCell} [attrs.headerCell] The header cell type. @param {string} [attrs.label] The label to show in the header. @param {boolean} [attrs.sortable=true] @param {boolean} [attrs.editable=true] @param {boolean} [attrs.renderable=true] @param {Backgrid.CellFormatter|Object|string} [attrs.formatter] The formatter to use to convert between raw model values and user input. @throws {TypeError} If attrs.cell or attrs.options are not supplied. @throws {ReferenceError} If attrs.cell is a string but a cell class of said name cannot be found in the Backgrid module. See: - Backgrid.Cell - Backgrid.CellFormatter */ initialize: function (attrs) { requireOptions(attrs, ["cell", "name"]); if (!this.has("label")) { this.set({ label: this.get("name") }, { silent: true }); } var cell = resolveNameToClass(this.get("cell"), "Cell"); this.set({ cell: cell }, { silent: true }); } }); /** A Backbone collection of Column instances. @class Backgrid.Columns @extends Backbone.Collection */ var Columns = Backgrid.Columns = Backbone.Collection.extend({ /** @property {Backgrid.Column} model */ model: Column }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Row is a simple container view that takes a model instance and a list of column metadata describing how each of the model's attribute is to be rendered, and apply the appropriate cell to each attribute. @class Backgrid.Row @extends Backbone.View */ var Row = Backgrid.Row = Backbone.View.extend({ /** @property */ tagName: "tr", /** Initializes a row view instance. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Model} options.model The model instance to render. @throws {TypeError} If options.columns or options.model is undefined. */ initialize: function (options) { requireOptions(options, ["columns", "model"]); var columns = this.columns = options.columns; if (!(columns instanceof Backbone.Collection)) { columns = this.columns = new Columns(columns); } this.listenTo(columns, "change:renderable", this.renderColumn); var cells = this.cells = []; for (var i = 0; i < columns.length; i++) { var column = columns.at(i); cells.push(new (column.get("cell"))({ column: column, model: this.model })); } this.listenTo(columns, "add", function (column, columns, options) { options = _.defaults(options || {}, {render: true}); var at = columns.indexOf(column); var cell = new (column.get("cell"))({ column: column, model: this.model }); cells.splice(at, 0, cell); this.renderColumn(column, column.get("renderable") && options.render); }); this.listenTo(columns, "remove", function (column) { this.renderColumn(column, false); }); }, /** Backbone event handler. Insert a table cell to the right column in the row if renderable is true, detach otherwise. @param {Backgrid.Column} column @param {boolean} renderable */ renderColumn: function (column, renderable) { var cells = this.cells; var columns = this.columns; var spliceIndex = -1; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; if (cell.column.get("name") == column.get("name")) { spliceIndex = i; break; } } if (spliceIndex != -1) { var $el = this.$el; if (renderable) { var cell = cells[spliceIndex]; if (spliceIndex === 0) { $el.prepend(cell.render().$el); } else if (spliceIndex === columns.length - 1) { $el.append(cell.render().$el); } else { $el.children().eq(spliceIndex).before(cell.render().$el); } } else { $el.children().eq(spliceIndex).detach(); } } }, /** Renders a row of cells for this row's model. */ render: function () { this.$el.empty(); var fragment = document.createDocumentFragment(); for (var i = 0; i < this.cells.length; i++) { var cell = this.cells[i]; if (cell.column.get("renderable")) { fragment.appendChild(cell.render().el); } } this.el.appendChild(fragment); return this; }, /** Clean up this row and its cells. @chainable */ remove: function () { for (var i = 0; i < this.cells.length; i++) { var cell = this.cells[i]; cell.remove.apply(cell, arguments); } return Backbone.View.prototype.remove.apply(this, arguments); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** HeaderCell is a special cell class that renders a column header cell. If the column is sortable, a sorter is also rendered and will trigger a table refresh after sorting. @class Backgrid.HeaderCell @extends Backbone.View */ var HeaderCell = Backgrid.HeaderCell = Backbone.View.extend({ /** @property */ tagName: "th", /** @property */ events: { "click a": "onClick" }, /** @property {null|"ascending"|"descending"} _direction The current sorting direction of this column. */ _direction: null, /** Initializer. @param {Object} options @param {Backgrid.Column|Object} options.column @throws {TypeError} If options.column or options.collection is undefined. */ initialize: function (options) { requireOptions(options, ["column", "collection"]); this.column = options.column; if (!(this.column instanceof Column)) { this.column = new Column(this.column); } this.listenTo(Backbone, "backgrid:sort", this._resetCellDirection); }, /** Gets or sets the direction of this cell. If called directly without parameters, returns the current direction of this cell, otherwise sets it. If a `null` is given, sets this cell back to the default order. @param {null|"ascending"|"descending"} dir @return {null|string} The current direction or the changed direction. */ direction: function (dir) { if (arguments.length) { if (this._direction) this.$el.removeClass(this._direction); if (dir) this.$el.addClass(dir); this._direction = dir; } return this._direction; }, /** Event handler for the Backbone `backgrid:sort` event. Resets this cell's direction to default if sorting is being done on another column. @private */ _resetCellDirection: function (sortByColName, direction, comparator, collection) { if (collection == this.collection) { if (sortByColName !== this.column.get("name")) this.direction(null); else this.direction(direction); } }, /** Event handler for the `click` event on the cell's anchor. If the column is sortable, clicking on the anchor will cycle through 3 sorting orderings - `ascending`, `descending`, and default. */ onClick: function (e) { e.preventDefault(); var columnName = this.column.get("name"); if (this.column.get("sortable")) { if (this.direction() === "ascending") { this.sort(columnName, "descending", function (left, right) { var leftVal = left.get(columnName); var rightVal = right.get(columnName); if (leftVal === rightVal) { return 0; } else if (leftVal > rightVal) { return -1; } return 1; }); } else if (this.direction() === "descending") { this.sort(columnName, null); } else { this.sort(columnName, "ascending", function (left, right) { var leftVal = left.get(columnName); var rightVal = right.get(columnName); if (leftVal === rightVal) { return 0; } else if (leftVal < rightVal) { return -1; } return 1; }); } } }, /** If the underlying collection is a Backbone.PageableCollection in server-mode or infinite-mode, a page of models is fetched after sorting is done on the server. If the underlying collection is a Backbone.PageableCollection in client-mode, or any [Backbone.Collection](http://backbonejs.org/#Collection) instance, sorting is done on the client side. If the collection is an instance of a Backbone.PageableCollection, sorting will be done globally on all the pages and the current page will then be returned. Triggers a Backbone `backgrid:sort` event when done. @param {string} columnName @param {null|"ascending"|"descending"} direction @param {function(*, *): number} [comparator] See [Backbone.Collection#comparator](http://backbonejs.org/#Collection-comparator) */ sort: function (columnName, direction, comparator) { comparator = comparator || this._cidComparator; var collection = this.collection; if (Backbone.PageableCollection && collection instanceof Backbone.PageableCollection) { var order; if (direction === "ascending") order = -1; else if (direction === "descending") order = 1; else order = null; collection.setSorting(order ? columnName : null, order); if (collection.mode == "client") { if (!collection.fullCollection.comparator) { collection.fullCollection.comparator = comparator; } collection.fullCollection.sort(); } else collection.fetch(); } else { collection.comparator = comparator; collection.sort(); } /** Global Backbone event. Fired when the sorter is clicked on a sortable column. @event backgrid:sort @param {string} columnName @param {null|"ascending"|"descending"} direction @param {function(*, *): number} comparator A Backbone.Collection#comparator. @param {Backbone.Collection} collection */ Backbone.trigger("backgrid:sort", columnName, direction, comparator, this.collection); }, /** Default comparator for Backbone.Collections. Sorts cids in ascending order. The cids of the models are assumed to be in insertion order. @private @param {*} left @param {*} right */ _cidComparator: function (left, right) { var lcid = left.cid, rcid = right.cid; if (!_.isUndefined(lcid) && !_.isUndefined(rcid)) { lcid = lcid.slice(1) * 1, rcid = rcid.slice(1) * 1; if (lcid < rcid) return -1; else if (lcid > rcid) return 1; } return 0; }, /** Renders a header cell with a sorter and a label. */ render: function () { this.$el.empty(); var $label = $("<a>").text(this.column.get("label")).append("<b class='sort-caret'></b>"); this.$el.append($label); return this; } }); /** HeaderRow is a controller for a row of header cells. @class Backgrid.HeaderRow @extends Backgrid.Row */ var HeaderRow = Backgrid.HeaderRow = Backgrid.Row.extend({ /** Initializer. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns @param {Backgrid.HeaderCell} [options.headerCell] Customized default HeaderCell for all the columns. Supply a HeaderCell class or instance to a the `headerCell` key in a column definition for column-specific header rendering. @throws {TypeError} If options.columns or options.collection is undefined. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); var columns = this.columns = options.columns; if (!(columns instanceof Backbone.Collection)) { columns = this.columns = new Columns(columns); } this.listenTo(columns, "change:renderable", this.renderColumn); var cells = this.cells = []; for (var i = 0; i < columns.length; i++) { var column = columns.at(i); var headerCell = column.get("headerCell") || options.headerCell || HeaderCell; cells.push(new headerCell({ column: column, collection: this.collection })); } this.listenTo(columns, "add", function (column, columns, opts) { opts = _.defaults(opts || {}, {render: true}); var at = columns.indexOf(column); var headerCell = column.get("headerCell") || options.headerCell || HeaderCell; headerCell = new headerCell({ column: column, collection: this.collection }); cells.splice(at, 0, headerCell); this.renderColumn(column, column.get("renderable") && opts.render); }); this.listenTo(columns, "remove", function (column) { this.renderColumn(column, false); }); } }); /** Header is a special structural view class that renders a table head with a single row of header cells. @class Backgrid.Header @extends Backbone.View */ var Header = Backgrid.Header = Backbone.View.extend({ /** @property */ tagName: "thead", /** Initializer. Initializes this table head view to contain a single header row view. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Model} options.model The model instance to render. @throws {TypeError} If options.columns or options.model is undefined. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Columns(this.columns); } this.row = new Backgrid.HeaderRow({ columns: this.columns, collection: this.collection }); }, /** Renders this table head with a single row of header cells. */ render: function () { this.$el.append(this.row.render().$el); return this; }, /** Clean up this header and its row. @chainable */ remove: function () { this.row.remove.apply(this.row, arguments); return Backbone.View.prototype.remove.apply(this, arguments); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Body is the table body which contains the rows inside a table. Body is responsible for refreshing the rows after sorting, insertion and removal. @class Backgrid.Body @extends Backbone.View */ var Body = Backgrid.Body = Backbone.View.extend({ /** @property */ tagName: "tbody", /** Initializer. @param {Object} options @param {Backbone.Collection} options.collection @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata @param {Backgrid.Row} [options.row=Backgrid.Row] The Row class to use. @throws {TypeError} If options.columns or options.collection is undefined. See Backgrid.Row. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Columns(this.columns); } this.row = options.row || Row; this.rows = this.collection.map(function (model) { var row = new this.row({ columns: this.columns, model: model }); return row; }, this); var collection = this.collection; this.listenTo(collection, "add", this.insertRow); this.listenTo(collection, "remove", this.removeRow); this.listenTo(collection, "sort", this.refresh); this.listenTo(collection, "reset", this.refresh); }, /** This method can be called either directly or as a callback to a [Backbone.Collecton#add](http://backbonejs.org/#Collection-add) event. When called directly, it accepts a model or an array of models and an option hash just like [Backbone.Collection#add](http://backbonejs.org/#Collection-add) and delegates to it. Once the model is added, a new row is inserted into the body and automatically rendered. When called as a callback of an `add` event, splices a new row into the body and renders it. @param {Backbone.Model} model The model to render as a row. @param {Backbone.Collection} collection When called directly, this parameter is actually the options to [Backbone.Collection#add](http://backbonejs.org/#Collection-add). @param {Object} options When called directly, this must be null. See: - [Backbone.Collection#add](http://backbonejs.org/#Collection-add) */ insertRow: function (model, collection, options) { // insertRow() is called directly if (!(collection instanceof Backbone.Collection) && !options) { this.collection.add(model, (options = collection)); return; } options = _.extend({render: true}, options || {}); var row = new this.row({ columns: this.columns, model: model }); var index = collection.indexOf(model); this.rows.splice(index, 0, row); var $el = this.$el; var $children = $el.children(); var $rowEl = row.render().$el; if (options.render) { if (index >= $children.length) { $el.append($rowEl); } else { $children.eq(index).before($rowEl); } } }, /** The method can be called either directly or as a callback to a [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) event. When called directly, it accepts a model or an array of models and an option hash just like [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) and delegates to it. Once the model is removed, a corresponding row is removed from the body. When called as a callback of a `remove` event, splices into the rows and removes the row responsible for rendering the model. @param {Backbone.Model} model The model to remove from the body. @param {Backbone.Collection} collection When called directly, this parameter is actually the options to [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove). @param {Object} options When called directly, this must be null. See: - [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) */ removeRow: function (model, collection, options) { // removeRow() is called directly if (!options) { this.collection.remove(model, (options = collection)); return; } if (_.isUndefined(options.render) || options.render) { this.rows[options.index].remove(); } this.rows.splice(options.index, 1); }, /** Reinitialize all the rows inside the body and re-render them. @chainable */ refresh: function () { var self = this; _.each(self.rows, function (row) { row.remove(); }); self.rows = self.collection.map(function (model) { var row = new self.row({ columns: self.columns, model: model }); return row; }); self.render(); Backbone.trigger("backgrid:refresh"); return self; }, /** Renders all the rows inside this body. */ render: function () { this.$el.empty(); var fragment = document.createDocumentFragment(); for (var i = 0; i < this.rows.length; i++) { var row = this.rows[i]; fragment.appendChild(row.render().el); } this.el.appendChild(fragment); return this; }, /** Clean up this body and it's rows. @chainable */ remove: function () { for (var i = 0; i < this.rows.length; i++) { var row = this.rows[i]; row.remove.apply(row, arguments); } return Backbone.View.prototype.remove.apply(this, arguments); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** A Footer is a generic class that only defines a default tag `tfoot` and number of required parameters in the initializer. @abstract @class Backgrid.Footer @extends Backbone.View */ var Footer = Backgrid.Footer = Backbone.View.extend({ /** @property */ tagName: "tfoot", /** Initializer. @param {Object} options @param {*} options.parent The parent view class of this footer. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Collection} options.collection @throws {TypeError} If options.columns or options.collection is undefined. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); this.parent = options.parent; this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Backgrid.Columns(this.columns); } } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Grid represents a data grid that has a header, body and an optional footer. By default, a Grid treats each model in a collection as a row, and each attribute in a model as a column. To render a grid you must provide a list of column metadata and a collection to the Grid constructor. Just like any Backbone.View class, the grid is rendered as a DOM node fragment when you call render(). var grid = Backgrid.Grid({ columns: [{ name: "id", label: "ID", type: "string" }, // ... ], collections: books }); $("#table-container").append(grid.render().el); Optionally, if you want to customize the rendering of the grid's header and footer, you may choose to extend Backgrid.Header and Backgrid.Footer, and then supply that class or an instance of that class to the Grid constructor. See the documentation for Header and Footer for further details. var grid = Backgrid.Grid({ columns: [{ name: "id", label: "ID", type: "string" }], collections: books, header: Backgrid.Header.extend({ //... }), footer: Backgrid.Paginator }); Finally, if you want to override how the rows are rendered in the table body, you can supply a Body subclass as the `body` attribute that uses a different Row class. @class Backgrid.Grid @extends Backbone.View See: - Backgrid.Column - Backgrid.Header - Backgrid.Body - Backgrid.Row - Backgrid.Footer */ var Grid = Backgrid.Grid = Backbone.View.extend({ /** @property */ tagName: "table", /** @property */ className: "backgrid", /** @property */ header: Header, /** @property */ body: Body, /** @property */ footer: null, /** Initializes a Grid instance. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Collection} options.collection The collection of tabular model data to display. @param {Backgrid.Header} [options.header=Backgrid.Header] An optional Header class to override the default. @param {Backgrid.Body} [options.body=Backgrid.Body] An optional Body class to override the default. @param {Backgrid.Row} [options.row=Backgrid.Row] An optional Row class to override the default. @param {Backgrid.Footer} [options.footer=Backgrid.Footer] An optional Footer class. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); // Convert the list of column objects here first so the subviews don't have // to. if (!(options.columns instanceof Backbone.Collection)) { options.columns = new Columns(options.columns); } this.columns = options.columns; this.header = options.header || this.header; this.header = new this.header(options); this.body = options.body || this.body; this.body = new this.body(options); this.footer = options.footer || this.footer; if (this.footer) { this.footer = new this.footer(options); } this.listenTo(this.columns, "reset", function () { this.header = new (this.header.remove().constructor)(options); this.body = new (this.body.remove().constructor)(options); if (this.footer) this.footer = new (this.footer.remove().constructor)(options); this.render(); }); }, /** Delegates to Backgrid.Body#insertRow. */ insertRow: function (model, collection, options) { return this.body.insertRow(model, collection, options); }, /** Delegates to Backgrid.Body#removeRow. */ removeRow: function (model, collection, options) { return this.body.removeRow(model, collection, options); }, /** Delegates to Backgrid.Columns#add for adding a column. Subviews can listen to the `add` event from their internal `columns` if rerendering needs to happen. @param {Object} [options] Options for `Backgrid.Columns#add`. @param {boolean} [options.render=true] Whether to render the column immediately after insertion. @chainable */ insertColumn: function (column, options) { var self = this; options = options || {render: true}; self.columns.add(column, options); return self; }, /** Delegates to Backgrid.Columns#remove for removing a column. Subviews can listen to the `remove` event from the internal `columns` if rerendering needs to happen. @param {Object} [options] Options for `Backgrid.Columns#remove`. @chainable */ removeColumn: function (column, options) { var self = this; self.columns.remove(column, options); return self; }, /** Renders the grid's header, then footer, then finally the body. */ render: function () { this.$el.empty(); this.$el.append(this.header.render().$el); if (this.footer) { this.$el.append(this.footer.render().$el); } this.$el.append(this.body.render().$el); /** Backbone event. Fired when the grid has been successfully rendered. @event rendered */ this.trigger("rendered"); return this; }, /** Clean up this grid and its subviews. @chainable */ remove: function () { this.header.remove.apply(this.header, arguments); this.body.remove.apply(this.body, arguments); this.footer && this.footer.remove.apply(this.footer, arguments); return Backbone.View.prototype.remove.apply(this, arguments); } }); }(this, $, _, Backbone));
BobbieBel/cdnjs
ajax/libs/backgrid.js/0.1.3/backgrid.js
JavaScript
mit
62,121
// { dg-do assemble } // { dg-options "-pedantic -Wno-deprecated" } // This code snippet should be rejected with -pedantic // Based on a test case by Louidor Erez <s3824888@techst02.technion.ac.il> template<class T> class Vector { public: typedef T* iterator; }; template<class T> void f() { Vector<T>::iterator i = 0; // { dg-error "typename" "typename" } missing typename } // { dg-error "expected" "expected" { target *-*-* } 16 }
selmentdev/selment-toolchain
source/gcc-latest/gcc/testsuite/g++.old-deja/g++.other/typename1.C
C++
gpl-3.0
442
// 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. // catch ret inside try region // note: this is NOT the test case // after vswhidbey:5875 is fixed, intry will be outside the outer try block using System; namespace hello { class Class1 { private static TestUtil.TestLog testLog; static Class1() { // Create test writer object to hold expected output System.IO.StringWriter expectedOut = new System.IO.StringWriter(); // Write expected output to string writer object expectedOut.WriteLine("1234"); expectedOut.WriteLine("test2"); expectedOut.WriteLine("end outer catch test2"); expectedOut.WriteLine("1234"); // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } static public int Main(string[] args) { //Start recording testLog.StartRecording(); int i = 1234; Console.WriteLine(i); goto begin2; begin: String s = "test1"; begin2: s = "test2"; intry: try { Console.WriteLine(s); throw new Exception(); } catch { try { if (i == 3) goto intry; // catch ret if (i >= 0) goto incatch; if (i < 0) goto begin; // catch ret } catch { if (i != 0) goto incatch; Console.WriteLine("end inner catch"); } Console.WriteLine("unreached"); incatch: Console.WriteLine("end outer catch " + s); } Console.WriteLine(i); // stop recoding testLog.StopRecording(); return testLog.VerifyOutput(); } } }
dpodder/coreclr
tests/src/JIT/Methodical/eh/leaves/oponerror.cs
C#
mit
2,172
// 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.CompilerServices; public class BringUpTest { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static double DblAddConst(double x) { return x+1; } public static int Main() { double y = DblAddConst(13d); Console.WriteLine(y); if (System.Math.Abs(y-14d) <= Double.Epsilon) return Pass; else return Fail; } }
Godin/coreclr
tests/src/JIT/CodeGenBringUpTests/DblAddConst.cs
C#
mit
663
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [ExportWorkspaceServiceFactory(typeof(VisualStudioRuleSetManager), ServiceLayer.Host), Shared] internal sealed class VisualStudioRuleSetManagerFactory : IWorkspaceServiceFactory { private readonly IServiceProvider _serviceProvider; private readonly IForegroundNotificationService _foregroundNotificationService; private readonly IAsynchronousOperationListener _listener; [ImportingConstructor] public VisualStudioRuleSetManagerFactory( SVsServiceProvider serviceProvider, IForegroundNotificationService foregroundNotificationService, [ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) { _serviceProvider = serviceProvider; _foregroundNotificationService = foregroundNotificationService; _listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.RuleSetEditor); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { IVsFileChangeEx fileChangeService = (IVsFileChangeEx)_serviceProvider.GetService(typeof(SVsFileChangeEx)); return new VisualStudioRuleSetManager(fileChangeService, _foregroundNotificationService, _listener); } } }
mmitche/roslyn
src/VisualStudio/Core/Def/Implementation/ProjectSystem/RuleSets/VisualStudioRuleSetManagerFactory.cs
C#
apache-2.0
1,917
default['yum']['epel-testing']['repositoryid'] = 'epel-testing' case node['platform'] when 'amazon' default['yum']['epel-testing']['description'] = 'Extra Packages for Enterprise Linux 6 - $basearch' default['yum']['epel-testing']['mirrorlist'] = 'http://mirrors.fedoraproject.org/mirrorlist?repo=epel-6&arch=$basearch' default['yum']['epel-testing']['gpgkey'] = 'http://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-6' else case node['platform_version'].to_i when 5 default['yum']['epel-testing']['description'] = 'Extra Packages for Enterprise Linux 5 - Testing - $basearch' default['yum']['epel-testing']['mirrorlist'] = 'http://mirrors.fedoraproject.org/mirrorlist?repo=testing-epel5&arch=$basearch' default['yum']['epel-testing']['gpgkey'] = 'http://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL' when 6 default['yum']['epel-testing']['description'] = 'Extra Packages for Enterprise Linux 6 - Testing - $basearch' default['yum']['epel-testing']['mirrorlist'] = 'https://mirrors.fedoraproject.org/metalink?repo=testing-epel6&arch=$basearch' default['yum']['epel-testing']['gpgkey'] = 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-6' when 7 default['yum']['epel-testing']['description'] = 'Extra Packages for Enterprise Linux 7 - Testing - $basearch' default['yum']['epel-testing']['mirrorlist'] = 'https://mirrors.fedoraproject.org/metalink?repo=testing-epel7&arch=$basearch' default['yum']['epel-testing']['gpgkey'] = 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7' end end default['yum']['epel-testing']['failovermethod'] = 'priority' default['yum']['epel-testing']['gpgcheck'] = true default['yum']['epel-testing']['enabled'] = false default['yum']['epel-testing']['managed'] = false
Audibene-GMBH/mule-cookbook
yum-epel/attributes/epel-testing.rb
Ruby
mit
1,768
<?php /** * @file * Contains \Drupal\views\Tests\Handler\ArgumentDateTest. */ namespace Drupal\views\Tests\Handler; use Drupal\views\Tests\ViewKernelTestBase; use Drupal\views\Views; /** * Tests the core date argument handlers. * * @group views * @see \Drupal\views\Plugin\views\argument\Date */ class ArgumentDateTest extends ViewKernelTestBase { /** * Views used by this test. * * @var array */ public static $testViews = array('test_argument_date'); /** * Stores the column map for this testCase. * * @var array */ protected $columnMap = array( 'id' => 'id', ); /** * {@inheritdoc} */ public function viewsData() { $data = parent::viewsData(); $date_plugins = array( 'date_fulldate', 'date_day', 'date_month', 'date_week', 'date_year', 'date_year_month', ); foreach ($date_plugins as $plugin_id) { $data['views_test_data'][$plugin_id] = $data['views_test_data']['created']; $data['views_test_data'][$plugin_id]['real field'] = 'created'; $data['views_test_data'][$plugin_id]['argument']['id'] = $plugin_id; } return $data; } /** * Tests the CreatedFullDate handler. * * @see \Drupal\node\Plugin\views\argument\CreatedFullDate */ public function testCreatedFullDateHandler() { $view = Views::getView('test_argument_date'); $view->setDisplay('default'); $this->executeView($view, array('20000102')); $expected = array(); $expected[] = array('id' => 2); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('default'); $this->executeView($view, array('20000101')); $expected = array(); $expected[] = array('id' => 1); $expected[] = array('id' => 3); $expected[] = array('id' => 4); $expected[] = array('id' => 5); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('default'); $this->executeView($view, array('20001023')); $expected = array(); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); } /** * Tests the Day handler. * * @see \Drupal\node\Plugin\views\argument\CreatedDay */ public function testDayHandler() { $view = Views::getView('test_argument_date'); $view->setDisplay('embed_1'); $this->executeView($view, array('02')); $expected = array(); $expected[] = array('id' => 2); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_1'); $this->executeView($view, array('01')); $expected = array(); $expected[] = array('id' => 1); $expected[] = array('id' => 3); $expected[] = array('id' => 4); $expected[] = array('id' => 5); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_1'); $this->executeView($view, array('23')); $expected = array(); $this->assertIdenticalResultset($view, $expected, $this->columnMap); } /** * Tests the Month handler. * * @see \Drupal\node\Plugin\views\argument\CreatedMonth */ public function testMonthHandler() { $view = Views::getView('test_argument_date'); $view->setDisplay('embed_2'); $this->executeView($view, array('01')); $expected = array(); $expected[] = array('id' => 1); $expected[] = array('id' => 2); $expected[] = array('id' => 3); $expected[] = array('id' => 4); $expected[] = array('id' => 5); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_2'); $this->executeView($view, array('12')); $expected = array(); $this->assertIdenticalResultset($view, $expected, $this->columnMap); } /** * Tests the Week handler. * * @see \Drupal\node\Plugin\views\argument\CreatedWeek */ public function testWeekHandler() { $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 9, 26, 2008))) ->condition('id', 1) ->execute(); $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 2, 29, 2004))) ->condition('id', 2) ->execute(); $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 1, 1, 2000))) ->condition('id', 3) ->execute(); $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 1, 10, 2000))) ->condition('id', 4) ->execute(); $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 2, 1, 2000))) ->condition('id', 5) ->execute(); $view = Views::getView('test_argument_date'); $view->setDisplay('embed_3'); // Check the week calculation for a leap year. // @see http://en.wikipedia.org/wiki/ISO_week_date#Calculation $this->executeView($view, array('39')); $expected = array(); $expected[] = array('id' => 1); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_3'); // Check the week calculation for the 29th of February in a leap year. // @see http://en.wikipedia.org/wiki/ISO_week_date#Calculation $this->executeView($view, array('09')); $expected = array(); $expected[] = array('id' => 2); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_3'); // The first jan 2000 was still in the last week of the previous year. $this->executeView($view, array('52')); $expected = array(); $expected[] = array('id' => 3); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_3'); $this->executeView($view, array('02')); $expected = array(); $expected[] = array('id' => 4); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_3'); $this->executeView($view, array('05')); $expected = array(); $expected[] = array('id' => 5); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_3'); $this->executeView($view, array('23')); $expected = array(); $this->assertIdenticalResultset($view, $expected, $this->columnMap); } /** * Tests the Year handler. * * @see \Drupal\node\Plugin\views\argument\CreatedYear */ public function testYearHandler() { $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 1, 1, 2001))) ->condition('id', 3) ->execute(); $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 1, 1, 2002))) ->condition('id', 4) ->execute(); $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 1, 1, 2002))) ->condition('id', 5) ->execute(); $view = Views::getView('test_argument_date'); $view->setDisplay('embed_4'); $this->executeView($view, array('2000')); $expected = array(); $expected[] = array('id' => 1); $expected[] = array('id' => 2); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_4'); $this->executeView($view, array('2001')); $expected = array(); $expected[] = array('id' => 3); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_4'); $this->executeView($view, array('2002')); $expected = array(); $expected[] = array('id' => 4); $expected[] = array('id' => 5); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_4'); $this->executeView($view, array('23')); $expected = array(); $this->assertIdenticalResultset($view, $expected, $this->columnMap); } /** * Tests the YearMonth handler. * * @see \Drupal\node\Plugin\views\argument\CreatedYearMonth */ public function testYearMonthHandler() { $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 1, 1, 2001))) ->condition('id', 3) ->execute(); $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 4, 1, 2001))) ->condition('id', 4) ->execute(); $this->container->get('database')->update('views_test_data') ->fields(array('created' => gmmktime(0, 0, 0, 4, 1, 2001))) ->condition('id', 5) ->execute(); $view = Views::getView('test_argument_date'); $view->setDisplay('embed_5'); $this->executeView($view, array('200001')); $expected = array(); $expected[] = array('id' => 1); $expected[] = array('id' => 2); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_5'); $this->executeView($view, array('200101')); $expected = array(); $expected[] = array('id' => 3); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_5'); $this->executeView($view, array('200104')); $expected = array(); $expected[] = array('id' => 4); $expected[] = array('id' => 5); $this->assertIdenticalResultset($view, $expected, $this->columnMap); $view->destroy(); $view->setDisplay('embed_5'); $this->executeView($view, array('201301')); $expected = array(); $this->assertIdenticalResultset($view, $expected, $this->columnMap); } }
nrackleff/capstone
web/core/modules/views/src/Tests/Handler/ArgumentDateTest.php
PHP
gpl-2.0
10,069
// Code generated by "stringer -type=ValueType valuetype.go"; DO NOT EDIT. package schema import "fmt" const _ValueType_name = "TypeInvalidTypeBoolTypeIntTypeFloatTypeStringTypeListTypeMapTypeSettypeObject" var _ValueType_index = [...]uint8{0, 11, 19, 26, 35, 45, 53, 60, 67, 77} func (i ValueType) String() string { if i < 0 || i >= ValueType(len(_ValueType_index)-1) { return fmt.Sprintf("ValueType(%d)", i) } return _ValueType_name[_ValueType_index[i]:_ValueType_index[i+1]] }
thiagocaiubi/terraform-provider-azurerm
vendor/github.com/hashicorp/terraform/helper/schema/valuetype_string.go
GO
mpl-2.0
490
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This file was automatically generated by lister-gen package v1 import ( "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" api "k8s.io/kubernetes/pkg/api" v1 "k8s.io/kubernetes/pkg/api/v1" ) // EndpointsLister helps list Endpoints. type EndpointsLister interface { // List lists all Endpoints in the indexer. List(selector labels.Selector) (ret []*v1.Endpoints, err error) // Endpoints returns an object that can list and get Endpoints. Endpoints(namespace string) EndpointsNamespaceLister EndpointsListerExpansion } // endpointsLister implements the EndpointsLister interface. type endpointsLister struct { indexer cache.Indexer } // NewEndpointsLister returns a new EndpointsLister. func NewEndpointsLister(indexer cache.Indexer) EndpointsLister { return &endpointsLister{indexer: indexer} } // List lists all Endpoints in the indexer. func (s *endpointsLister) List(selector labels.Selector) (ret []*v1.Endpoints, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1.Endpoints)) }) return ret, err } // Endpoints returns an object that can list and get Endpoints. func (s *endpointsLister) Endpoints(namespace string) EndpointsNamespaceLister { return endpointsNamespaceLister{indexer: s.indexer, namespace: namespace} } // EndpointsNamespaceLister helps list and get Endpoints. type EndpointsNamespaceLister interface { // List lists all Endpoints in the indexer for a given namespace. List(selector labels.Selector) (ret []*v1.Endpoints, err error) // Get retrieves the Endpoints from the indexer for a given namespace and name. Get(name string) (*v1.Endpoints, error) EndpointsNamespaceListerExpansion } // endpointsNamespaceLister implements the EndpointsNamespaceLister // interface. type endpointsNamespaceLister struct { indexer cache.Indexer namespace string } // List lists all Endpoints in the indexer for a given namespace. func (s endpointsNamespaceLister) List(selector labels.Selector) (ret []*v1.Endpoints, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1.Endpoints)) }) return ret, err } // Get retrieves the Endpoints from the indexer for a given namespace and name. func (s endpointsNamespaceLister) Get(name string) (*v1.Endpoints, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(api.Resource("endpoints"), name) } return obj.(*v1.Endpoints), nil }
mikegrass/minikube
vendor/k8s.io/kubernetes/pkg/client/listers/core/v1/endpoints.go
GO
apache-2.0
3,176
<?php /* * This file is part of the Assetic package, an OpenSky project. * * (c) 2010-2013 OpenSky Project Inc * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Assetic\Filter; use Assetic\Asset\AssetInterface; use Assetic\Exception\FilterException; /** * Loads LESS files. * * @link http://lesscss.org/ * @author Kris Wallsmith <kris.wallsmith@gmail.com> */ class LessFilter extends BaseNodeFilter { private $nodeBin; private $compress; /** * Load Paths * * A list of paths which less will search for includes. * * @var array */ protected $loadPaths = array(); /** * Constructor. * * @param string $nodeBin The path to the node binary * @param array $nodePaths An array of node paths */ public function __construct($nodeBin = '/usr/bin/node', array $nodePaths = array()) { $this->nodeBin = $nodeBin; $this->setNodePaths($nodePaths); } public function setCompress($compress) { $this->compress = $compress; } /** * Adds a path where less will search for includes * * @param string $path Load path (absolute) */ public function addLoadPath($path) { $this->loadPaths[] = $path; } public function filterLoad(AssetInterface $asset) { static $format = <<<'EOF' var less = require('less'); var sys = require(process.binding('natives').util ? 'util' : 'sys'); new(less.Parser)(%s).parse(%s, function(e, tree) { if (e) { less.writeError(e); process.exit(2); } try { sys.print(tree.toCSS(%s)); } catch (e) { less.writeError(e); process.exit(3); } }); EOF; $root = $asset->getSourceRoot(); $path = $asset->getSourcePath(); // parser options $parserOptions = array(); if ($root && $path) { $parserOptions['paths'] = array(dirname($root.'/'.$path)); $parserOptions['filename'] = basename($path); } foreach ($this->loadPaths as $loadPath) { $parserOptions['paths'][] = $loadPath; } // tree options $treeOptions = array(); if (null !== $this->compress) { $treeOptions['compress'] = $this->compress; } $pb = $this->createProcessBuilder(); $pb->inheritEnvironmentVariables(); $pb->add($this->nodeBin)->add($input = tempnam(sys_get_temp_dir(), 'assetic_less')); file_put_contents($input, sprintf($format, json_encode($parserOptions), json_encode($asset->getContent()), json_encode($treeOptions) )); $proc = $pb->getProcess(); $code = $proc->run(); unlink($input); if (0 !== $code) { throw FilterException::fromProcess($proc)->setInput($asset->getContent()); } $asset->setContent($proc->getOutput()); } public function filterDump(AssetInterface $asset) { } }
nandy-andy/performance-blog
vendors/assetic/Assetic/Filter/LessFilter.php
PHP
gpl-2.0
3,106
/* * Copyright (C) 2007 The Guava 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.common.collect; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; /** * GWT emulation of {@code HashBiMap} that just delegates to two HashMaps. * * @author Mike Bostock */ public final class HashBiMap<K, V> extends AbstractBiMap<K, V> { /** * Returns a new, empty {@code HashBiMap} with the default initial capacity * (16). */ public static <K, V> HashBiMap<K, V> create() { return new HashBiMap<K, V>(); } /** * Constructs a new, empty bimap with the specified expected size. * * @param expectedSize the expected number of entries * @throws IllegalArgumentException if the specified expected size is * negative */ public static <K, V> HashBiMap<K, V> create(int expectedSize) { return new HashBiMap<K, V>(expectedSize); } /** * Constructs a new bimap containing initial values from {@code map}. The * bimap is created with an initial capacity sufficient to hold the mappings * in the specified map. */ public static <K, V> HashBiMap<K, V> create( Map<? extends K, ? extends V> map) { HashBiMap<K, V> bimap = create(map.size()); bimap.putAll(map); return bimap; } private HashBiMap() { super(new HashMap<K, V>(), new HashMap<V, K>()); } private HashBiMap(int expectedSize) { super( Maps.<K, V>newHashMapWithExpectedSize(expectedSize), Maps.<V, K>newHashMapWithExpectedSize(expectedSize)); } // Override these two methods to show that keys and values may be null @Override public V put(@Nullable K key, @Nullable V value) { return super.put(key, value); } @Override public V forcePut(@Nullable K key, @Nullable V value) { return super.forcePut(key, value); } }
congdepeng/java-guava-lib-demo
guava-libraries/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/HashBiMap.java
Java
apache-2.0
2,365
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["Slider"] = factory(require("react")); else root["Slider"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _innerSlider = __webpack_require__(5); var _objectAssign = __webpack_require__(23); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _json2mq = __webpack_require__(2); var _json2mq2 = _interopRequireDefault(_json2mq); var _reactResponsiveMixin = __webpack_require__(26); var _reactResponsiveMixin2 = _interopRequireDefault(_reactResponsiveMixin); var _defaultProps = __webpack_require__(9); var _defaultProps2 = _interopRequireDefault(_defaultProps); var Slider = _react2['default'].createClass({ displayName: 'Slider', mixins: [_reactResponsiveMixin2['default']], getInitialState: function getInitialState() { return { breakpoint: null }; }, componentDidMount: function componentDidMount() { var _this = this; if (this.props.responsive) { var breakpoints = this.props.responsive.map(function (breakpt) { return breakpt.breakpoint; }); breakpoints.sort(function (x, y) { return x - y; }); breakpoints.forEach(function (breakpoint, index) { var bQuery; if (index === 0) { bQuery = (0, _json2mq2['default'])({ minWidth: 0, maxWidth: breakpoint }); } else { bQuery = (0, _json2mq2['default'])({ minWidth: breakpoints[index - 1], maxWidth: breakpoint }); } _this.media(bQuery, function () { _this.setState({ breakpoint: breakpoint }); }); }); // Register media query for full screen. Need to support resize from small to large var query = (0, _json2mq2['default'])({ minWidth: breakpoints.slice(-1)[0] }); this.media(query, function () { _this.setState({ breakpoint: null }); }); } }, render: function render() { var _this2 = this; var settings; var newProps; if (this.state.breakpoint) { newProps = this.props.responsive.filter(function (resp) { return resp.breakpoint === _this2.state.breakpoint; }); settings = newProps[0].settings === 'unslick' ? 'unslick' : (0, _objectAssign2['default'])({}, this.props, newProps[0].settings); } else { settings = (0, _objectAssign2['default'])({}, _defaultProps2['default'], this.props); } if (settings === 'unslick') { // if 'unslick' responsive breakpoint setting used, just return the <Slider> tag nested HTML return _react2['default'].createElement( 'div', null, this.props.children ); } else { return _react2['default'].createElement( _innerSlider.InnerSlider, settings, this.props.children ); } } }); module.exports = Slider; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var camel2hyphen = __webpack_require__(3); var isDimension = function (feature) { var re = /[height|width]$/; return re.test(feature); }; var obj2mq = function (obj) { var mq = ''; var features = Object.keys(obj); features.forEach(function (feature, index) { var value = obj[feature]; feature = camel2hyphen(feature); // Add px to dimension features if (isDimension(feature) && typeof value === 'number') { value = value + 'px'; } if (value === true) { mq += feature; } else if (value === false) { mq += 'not ' + feature; } else { mq += '(' + feature + ': ' + value + ')'; } if (index < features.length-1) { mq += ' and ' } }); return mq; }; var json2mq = function (query) { var mq = ''; if (typeof query === 'string') { return query; } // Handling array of media queries if (query instanceof Array) { query.forEach(function (q, index) { mq += obj2mq(q); if (index < query.length-1) { mq += ', ' } }); return mq; } // Handling single media query return obj2mq(query); }; module.exports = json2mq; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var camel2hyphen = function (str) { return str .replace(/[A-Z]/g, function (match) { return '-' + match.toLowerCase(); }) .toLowerCase(); }; module.exports = camel2hyphen; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _mixinsEventHandlers = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"./mixins/event-handlers\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())); var _mixinsEventHandlers2 = _interopRequireDefault(_mixinsEventHandlers); var _mixinsHelpers = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"./mixins/helpers\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())); var _mixinsHelpers2 = _interopRequireDefault(_mixinsHelpers); var _initialState = __webpack_require__(8); var _initialState2 = _interopRequireDefault(_initialState); var _defaultProps = __webpack_require__(9); var _defaultProps2 = _interopRequireDefault(_defaultProps); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _track = __webpack_require__(11); var _dots = __webpack_require__(24); var _arrows = __webpack_require__(25); var InnerSlider = _react2['default'].createClass({ displayName: 'InnerSlider', mixins: [_mixinsHelpers2['default'], _mixinsEventHandlers2['default']], getInitialState: function getInitialState() { return _initialState2['default']; }, getDefaultProps: function getDefaultProps() { return _defaultProps2['default']; }, componentWillMount: function componentWillMount() { if (this.props.init) { this.props.init(); } this.setState({ mounted: true }); var lazyLoadedList = []; for (var i = 0; i < this.props.children.length; i++) { if (i >= this.state.currentSlide && i < this.state.currentSlide + this.props.slidesToShow) { lazyLoadedList.push(i); } } if (this.props.lazyLoad && this.state.lazyLoadedList.length === 0) { this.setState({ lazyLoadedList: lazyLoadedList }); } }, componentDidMount: function componentDidMount() { // Hack for autoplay -- Inspect Later this.initialize(this.props); this.adaptHeight(); }, componentDidUpdate: function componentDidUpdate() { this.adaptHeight(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.initialize(nextProps); }, render: function render() { var className = (0, _classnames2['default'])('slick-initialized', 'slick-slider', this.props.className); var trackProps = { fade: this.props.fade, cssEase: this.props.cssEase, speed: this.props.speed, infinite: this.props.infinite, centerMode: this.props.centerMode, currentSlide: this.state.currentSlide, lazyLoad: this.props.lazyLoad, lazyLoadedList: this.state.lazyLoadedList, rtl: this.props.rtl, slideWidth: this.state.slideWidth, slidesToShow: this.props.slidesToShow, slideCount: this.state.slideCount, trackStyle: this.state.trackStyle, variableWidth: this.props.variableWidth }; var dots; if (this.props.dots === true && this.state.slideCount > this.props.slidesToShow) { var dotProps = { dotsClass: this.props.dotsClass, slideCount: this.state.slideCount, slidesToShow: this.props.slidesToShow, currentSlide: this.state.currentSlide, slidesToScroll: this.props.slidesToScroll, clickHandler: this.changeSlide }; dots = _react2['default'].createElement(_dots.Dots, dotProps); } var prevArrow, nextArrow; var arrowProps = { infinite: this.props.infinite, centerMode: this.props.centerMode, currentSlide: this.state.currentSlide, slideCount: this.state.slideCount, slidesToShow: this.props.slidesToShow, prevArrow: this.props.prevArrow, nextArrow: this.props.nextArrow, clickHandler: this.changeSlide }; if (this.props.arrows) { prevArrow = _react2['default'].createElement(_arrows.PrevArrow, arrowProps); nextArrow = _react2['default'].createElement(_arrows.NextArrow, arrowProps); } return _react2['default'].createElement( 'div', { className: className }, _react2['default'].createElement( 'div', { ref: 'list', className: 'slick-list', onMouseDown: this.swipeStart, onMouseMove: this.state.dragging ? this.swipeMove : null, onMouseUp: this.swipeEnd, onMouseLeave: this.state.dragging ? this.swipeEnd : null, onTouchStart: this.swipeStart, onTouchMove: this.state.dragging ? this.swipeMove : null, onTouchEnd: this.swipeEnd, onTouchCancel: this.state.dragging ? this.swipeEnd : null }, _react2['default'].createElement( _track.Track, _extends({ ref: 'track' }, trackProps), this.props.children ) ), prevArrow, nextArrow, dots ); } }); exports.InnerSlider = InnerSlider; /***/ }, /* 6 */, /* 7 */, /* 8 */ /***/ function(module, exports, __webpack_require__) { var initialState = { animating: false, dragging: false, autoPlayTimer: null, currentDirection: 0, currentLeft: null, currentSlide: 0, direction: 1, // listWidth: null, // listHeight: null, // loadIndex: 0, slideCount: null, slideWidth: null, // sliding: false, // slideOffset: 0, swipeLeft: null, touchObject: { startX: 0, startY: 0, curX: 0, curY: 0 }, lazyLoadedList: [], // added for react initialized: false, edgeDragged: false, swiped: false, // used by swipeEvent. differentites between touch and swipe. trackStyle: {}, trackWidth: 0 // Removed // transformsEnabled: false, // $nextArrow: null, // $prevArrow: null, // $dots: null, // $list: null, // $slideTrack: null, // $slides: null, }; module.exports = initialState; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var defaultProps = { className: '', // accessibility: true, adaptiveHeight: false, arrows: true, autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: false, responsive: null, rtl: false, slide: 'div', slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, // waitForAnimate: true, afterChange: null, beforeChange: null, edgeEvent: null, init: null, swipeEvent: null, // nextArrow, prevArrow are react componets nextArrow: null, prevArrow: null }; module.exports = defaultProps; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames () { 'use strict'; var classes = ''; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if ('string' === argType || 'number' === argType) { classes += ' ' + arg; } else if (Array.isArray(arg)) { classes += ' ' + classNames.apply(null, arg); } else if ('object' === argType) { for (var key in arg) { if (arg.hasOwnProperty(key) && arg[key]) { classes += ' ' + key; } } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } /* global define */ // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactLibCloneWithProps = __webpack_require__(12); var _reactLibCloneWithProps2 = _interopRequireDefault(_reactLibCloneWithProps); var _objectAssign = __webpack_require__(23); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var getSlideClasses = function getSlideClasses(spec) { var slickActive, slickCenter, slickCloned; var centerOffset, index; if (spec.rtl) { index = spec.slideCount - 1 - spec.index; console.log(); } else { index = spec.index; } slickCloned = index < 0 || index >= spec.slideCount; if (spec.centerMode) { centerOffset = Math.floor(spec.slidesToShow / 2); slickCenter = spec.currentSlide === index; if (index > spec.currentSlide - centerOffset - 1 && index <= spec.currentSlide + centerOffset) { slickActive = true; } } else { slickActive = spec.currentSlide <= index && index < spec.currentSlide + spec.slidesToShow; } return (0, _classnames2['default'])({ 'slick-slide': true, 'slick-active': slickActive, 'slick-center': slickCenter, 'slick-cloned': slickCloned }); }; var getSlideStyle = function getSlideStyle(spec) { var style = {}; if (spec.variableWidth === undefined || spec.variableWidth === false) { style.width = spec.slideWidth; } if (spec.fade) { style.position = 'relative'; style.left = -spec.index * spec.slideWidth; style.opacity = spec.currentSlide === spec.index ? 1 : 0; style.transition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase; style.WebkitTransition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase; } return style; }; var renderSlides = function renderSlides(spec) { var key; var slides = []; var preCloneSlides = []; var postCloneSlides = []; var count = _react2['default'].Children.count(spec.children); var child; _react2['default'].Children.forEach(spec.children, function (elem, index) { if (!spec.lazyLoad | (spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0)) { child = elem; } else { child = _react2['default'].createElement('div', null); } var childStyle = getSlideStyle((0, _objectAssign2['default'])({}, spec, { index: index })); slides.push((0, _reactLibCloneWithProps2['default'])(child, { key: index, 'data-index': index, className: getSlideClasses((0, _objectAssign2['default'])({ index: index }, spec)), style: childStyle })); // variableWidth doesn't wrap properly. if (spec.infinite && spec.fade === false) { var infiniteCount = spec.variableWidth ? spec.slidesToShow + 1 : spec.slidesToShow; if (index >= count - infiniteCount) { key = -(count - index); preCloneSlides.push((0, _reactLibCloneWithProps2['default'])(child, { key: key, 'data-index': key, className: getSlideClasses((0, _objectAssign2['default'])({ index: key }, spec)), style: childStyle })); } if (index < infiniteCount) { key = count + index; postCloneSlides.push((0, _reactLibCloneWithProps2['default'])(child, { key: key, 'data-index': key, className: getSlideClasses((0, _objectAssign2['default'])({ index: key }, spec)), style: childStyle })); } } }); if (spec.rtl) { return preCloneSlides.concat(slides, postCloneSlides).reverse(); } else { return preCloneSlides.concat(slides, postCloneSlides); } }; var Track = _react2['default'].createClass({ displayName: 'Track', render: function render() { var slides = renderSlides(this.props); return _react2['default'].createElement( 'div', { className: 'slick-track', style: this.props.trackStyle }, slides ); } }); exports.Track = Track; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule cloneWithProps */ 'use strict'; var ReactElement = __webpack_require__(13); var ReactPropTransferer = __webpack_require__(20); var keyOf = __webpack_require__(22); var warning = __webpack_require__(14); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {ReactElement} child child element you'd like to clone * @param {object} props props you'd like to modify. className and style will be * merged automatically. * @return {ReactElement} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== (undefined)) { ("production" !== (undefined) ? warning( !child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var ReactContext = __webpack_require__(16); var ReactCurrentOwner = __webpack_require__(19); var assign = __webpack_require__(17); var warning = __webpack_require__(14); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== (undefined) ? warning( false, 'Don\'t set the %s property of the React element. Instead, ' + 'specify the correct value when initially creating the element.', key ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== (undefined)) { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== (undefined)) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== (undefined)) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function(element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return new ReactElement( element.type, key, ref, owner, element._context, props ); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ "use strict"; var emptyFunction = __webpack_require__(15); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== (undefined)) { warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || /^[s\W]*$/.test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}); console.warn(message); try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function() { return this; }; emptyFunction.thatReturnsArgument = function(arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactContext */ 'use strict'; var assign = __webpack_require__(17); var emptyObject = __webpack_require__(18); var warning = __webpack_require__(14); var didWarn = false; /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: emptyObject, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { if ("production" !== (undefined)) { ("production" !== (undefined) ? warning( didWarn, 'withContext is deprecated and will be removed in a future version. ' + 'Use a wrapper component with getChildContext instead.' ) : null); didWarn = true; } var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== (undefined)) { Object.freeze(emptyObject); } module.exports = emptyObject; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTransferer */ 'use strict'; var assign = __webpack_require__(17); var emptyFunction = __webpack_require__(15); var joinClasses = __webpack_require__(21); /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); } }; module.exports = ReactPropTransferer; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ 'use strict'; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var getDotCount = function getDotCount(spec) { var dots; dots = Math.ceil(spec.slideCount / spec.slidesToScroll); return dots; }; var Dots = _react2['default'].createClass({ displayName: 'Dots', clickHandler: function clickHandler(options, e) { // In Autoplay the focus stays on clicked button even after transition // to next slide. That only goes away by click somewhere outside e.preventDefault(); this.props.clickHandler(options); }, render: function render() { var _this = this; var dotCount = getDotCount({ slideCount: this.props.slideCount, slidesToScroll: this.props.slidesToScroll }); var dots = Array.apply(null, { length: dotCount }).map(function (x, i) { var className = (0, _classnames2['default'])({ 'slick-active': _this.props.currentSlide === i * _this.props.slidesToScroll }); var dotOptions = { message: 'dots', index: i, slidesToScroll: _this.props.slidesToScroll, currentSlide: _this.props.currentSlide }; return _react2['default'].createElement( 'li', { key: i, className: className }, _react2['default'].createElement( 'button', { onClick: _this.clickHandler.bind(_this, dotOptions) }, i ) ); }); return _react2['default'].createElement( 'ul', { className: this.props.dotsClass, style: { display: 'block' } }, dots ); } }); exports.Dots = Dots; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var PrevArrow = _react2['default'].createClass({ displayName: 'PrevArrow', clickHandler: function clickHandler(options, e) { e.preventDefault(); this.props.clickHandler(options, e); }, render: function render() { var prevClasses = { 'slick-prev': true }; var prevHandler = this.clickHandler.bind(this, { message: 'previous' }); if (!this.props.infinite && (this.props.currentSlide === 0 || this.props.slideCount <= this.props.slidesToShow)) { prevClasses['slick-disabled'] = true; prevHandler = null; } var prevArrowProps = { key: '0', ref: 'previous', 'data-role': 'none', className: (0, _classnames2['default'])(prevClasses), style: { display: 'block' }, onClick: prevHandler }; var prevArrow; if (this.props.prevArrow) { prevArrow = _react2['default'].createElement(this.props.prevArrow, prevArrowProps); } else { prevArrow = _react2['default'].createElement( 'button', _extends({ key: '0', type: 'button' }, prevArrowProps), ' Previous' ); } return prevArrow; } }); exports.PrevArrow = PrevArrow; var NextArrow = _react2['default'].createClass({ displayName: 'NextArrow', clickHandler: function clickHandler(options, e) { e.preventDefault(); this.props.clickHandler(options, e); }, render: function render() { var nextClasses = { 'slick-next': true }; var nextHandler = this.clickHandler.bind(this, { message: 'next' }); if (!this.props.infinite) { if (this.props.centerMode && this.props.currentSlide >= this.props.slideCount - 1) { nextClasses['slick-disabled'] = true; nextHandler = null; } else { if (this.props.currentSlide >= this.props.slideCount - this.props.slidesToShow) { nextClasses['slick-disabled'] = true; nextHandler = null; } } if (this.props.slideCount <= this.props.slidesToShow) { nextClasses['slick-disabled'] = true; nextHandler = null; } } var nextArrowProps = { key: '1', ref: 'next', 'data-role': 'none', className: (0, _classnames2['default'])(nextClasses), style: { display: 'block' }, onClick: nextHandler }; var nextArrow; if (this.props.nextArrow) { nextArrow = _react2['default'].createElement(this.props.nextArrow, nextArrowProps); } else { nextArrow = _react2['default'].createElement( 'button', _extends({ key: '1', type: 'button' }, nextArrowProps), ' Next' ); } return nextArrow; } }); exports.NextArrow = NextArrow; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var canUseDOM = __webpack_require__(27); var enquire = canUseDOM && __webpack_require__(28); var json2mq = __webpack_require__(2); var ResponsiveMixin = { media: function (query, handler) { query = json2mq(query); if (typeof handler === 'function') { handler = { match: handler }; } enquire.register(query, handler); // Queue the handlers to unregister them at unmount if (! this._responsiveMediaHandlers) { this._responsiveMediaHandlers = []; } this._responsiveMediaHandlers.push({query: query, handler: handler}); }, componentWillUnmount: function () { this._responsiveMediaHandlers.forEach(function(obj) { enquire.unregister(obj.query, obj.handler); }); } }; module.exports = ResponsiveMixin; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); module.exports = canUseDOM; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! * enquire.js v2.1.1 - Awesome Media Queries in JavaScript * Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/enquire.js * License: MIT (http://www.opensource.org/licenses/mit-license.php) */ ;(function (name, context, factory) { var matchMedia = window.matchMedia; if (typeof module !== 'undefined' && module.exports) { module.exports = factory(matchMedia); } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return (context[name] = factory(matchMedia)); }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { context[name] = factory(matchMedia); } }('enquire', this, function (matchMedia) { 'use strict'; /*jshint unused:false */ /** * Helper function for iterating over a collection * * @param collection * @param fn */ function each(collection, fn) { var i = 0, length = collection.length, cont; for(i; i < length; i++) { cont = fn(collection[i], i); if(cont === false) { break; //allow early exit } } } /** * Helper function for determining whether target object is an array * * @param target the object under test * @return {Boolean} true if array, false otherwise */ function isArray(target) { return Object.prototype.toString.apply(target) === '[object Array]'; } /** * Helper function for determining whether target object is a function * * @param target the object under test * @return {Boolean} true if function, false otherwise */ function isFunction(target) { return typeof target === 'function'; } /** * Delegate to handle a media query being matched and unmatched. * * @param {object} options * @param {function} options.match callback for when the media query is matched * @param {function} [options.unmatch] callback for when the media query is unmatched * @param {function} [options.setup] one-time callback triggered the first time a query is matched * @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched? * @constructor */ function QueryHandler(options) { this.options = options; !options.deferSetup && this.setup(); } QueryHandler.prototype = { /** * coordinates setup of the handler * * @function */ setup : function() { if(this.options.setup) { this.options.setup(); } this.initialised = true; }, /** * coordinates setup and triggering of the handler * * @function */ on : function() { !this.initialised && this.setup(); this.options.match && this.options.match(); }, /** * coordinates the unmatch event for the handler * * @function */ off : function() { this.options.unmatch && this.options.unmatch(); }, /** * called when a handler is to be destroyed. * delegates to the destroy or unmatch callbacks, depending on availability. * * @function */ destroy : function() { this.options.destroy ? this.options.destroy() : this.off(); }, /** * determines equality by reference. * if object is supplied compare options, if function, compare match callback * * @function * @param {object || function} [target] the target for comparison */ equals : function(target) { return this.options === target || this.options.match === target; } }; /** * Represents a single media query, manages it's state and registered handlers for this query * * @constructor * @param {string} query the media query string * @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design */ function MediaQuery(query, isUnconditional) { this.query = query; this.isUnconditional = isUnconditional; this.handlers = []; this.mql = matchMedia(query); var self = this; this.listener = function(mql) { self.mql = mql; self.assess(); }; this.mql.addListener(this.listener); } MediaQuery.prototype = { /** * add a handler for this query, triggering if already active * * @param {object} handler * @param {function} handler.match callback for when query is activated * @param {function} [handler.unmatch] callback for when query is deactivated * @param {function} [handler.setup] callback for immediate execution when a query handler is registered * @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched? */ addHandler : function(handler) { var qh = new QueryHandler(handler); this.handlers.push(qh); this.matches() && qh.on(); }, /** * removes the given handler from the collection, and calls it's destroy methods * * @param {object || function} handler the handler to remove */ removeHandler : function(handler) { var handlers = this.handlers; each(handlers, function(h, i) { if(h.equals(handler)) { h.destroy(); return !handlers.splice(i,1); //remove from array and exit each early } }); }, /** * Determine whether the media query should be considered a match * * @return {Boolean} true if media query can be considered a match, false otherwise */ matches : function() { return this.mql.matches || this.isUnconditional; }, /** * Clears all handlers and unbinds events */ clear : function() { each(this.handlers, function(handler) { handler.destroy(); }); this.mql.removeListener(this.listener); this.handlers.length = 0; //clear array }, /* * Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match */ assess : function() { var action = this.matches() ? 'on' : 'off'; each(this.handlers, function(handler) { handler[action](); }); } }; /** * Allows for registration of query handlers. * Manages the query handler's state and is responsible for wiring up browser events * * @constructor */ function MediaQueryDispatch () { if(!matchMedia) { throw new Error('matchMedia not present, legacy browsers require a polyfill'); } this.queries = {}; this.browserIsIncapable = !matchMedia('only all').matches; } MediaQueryDispatch.prototype = { /** * Registers a handler for the given media query * * @param {string} q the media query * @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers * @param {function} options.match fired when query matched * @param {function} [options.unmatch] fired when a query is no longer matched * @param {function} [options.setup] fired when handler first triggered * @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched * @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers */ register : function(q, options, shouldDegrade) { var queries = this.queries, isUnconditional = shouldDegrade && this.browserIsIncapable; if(!queries[q]) { queries[q] = new MediaQuery(q, isUnconditional); } //normalise to object in an array if(isFunction(options)) { options = { match : options }; } if(!isArray(options)) { options = [options]; } each(options, function(handler) { queries[q].addHandler(handler); }); return this; }, /** * unregisters a query and all it's handlers, or a specific handler for a query * * @param {string} q the media query to target * @param {object || function} [handler] specific handler to unregister */ unregister : function(q, handler) { var query = this.queries[q]; if(query) { if(handler) { query.removeHandler(handler); } else { query.clear(); delete this.queries[q]; } } return this; } }; return new MediaQueryDispatch(); })); /***/ } /******/ ]) }); ;
maruilian11/cdnjs
ajax/libs/react-slick/0.6.0/react-slick.js
JavaScript
mit
61,015
/*! * Bootstrap-select v1.6.3 (http://silviomoreto.github.io/bootstrap-select) * * Copyright 2013-2015 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Niets geselecteerd', noneResultsText: 'Geen resultaten gevonden voor {0}', countSelectedText: '{0} van {1} geselecteerd', maxOptionsText: ['Limiet bereikt ({n} {var} max)', 'Groep limiet bereikt ({n} {var} max)', ['items', 'item']], multipleSeparator: ', ' }; })(jQuery);
jhonrsalcedo/sitio
wp-content/themes/viviendas/assets/libraries/bootstrap-select/dist/js/i18n/defaults-nl_NL.js
JavaScript
gpl-2.0
582
package com.bumptech.glide.gifdecoder; import java.util.ArrayList; import java.util.List; public class GifHeader { public int[] gct = null; /** * Global status code of GIF data parsing */ public int status = GifDecoder.STATUS_OK; public int frameCount = 0; public GifFrame currentFrame; public List<GifFrame> frames = new ArrayList<GifFrame>(); // logical screen size public int width; // full image width public int height; // full image height public boolean gctFlag; // 1 : global color table flag // 2-4 : color resolution // 5 : gct sort flag public int gctSize; // 6-8 : gct size public int bgIndex; // background color index public int pixelAspect; // pixel aspect ratio //TODO: this is set both during reading the header and while decoding frames... public int bgColor; public boolean isTransparent; public int loopCount; }
heymind/iosched
third_party/gif_decoder/src/main/java/com/bumptech/glide/gifdecoder/GifHeader.java
Java
apache-2.0
924
import {has, isArray} from "./util" import {SourceLocation} from "./locutil" // A second optional argument can be given to further configure // the parser process. These options are recognized: export const defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must // be either 3, or 5, or 6. This influences support for strict // mode, the set of reserved words, support for getters and // setters and other features. The default is 6. ecmaVersion: 6, // Source type ("script" or "module") for different semantics sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // th position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program. allowImportExportEverywhere: false, // When enabled, hashbang directive in the beginning of file // is allowed and treated as a line comment. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callback—that will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false, plugins: {} } // Interpret and default an options object export function getOptions(opts) { let options = {} for (let opt in defaultOptions) options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt] if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5 if (isArray(options.onToken)) { let tokens = options.onToken options.onToken = (token) => tokens.push(token) } if (isArray(options.onComment)) options.onComment = pushComment(options, options.onComment) return options } function pushComment(options, array) { return function (block, text, start, end, startLoc, endLoc) { let comment = { type: block ? 'Block' : 'Line', value: text, start: start, end: end } if (options.locations) comment.loc = new SourceLocation(this, startLoc, endLoc) if (options.ranges) comment.range = [start, end] array.push(comment) } }
hellokidder/js-studying
微信小程序/wxtest/node_modules/acorn-jsx/node_modules/acorn/src/options.js
JavaScript
mit
5,026
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { internal struct BraceCharacterAndKind { public char Character { get; } public int Kind { get; } public BraceCharacterAndKind(char character, int kind) : this() { this.Character = character; this.Kind = kind; } } }
mmitche/roslyn
src/EditorFeatures/Core/Implementation/BraceMatching/BraceCharacterAndKind.cs
C#
apache-2.0
539
// Copyright 2013 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 language_test import ( "fmt" "net/http" "golang.org/x/text/language" ) func ExampleCanonType() { p := func(id string) { fmt.Printf("Default(%s) -> %s\n", id, language.Make(id)) fmt.Printf("BCP47(%s) -> %s\n", id, language.BCP47.Make(id)) fmt.Printf("Macro(%s) -> %s\n", id, language.Macro.Make(id)) fmt.Printf("All(%s) -> %s\n", id, language.All.Make(id)) } p("en-Latn") p("sh") p("zh-cmn") p("bjd") p("iw-Latn-fonipa-u-cu-usd") // Output: // Default(en-Latn) -> en-Latn // BCP47(en-Latn) -> en // Macro(en-Latn) -> en-Latn // All(en-Latn) -> en // Default(sh) -> sr-Latn // BCP47(sh) -> sh // Macro(sh) -> sh // All(sh) -> sr-Latn // Default(zh-cmn) -> cmn // BCP47(zh-cmn) -> cmn // Macro(zh-cmn) -> zh // All(zh-cmn) -> zh // Default(bjd) -> drl // BCP47(bjd) -> drl // Macro(bjd) -> bjd // All(bjd) -> drl // Default(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd // BCP47(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd // Macro(iw-Latn-fonipa-u-cu-usd) -> iw-Latn-fonipa-u-cu-usd // All(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd } func ExampleTag_Base() { fmt.Println(language.Make("und").Base()) fmt.Println(language.Make("und-US").Base()) fmt.Println(language.Make("und-NL").Base()) fmt.Println(language.Make("und-419").Base()) // Latin America fmt.Println(language.Make("und-ZZ").Base()) // Output: // en Low // en High // nl High // es Low // en Low } func ExampleTag_Script() { en := language.Make("en") sr := language.Make("sr") sr_Latn := language.Make("sr_Latn") fmt.Println(en.Script()) fmt.Println(sr.Script()) // Was a script explicitly specified? _, c := sr.Script() fmt.Println(c == language.Exact) _, c = sr_Latn.Script() fmt.Println(c == language.Exact) // Output: // Latn High // Cyrl Low // false // true } func ExampleTag_Region() { ru := language.Make("ru") en := language.Make("en") fmt.Println(ru.Region()) fmt.Println(en.Region()) // Output: // RU Low // US Low } func ExampleRegion_TLD() { us := language.MustParseRegion("US") gb := language.MustParseRegion("GB") uk := language.MustParseRegion("UK") bu := language.MustParseRegion("BU") fmt.Println(us.TLD()) fmt.Println(gb.TLD()) fmt.Println(uk.TLD()) fmt.Println(bu.TLD()) fmt.Println(us.Canonicalize().TLD()) fmt.Println(gb.Canonicalize().TLD()) fmt.Println(uk.Canonicalize().TLD()) fmt.Println(bu.Canonicalize().TLD()) // Output: // US <nil> // UK <nil> // UK <nil> // ZZ language: region is not a valid ccTLD // US <nil> // UK <nil> // UK <nil> // MM <nil> } func ExampleCompose() { nl, _ := language.ParseBase("nl") us, _ := language.ParseRegion("US") de := language.Make("de-1901-u-co-phonebk") jp := language.Make("ja-JP") fi := language.Make("fi-x-ing") u, _ := language.ParseExtension("u-nu-arabic") x, _ := language.ParseExtension("x-piglatin") // Combine a base language and region. fmt.Println(language.Compose(nl, us)) // Combine a base language and extension. fmt.Println(language.Compose(nl, x)) // Replace the region. fmt.Println(language.Compose(jp, us)) // Combine several tags. fmt.Println(language.Compose(us, nl, u)) // Replace the base language of a tag. fmt.Println(language.Compose(de, nl)) fmt.Println(language.Compose(de, nl, u)) // Remove the base language. fmt.Println(language.Compose(de, language.Base{})) // Remove all variants. fmt.Println(language.Compose(de, []language.Variant{})) // Remove all extensions. fmt.Println(language.Compose(de, []language.Extension{})) fmt.Println(language.Compose(fi, []language.Extension{})) // Remove all variants and extensions. fmt.Println(language.Compose(de.Raw())) // An error is gobbled or returned if non-nil. fmt.Println(language.Compose(language.ParseRegion("ZA"))) fmt.Println(language.Compose(language.ParseRegion("HH"))) // Compose uses the same Default canonicalization as Make. fmt.Println(language.Compose(language.Raw.Parse("en-Latn-UK"))) // Call compose on a different CanonType for different results. fmt.Println(language.All.Compose(language.Raw.Parse("en-Latn-UK"))) // Output: // nl-US <nil> // nl-x-piglatin <nil> // ja-US <nil> // nl-US-u-nu-arabic <nil> // nl-1901-u-co-phonebk <nil> // nl-1901-u-nu-arabic <nil> // und-1901-u-co-phonebk <nil> // de-u-co-phonebk <nil> // de-1901 <nil> // fi <nil> // de <nil> // und-ZA <nil> // und language: subtag "HH" is well-formed but unknown // en-Latn-GB <nil> // en-GB <nil> } func ExampleParse_errors() { for _, s := range []string{"Foo", "Bar", "Foobar"} { _, err := language.Parse(s) if err != nil { if inv, ok := err.(language.ValueError); ok { fmt.Println(inv.Subtag()) } else { fmt.Println(s) } } } for _, s := range []string{"en", "aa-Uuuu", "AC", "ac-u"} { _, err := language.Parse(s) switch e := err.(type) { case language.ValueError: fmt.Printf("%s: culprit %q\n", s, e.Subtag()) case nil: // No error. default: // A syntax error. fmt.Printf("%s: ill-formed\n", s) } } // Output: // foo // Foobar // aa-Uuuu: culprit "Uuuu" // AC: culprit "ac" // ac-u: ill-formed } func ExampleParent() { p := func(tag string) { fmt.Printf("parent(%v): %v\n", tag, language.Make(tag).Parent()) } p("zh-CN") // Australian English inherits from World English. p("en-AU") // If the tag has a different maximized script from its parent, a tag with // this maximized script is inserted. This allows different language tags // which have the same base language and script in common to inherit from // a common set of settings. p("zh-HK") // If the maximized script of the parent is not identical, CLDR will skip // inheriting from it, as it means there will not be many entries in common // and inheriting from it is nonsensical. p("zh-Hant") // The parent of a tag with variants and extensions is the tag with all // variants and extensions removed. p("de-1994-u-co-phonebk") // Remove default script. p("de-Latn-LU") // Output: // parent(zh-CN): zh // parent(en-AU): en-001 // parent(zh-HK): zh-Hant // parent(zh-Hant): und // parent(de-1994-u-co-phonebk): de // parent(de-Latn-LU): de } // ExampleMatcher_bestMatch gives some examples of getting the best match of // a set of tags to any of the tags of given set. func ExampleMatcher() { // This is the set of tags from which we want to pick the best match. These // can be, for example, the supported languages for some package. tags := []language.Tag{ language.English, language.BritishEnglish, language.French, language.Afrikaans, language.BrazilianPortuguese, language.EuropeanPortuguese, language.Croatian, language.SimplifiedChinese, language.Raw.Make("iw-IL"), language.Raw.Make("iw"), language.Raw.Make("he"), } m := language.NewMatcher(tags) // A simple match. fmt.Println(m.Match(language.Make("fr"))) // Australian English is closer to British than American English. fmt.Println(m.Match(language.Make("en-AU"))) // Default to the first tag passed to the Matcher if there is no match. fmt.Println(m.Match(language.Make("ar"))) // Get the default tag. fmt.Println(m.Match()) fmt.Println("----") // Someone specifying sr-Latn is probably fine with getting Croatian. fmt.Println(m.Match(language.Make("sr-Latn"))) // We match SimplifiedChinese, but with Low confidence. fmt.Println(m.Match(language.TraditionalChinese)) // Serbian in Latin script is a closer match to Croatian than Traditional // Chinese to Simplified Chinese. fmt.Println(m.Match(language.TraditionalChinese, language.Make("sr-Latn"))) fmt.Println("----") // In case a multiple variants of a language are available, the most spoken // variant is typically returned. fmt.Println(m.Match(language.Portuguese)) // Pick the first value passed to Match in case of a tie. fmt.Println(m.Match(language.Dutch, language.Make("fr-BE"), language.Make("af-NA"))) fmt.Println(m.Match(language.Dutch, language.Make("af-NA"), language.Make("fr-BE"))) fmt.Println("----") // If a Matcher is initialized with a language and it's deprecated version, // it will distinguish between them. fmt.Println(m.Match(language.Raw.Make("iw"))) // However, for non-exact matches, it will treat deprecated versions as // equivalent and consider other factors first. fmt.Println(m.Match(language.Raw.Make("he-IL"))) fmt.Println("----") // User settings passed to the Unicode extension are ignored for matching // and preserved in the returned tag. fmt.Println(m.Match(language.Make("de-u-co-phonebk"), language.Make("fr-u-cu-frf"))) // Even if the matching language is different. fmt.Println(m.Match(language.Make("de-u-co-phonebk"), language.Make("br-u-cu-frf"))) // If there is no matching language, the options of the first preferred tag are used. fmt.Println(m.Match(language.Make("de-u-co-phonebk"))) // Output: // fr 2 Exact // en-GB 1 High // en 0 No // en 0 No // ---- // hr 6 High // zh-Hans 7 Low // hr 6 High // ---- // pt-BR 4 High // fr 2 High // af 3 High // ---- // iw 9 Exact // he 10 Exact // ---- // fr-u-cu-frf 2 Exact // fr-u-cu-frf 2 High // en-u-co-phonebk 0 No // TODO: "he" should be "he-u-rg-IL High" } func ExampleMatchStrings() { // languages supported by this service: matcher := language.NewMatcher([]language.Tag{ language.English, language.Dutch, language.German, }) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { lang, _ := r.Cookie("lang") tag, _ := language.MatchStrings(matcher, lang.String(), r.Header.Get("Accept-Language")) fmt.Println("User language:", tag) }) } func ExampleComprehends() { // Various levels of comprehensibility. fmt.Println(language.Comprehends(language.English, language.English)) fmt.Println(language.Comprehends(language.AmericanEnglish, language.BritishEnglish)) // An explicit Und results in no match. fmt.Println(language.Comprehends(language.English, language.Und)) fmt.Println("----") // There is usually no mutual comprehensibility between different scripts. fmt.Println(language.Comprehends(language.Make("en-Dsrt"), language.English)) // One exception is for Traditional versus Simplified Chinese, albeit with // a low confidence. fmt.Println(language.Comprehends(language.TraditionalChinese, language.SimplifiedChinese)) fmt.Println("----") // A Swiss German speaker will often understand High German. fmt.Println(language.Comprehends(language.Make("gsw"), language.Make("de"))) // The converse is not generally the case. fmt.Println(language.Comprehends(language.Make("de"), language.Make("gsw"))) // Output: // Exact // High // No // ---- // No // Low // ---- // High // No } func ExampleTag_values() { us := language.MustParseRegion("US") en := language.MustParseBase("en") lang, _, region := language.AmericanEnglish.Raw() fmt.Println(lang == en, region == us) lang, _, region = language.BritishEnglish.Raw() fmt.Println(lang == en, region == us) // Tags can be compared for exact equivalence using '=='. en_us, _ := language.Compose(en, us) fmt.Println(en_us == language.AmericanEnglish) // Output: // true true // true false // true }
kettle11/wabi
wabi/vendor/golang.org/x/text/language/examples_test.go
GO
mit
11,347
function thisIsAFunctionWithAVeryLongNameAndWayTooManyParameters(thisIsTheFirstParameter, andThisOneIsRelatedToIt, butNotThisOne, andNeitherThis, inFactThereArentThatManyParameters) { throw null; }
lokiiart/upali-mobile
www/frontend/node_modules/babel-plugin-syntax-trailing-function-commas/test/fixtures/trailing-function-commas/declaration/expected.js
JavaScript
gpl-3.0
200
<?php /** * CFileValidator class file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2011 Yii Software LLC * @license http://www.yiiframework.com/license/ */ /** * CFileValidator verifies if an attribute is receiving a valid uploaded file. * * It uses the model class and attribute name to retrieve the information * about the uploaded file. It then checks if a file is uploaded successfully, * if the file size is within the limit and if the file type is allowed. * * This validator will attempt to fetch uploaded data if attribute is not * previously set. Please note that this cannot be done if input is tabular: * <pre> * foreach($models as $i=>$model) * $model->attribute = CUploadedFile::getInstance($model, "[$i]attribute"); * </pre> * Please note that you must use {@link CUploadedFile::getInstances} for multiple * file uploads. * * When using CFileValidator with an active record, the following code is often used: * <pre> * if($model->save()) * { * // single upload * $model->attribute->saveAs($path); * // multiple upload * foreach($model->attribute as $file) * $file->saveAs($path); * } * </pre> * * You can use {@link CFileValidator} to validate the file attribute. * * In addition to the {@link message} property for setting a custom error message, * CFileValidator has a few custom error messages you can set that correspond to different * validation scenarios. When the file is too large, you may use the {@link tooLarge} property * to define a custom error message. Similarly for {@link tooSmall}, {@link wrongType} and * {@link tooMany}. The messages may contain additional placeholders that will be replaced * with the actual content. In addition to the "{attribute}" placeholder, recognized by all * validators (see {@link CValidator}), CFileValidator allows for the following placeholders * to be specified: * <ul> * <li>{file}: replaced with the name of the file.</li> * <li>{limit}: when using {@link tooLarge}, replaced with {@link maxSize}; * when using {@link tooSmall}, replaced with {@link minSize}; and when using {@link tooMany} * replaced with {@link maxFiles}.</li> * <li>{extensions}: when using {@link wrongType}, it will be replaced with the allowed extensions.</li> * </ul> * * @author Qiang Xue <qiang.xue@gmail.com> * @package system.validators * @since 1.0 */ class CFileValidator extends CValidator { /** * @var boolean whether the attribute requires a file to be uploaded or not. * Defaults to false, meaning a file is required to be uploaded. */ public $allowEmpty=false; /** * @var mixed a list of file name extensions that are allowed to be uploaded. * This can be either an array or a string consisting of file extension names * separated by space or comma (e.g. "gif, jpg"). * Extension names are case-insensitive. Defaults to null, meaning all file name * extensions are allowed. */ public $types; /** * @var mixed a list of MIME-types of the file that are allowed to be uploaded. * This can be either an array or a string consisting of MIME-types separated * by space or comma (e.g. "image/gif, image/jpeg"). MIME-types are * case-insensitive. Defaults to null, meaning all MIME-types are allowed. * In order to use this property fileinfo PECL extension should be installed. * @since 1.1.11 */ public $mimeTypes; /** * @var integer the minimum number of bytes required for the uploaded file. * Defaults to null, meaning no limit. * @see tooSmall */ public $minSize; /** * @var integer the maximum number of bytes required for the uploaded file. * Defaults to null, meaning no limit. * Note, the size limit is also affected by 'upload_max_filesize' INI setting * and the 'MAX_FILE_SIZE' hidden field value. * @see tooLarge */ public $maxSize; /** * @var string the error message used when the uploaded file is too large. * @see maxSize */ public $tooLarge; /** * @var string the error message used when the uploaded file is too small. * @see minSize */ public $tooSmall; /** * @var string the error message used when the uploaded file has an extension name * that is not listed among {@link types}. */ public $wrongType; /** * @var string the error message used when the uploaded file has a MIME-type * that is not listed among {@link mimeTypes}. In order to use this property * fileinfo PECL extension should be installed. * @since 1.1.11 */ public $wrongMimeType; /** * @var integer the maximum file count the given attribute can hold. * It defaults to 1, meaning single file upload. By defining a higher number, * multiple uploads become possible. */ public $maxFiles=1; /** * @var string the error message used if the count of multiple uploads exceeds * limit. */ public $tooMany; /** * @var boolean whether attributes listed with this validator should be considered safe for massive assignment. * For this validator it defaults to false. * @since 1.1.12 */ public $safe=false; /** * Set the attribute and then validates using {@link validateFile}. * If there is any error, the error message is added to the object. * @param CModel $object the object being validated * @param string $attribute the attribute being validated */ protected function validateAttribute($object, $attribute) { if($this->maxFiles > 1) { $files=$object->$attribute; if(!is_array($files) || !isset($files[0]) || !$files[0] instanceof CUploadedFile) $files = CUploadedFile::getInstances($object, $attribute); if(array()===$files) return $this->emptyAttribute($object, $attribute); if(count($files) > $this->maxFiles) { $message=$this->tooMany!==null?$this->tooMany : Yii::t('yii', '{attribute} cannot accept more than {limit} files.'); $this->addError($object, $attribute, $message, array('{attribute}'=>$attribute, '{limit}'=>$this->maxFiles)); } else foreach($files as $file) $this->validateFile($object, $attribute, $file); } else { $file = $object->$attribute; if(!$file instanceof CUploadedFile) { $file = CUploadedFile::getInstance($object, $attribute); if(null===$file) return $this->emptyAttribute($object, $attribute); } $this->validateFile($object, $attribute, $file); } } /** * Internally validates a file object. * @param CModel $object the object being validated * @param string $attribute the attribute being validated * @param CUploadedFile $file uploaded file passed to check against a set of rules */ protected function validateFile($object, $attribute, $file) { if(null===$file || ($error=$file->getError())==UPLOAD_ERR_NO_FILE) return $this->emptyAttribute($object, $attribute); elseif($error==UPLOAD_ERR_INI_SIZE || $error==UPLOAD_ERR_FORM_SIZE || $this->maxSize!==null && $file->getSize()>$this->maxSize) { $message=$this->tooLarge!==null?$this->tooLarge : Yii::t('yii','The file "{file}" is too large. Its size cannot exceed {limit} bytes.'); $this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{limit}'=>$this->getSizeLimit())); } elseif($error==UPLOAD_ERR_PARTIAL) throw new CException(Yii::t('yii','The file "{file}" was only partially uploaded.',array('{file}'=>$file->getName()))); elseif($error==UPLOAD_ERR_NO_TMP_DIR) throw new CException(Yii::t('yii','Missing the temporary folder to store the uploaded file "{file}".',array('{file}'=>$file->getName()))); elseif($error==UPLOAD_ERR_CANT_WRITE) throw new CException(Yii::t('yii','Failed to write the uploaded file "{file}" to disk.',array('{file}'=>$file->getName()))); elseif(defined('UPLOAD_ERR_EXTENSION') && $error==UPLOAD_ERR_EXTENSION) // available for PHP 5.2.0 or above throw new CException(Yii::t('yii','File upload was stopped by extension.')); if($this->minSize!==null && $file->getSize()<$this->minSize) { $message=$this->tooSmall!==null?$this->tooSmall : Yii::t('yii','The file "{file}" is too small. Its size cannot be smaller than {limit} bytes.'); $this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{limit}'=>$this->minSize)); } if($this->types!==null) { if(is_string($this->types)) $types=preg_split('/[\s,]+/',strtolower($this->types),-1,PREG_SPLIT_NO_EMPTY); else $types=$this->types; if(!in_array(strtolower($file->getExtensionName()),$types)) { $message=$this->wrongType!==null?$this->wrongType : Yii::t('yii','The file "{file}" cannot be uploaded. Only files with these extensions are allowed: {extensions}.'); $this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{extensions}'=>implode(', ',$types))); } } if($this->mimeTypes!==null) { if(function_exists('finfo_open')) { $mimeType=false; if($info=finfo_open(defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME)) $mimeType=finfo_file($info,$file->getTempName()); } elseif(function_exists('mime_content_type')) $mimeType=mime_content_type($file->getTempName()); else throw new CException(Yii::t('yii','In order to use MIME-type validation provided by CFileValidator fileinfo PECL extension should be installed.')); if(is_string($this->mimeTypes)) $mimeTypes=preg_split('/[\s,]+/',strtolower($this->mimeTypes),-1,PREG_SPLIT_NO_EMPTY); else $mimeTypes=$this->mimeTypes; if($mimeType===false || !in_array(strtolower($mimeType),$mimeTypes)) { $message=$this->wrongMimeType!==null?$this->wrongMimeType : Yii::t('yii','The file "{file}" cannot be uploaded. Only files of these MIME-types are allowed: {mimeTypes}.'); $this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{mimeTypes}'=>implode(', ',$mimeTypes))); } } } /** * Raises an error to inform end user about blank attribute. * @param CModel $object the object being validated * @param string $attribute the attribute being validated */ protected function emptyAttribute($object, $attribute) { if(!$this->allowEmpty) { $message=$this->message!==null?$this->message : Yii::t('yii','{attribute} cannot be blank.'); $this->addError($object,$attribute,$message); } } /** * Returns the maximum size allowed for uploaded files. * This is determined based on three factors: * <ul> * <li>'upload_max_filesize' in php.ini</li> * <li>'MAX_FILE_SIZE' hidden field</li> * <li>{@link maxSize}</li> * </ul> * * @return integer the size limit for uploaded files. */ protected function getSizeLimit() { $limit=ini_get('upload_max_filesize'); $limit=$this->sizeToBytes($limit); if($this->maxSize!==null && $limit>0 && $this->maxSize<$limit) $limit=$this->maxSize; if(isset($_POST['MAX_FILE_SIZE']) && $_POST['MAX_FILE_SIZE']>0 && $_POST['MAX_FILE_SIZE']<$limit) $limit=$_POST['MAX_FILE_SIZE']; return $limit; } /** * Converts php.ini style size to bytes. Examples of size strings are: 150, 1g, 500k, 5M (size suffix * is case insensitive). If you pass here the number with a fractional part, then everything after * the decimal point will be ignored (php.ini values common behavior). For example 1.5G value would be * treated as 1G and 1073741824 number will be returned as a result. This method is public * (was private before) since 1.1.11. * * @param string $sizeStr the size string to convert. * @return integer the byte count in the given size string. * @since 1.1.11 */ public function sizeToBytes($sizeStr) { // get the latest character switch (strtolower(substr($sizeStr, -1))) { case 'm': return (int)$sizeStr * 1048576; // 1024 * 1024 case 'k': return (int)$sizeStr * 1024; // 1024 case 'g': return (int)$sizeStr * 1073741824; // 1024 * 1024 * 1024 default: return (int)$sizeStr; // do nothing } } }
thu0ng91/yanyen
yii/validators/CFileValidator.php
PHP
bsd-2-clause
11,916
// 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. namespace System.Reflection.Metadata { public enum ImportDefinitionKind { ImportNamespace = 1, ImportAssemblyNamespace = 2, ImportType = 3, ImportXmlNamespace = 4, ImportAssemblyReferenceAlias = 5, AliasAssemblyReference = 6, AliasNamespace = 7, AliasAssemblyNamespace = 8, AliasType = 9 } }
shahid-pk/corefx
src/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/ImportDefinitionKind.cs
C#
mit
580
/* 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 protoc-gen-gogo. DO NOT EDIT. // source: k8s.io/kubernetes/vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.proto package v1alpha1 import ( fmt "fmt" io "io" proto "github.com/gogo/protobuf/proto" math "math" math_bits "math/bits" reflect "reflect" strings "strings" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package func (m *ServerStorageVersion) Reset() { *m = ServerStorageVersion{} } func (*ServerStorageVersion) ProtoMessage() {} func (*ServerStorageVersion) Descriptor() ([]byte, []int) { return fileDescriptor_a3903ff5e3cc7a03, []int{0} } func (m *ServerStorageVersion) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ServerStorageVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } func (m *ServerStorageVersion) XXX_Merge(src proto.Message) { xxx_messageInfo_ServerStorageVersion.Merge(m, src) } func (m *ServerStorageVersion) XXX_Size() int { return m.Size() } func (m *ServerStorageVersion) XXX_DiscardUnknown() { xxx_messageInfo_ServerStorageVersion.DiscardUnknown(m) } var xxx_messageInfo_ServerStorageVersion proto.InternalMessageInfo func (m *StorageVersion) Reset() { *m = StorageVersion{} } func (*StorageVersion) ProtoMessage() {} func (*StorageVersion) Descriptor() ([]byte, []int) { return fileDescriptor_a3903ff5e3cc7a03, []int{1} } func (m *StorageVersion) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *StorageVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } func (m *StorageVersion) XXX_Merge(src proto.Message) { xxx_messageInfo_StorageVersion.Merge(m, src) } func (m *StorageVersion) XXX_Size() int { return m.Size() } func (m *StorageVersion) XXX_DiscardUnknown() { xxx_messageInfo_StorageVersion.DiscardUnknown(m) } var xxx_messageInfo_StorageVersion proto.InternalMessageInfo func (m *StorageVersionCondition) Reset() { *m = StorageVersionCondition{} } func (*StorageVersionCondition) ProtoMessage() {} func (*StorageVersionCondition) Descriptor() ([]byte, []int) { return fileDescriptor_a3903ff5e3cc7a03, []int{2} } func (m *StorageVersionCondition) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *StorageVersionCondition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } func (m *StorageVersionCondition) XXX_Merge(src proto.Message) { xxx_messageInfo_StorageVersionCondition.Merge(m, src) } func (m *StorageVersionCondition) XXX_Size() int { return m.Size() } func (m *StorageVersionCondition) XXX_DiscardUnknown() { xxx_messageInfo_StorageVersionCondition.DiscardUnknown(m) } var xxx_messageInfo_StorageVersionCondition proto.InternalMessageInfo func (m *StorageVersionList) Reset() { *m = StorageVersionList{} } func (*StorageVersionList) ProtoMessage() {} func (*StorageVersionList) Descriptor() ([]byte, []int) { return fileDescriptor_a3903ff5e3cc7a03, []int{3} } func (m *StorageVersionList) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *StorageVersionList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } func (m *StorageVersionList) XXX_Merge(src proto.Message) { xxx_messageInfo_StorageVersionList.Merge(m, src) } func (m *StorageVersionList) XXX_Size() int { return m.Size() } func (m *StorageVersionList) XXX_DiscardUnknown() { xxx_messageInfo_StorageVersionList.DiscardUnknown(m) } var xxx_messageInfo_StorageVersionList proto.InternalMessageInfo func (m *StorageVersionSpec) Reset() { *m = StorageVersionSpec{} } func (*StorageVersionSpec) ProtoMessage() {} func (*StorageVersionSpec) Descriptor() ([]byte, []int) { return fileDescriptor_a3903ff5e3cc7a03, []int{4} } func (m *StorageVersionSpec) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *StorageVersionSpec) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } func (m *StorageVersionSpec) XXX_Merge(src proto.Message) { xxx_messageInfo_StorageVersionSpec.Merge(m, src) } func (m *StorageVersionSpec) XXX_Size() int { return m.Size() } func (m *StorageVersionSpec) XXX_DiscardUnknown() { xxx_messageInfo_StorageVersionSpec.DiscardUnknown(m) } var xxx_messageInfo_StorageVersionSpec proto.InternalMessageInfo func (m *StorageVersionStatus) Reset() { *m = StorageVersionStatus{} } func (*StorageVersionStatus) ProtoMessage() {} func (*StorageVersionStatus) Descriptor() ([]byte, []int) { return fileDescriptor_a3903ff5e3cc7a03, []int{5} } func (m *StorageVersionStatus) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *StorageVersionStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } func (m *StorageVersionStatus) XXX_Merge(src proto.Message) { xxx_messageInfo_StorageVersionStatus.Merge(m, src) } func (m *StorageVersionStatus) XXX_Size() int { return m.Size() } func (m *StorageVersionStatus) XXX_DiscardUnknown() { xxx_messageInfo_StorageVersionStatus.DiscardUnknown(m) } var xxx_messageInfo_StorageVersionStatus proto.InternalMessageInfo func init() { proto.RegisterType((*ServerStorageVersion)(nil), "k8s.io.api.apiserverinternal.v1alpha1.ServerStorageVersion") proto.RegisterType((*StorageVersion)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersion") proto.RegisterType((*StorageVersionCondition)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersionCondition") proto.RegisterType((*StorageVersionList)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersionList") proto.RegisterType((*StorageVersionSpec)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersionSpec") proto.RegisterType((*StorageVersionStatus)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersionStatus") } func init() { proto.RegisterFile("k8s.io/kubernetes/vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.proto", fileDescriptor_a3903ff5e3cc7a03) } var fileDescriptor_a3903ff5e3cc7a03 = []byte{ // 763 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4f, 0x4f, 0x13, 0x41, 0x14, 0xef, 0xd2, 0x52, 0x60, 0xaa, 0x54, 0x46, 0x08, 0xb5, 0x26, 0x5b, 0x6c, 0xa2, 0x41, 0x8d, 0xbb, 0xd2, 0x88, 0x91, 0x98, 0x68, 0x58, 0x20, 0x06, 0x03, 0x62, 0x06, 0xe2, 0x01, 0x3d, 0x38, 0xdd, 0x1d, 0xb7, 0x6b, 0xbb, 0x3b, 0x9b, 0x9d, 0x69, 0x13, 0x2e, 0xc6, 0x8f, 0xe0, 0x07, 0xf1, 0xe8, 0x87, 0xe0, 0x64, 0xb8, 0x98, 0x90, 0x98, 0x34, 0xb2, 0x7e, 0x0b, 0x4e, 0x66, 0x66, 0x77, 0x5b, 0xb6, 0x2d, 0xb1, 0xe1, 0xb0, 0xc9, 0xce, 0x7b, 0xef, 0xf7, 0x7b, 0x7f, 0xe6, 0x37, 0x0f, 0xbc, 0x69, 0x3e, 0x63, 0x9a, 0x43, 0xf5, 0x66, 0xbb, 0x4e, 0x02, 0x8f, 0x70, 0xc2, 0xf4, 0x0e, 0xf1, 0x2c, 0x1a, 0xe8, 0xb1, 0x03, 0xfb, 0x8e, 0xf8, 0x18, 0x09, 0x3a, 0x24, 0x70, 0x3c, 0x4e, 0x02, 0x0f, 0xb7, 0xf4, 0xce, 0x0a, 0x6e, 0xf9, 0x0d, 0xbc, 0xa2, 0xdb, 0xc4, 0x23, 0x01, 0xe6, 0xc4, 0xd2, 0xfc, 0x80, 0x72, 0x0a, 0xef, 0x46, 0x30, 0x0d, 0xfb, 0x8e, 0x36, 0x04, 0xd3, 0x12, 0x58, 0xf9, 0x91, 0xed, 0xf0, 0x46, 0xbb, 0xae, 0x99, 0xd4, 0xd5, 0x6d, 0x6a, 0x53, 0x5d, 0xa2, 0xeb, 0xed, 0x4f, 0xf2, 0x24, 0x0f, 0xf2, 0x2f, 0x62, 0x2d, 0x3f, 0xe9, 0x17, 0xe3, 0x62, 0xb3, 0xe1, 0x78, 0x24, 0x38, 0xd2, 0xfd, 0xa6, 0x2d, 0x2b, 0xd3, 0x5d, 0xc2, 0xb1, 0xde, 0x19, 0xaa, 0xa5, 0xac, 0x5f, 0x86, 0x0a, 0xda, 0x1e, 0x77, 0x5c, 0x32, 0x04, 0x78, 0xfa, 0x3f, 0x00, 0x33, 0x1b, 0xc4, 0xc5, 0x83, 0xb8, 0xea, 0x2f, 0x05, 0xcc, 0xef, 0xcb, 0x4e, 0xf7, 0x39, 0x0d, 0xb0, 0x4d, 0xde, 0x91, 0x80, 0x39, 0xd4, 0x83, 0xab, 0xa0, 0x80, 0x7d, 0x27, 0x72, 0x6d, 0x6f, 0x96, 0x94, 0x25, 0x65, 0x79, 0xc6, 0xb8, 0x79, 0xdc, 0xad, 0x64, 0xc2, 0x6e, 0xa5, 0xb0, 0xfe, 0x76, 0x3b, 0x71, 0xa1, 0x8b, 0x71, 0x70, 0x1d, 0x14, 0x89, 0x67, 0x52, 0xcb, 0xf1, 0xec, 0x98, 0xa9, 0x34, 0x21, 0xa1, 0x8b, 0x31, 0xb4, 0xb8, 0x95, 0x76, 0xa3, 0xc1, 0x78, 0xb8, 0x01, 0xe6, 0x2c, 0x62, 0x52, 0x0b, 0xd7, 0x5b, 0x49, 0x35, 0xac, 0x94, 0x5d, 0xca, 0x2e, 0xcf, 0x18, 0x0b, 0x61, 0xb7, 0x32, 0xb7, 0x39, 0xe8, 0x44, 0xc3, 0xf1, 0xd5, 0x1f, 0x13, 0x60, 0x76, 0xa0, 0xa3, 0x8f, 0x60, 0x5a, 0x8c, 0xdb, 0xc2, 0x1c, 0xcb, 0x76, 0x0a, 0xb5, 0xc7, 0x5a, 0xff, 0xca, 0x7b, 0x53, 0xd3, 0xfc, 0xa6, 0x2d, 0xef, 0x5f, 0x13, 0xd1, 0x5a, 0x67, 0x45, 0xdb, 0xab, 0x7f, 0x26, 0x26, 0xdf, 0x25, 0x1c, 0x1b, 0x30, 0xee, 0x02, 0xf4, 0x6d, 0xa8, 0xc7, 0x0a, 0xdf, 0x83, 0x1c, 0xf3, 0x89, 0x29, 0x3b, 0x2e, 0xd4, 0xd6, 0xb4, 0xb1, 0x04, 0xa5, 0xa5, 0xcb, 0xdc, 0xf7, 0x89, 0x69, 0x5c, 0x8b, 0xd3, 0xe4, 0xc4, 0x09, 0x49, 0x52, 0x68, 0x82, 0x3c, 0xe3, 0x98, 0xb7, 0xc5, 0x2c, 0x04, 0xfd, 0xf3, 0xab, 0xd1, 0x4b, 0x0a, 0x63, 0x36, 0x4e, 0x90, 0x8f, 0xce, 0x28, 0xa6, 0xae, 0x7e, 0xcf, 0x82, 0xc5, 0x34, 0x60, 0x83, 0x7a, 0x96, 0xc3, 0xc5, 0xfc, 0x5e, 0x82, 0x1c, 0x3f, 0xf2, 0x49, 0x2c, 0x85, 0x87, 0x49, 0x89, 0x07, 0x47, 0x3e, 0x39, 0xef, 0x56, 0x6e, 0x5f, 0x02, 0x13, 0x6e, 0x24, 0x81, 0x70, 0xad, 0xd7, 0x41, 0x24, 0x89, 0x3b, 0xe9, 0x22, 0xce, 0xbb, 0x95, 0x62, 0x0f, 0x96, 0xae, 0x0b, 0xbe, 0x06, 0x90, 0xd6, 0x65, 0x87, 0xd6, 0xab, 0x48, 0xc1, 0x42, 0x59, 0x62, 0x10, 0x59, 0xa3, 0x1c, 0xd3, 0xc0, 0xbd, 0xa1, 0x08, 0x34, 0x02, 0x05, 0x3b, 0x00, 0xb6, 0x30, 0xe3, 0x07, 0x01, 0xf6, 0x58, 0x54, 0xa2, 0xe3, 0x92, 0x52, 0x4e, 0x0e, 0xf5, 0xc1, 0x78, 0x8a, 0x10, 0x88, 0x7e, 0xde, 0x9d, 0x21, 0x36, 0x34, 0x22, 0x03, 0xbc, 0x07, 0xf2, 0x01, 0xc1, 0x8c, 0x7a, 0xa5, 0x49, 0xd9, 0x7e, 0xef, 0x0e, 0x90, 0xb4, 0xa2, 0xd8, 0x0b, 0xef, 0x83, 0x29, 0x97, 0x30, 0x86, 0x6d, 0x52, 0xca, 0xcb, 0xc0, 0x62, 0x1c, 0x38, 0xb5, 0x1b, 0x99, 0x51, 0xe2, 0xaf, 0xfe, 0x54, 0x00, 0x4c, 0xcf, 0x7d, 0xc7, 0x61, 0x1c, 0x7e, 0x18, 0x52, 0xba, 0x36, 0x5e, 0x5f, 0x02, 0x2d, 0x75, 0x7e, 0x23, 0x4e, 0x39, 0x9d, 0x58, 0x2e, 0xa8, 0xfc, 0x10, 0x4c, 0x3a, 0x9c, 0xb8, 0xe2, 0x16, 0xb3, 0xcb, 0x85, 0xda, 0xea, 0x95, 0x74, 0x68, 0x5c, 0x8f, 0x33, 0x4c, 0x6e, 0x0b, 0x2e, 0x14, 0x51, 0x56, 0xe7, 0x07, 0xfb, 0x11, 0x0f, 0xa0, 0xfa, 0x7b, 0x02, 0xcc, 0x8f, 0x92, 0x31, 0xfc, 0x02, 0x8a, 0x2c, 0x65, 0x67, 0x25, 0x45, 0x16, 0x35, 0xf6, 0xe3, 0x18, 0xb1, 0xfa, 0xfa, 0xab, 0x2a, 0x6d, 0x67, 0x68, 0x30, 0x19, 0xdc, 0x03, 0x0b, 0x26, 0x75, 0x5d, 0xea, 0x6d, 0x8d, 0xdc, 0x79, 0xb7, 0xc2, 0x6e, 0x65, 0x61, 0x63, 0x54, 0x00, 0x1a, 0x8d, 0x83, 0x01, 0x00, 0x66, 0xf2, 0x04, 0xa2, 0xa5, 0x57, 0xa8, 0xbd, 0xb8, 0xd2, 0x80, 0x7b, 0x2f, 0xa9, 0xbf, 0xb3, 0x7a, 0x26, 0x86, 0x2e, 0x64, 0x31, 0xb4, 0xe3, 0x33, 0x35, 0x73, 0x72, 0xa6, 0x66, 0x4e, 0xcf, 0xd4, 0xcc, 0xd7, 0x50, 0x55, 0x8e, 0x43, 0x55, 0x39, 0x09, 0x55, 0xe5, 0x34, 0x54, 0x95, 0x3f, 0xa1, 0xaa, 0x7c, 0xfb, 0xab, 0x66, 0x0e, 0xa7, 0x93, 0x3c, 0xff, 0x02, 0x00, 0x00, 0xff, 0xff, 0xa1, 0x5f, 0xcf, 0x37, 0x78, 0x07, 0x00, 0x00, } func (m *ServerStorageVersion) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ServerStorageVersion) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ServerStorageVersion) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.DecodableVersions) > 0 { for iNdEx := len(m.DecodableVersions) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.DecodableVersions[iNdEx]) copy(dAtA[i:], m.DecodableVersions[iNdEx]) i = encodeVarintGenerated(dAtA, i, uint64(len(m.DecodableVersions[iNdEx]))) i-- dAtA[i] = 0x1a } } i -= len(m.EncodingVersion) copy(dAtA[i:], m.EncodingVersion) i = encodeVarintGenerated(dAtA, i, uint64(len(m.EncodingVersion))) i-- dAtA[i] = 0x12 i -= len(m.APIServerID) copy(dAtA[i:], m.APIServerID) i = encodeVarintGenerated(dAtA, i, uint64(len(m.APIServerID))) i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *StorageVersion) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *StorageVersion) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *StorageVersion) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a { size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 { size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *StorageVersionCondition) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *StorageVersionCondition) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *StorageVersionCondition) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l i -= len(m.Message) copy(dAtA[i:], m.Message) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Message))) i-- dAtA[i] = 0x32 i -= len(m.Reason) copy(dAtA[i:], m.Reason) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Reason))) i-- dAtA[i] = 0x2a { size, err := m.LastTransitionTime.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x22 i = encodeVarintGenerated(dAtA, i, uint64(m.ObservedGeneration)) i-- dAtA[i] = 0x18 i -= len(m.Status) copy(dAtA[i:], m.Status) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Status))) i-- dAtA[i] = 0x12 i -= len(m.Type) copy(dAtA[i:], m.Type) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Type))) i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *StorageVersionList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *StorageVersionList) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *StorageVersionList) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Items) > 0 { for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } } { size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *StorageVersionSpec) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *StorageVersionSpec) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *StorageVersionSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func (m *StorageVersionStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *StorageVersionStatus) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *StorageVersionStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Conditions) > 0 { for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a } } if m.CommonEncodingVersion != nil { i -= len(*m.CommonEncodingVersion) copy(dAtA[i:], *m.CommonEncodingVersion) i = encodeVarintGenerated(dAtA, i, uint64(len(*m.CommonEncodingVersion))) i-- dAtA[i] = 0x12 } if len(m.StorageVersions) > 0 { for iNdEx := len(m.StorageVersions) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.StorageVersions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { offset -= sovGenerated(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *ServerStorageVersion) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.APIServerID) n += 1 + l + sovGenerated(uint64(l)) l = len(m.EncodingVersion) n += 1 + l + sovGenerated(uint64(l)) if len(m.DecodableVersions) > 0 { for _, s := range m.DecodableVersions { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *StorageVersion) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.ObjectMeta.Size() n += 1 + l + sovGenerated(uint64(l)) l = m.Spec.Size() n += 1 + l + sovGenerated(uint64(l)) l = m.Status.Size() n += 1 + l + sovGenerated(uint64(l)) return n } func (m *StorageVersionCondition) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Type) n += 1 + l + sovGenerated(uint64(l)) l = len(m.Status) n += 1 + l + sovGenerated(uint64(l)) n += 1 + sovGenerated(uint64(m.ObservedGeneration)) l = m.LastTransitionTime.Size() n += 1 + l + sovGenerated(uint64(l)) l = len(m.Reason) n += 1 + l + sovGenerated(uint64(l)) l = len(m.Message) n += 1 + l + sovGenerated(uint64(l)) return n } func (m *StorageVersionList) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.ListMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Items) > 0 { for _, e := range m.Items { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *StorageVersionSpec) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func (m *StorageVersionStatus) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.StorageVersions) > 0 { for _, e := range m.StorageVersions { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } if m.CommonEncodingVersion != nil { l = len(*m.CommonEncodingVersion) n += 1 + l + sovGenerated(uint64(l)) } if len(m.Conditions) > 0 { for _, e := range m.Conditions { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } return n } func sovGenerated(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *ServerStorageVersion) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&ServerStorageVersion{`, `APIServerID:` + fmt.Sprintf("%v", this.APIServerID) + `,`, `EncodingVersion:` + fmt.Sprintf("%v", this.EncodingVersion) + `,`, `DecodableVersions:` + fmt.Sprintf("%v", this.DecodableVersions) + `,`, `}`, }, "") return s } func (this *StorageVersion) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&StorageVersion{`, `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "StorageVersionSpec", "StorageVersionSpec", 1), `&`, ``, 1) + `,`, `Status:` + strings.Replace(strings.Replace(this.Status.String(), "StorageVersionStatus", "StorageVersionStatus", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *StorageVersionCondition) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&StorageVersionCondition{`, `Type:` + fmt.Sprintf("%v", this.Type) + `,`, `Status:` + fmt.Sprintf("%v", this.Status) + `,`, `ObservedGeneration:` + fmt.Sprintf("%v", this.ObservedGeneration) + `,`, `LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, `Message:` + fmt.Sprintf("%v", this.Message) + `,`, `}`, }, "") return s } func (this *StorageVersionList) String() string { if this == nil { return "nil" } repeatedStringForItems := "[]StorageVersion{" for _, f := range this.Items { repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "StorageVersion", "StorageVersion", 1), `&`, ``, 1) + "," } repeatedStringForItems += "}" s := strings.Join([]string{`&StorageVersionList{`, `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, `Items:` + repeatedStringForItems + `,`, `}`, }, "") return s } func (this *StorageVersionSpec) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&StorageVersionSpec{`, `}`, }, "") return s } func (this *StorageVersionStatus) String() string { if this == nil { return "nil" } repeatedStringForStorageVersions := "[]ServerStorageVersion{" for _, f := range this.StorageVersions { repeatedStringForStorageVersions += strings.Replace(strings.Replace(f.String(), "ServerStorageVersion", "ServerStorageVersion", 1), `&`, ``, 1) + "," } repeatedStringForStorageVersions += "}" repeatedStringForConditions := "[]StorageVersionCondition{" for _, f := range this.Conditions { repeatedStringForConditions += strings.Replace(strings.Replace(f.String(), "StorageVersionCondition", "StorageVersionCondition", 1), `&`, ``, 1) + "," } repeatedStringForConditions += "}" s := strings.Join([]string{`&StorageVersionStatus{`, `StorageVersions:` + repeatedStringForStorageVersions + `,`, `CommonEncodingVersion:` + valueToStringGenerated(this.CommonEncodingVersion) + `,`, `Conditions:` + repeatedStringForConditions + `,`, `}`, }, "") return s } func valueToStringGenerated(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } func (m *ServerStorageVersion) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ServerStorageVersion: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ServerStorageVersion: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field APIServerID", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.APIServerID = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field EncodingVersion", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.EncodingVersion = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DecodableVersions", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.DecodableVersions = append(m.DecodableVersions, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *StorageVersion) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: StorageVersion: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: StorageVersion: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *StorageVersionCondition) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: StorageVersionCondition: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: StorageVersionCondition: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.Type = StorageVersionConditionType(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.Status = ConditionStatus(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field ObservedGeneration", wireType) } m.ObservedGeneration = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.ObservedGeneration |= int64(b&0x7F) << shift if b < 0x80 { break } } case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field LastTransitionTime", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.LastTransitionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.Reason = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.Message = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *StorageVersionList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: StorageVersionList: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: StorageVersionList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.Items = append(m.Items, StorageVersion{}) if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *StorageVersionSpec) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: StorageVersionSpec: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: StorageVersionSpec: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *StorageVersionStatus) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: StorageVersionStatus: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: StorageVersionStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StorageVersions", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.StorageVersions = append(m.StorageVersions, ServerStorageVersion{}) if err := m.StorageVersions[len(m.StorageVersions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field CommonEncodingVersion", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } s := string(dAtA[iNdEx:postIndex]) m.CommonEncodingVersion = &s iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.Conditions = append(m.Conditions, StorageVersionCondition{}) if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenerated(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthGenerated } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupGenerated } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthGenerated } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group") )
grafana/loki
vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.pb.go
GO
agpl-3.0
45,028
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package sysctl import ( "testing" "k8s.io/kubernetes/pkg/api" ) func TestValidate(t *testing.T) { tests := map[string]struct { patterns []string allowed []string disallowed []string }{ // no container requests "nil": { patterns: nil, allowed: []string{"foo"}, }, "empty": { patterns: []string{}, disallowed: []string{"foo"}, }, "without wildcard": { patterns: []string{"a", "a.b"}, allowed: []string{"a", "a.b"}, disallowed: []string{"b"}, }, "with catch-all wildcard": { patterns: []string{"*"}, allowed: []string{"a", "a.b"}, }, "with catch-all wildcard and non-wildcard": { patterns: []string{"a.b.c", "*"}, allowed: []string{"a", "a.b", "a.b.c", "b"}, }, "without catch-all wildcard": { patterns: []string{"a.*", "b.*", "c.d.e", "d.e.f.*"}, allowed: []string{"a.b", "b.c", "c.d.e", "d.e.f.g.h"}, disallowed: []string{"a", "b", "c", "c.d", "d.e", "d.e.f"}, }, } for k, v := range tests { strategy := NewMustMatchPatterns(v.patterns) pod := &api.Pod{} errs := strategy.Validate(pod) if len(errs) != 0 { t.Errorf("%s: unexpected validaton errors for empty sysctls: %v", k, errs) } sysctls := []api.Sysctl{} for _, s := range v.allowed { sysctls = append(sysctls, api.Sysctl{ Name: s, Value: "dummy", }) } testAllowed := func(key string, category string) { pod.Annotations = map[string]string{ key: api.PodAnnotationsFromSysctls(sysctls), } errs = strategy.Validate(pod) if len(errs) != 0 { t.Errorf("%s: unexpected validaton errors for %s sysctls: %v", k, category, errs) } } testDisallowed := func(key string, category string) { for _, s := range v.disallowed { pod.Annotations = map[string]string{ key: api.PodAnnotationsFromSysctls([]api.Sysctl{{Name: s, Value: "dummy"}}), } errs = strategy.Validate(pod) if len(errs) == 0 { t.Errorf("%s: expected error for %s sysctl %q", k, category, s) } } } testAllowed(api.SysctlsPodAnnotationKey, "safe") testAllowed(api.UnsafeSysctlsPodAnnotationKey, "unsafe") testDisallowed(api.SysctlsPodAnnotationKey, "safe") testDisallowed(api.UnsafeSysctlsPodAnnotationKey, "unsafe") } }
wongma7/efs-provisioner
vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/sysctl/mustmatchpatterns_test.go
GO
apache-2.0
2,810
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * @providesModule ReactCSSTransitionGroupChild */ 'use strict'; var React = require('./React'); var ReactDOM = require('./ReactDOM'); var CSSCore = require('fbjs/lib/CSSCore'); var ReactTransitionEvents = require('./ReactTransitionEvents'); var onlyChild = require('./onlyChild'); // We don't remove the element from the DOM until we receive an animationend or // transitionend event. If the user screws up and forgets to add an animation // their node will be stuck in the DOM forever, so we detect if an animation // does not start and if it doesn't, we just call the end listener immediately. var TICK = 17; var ReactCSSTransitionGroupChild = React.createClass({ displayName: 'ReactCSSTransitionGroupChild', propTypes: { name: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.shape({ enter: React.PropTypes.string, leave: React.PropTypes.string, active: React.PropTypes.string }), React.PropTypes.shape({ enter: React.PropTypes.string, enterActive: React.PropTypes.string, leave: React.PropTypes.string, leaveActive: React.PropTypes.string, appear: React.PropTypes.string, appearActive: React.PropTypes.string })]).isRequired, // Once we require timeouts to be specified, we can remove the // boolean flags (appear etc.) and just accept a number // or a bool for the timeout flags (appearTimeout etc.) appear: React.PropTypes.bool, enter: React.PropTypes.bool, leave: React.PropTypes.bool, appearTimeout: React.PropTypes.number, enterTimeout: React.PropTypes.number, leaveTimeout: React.PropTypes.number }, transition: function (animationType, finishCallback, userSpecifiedDelay) { var node = ReactDOM.findDOMNode(this); if (!node) { if (finishCallback) { finishCallback(); } return; } var className = this.props.name[animationType] || this.props.name + '-' + animationType; var activeClassName = this.props.name[animationType + 'Active'] || className + '-active'; var timeout = null; var endListener = function (e) { if (e && e.target !== node) { return; } clearTimeout(timeout); CSSCore.removeClass(node, className); CSSCore.removeClass(node, activeClassName); ReactTransitionEvents.removeEndEventListener(node, endListener); // Usually this optional callback is used for informing an owner of // a leave animation and telling it to remove the child. if (finishCallback) { finishCallback(); } }; CSSCore.addClass(node, className); // Need to do this to actually trigger a transition. this.queueClass(activeClassName); // If the user specified a timeout delay. if (userSpecifiedDelay) { // Clean-up the animation after the specified delay timeout = setTimeout(endListener, userSpecifiedDelay); this.transitionTimeouts.push(timeout); } else { // DEPRECATED: this listener will be removed in a future version of react ReactTransitionEvents.addEndEventListener(node, endListener); } }, queueClass: function (className) { this.classNameQueue.push(className); if (!this.timeout) { this.timeout = setTimeout(this.flushClassNameQueue, TICK); } }, flushClassNameQueue: function () { if (this.isMounted()) { this.classNameQueue.forEach(CSSCore.addClass.bind(CSSCore, ReactDOM.findDOMNode(this))); } this.classNameQueue.length = 0; this.timeout = null; }, componentWillMount: function () { this.classNameQueue = []; this.transitionTimeouts = []; }, componentWillUnmount: function () { if (this.timeout) { clearTimeout(this.timeout); } this.transitionTimeouts.forEach(function (timeout) { clearTimeout(timeout); }); }, componentWillAppear: function (done) { if (this.props.appear) { this.transition('appear', done, this.props.appearTimeout); } else { done(); } }, componentWillEnter: function (done) { if (this.props.enter) { this.transition('enter', done, this.props.enterTimeout); } else { done(); } }, componentWillLeave: function (done) { if (this.props.leave) { this.transition('leave', done, this.props.leaveTimeout); } else { done(); } }, render: function () { return onlyChild(this.props.children); } }); module.exports = ReactCSSTransitionGroupChild;
emineKoc/WiseWit
wisewit_front_end/node_modules/react/lib/ReactCSSTransitionGroupChild.js
JavaScript
gpl-3.0
4,805
var _ = require('lodash'); /** * formats variables for handlebars in multi-post contexts. * If extraValues are available, they are merged in the final value * @return {Object} containing page variables */ function formatPageResponse(result) { var response = { posts: result.posts, pagination: result.meta.pagination }; _.each(result.data, function (data, name) { if (data.meta) { // Move pagination to be a top level key response[name] = data; response[name].pagination = data.meta.pagination; delete response[name].meta; } else { // This is a single object, don't wrap it in an array response[name] = data[0]; } }); return response; } /** * similar to formatPageResponse, but for single post pages * @return {Object} containing page variables */ function formatResponse(post) { return { post: post }; } module.exports = { channel: formatPageResponse, single: formatResponse };
norsasono/openshift-ghost-starter
node_modules/ghost/core/server/controllers/frontend/format-response.js
JavaScript
mit
1,048
package dns import "github.com/jen20/riviera/azure" type DeleteRecordSet struct { Name string `json:"-"` ResourceGroupName string `json:"-"` ZoneName string `json:"-"` RecordSetType string `json:"-"` } func (command DeleteRecordSet) APIInfo() azure.APIInfo { return azure.APIInfo{ APIVersion: apiVersion, Method: "DELETE", URLPathFunc: dnsRecordSetDefaultURLPathFunc(command.ResourceGroupName, command.ZoneName, command.RecordSetType, command.Name), ResponseTypeFunc: func() interface{} { return nil }, } }
TStraub-rms/terraform
vendor/github.com/jen20/riviera/dns/delete_dns_recordset.go
GO
mpl-2.0
561
/* 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 applyconfiguration-gen. DO NOT EDIT. package v1beta1 import ( corev1 "k8s.io/client-go/applyconfigurations/core/v1" v1 "k8s.io/client-go/applyconfigurations/meta/v1" ) // ReplicaSetSpecApplyConfiguration represents an declarative configuration of the ReplicaSetSpec type for use // with apply. type ReplicaSetSpecApplyConfiguration struct { Replicas *int32 `json:"replicas,omitempty"` MinReadySeconds *int32 `json:"minReadySeconds,omitempty"` Selector *v1.LabelSelectorApplyConfiguration `json:"selector,omitempty"` Template *corev1.PodTemplateSpecApplyConfiguration `json:"template,omitempty"` } // ReplicaSetSpecApplyConfiguration constructs an declarative configuration of the ReplicaSetSpec type for use with // apply. func ReplicaSetSpec() *ReplicaSetSpecApplyConfiguration { return &ReplicaSetSpecApplyConfiguration{} } // WithReplicas sets the Replicas field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Replicas field is set to the value of the last call. func (b *ReplicaSetSpecApplyConfiguration) WithReplicas(value int32) *ReplicaSetSpecApplyConfiguration { b.Replicas = &value return b } // WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the MinReadySeconds field is set to the value of the last call. func (b *ReplicaSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *ReplicaSetSpecApplyConfiguration { b.MinReadySeconds = &value return b } // WithSelector sets the Selector field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Selector field is set to the value of the last call. func (b *ReplicaSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ReplicaSetSpecApplyConfiguration { b.Selector = value return b } // WithTemplate sets the Template field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Template field is set to the value of the last call. func (b *ReplicaSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *ReplicaSetSpecApplyConfiguration { b.Template = value return b }
k8sdb/postgres
vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetspec.go
GO
apache-2.0
3,284
class Mp3wrap < Formula desc "Wrap two or more mp3 files in a single large file" homepage "http://mp3wrap.sourceforge.net/" url "https://downloads.sourceforge.net/project/mp3wrap/mp3wrap/mp3wrap%200.5/mp3wrap-0.5-src.tar.gz" sha256 "1b4644f6b7099dcab88b08521d59d6f730fa211b5faf1f88bd03bf61fedc04e7" bottle do cellar :any sha256 "4e8f01653ab2067bcb7ed2716fdb864aac08b517c995839f6d3b942cb705504c" => :mavericks sha256 "ea4a05df9dc44f6fc5f9658fcc6694c0ec0c649a882bc97b3b37354de08f7d0f" => :mountain_lion sha256 "10128ee1f87efb4e7259c39c14633d16d1f6138f6bde064a50e66d3ba8427b1f" => :lion end def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}" system "make", "install" end test do source = test_fixtures("test.mp3") system "#{bin}/mp3wrap", "#{testpath}/t.mp3", source, source assert File.exist? testpath/"t_MP3WRAP.mp3" end end
rokn/Count_Words_2015
fetched_code/ruby/mp3wrap.rb
Ruby
mit
1,036
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package rpc import ( "errors" "fmt" "net" "runtime" "strings" "testing" ) type shutdownCodec struct { responded chan int closed bool } func (c *shutdownCodec) WriteRequest(*Request, interface{}) error { return nil } func (c *shutdownCodec) ReadResponseBody(interface{}) error { return nil } func (c *shutdownCodec) ReadResponseHeader(*Response) error { c.responded <- 1 return errors.New("shutdownCodec ReadResponseHeader") } func (c *shutdownCodec) Close() error { c.closed = true return nil } func TestCloseCodec(t *testing.T) { codec := &shutdownCodec{responded: make(chan int)} client := NewClientWithCodec(codec) <-codec.responded client.Close() if !codec.closed { t.Error("client.Close did not close codec") } } // Test that errors in gob shut down the connection. Issue 7689. type R struct { msg []byte // Not exported, so R does not work with gob. } type S struct{} func (s *S) Recv(nul *struct{}, reply *R) error { *reply = R{[]byte("foo")} return nil } func TestGobError(t *testing.T) { if runtime.GOOS == "plan9" { t.Skip("skipping test; see https://golang.org/issue/8908") } defer func() { err := recover() if err == nil { t.Fatal("no error") } if !strings.Contains("reading body EOF", err.(error).Error()) { t.Fatal("expected `reading body EOF', got", err) } }() Register(new(S)) listen, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) } go Accept(listen) client, err := Dial("tcp", listen.Addr().String()) if err != nil { panic(err) } var reply Reply err = client.Call("S.Recv", &struct{}{}, &reply) if err != nil { panic(err) } fmt.Printf("%#v\n", reply) client.Close() listen.Close() }
KeyTalk/ApplicationInterfaceGateway
vendor/src/net/rpc/client_test.go
GO
bsd-3-clause
1,870
package main func main() { c := make(chan int, 1); c <- 0; if <-c != 0 { panic(0) } }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/go.go-torture/execute/chan-1.go
GO
gpl-2.0
93
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package priorities import ( "reflect" "testing" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) func TestBalancedResourceAllocation(t *testing.T) { labels1 := map[string]string{ "foo": "bar", "baz": "blah", } labels2 := map[string]string{ "bar": "foo", "baz": "blah", } machine1Spec := v1.PodSpec{ NodeName: "machine1", } machine2Spec := v1.PodSpec{ NodeName: "machine2", } noResources := v1.PodSpec{ Containers: []v1.Container{}, } cpuOnly := v1.PodSpec{ NodeName: "machine1", Containers: []v1.Container{ { Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ "cpu": resource.MustParse("1000m"), "memory": resource.MustParse("0"), }, }, }, { Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ "cpu": resource.MustParse("2000m"), "memory": resource.MustParse("0"), }, }, }, }, } cpuOnly2 := cpuOnly cpuOnly2.NodeName = "machine2" cpuAndMemory := v1.PodSpec{ NodeName: "machine2", Containers: []v1.Container{ { Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ "cpu": resource.MustParse("1000m"), "memory": resource.MustParse("2000"), }, }, }, { Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ "cpu": resource.MustParse("2000m"), "memory": resource.MustParse("3000"), }, }, }, }, } tests := []struct { pod *v1.Pod pods []*v1.Pod nodes []*v1.Node expectedList schedulerapi.HostPriorityList test string }{ { /* Node1 scores (remaining resources) on 0-10 scale CPU Fraction: 0 / 4000 = 0% Memory Fraction: 0 / 10000 = 0% Node1 Score: 10 - (0-0)*10 = 10 Node2 scores (remaining resources) on 0-10 scale CPU Fraction: 0 / 4000 = 0 % Memory Fraction: 0 / 10000 = 0% Node2 Score: 10 - (0-0)*10 = 10 */ pod: &v1.Pod{Spec: noResources}, nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}}, test: "nothing scheduled, nothing requested", }, { /* Node1 scores on 0-10 scale CPU Fraction: 3000 / 4000= 75% Memory Fraction: 5000 / 10000 = 50% Node1 Score: 10 - (0.75-0.5)*10 = 7 Node2 scores on 0-10 scale CPU Fraction: 3000 / 6000= 50% Memory Fraction: 5000/10000 = 50% Node2 Score: 10 - (0.5-0.5)*10 = 10 */ pod: &v1.Pod{Spec: cpuAndMemory}, nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 6000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 7}, {Host: "machine2", Score: 10}}, test: "nothing scheduled, resources requested, differently sized machines", }, { /* Node1 scores on 0-10 scale CPU Fraction: 0 / 4000= 0% Memory Fraction: 0 / 10000 = 0% Node1 Score: 10 - (0-0)*10 = 10 Node2 scores on 0-10 scale CPU Fraction: 0 / 4000= 0% Memory Fraction: 0 / 10000 = 0% Node2 Score: 10 - (0-0)*10 = 10 */ pod: &v1.Pod{Spec: noResources}, nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}}, test: "no resources requested, pods scheduled", pods: []*v1.Pod{ {Spec: machine1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels2}}, {Spec: machine1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: machine2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: machine2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, }, }, { /* Node1 scores on 0-10 scale CPU Fraction: 6000 / 10000 = 60% Memory Fraction: 0 / 20000 = 0% Node1 Score: 10 - (0.6-0)*10 = 4 Node2 scores on 0-10 scale CPU Fraction: 6000 / 10000 = 60% Memory Fraction: 5000 / 20000 = 25% Node2 Score: 10 - (0.6-0.25)*10 = 6 */ pod: &v1.Pod{Spec: noResources}, nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 4}, {Host: "machine2", Score: 6}}, test: "no resources requested, pods scheduled with resources", pods: []*v1.Pod{ {Spec: cpuOnly, ObjectMeta: metav1.ObjectMeta{Labels: labels2}}, {Spec: cpuOnly, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: cpuOnly2, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: cpuAndMemory, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, }, }, { /* Node1 scores on 0-10 scale CPU Fraction: 6000 / 10000 = 60% Memory Fraction: 5000 / 20000 = 25% Node1 Score: 10 - (0.6-0.25)*10 = 6 Node2 scores on 0-10 scale CPU Fraction: 6000 / 10000 = 60% Memory Fraction: 10000 / 20000 = 50% Node2 Score: 10 - (0.6-0.5)*10 = 9 */ pod: &v1.Pod{Spec: cpuAndMemory}, nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 6}, {Host: "machine2", Score: 9}}, test: "resources requested, pods scheduled with resources", pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, }, { /* Node1 scores on 0-10 scale CPU Fraction: 6000 / 10000 = 60% Memory Fraction: 5000 / 20000 = 25% Node1 Score: 10 - (0.6-0.25)*10 = 6 Node2 scores on 0-10 scale CPU Fraction: 6000 / 10000 = 60% Memory Fraction: 10000 / 50000 = 20% Node2 Score: 10 - (0.6-0.2)*10 = 6 */ pod: &v1.Pod{Spec: cpuAndMemory}, nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 50000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 6}, {Host: "machine2", Score: 6}}, test: "resources requested, pods scheduled with resources, differently sized machines", pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, }, { /* Node1 scores on 0-10 scale CPU Fraction: 6000 / 4000 > 100% ==> Score := 0 Memory Fraction: 0 / 10000 = 0 Node1 Score: 0 Node2 scores on 0-10 scale CPU Fraction: 6000 / 4000 > 100% ==> Score := 0 Memory Fraction 5000 / 10000 = 50% Node2 Score: 0 */ pod: &v1.Pod{Spec: cpuOnly}, nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}}, test: "requested resources exceed node capacity", pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, }, { pod: &v1.Pod{Spec: noResources}, nodes: []*v1.Node{makeNode("machine1", 0, 0), makeNode("machine2", 0, 0)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}}, test: "zero node resources, pods scheduled with resources", pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, }, } for _, test := range tests { nodeNameToInfo := schedulercache.CreateNodeNameToInfoMap(test.pods, test.nodes) list, err := priorityFunction(BalancedResourceAllocationMap, nil)(test.pod, nodeNameToInfo, test.nodes) if err != nil { t.Errorf("unexpected error: %v", err) } if !reflect.DeepEqual(test.expectedList, list) { t.Errorf("%s: expected %#v, got %#v", test.test, test.expectedList, list) } } }
wanghaoran1988/origin
vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation_test.go
GO
apache-2.0
8,474
'use strict'; var times = require('../times'); var moment = require('moment'); function init (ctx) { var translate = ctx.language.translate; var basal = { name: 'basal' , label: 'Basal Profile' , pluginType: 'pill-minor' }; basal.setProperties = function setProperties (sbx) { if (hasRequiredInfo(sbx)) { var profile = sbx.data.profile; var current = profile.getTempBasal(sbx.time); var tempMark = ''; tempMark += current.treatment ? 'T' : ''; tempMark += current.combobolustreatment ? 'C' : ''; tempMark += tempMark ? ': ' : ''; sbx.offerProperty('basal', function setBasal() { return { display: tempMark + current.totalbasal.toFixed(3) + 'U' , current: current }; }); } }; function hasRequiredInfo (sbx) { if (!sbx.data.profile) { return false; } if (!sbx.data.profile.hasData()) { console.warn('For the Basal plugin to function you need a treatment profile'); return false; } if (!sbx.data.profile.getBasal()) { console.warn('For the Basal plugin to function you need a basal profile'); return false; } return true; } basal.updateVisualisation = function updateVisualisation (sbx) { if (!hasRequiredInfo(sbx)) { return; } var profile = sbx.data.profile; var prop = sbx.properties.basal; var basalValue = prop && prop.current; var tzMessage = profile.getTimezone() ? profile.getTimezone() : 'Timezone not set in profile'; var info = [{label: translate('Current basal'), value: prop.display} , {label: translate('Sensitivity'), value: profile.getSensitivity(sbx.time) + ' ' + sbx.settings.units + ' / U'} , {label: translate('Current Carb Ratio'), value: '1 U / ' + profile.getCarbRatio(sbx.time) + 'g'} , {label: translate('Basal timezone'), value: tzMessage} , {label: '------------', value: ''} , {label: translate('Active profile'), value: profile.activeProfileToTime(sbx.time)} ]; var tempText, remaining; if (basalValue.treatment) { tempText = basalValue.treatment.percent ? (basalValue.treatment.percent > 0 ? '+' : '') + basalValue.treatment.percent + '%' : !isNaN(basalValue.treatment.absolute) ? basalValue.treatment.absolute + 'U/h' : ''; remaining = parseInt(basalValue.treatment.duration - times.msecs(sbx.time - basalValue.treatment.mills).mins); info.push({label: '------------', value: ''}); info.push({label: translate('Active temp basal'), value: tempText}); info.push({label: translate('Active temp basal start'), value: new Date(basalValue.treatment.mills).toLocaleString()}); info.push({label: translate('Active temp basal duration'), value: parseInt(basalValue.treatment.duration) + ' ' + translate('mins')}); info.push({label: translate('Active temp basal remaining'), value: remaining + ' ' + translate('mins')}); info.push({label: translate('Basal profile value'), value: basalValue.basal.toFixed(3) + ' U'}); } if (basalValue.combobolustreatment) { tempText = (basalValue.combobolustreatment.relative ? '+' + basalValue.combobolustreatment.relative + 'U/h' : ''); remaining = parseInt(basalValue.combobolustreatment.duration - times.msecs(sbx.time - basalValue.combobolustreatment.mills).mins); info.push({label: '------------', value: ''}); info.push({label: translate('Active combo bolus'), value: tempText}); info.push({label: translate('Active combo bolus start'), value: new Date(basalValue.combobolustreatment.mills).toLocaleString()}); info.push({label: translate('Active combo bolus duration'), value: parseInt(basalValue.combobolustreatment.duration) + ' ' + translate('mins')}); info.push({label: translate('Active combo bolus remaining'), value: remaining + ' ' + translate('mins')}); } sbx.pluginBase.updatePillText(basal, { value: prop.display , label: translate('BASAL') , info: info }); }; function basalMessage(slots, sbx) { var basalValue = sbx.data.profile.getTempBasal(sbx.time); var response = 'Unable to determine current basal'; var preamble = ''; if (basalValue.treatment) { preamble = (slots && slots.pwd && slots.pwd.value) ? translate('alexaPreamble3person', { params: [ slots.pwd.value ] }) : translate('alexaPreamble'); var minutesLeft = moment(basalValue.treatment.endmills).from(moment(sbx.time)); response = translate('alexaBasalTemp', { params: [ preamble, basalValue.totalbasal, minutesLeft ] }); } else { preamble = (slots && slots.pwd && slots.pwd.value) ? translate('alexaPreamble3person', { params: [ slots.pwd.value ] }) : translate('alexaPreamble'); response = translate('alexaBasal', { params: [ preamble, basalValue.totalbasal ] }); } return response; } function alexaRollupCurrentBasalHandler (slots, sbx, callback) { callback(null, {results: basalMessage(slots, sbx), priority: 1}); } function alexaCurrentBasalhandler (next, slots, sbx) { next('Current Basal', basalMessage(slots, sbx)); } basal.alexa = { rollupHandlers: [{ rollupGroup: 'Status' , rollupName: 'current basal' , rollupHandler: alexaRollupCurrentBasalHandler }], intentHandlers: [{ intent: 'MetricNow' , routableSlot:'metric' , slots:['basal', 'current basal'] , intentHandler: alexaCurrentBasalhandler }] }; return basal; } module.exports = init;
GarthDB/cgm-remote-monitor
lib/plugins/basalprofile.js
JavaScript
agpl-3.0
5,961
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Util; use Symfony\Component\PropertyAccess\PropertyPathIteratorInterface as BasePropertyPathIteratorInterface; /** * Alias for {@link \Symfony\Component\PropertyAccess\PropertyPathIteratorInterface}. * * @author Bernhard Schussek <bschussek@gmail.com> * * @deprecated deprecated since version 2.2, to be removed in 2.3. Use * {@link \Symfony\Component\PropertyAccess\PropertyPathIterator} * instead. */ interface PropertyPathIteratorInterface extends BasePropertyPathIteratorInterface { }
nandy-andy/performance-blog
vendors/silex/symfony/form/Symfony/Component/Form/Util/PropertyPathIteratorInterface.php
PHP
gpl-2.0
794
<?php /** * @file * Contains database additions to drupal-8.bare.standard.php.gz for testing the * upgrade path of https://www.drupal.org/node/507488. */ use Drupal\Core\Database\Database; $connection = Database::getConnection(); // Structure of a custom block with visibility settings. $block_configs[] = \Drupal\Component\Serialization\Yaml::decode(file_get_contents(__DIR__ . '/block.block.testfor2569529.yml')); foreach ($block_configs as $block_config) { $connection->insert('config') ->fields([ 'collection', 'name', 'data', ]) ->values([ 'collection' => '', 'name' => 'block.block.' . $block_config['id'], 'data' => serialize($block_config), ]) ->execute(); } // Update the config entity query "index". $existing_blocks = $connection->select('key_value') ->fields('key_value', ['value']) ->condition('collection', 'config.entity.key_store.block') ->condition('name', 'theme:seven') ->execute() ->fetchField(); $existing_blocks = unserialize($existing_blocks); $connection->update('key_value') ->fields([ 'value' => serialize(array_merge($existing_blocks, ['block.block.seven_secondary_local_tasks'])) ]) ->condition('collection', 'config.entity.key_store.block') ->condition('name', 'theme:seven') ->execute();
nrackleff/capstone
web/core/modules/system/tests/fixtures/update/drupal-8.seven-secondary-local-tasks-block-2569529.php
PHP
gpl-2.0
1,321
module GitStyleBinary module Commands class Help # not loving this syntax, but works for now GitStyleBinary.command do short_desc "get help for a specific command" run do |command| # this is slightly ugly b/c it has to muck around in the internals to # get information about commands other than itself. This isn't a # typical case self.class.send :define_method, :educate_about_command do |name| load_all_commands if GitStyleBinary.known_commands.has_key?(name) cmd = GitStyleBinary.known_commands[name] cmd.process_parser! cmd.parser.educate else puts "Unknown command '#{name}'" end end if command.argv.size > 0 command.argv.first == "help" ? educate : educate_about_command(command.argv.first) else educate end end end end end end
tyok/dotfiles
bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/commands/help.rb
Ruby
bsd-2-clause
998
var baseIndexOf = require('./_baseIndexOf'), toInteger = require('./toInteger'); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } module.exports = indexOf;
ElvisLouis/code
work/project/Edison/elvis/work/js/node_modules/async/node_modules/lodash/indexOf.js
JavaScript
gpl-2.0
1,232
<?php /** * @file * Contains \Drupal\views\Plugin\views\sort\Broken. */ namespace Drupal\views\Plugin\views\sort; use Drupal\views\Plugin\views\BrokenHandlerTrait; /** * A special handler to take the place of missing or broken handlers. * * @ingroup views_sort_handlers * * @ViewsSort("broken") */ class Broken extends SortPluginBase { use BrokenHandlerTrait; }
komejo/d8demo-dev
web/core/modules/views/src/Plugin/views/sort/Broken.php
PHP
mit
378
(function(){ if ( (typeof self === 'undefined' || !self.Prism) && (typeof global === 'undefined' || !global.Prism) ) { return; } var options = { classMap: {} }; Prism.plugins.customClass = { map: function map(cm) { options.classMap = cm; }, prefix: function prefix(string) { options.prefixString = string; } } Prism.hooks.add('wrap', function (env) { if (!options.classMap && !options.prefixString) { return; } env.classes = env.classes.map(function(c) { return (options.prefixString || '') + (options.classMap[c] || c); }); }); })();
ihmcrobotics/ihmc-realtime
websitedocs/website/node_modules/prismjs/plugins/custom-class/prism-custom-class.js
JavaScript
apache-2.0
559
// PR c++/28385 // instantiating op() with void()() was making the compiler think that 'fcn' // was const, so it could eliminate the call. // { dg-do run } extern "C" void abort (void); int barcnt = 0; class Foo { public: template<typename T> void operator()(const T& fcn) { fcn(); } }; void bar() { barcnt++; } int main() { Foo myFoo; myFoo(bar); myFoo(&bar); if (barcnt != 2) abort (); return 0; }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.dg/template/const1.C
C++
gpl-2.0
442
// +build go1.6,!go1.7 /* * Copyright 2016, 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. * */ package transport import ( "net" "golang.org/x/net/context" ) // dialContext connects to the address on the named network. func dialContext(ctx context.Context, network, address string) (net.Conn, error) { return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) }
ae6rt/decap
web/vendor/google.golang.org/grpc/transport/go16.go
GO
mit
1,869
// { dg-require-namedlocale "ja_JP.eucjp" } // { dg-require-namedlocale "de_DE" } // { dg-require-namedlocale "en_HK" } // 2001-08-15 Benjamin Kosnik <bkoz@redhat.com> // Copyright (C) 2001, 2002, 2003, 2005, 2009 Free Software Foundation // // 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. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 22.2.4.1.1 collate members #include <testsuite_hooks.h> #define main discard_main_1 #include "1.cc" #undef main #define main discard_main_2 #include "2.cc" #undef main #define main discard_main_3 #include "3.cc" #undef main int main() { using namespace __gnu_test; func_callback two; two.push_back(&test01); two.push_back(&test02); two.push_back(&test03); run_tests_wrapped_locale("ja_JP.eucjp", two); return 0; }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/libstdc++-v3/testsuite/22_locale/time_get/get_weekday/char/wrapped_locale.cc
C++
gpl-2.0
1,387
package httputils import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" ) func TestDownload(t *testing.T) { expected := "Hello, docker !" ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, expected) })) defer ts.Close() response, err := Download(ts.URL) if err != nil { t.Fatal(err) } actual, err := ioutil.ReadAll(response.Body) response.Body.Close() if err != nil || string(actual) != expected { t.Fatalf("Expected the response %q, got err:%v, response:%v, actual:%s", expected, err, response, string(actual)) } } func TestDownload400Errors(t *testing.T) { expectedError := "Got HTTP status code >= 400: 403 Forbidden" ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 403 http.Error(w, "something failed (forbidden)", http.StatusForbidden) })) defer ts.Close() // Expected status code = 403 if _, err := Download(ts.URL); err == nil || err.Error() != expectedError { t.Fatalf("Expected the the error %q, got %v", expectedError, err) } } func TestDownloadOtherErrors(t *testing.T) { if _, err := Download("I'm not an url.."); err == nil || !strings.Contains(err.Error(), "unsupported protocol scheme") { t.Fatalf("Expected an error with 'unsupported protocol scheme', got %v", err) } } func TestNewHTTPRequestError(t *testing.T) { errorMessage := "Some error message" ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 403 http.Error(w, errorMessage, http.StatusForbidden) })) defer ts.Close() httpResponse, err := http.Get(ts.URL) if err != nil { t.Fatal(err) } if err := NewHTTPRequestError(errorMessage, httpResponse); err.Error() != errorMessage { t.Fatalf("Expected err to be %q, got %v", errorMessage, err) } } func TestParseServerHeader(t *testing.T) { inputs := map[string][]string{ "bad header": {"error"}, "(bad header)": {"error"}, "(without/spaces)": {"error"}, "(header/with spaces)": {"error"}, "foo/bar (baz)": {"foo", "bar", "baz"}, "foo/bar": {"error"}, "foo": {"error"}, "foo/bar (baz space)": {"foo", "bar", "baz space"}, " f f / b b ( b s ) ": {"f f", "b b", "b s"}, "foo/bar (baz) ignore": {"foo", "bar", "baz"}, "foo/bar ()": {"error"}, "foo/bar()": {"error"}, "foo/bar(baz)": {"foo", "bar", "baz"}, "foo/bar/zzz(baz)": {"foo/bar", "zzz", "baz"}, "foo/bar(baz/abc)": {"foo", "bar", "baz/abc"}, "foo/bar(baz (abc))": {"foo", "bar", "baz (abc)"}, } for header, values := range inputs { serverHeader, err := ParseServerHeader(header) if err != nil { if err != errInvalidHeader { t.Fatalf("Failed to parse %q, and got some unexpected error: %q", header, err) } if values[0] == "error" { continue } t.Fatalf("Header %q failed to parse when it shouldn't have", header) } if values[0] == "error" { t.Fatalf("Header %q parsed ok when it should have failed(%q).", header, serverHeader) } if serverHeader.App != values[0] { t.Fatalf("Expected serverHeader.App for %q to equal %q, got %q", header, values[0], serverHeader.App) } if serverHeader.Ver != values[1] { t.Fatalf("Expected serverHeader.Ver for %q to equal %q, got %q", header, values[1], serverHeader.Ver) } if serverHeader.OS != values[2] { t.Fatalf("Expected serverHeader.OS for %q to equal %q, got %q", header, values[2], serverHeader.OS) } } }
nalind/graphc
vendor/src/github.com/docker/docker/pkg/httputils/httputils_test.go
GO
apache-2.0
3,629
/* * Copyright 2012-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.testng.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class HelloWorldService { @Value("${name:World}") private String name; public String getHelloMessage() { return "Hello " + this.name; } }
rokn/Count_Words_2015
testing/spring-boot-master/spring-boot-samples/spring-boot-sample-testng/src/main/java/sample/testng/service/HelloWorldService.java
Java
mit
928
<?php namespace Codeception\Exception; class ExtensionException extends \Exception { public function __construct($extension, $message, \Exception $previous = null) { parent::__construct($message, $previous); if (is_object($extension)) { $extension = get_class($extension); } $this->message = $extension . "\n\n" . $this->message; } }
yeqingwen/Yii2_PHP7_Redis
yii2/vendor/codeception/base/src/Codeception/Exception/ExtensionException.php
PHP
apache-2.0
391
/* YUI 3.17.1 (build 0eb5a52) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {EventHandle} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {EventHandle} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {EventHandle} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor === DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor === DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} defaults configuration object. * @class CustomEvent * @constructor */ /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ Y.CustomEvent = function(type, defaults) { this._kds = Y.CustomEvent.keepDeprecatedSubs; this.id = Y.guid(); this.type = type; this.silent = this.logSystem = (type === YUI_LOG); if (this._kds) { /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ /** * 'After' subscribers * @property afters * @type Subscriber {} * @deprecated */ this.subscribers = {}; this.afters = {}; } if (defaults) { mixConfigs(this, defaults, true); } }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ /** * This event has fired if true * * @property fired * @type boolean * @default false; */ /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ /** * Flag for the default function to execute only if the * firing event is the current target. This happens only * when using custom event delegation and setting the * flag to `true` mimics the behavior of event delegation * in the DOM. * * @property defaultTargetOnly * @type Boolean * @default false */ /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ signature : YUI3_SIGNATURE, /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ context : Y, /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ preventable : true, /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ bubbles : true, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = 0, a = 0, subs = this._subscribers, afters = this._afters, sib = this.sibling; if (subs) { s = subs.length; } if (afters) { a = afters.length; } if (sib) { subs = sib._subscribers; afters = sib._afters; if (subs) { s += subs.length; } if (afters) { a += afters.length; } } if (when) { return (when === 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var sibling = this.sibling, subs = this._subscribers, afters = this._afters, siblingSubs, siblingAfters; if (sibling) { siblingSubs = sibling._subscribers; siblingAfters = sibling._afters; } if (siblingSubs) { if (subs) { subs = subs.concat(siblingSubs); } else { subs = siblingSubs.concat(); } } else { if (subs) { subs = subs.concat(); } else { subs = []; } } if (siblingAfters) { if (afters) { afters = afters.concat(siblingAfters); } else { afters = siblingAfters.concat(); } } else { if (afters) { afters = afters.concat(); } else { afters = []; } } return [subs, afters]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when), firedWith; if (this.fireOnce && this.fired) { firedWith = this.firedWith; // It's a little ugly for this to know about facades, // but given the current breakup, not much choice without // moving a whole lot of stuff around. if (this.emitFacade && this._addFacadeToArgs) { this._addFacadeToArgs(firedWith); } if (this.async) { setTimeout(Y.bind(this._notify, this, s, firedWith), 0); } else { this._notify(s, firedWith); } } if (when === AFTER) { if (!this._afters) { this._afters = []; } this._afters.push(s); } else { if (!this._subscribers) { this._subscribers = []; } this._subscribers.push(s); } if (this._kds) { if (when === AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {Number} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; if (subs) { for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } } if (afters) { for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { // push is the fastest way to go from arguments to arrays // for most browsers currently // http://jsperf.com/push-vs-concat-vs-slice/2 var args = []; args.push.apply(args, arguments); return this._fire(args); }, /** * Private internal implementation for `fire`, which is can be used directly by * `EventTarget` and other event module classes which have already converted from * an `arguments` list to an array, to avoid the repeated overhead. * * @method _fire * @private * @param {Array} args The array of arguments passed to be passed to handlers. * @return {boolean} false if one of the subscribers returned false, true otherwise. */ _fire: function(args) { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } if (this.broadcast) { this._broadcast(args); } return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped === 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast === 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {Number} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {Number} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; } if (subs) { i = YArray.indexOf(subs, s, 0); if (s && subs[i] === s) { subs.splice(i, 1); } } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.guid(); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn === fn) && this.context === context); } else { return (this.fn === fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {Number} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = function(type, pre) { if (!pre || !type || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }, /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t === '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var etState = this._yuievt, etConfig; if (!etState) { etState = this._yuievt = { events: {}, // PERF: Not much point instantiating lazily. We're bound to have events targets: null, // PERF: Instantiate lazily, if user actually adds target, config: { host: this, context: this }, chain: Y.config.chain }; } etConfig = etState.config; if (opts) { mixConfigs(etConfig, opts, true); if (opts.chain !== undefined) { etState.chain = opts.chain; } if (opts.prefix) { etConfig.prefix = opts.prefix; } } }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre] The prefix. Defaults to this._yuievt.config.prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); // TODO: More robust regex, accounting for category if (type.indexOf("*:") !== -1) { this._hasSiblings = true; } } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var ret, etState = this._yuievt, etConfig = etState.config, pre = etConfig.prefix; if (typeof type === "string") { if (pre) { type = _getType(type, pre); } ret = this._publish(type, etConfig, opts); } else { ret = {}; Y.each(type, function(v, k) { if (pre) { k = _getType(k, pre); } ret[k] = this._publish(k, etConfig, v || opts); }, this); } return ret; }, /** * Returns the fully qualified type, given a short type string. * That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix. * * NOTE: This method, unlike _getType, does no checking of the value passed in, and * is designed to be used with the low level _publish() method, for critical path * implementations which need to fast-track publish for performance reasons. * * @method _getFullType * @private * @param {String} type The short type to prefix * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in */ _getFullType : function(type) { var pre = this._yuievt.config.prefix; if (pre) { return pre + PREFIX_DELIMITER + type; } else { return type; } }, /** * The low level event publish implementation. It expects all the massaging to have been done * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast * path publish, which can be used by critical code paths to improve performance. * * @method _publish * @private * @param {String} fullType The prefixed type of the event to publish. * @param {Object} etOpts The EventTarget specific configuration to mix into the published event. * @param {Object} ceOpts The publish specific configuration to mix into the published event. * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will * be the default `CustomEvent` instance, and can be configured independently. */ _publish : function(fullType, etOpts, ceOpts) { var ce, etState = this._yuievt, etConfig = etState.config, host = etConfig.host, context = etConfig.context, events = etState.events; ce = events[fullType]; // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight. if ((etConfig.monitored && !ce) || (ce && ce.monitored)) { this._monitor('publish', fullType, { args: arguments }); } if (!ce) { // Publish event ce = events[fullType] = new Y.CustomEvent(fullType, etOpts); if (!etOpts) { ce.host = host; ce.context = context; } } if (ceOpts) { mixConfigs(ce, ceOpts, true); } return ce; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {Boolean} True if the whole lifecycle of the event went through, * false if at any point the event propagation was halted. */ fire: function(type) { var typeIncluded = (typeof type === "string"), argCount = arguments.length, t = type, yuievt = this._yuievt, etConfig = yuievt.config, pre = etConfig.prefix, ret, ce, ce2, args; if (typeIncluded && argCount <= 3) { // PERF: Try to avoid slice/iteration for the common signatures // Most common if (argCount === 2) { args = [arguments[1]]; // fire("foo", {}) } else if (argCount === 3) { args = [arguments[1], arguments[2]]; // fire("foo", {}, opts) } else { args = []; // fire("foo") } } else { args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0)); } if (!typeIncluded) { t = (type && type.type); } if (pre) { t = _getType(t, pre); } ce = yuievt.events[t]; if (this._hasSiblings) { ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } } // PERF: trying to avoid function call, since this is a critical path if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { this._monitor('fire', (ce || t), { args: args }); } // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { if (ce2) { ce.sibling = ce2; } ret = ce._fire(args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); ce2 = this.getEvent(type, true); if (ce2) { ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '3.17.1', {"requires": ["oop"]});
extend1994/cdnjs
ajax/libs/yui/3.17.1/event-custom-base/event-custom-base-debug.js
JavaScript
mit
75,885
<?php namespace Drupal\Tests\serialization\Kernel; use Drupal\Core\Url; use Drupal\entity_test\Entity\EntityTestMulRev; use Drupal\field\Entity\FieldConfig; use Drupal\field\Entity\FieldStorageConfig; /** * Tests that entities references can be resolved. * * @group serialization */ class EntityResolverTest extends NormalizerTestBase { /** * Modules to enable. * * @var array */ public static $modules = ['hal', 'rest']; /** * The format being tested. * * @var string */ protected $format = 'hal_json'; protected function setUp() { parent::setUp(); \Drupal::service('router.builder')->rebuild(); // Create the test field storage. FieldStorageConfig::create([ 'entity_type' => 'entity_test_mulrev', 'field_name' => 'field_test_entity_reference', 'type' => 'entity_reference', 'settings' => [ 'target_type' => 'entity_test_mulrev', ], ])->save(); // Create the test field. FieldConfig::create([ 'entity_type' => 'entity_test_mulrev', 'field_name' => 'field_test_entity_reference', 'bundle' => 'entity_test_mulrev', ])->save(); } /** * Test that fields referencing UUIDs can be denormalized. */ public function testUuidEntityResolver() { // Create an entity to get the UUID from. $entity = EntityTestMulRev::create(['type' => 'entity_test_mulrev']); $entity->set('name', 'foobar'); $entity->set('field_test_entity_reference', [['target_id' => 1]]); $entity->save(); $field_uri = Url::fromUri('base:rest/relation/entity_test_mulrev/entity_test_mulrev/field_test_entity_reference', ['absolute' => TRUE])->toString(); $data = [ '_links' => [ 'type' => [ 'href' => Url::fromUri('base:rest/type/entity_test_mulrev/entity_test_mulrev', ['absolute' => TRUE])->toString(), ], $field_uri => [ [ 'href' => $entity->url(), ], ], ], '_embedded' => [ $field_uri => [ [ '_links' => [ 'self' => $entity->url(), ], 'uuid' => [ [ 'value' => $entity->uuid(), ], ], ], ], ], ]; $denormalized = $this->container->get('serializer')->denormalize($data, 'Drupal\entity_test\Entity\EntityTestMulRev', $this->format); $field_value = $denormalized->get('field_test_entity_reference')->getValue(); $this->assertEqual($field_value[0]['target_id'], 1, 'Entity reference resolved using UUID.'); } }
sunlight25/d8
web/core/modules/serialization/tests/src/Kernel/EntityResolverTest.php
PHP
gpl-2.0
2,605
class Axel < Formula desc "Light UNIX download accelerator" homepage "https://packages.debian.org/sid/axel" url "https://mirrors.kernel.org/debian/pool/main/a/axel/axel_2.4.orig.tar.gz" mirror "http://ftp.de.debian.org/debian/pool/main/a/axel/axel_2.4.orig.tar.gz" sha256 "359a57ab4e354bcb6075430d977c59d33eb3e2f1415a811948fa8ae657ca8036" bottle do sha1 "419b8e2f1f17909363fb48307eb74f9672ceb25e" => :yosemite sha1 "0307ac6796e0b7e5fafac6c6085d0ba5230e50e5" => :mavericks sha1 "22c1e32858c443a04eaec96617773e99e036bf0b" => :mountain_lion end def install system "./configure", "--prefix=#{prefix}", "--debug=0", "--i18n=0" system "make" system "make", "install" end test do filename = (testpath/"axel.tar.gz") system bin/"axel", "-o", "axel.tar.gz", stable.url filename.verify_checksum stable.checksum assert File.exist?("axel.tar.gz") end end
petemcw/homebrew
Library/Formula/axel.rb
Ruby
bsd-2-clause
908
/** * Copyright 2011 Rackspace * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ var sprintf = require('./sprintf').sprintf; var utils = require('./utils'); var SyntaxError = require('./errors').SyntaxError; var _cache = {}; var RE = new RegExp( "(" + "'[^']*'|\"[^\"]*\"|" + "::|" + "//?|" + "\\.\\.|" + "\\(\\)|" + "[/.*:\\[\\]\\(\\)@=])|" + "((?:\\{[^}]+\\})?[^/\\[\\]\\(\\)@=\\s]+)|" + "\\s+", 'g' ); var xpath_tokenizer = utils.findall.bind(null, RE); function prepare_tag(next, token) { var tag = token[0]; function select(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; elem._children.forEach(function(e) { if (e.tag === tag) { rv.push(e); } }); } return rv; } return select; } function prepare_star(next, token) { function select(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; elem._children.forEach(function(e) { rv.push(e); }); } return rv; } return select; } function prepare_dot(next, token) { function select(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; rv.push(elem); } return rv; } return select; } function prepare_iter(next, token) { var tag; token = next(); if (token[1] === '*') { tag = '*'; } else if (!token[1]) { tag = token[0] || ''; } else { throw new SyntaxError(token); } function select(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; elem.iter(tag, function(e) { if (e !== elem) { rv.push(e); } }); } return rv; } return select; } function prepare_dot_dot(next, token) { function select(context, result) { var i, len, elem, rv = [], parent_map = context.parent_map; if (!parent_map) { context.parent_map = parent_map = {}; context.root.iter(null, function(p) { p._children.forEach(function(e) { parent_map[e] = p; }); }); } for (i = 0, len = result.length; i < len; i++) { elem = result[i]; if (parent_map.hasOwnProperty(elem)) { rv.push(parent_map[elem]); } } return rv; } return select; } function prepare_predicate(next, token) { var tag, key, value, select; token = next(); if (token[1] === '@') { // attribute token = next(); if (token[1]) { throw new SyntaxError(token, 'Invalid attribute predicate'); } key = token[0]; token = next(); if (token[1] === ']') { select = function(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; if (elem.get(key)) { rv.push(elem); } } return rv; }; } else if (token[1] === '=') { value = next()[1]; if (value[0] === '"' || value[value.length - 1] === '\'') { value = value.slice(1, value.length - 1); } else { throw new SyntaxError(token, 'Ivalid comparison target'); } token = next(); select = function(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; if (elem.get(key) === value) { rv.push(elem); } } return rv; }; } if (token[1] !== ']') { throw new SyntaxError(token, 'Invalid attribute predicate'); } } else if (!token[1]) { tag = token[0] || ''; token = next(); if (token[1] !== ']') { throw new SyntaxError(token, 'Invalid node predicate'); } select = function(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; if (elem.find(tag)) { rv.push(elem); } } return rv; }; } else { throw new SyntaxError(null, 'Invalid predicate'); } return select; } var ops = { "": prepare_tag, "*": prepare_star, ".": prepare_dot, "..": prepare_dot_dot, "//": prepare_iter, "[": prepare_predicate, }; function _SelectorContext(root) { this.parent_map = null; this.root = root; } function findall(elem, path) { var selector, result, i, len, token, value, select, context; if (_cache.hasOwnProperty(path)) { selector = _cache[path]; } else { // TODO: Use smarter cache purging approach if (Object.keys(_cache).length > 100) { _cache = {}; } if (path.charAt(0) === '/') { throw new SyntaxError(null, 'Cannot use absolute path on element'); } result = xpath_tokenizer(path); selector = []; function getToken() { return result.shift(); } token = getToken(); while (true) { var c = token[1] || ''; value = ops[c](getToken, token); if (!value) { throw new SyntaxError(null, sprintf('Invalid path: %s', path)); } selector.push(value); token = getToken(); if (!token) { break; } else if (token[1] === '/') { token = getToken(); } if (!token) { break; } } _cache[path] = selector; } // Execute slector pattern result = [elem]; context = new _SelectorContext(elem); for (i = 0, len = selector.length; i < len; i++) { select = selector[i]; result = select(context, result); } return result || []; } function find(element, path) { var resultElements = findall(element, path); if (resultElements && resultElements.length > 0) { return resultElements[0]; } return null; } function findtext(element, path, defvalue) { var resultElements = findall(element, path); if (resultElements && resultElements.length > 0) { return resultElements[0].text; } return defvalue; } exports.find = find; exports.findall = findall; exports.findtext = findtext;
zendey/Zendey
zendey/platforms/android/cordova/node_modules/elementtree/lib/elementpath.js
JavaScript
gpl-3.0
6,742
var now = require('../time/now') var timeout = require('./timeout') var append = require('../array/append') // ensure a minimum delay for callbacks function awaitDelay (fn, delay) { var baseTime = now() + delay return function () { // ensure all browsers will execute it asynchronously (avoid hard // to catch errors) not using "0" because of old browsers and also // since new browsers increase the value to be at least "4" // http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout var ms = Math.max(baseTime - now(), 4) return timeout.apply(this, append([fn, ms, this], arguments)) } } module.exports = awaitDelay
akileez/toolz
src/function/awaitDelay.js
JavaScript
isc
694
import chai from 'chai'; import cas from 'chai-as-promised'; chai.use(cas); export default { expect: chai.expect };
romeovs/all
test/instrument.js
JavaScript
isc
121
export type StyleToHexColor = Readonly<Record<string, string>>; export const styleToHexColor: StyleToHexColor = { orange: 'ff5f00', grayLight: '808080', 'gray-light': '808080', };
christophehurpeau/nightingale
packages/nightingale-formatter/src/styleToHexColor.ts
TypeScript
isc
187
'use strict'; var test = require('tap').test, _ = require('lodash'), parse = require('../../../lib/parsers/javascript'), inferMembership = require('../../../lib/infer/membership')(); function toComment(fn, file) { return parse({ file: file, source: fn instanceof Function ? '(' + fn.toString() + ')' : fn }); } function evaluate(fn, file) { return toComment(fn, file).map(inferMembership); } function Foo() {} function lend() {} test('inferMembership - explicit', function (t) { t.deepEqual(_.pick(evaluate(function () { /** * Test * @memberof Bar * @static */ Foo.bar = 0; })[0], ['memberof', 'scope']), { memberof: 'Bar', scope: 'static' }, 'explicit'); t.deepEqual(_.pick(evaluate(function () { /** Test */ Foo.bar = 0; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'implicit'); t.deepEqual(_.pick(evaluate(function () { /** Test */ Foo.prototype.bar = 0; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }, 'instance'); t.deepEqual(_.pick(evaluate(function () { /** Test */ Foo.bar.baz = 0; })[0], ['memberof', 'scope']), { memberof: 'Foo.bar', scope: 'static' }, 'compound'); t.deepEqual(_.pick(evaluate(function () { /** Test */ (0).baz = 0; })[0], ['memberof', 'scope']), { }, 'unknown'); t.deepEqual(_.pick(evaluate(function () { Foo.bar = { /** Test */ baz: 0 }; })[0], ['memberof', 'scope']), { memberof: 'Foo.bar', scope: 'static' }, 'static object assignment'); t.deepEqual(_.pick(evaluate(function () { Foo.prototype = { /** Test */ bar: 0 }; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }, 'instance object assignment'); t.deepEqual(_.pick(evaluate(function () { Foo.prototype = { /** * Test */ bar: function () {} }; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }, 'instance object assignment, function'); t.deepEqual(_.pick(evaluate(function () { var Foo = { /** Test */ baz: 0 }; return Foo; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'variable object assignment'); t.deepEqual(_.pick(evaluate(function () { var Foo = { /** Test */ baz: function () {} }; return Foo; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'variable object assignment, function'); t.deepEqual(_.pick(evaluate(function () { /** Test */ module.exports = function () {}; })[0], ['memberof', 'scope']), { memberof: 'module', scope: 'static' }, 'simple'); t.deepEqual(_.pick(evaluate(function () { lend(/** @lends Foo */{ /** Test */ bar: 0 }); })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'lends, static'); t.deepEqual(_.pick(evaluate(function () { lend(/** @lends Foo */{ /** Test */ bar: function () {} }); })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'inferMembership - lends, static, function'); t.deepEqual(_.pick(evaluate(function () { lend(/** @lends Foo.prototype */{ /** Test */ bar: 0 }); })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }); t.deepEqual(_.pick(evaluate(function () { lend(/** @lends Foo.prototype */{ /** Test */ bar: function () {} }); })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }, 'inferMembership - lends, instance, function'); t.deepEqual(_.pick(evaluate(function () { /** Foo */ function Foo() { /** Test */ function bar() {} return { bar: bar }; } })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'inferMembership - revealing, static, function'); t.equal(evaluate(function () { lend(/** @lends Foo */{}); /** Test */ })[1].memberof, undefined, 'inferMembership - lends applies only to following object'); t.equal(evaluate(function () { lend(/** @lends Foo */{}); })[0], undefined, 'inferMembership - drops lends'); t.end(); }); test('inferMembership - exports', function (t) { t.equal(evaluate(function () { /** @module mod */ /** foo */ exports.foo = 1; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ /** foo */ exports.foo = function () {}; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ /** bar */ exports.foo.bar = 1; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ exports.foo = { /** bar */ bar: 1 }; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ exports.foo = { /** bar */ bar: function () {} }; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ /** bar */ exports.foo.prototype.bar = function () {}; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ exports.foo.prototype = { /** bar */ bar: function () {} }; })[1].memberof, 'mod.foo'); t.end(); }); test('inferMembership - module.exports', function (t) { t.equal(evaluate(function () { /** @module mod */ /** foo */ module.exports.foo = 1; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ /** foo */ module.exports.foo = function () {}; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ /** bar */ module.exports.foo.bar = 1; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ module.exports.foo = { /** bar */ bar: 1 }; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ module.exports.foo = { /** bar */ bar: function () {} }; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ /** bar */ module.exports.prototype.bar = function () {}; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ module.exports.prototype = { /** bar */ bar: function () {} }; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** * @module mod * @name exports */ module.exports = 1; })[0].memberof, undefined); t.equal(evaluate(function () { /** * @module mod * @name exports */ module.exports = function () {}; })[0].memberof, undefined); t.equal(evaluate(function () { /** @module mod */ module.exports = { /** foo */ foo: 1 }; })[1].memberof, 'mod'); t.end(); }); test('inferMembership - not module exports', function (t) { var result = evaluate(function () { /** * @module mod */ /** Test */ global.module.exports.foo = 1; }, '/path/mod.js'); t.equal(result.length, 2); t.notEqual(result[0].memberof, 'mod'); t.end(); }); test('inferMembership - anonymous @module', function (t) { var result = evaluate(function () { /** * @module */ /** Test */ exports.foo = 1; }, '/path/mod.js'); t.equal(result.length, 2); t.equal(result[1].memberof, 'mod'); t.end(); }); test('inferMembership - no @module', function (t) { var result = evaluate(function () { /** Test */ exports.foo = 1; }, '/path/mod.js'); t.equal(result.length, 1); t.equal(result[0].memberof, 'mod'); t.end(); });
researchgate/documentation
test/lib/infer/membership.js
JavaScript
isc
7,692
'use strict' const t = require('tap') const Parse = require('../lib/parse.js') const makeTar = require('./make-tar.js') const fs = require('fs') const path = require('path') const tardir = path.resolve(__dirname, 'fixtures/tars') const zlib = require('zlib') const MiniPass = require('minipass') const Header = require('../lib/header.js') const EE = require('events').EventEmitter t.test('fixture tests', t => { class ByteStream extends MiniPass { write (chunk) { for (let i = 0; i < chunk.length - 1; i++) super.write(chunk.slice(i, i + 1)) return super.write(chunk.slice(chunk.length - 1, chunk.length)) } } const trackEvents = (t, expect, p, slow) => { let ok = true let cursor = 0 p.on('entry', entry => { ok = ok && t.match(['entry', entry], expect[cursor++], entry.path) if (slow) setTimeout(_ => entry.resume()) else entry.resume() }) p.on('ignoredEntry', entry => { ok = ok && t.match(['ignoredEntry', entry], expect[cursor++], 'ignored: ' + entry.path) }) p.on('warn', (c, message, data) => { ok = ok && t.match(['warn', c, message], expect[cursor++], 'warn') }) p.on('nullBlock', _ => { ok = ok && t.match(['nullBlock'], expect[cursor++], 'null') }) p.on('error', er => { ok = ok && t.match(['error', er], expect[cursor++], 'error') }) p.on('meta', meta => { ok = ok && t.match(['meta', meta], expect[cursor++], 'meta') }) p.on('eof', _ => { ok = ok && t.match(['eof'], expect[cursor++], 'eof') }) p.on('end', _ => { ok = ok && t.match(['end'], expect[cursor++], 'end') t.end() }) } t.jobs = 4 const path = require('path') const parsedir = path.resolve(__dirname, 'fixtures/parse') const files = fs.readdirSync(tardir) const maxMetaOpt = [250, null] const filterOpt = [true, false] const strictOpt = [true, false] const runTest = (file, maxMeta, filter, strict) => { const tardata = fs.readFileSync(file) const base = path.basename(file, '.tar') t.test('file=' + base + '.tar' + ' maxmeta=' + maxMeta + ' filter=' + filter + ' strict=' + strict, t => { const o = (maxMeta ? '-meta-' + maxMeta : '') + (filter ? '-filter' : '') + (strict ? '-strict' : '') const tail = (o ? '-' + o : '') + '.json' const eventsFile = parsedir + '/' + base + tail const expect = require(eventsFile) t.test('one byte at a time', t => { const bs = new ByteStream() const opt = (maxMeta || filter || strict) ? { maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, } : null const bp = new Parse(opt) trackEvents(t, expect, bp) bs.pipe(bp) bs.end(tardata) }) t.test('all at once', t => { const p = new Parse({ maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, }) trackEvents(t, expect, p) p.end(tardata) }) t.test('gzipped all at once', t => { const p = new Parse({ maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, }) trackEvents(t, expect, p) p.end(zlib.gzipSync(tardata)) }) t.test('gzipped byte at a time', t => { const bs = new ByteStream() const bp = new Parse({ maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, }) trackEvents(t, expect, bp) bs.pipe(bp) bs.end(zlib.gzipSync(tardata)) }) t.test('async chunks', t => { const p = new Parse({ maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, }) trackEvents(t, expect, p, true) p.write(tardata.slice(0, Math.floor(tardata.length / 2))) process.nextTick(_ => p.end(tardata.slice(Math.floor(tardata.length / 2)))) }) t.end() }) } files .map(f => path.resolve(tardir, f)).forEach(file => maxMetaOpt.forEach(maxMeta => strictOpt.forEach(strict => filterOpt.forEach(filter => runTest(file, maxMeta, filter, strict))))) t.end() }) t.test('strict warn with an error emits that error', t => { t.plan(1) const p = new Parse({ strict: true, }) p.on('error', emitted => t.equal(emitted, er)) const er = new Error('yolo') p.warn('TAR_TEST', er) }) t.test('onwarn gets added to the warn event', t => { t.plan(1) const p = new Parse({ onwarn (code, message) { t.equal(message, 'this is fine') }, }) p.warn('TAR_TEST', 'this is fine') }) t.test('onentry gets added to entry event', t => { t.plan(1) const p = new Parse({ onentry: entry => t.equal(entry, 'yes hello this is dog'), }) p.emit('entry', 'yes hello this is dog') }) t.test('drain event timings', t => { let sawOndone = false const ondone = function () { sawOndone = true this.emit('prefinish') this.emit('finish') this.emit('end') this.emit('close') } // write 1 header and body, write 2 header, verify false return // wait for drain event before continuing. // write 2 body, 3 header and body, 4 header, verify false return // wait for drain event // write 4 body and null blocks const data = [ [ { path: 'one', size: 513, type: 'File', }, new Array(513).join('1'), '1', { path: 'two', size: 513, type: 'File', }, new Array(513).join('2'), '2', { path: 'three', size: 1024, type: 'File', }, ], [ new Array(513).join('3'), new Array(513).join('3'), { path: 'four', size: 513, type: 'File', }, ], [ new Array(513).join('4'), '4', { path: 'five', size: 1024, type: 'File', }, new Array(513).join('5'), new Array(513).join('5'), { path: 'six', size: 1024, type: 'File', }, new Array(513).join('6'), new Array(513).join('6'), { path: 'seven', size: 1024, type: 'File', }, new Array(513).join('7'), new Array(513).join('7'), { path: 'eight', size: 1024, type: 'File', }, new Array(513).join('8'), new Array(513).join('8'), { path: 'four', size: 513, type: 'File', }, new Array(513).join('4'), '4', { path: 'five', size: 1024, type: 'File', }, new Array(513).join('5'), new Array(513).join('5'), { path: 'six', size: 1024, type: 'File', }, new Array(513).join('6'), new Array(513).join('6'), { path: 'seven', size: 1024, type: 'File', }, new Array(513).join('7'), new Array(513).join('7'), { path: 'eight', size: 1024, type: 'File', }, new Array(513).join('8'), ], [ new Array(513).join('8'), { path: 'nine', size: 1537, type: 'File', }, new Array(513).join('9'), ], [new Array(513).join('9')], [new Array(513).join('9')], ['9'], ].map(chunks => makeTar(chunks)) const expect = [ 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'four', 'five', 'six', 'seven', 'eight', 'nine', ] class SlowStream extends EE { write () { setTimeout(_ => this.emit('drain')) return false } end () { return this.write() } } let currentEntry const autoPipe = true const p = new Parse({ ondone, onentry: entry => { t.equal(entry.path, expect.shift()) currentEntry = entry if (autoPipe) setTimeout(_ => entry.pipe(new SlowStream())) }, }) data.forEach(d => { if (!t.equal(p.write(d), false, 'write should return false')) return t.end() }) let interval const go = _ => { const d = data.shift() if (d === undefined) return p.end() let paused if (currentEntry) { currentEntry.pause() paused = true } const hunklen = Math.floor(d.length / 2) const hunks = [ d.slice(0, hunklen), d.slice(hunklen), ] p.write(hunks[0]) if (currentEntry && !paused) { console.error('has current entry') currentEntry.pause() paused = true } if (!t.equal(p.write(hunks[1]), false, 'write should return false: ' + d)) return t.end() p.once('drain', go) if (paused) currentEntry.resume() } p.once('drain', go) p.on('end', _ => { clearInterval(interval) t.ok(sawOndone) t.end() }) go() }) t.test('consume while consuming', t => { const data = makeTar([ { path: 'one', size: 0, type: 'File', }, { path: 'zero', size: 0, type: 'File', }, { path: 'two', size: 513, type: 'File', }, new Array(513).join('2'), '2', { path: 'three', size: 1024, type: 'File', }, new Array(513).join('3'), new Array(513).join('3'), { path: 'zero', size: 0, type: 'File', }, { path: 'zero', size: 0, type: 'File', }, { path: 'four', size: 1024, type: 'File', }, new Array(513).join('4'), new Array(513).join('4'), { path: 'zero', size: 0, type: 'File', }, { path: 'zero', size: 0, type: 'File', }, ]) const runTest = (t, size) => { const p = new Parse() const first = data.slice(0, size) const rest = data.slice(size) p.once('entry', entry => { for (let pos = 0; pos < rest.length; pos += size) p.write(rest.slice(pos, pos + size)) p.end() }) .on('entry', entry => entry.resume()) .on('end', _ => t.end()) .write(first) } // one that aligns, and another that doesn't, so that we // get some cases where there's leftover chunk and a buffer t.test('size=1000', t => runTest(t, 1000)) t.test('size=1024', t => runTest(t, 4096)) t.end() }) t.test('truncated input', t => { const data = makeTar([ { path: 'foo/', type: 'Directory', }, { path: 'foo/bar', type: 'File', size: 18, }, ]) t.test('truncated at block boundary', t => { const warnings = [] const p = new Parse({ onwarn: (c, message) => warnings.push(message) }) p.end(data) t.same(warnings, [ 'Truncated input (needed 512 more bytes, only 0 available)', ]) t.end() }) t.test('truncated mid-block', t => { const warnings = [] const p = new Parse({ onwarn: (c, message) => warnings.push(message) }) p.write(data) p.end(Buffer.from('not a full block')) t.same(warnings, [ 'Truncated input (needed 512 more bytes, only 16 available)', ]) t.end() }) t.end() }) t.test('truncated gzip input', t => { const raw = makeTar([ { path: 'foo/', type: 'Directory', }, { path: 'foo/bar', type: 'File', size: 18, }, new Array(19).join('x'), '', '', ]) const tgz = zlib.gzipSync(raw) const split = Math.floor(tgz.length * 2 / 3) const trunc = tgz.slice(0, split) const skipEarlyEnd = process.version.match(/^v4\./) t.test('early end', { skip: skipEarlyEnd ? 'not a zlib error on v4' : false, }, t => { const warnings = [] const p = new Parse() p.on('error', er => warnings.push(er.message)) let aborted = false p.on('abort', _ => aborted = true) p.end(trunc) t.equal(aborted, true, 'aborted writing') t.same(warnings, ['zlib: unexpected end of file']) t.end() }) t.test('just wrong', t => { const warnings = [] const p = new Parse() p.on('error', er => warnings.push(er.message)) let aborted = false p.on('abort', _ => aborted = true) p.write(trunc) p.write(trunc) p.write(tgz.slice(split)) p.end() t.equal(aborted, true, 'aborted writing') t.same(warnings, ['zlib: incorrect data check']) t.end() }) t.end() }) t.test('end while consuming', t => { // https://github.com/npm/node-tar/issues/157 const data = zlib.gzipSync(makeTar([ { path: 'package/package.json', type: 'File', size: 130, }, new Array(131).join('x'), { path: 'package/node_modules/@c/d/node_modules/e/package.json', type: 'File', size: 30, }, new Array(31).join('e'), { path: 'package/node_modules/@c/d/package.json', type: 'File', size: 33, }, new Array(34).join('d'), { path: 'package/node_modules/a/package.json', type: 'File', size: 59, }, new Array(60).join('a'), { path: 'package/node_modules/b/package.json', type: 'File', size: 30, }, new Array(31).join('b'), '', '', ])) const actual = [] const expect = [ 'package/package.json', 'package/node_modules/@c/d/node_modules/e/package.json', 'package/node_modules/@c/d/package.json', 'package/node_modules/a/package.json', 'package/node_modules/b/package.json', ] const mp = new MiniPass() const p = new Parse({ onentry: entry => { actual.push(entry.path) entry.resume() }, onwarn: (c, m, data) => t.fail(`${c}: ${m}`, data), }) p.on('end', () => { t.same(actual, expect) t.end() }) mp.end(data) mp.pipe(p) }) t.test('bad archives', t => { const p = new Parse() const warnings = [] p.on('warn', (code, msg, data) => { warnings.push([code, msg, data]) }) p.on('end', () => { // last one should be 'this archive sucks' t.match(warnings.pop(), [ 'TAR_BAD_ARCHIVE', 'Unrecognized archive format', { code: 'TAR_BAD_ARCHIVE', tarCode: 'TAR_BAD_ARCHIVE' }, ]) t.end() }) // javascript test is not a tarball. p.end(fs.readFileSync(__filename)) }) t.test('header that throws', t => { const p = new Parse() p.on('warn', (c, m, d) => { t.equal(m, 'invalid base256 encoding') t.match(d, { code: 'TAR_ENTRY_INVALID', }) t.end() }) const h = new Header({ path: 'path', mode: 0o07777, // gonna make this one invalid uid: 1234, gid: 4321, type: 'File', size: 1, }) h.encode() const buf = h.block const bad = Buffer.from([0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) bad.copy(buf, 100) t.throws(() => new Header(buf), 'the header with that buffer throws') p.write(buf) }) t.test('warnings that are not so bad', t => { const p = new Parse() const warnings = [] p.on('warn', (code, m, d) => { warnings.push([code, m, d]) t.fail('should get no warnings') }) // the parser doesn't actually decide what's "ok" or "supported", // it just parses. So we have to set it ourselves like unpack does p.once('entry', entry => entry.invalid = true) p.on('entry', entry => entry.resume()) const data = makeTar([ { path: '/a/b/c', type: 'File', size: 1, }, 'a', { path: 'a/b/c', type: 'Directory', }, '', '', ]) p.on('end', () => { t.same(warnings, []) t.end() }) p.end(data) })
npm/node-tar
test/parse.js
JavaScript
isc
15,911
// This takes in a set of pairs and writes them to the database. /*jshint node: true */ "use strict"; var csv = require('fast-csv'); var database = require('./database'); var data = csv.fromPath('team.csv', {headers : true}). on("data", function(datum) { database.writeUser({name: datum.User, location: datum.Location, active: true}); });
tahoemph/random_pairs
import_users.js
JavaScript
isc
345
import capitalize from './util/capitalize'; const unitNames = { npc_dota_roshan_spawner: 'Roshan', dota_item_rune_spawner_powerup: 'Rune', dota_item_rune_spawner_bounty: 'Bounty Rune', ent_dota_tree: 'Tree', npc_dota_healer: 'Shrine', ent_dota_fountain: 'Fountain', npc_dota_fort: 'Ancient', ent_dota_shop: 'Shop', npc_dota_tower: 'Tower', npc_dota_barracks: 'Barracks', npc_dota_filler: 'Building', npc_dota_watch_tower: 'Outpost', trigger_multiple: 'Neutral Camp Spawn Box', npc_dota_neutral_spawner: 'Neutral Camp', observer: 'Observer Ward', sentry: 'Sentry Ward', }; const getUnitName = (unitType, unitSubType) => (unitSubType ? `${capitalize(unitSubType.replace('tower', 'Tier ').replace('range', 'Ranged'))} ` : '') + unitNames[unitType]; const pullTypes = ['Normal', 'Fast', 'Slow']; const neutralTypes = ['Easy', 'Medium', 'Hard', 'Ancient']; const getPopupContent = (stats, feature) => { const dotaProps = feature.get('dotaProps'); const unitClass = dotaProps.subType ? `${dotaProps.id}_${dotaProps.subType}` : dotaProps.id; const unitStats = stats[unitClass]; let htmlContent = `<div class="info"><span class="info-header">${getUnitName(dotaProps.id, dotaProps.subType)}</span><span class="info-body">`; if (dotaProps.pullType != null) { htmlContent += `<br><span class="info-line">Pull Type: ${pullTypes[dotaProps.pullType]}</span>`; } if (dotaProps.neutralType != null) { htmlContent += `<br><span class="info-line">Difficulty: ${neutralTypes[dotaProps.neutralType]}</span>`; } if (stats && unitStats) { if (unitStats.hasOwnProperty('damageMin') && unitStats.hasOwnProperty('damageMax')) { htmlContent += `<br><span class="info-line">Damage: ${unitStats.damageMin}&ndash;${unitStats.damageMax}</span>`; } if (unitStats.hasOwnProperty('bat')) { htmlContent += `<br><span class="info-line">BAT: ${unitStats.bat}</span>`; } if (unitStats.hasOwnProperty('attackRange')) { htmlContent += `<br><span class="info-line">Attack Range: ${unitStats.attackRange}</span>`; } if (unitStats.hasOwnProperty('health')) { htmlContent += `<br><span class="info-line">Health: ${unitStats.health}</span>`; } if (unitStats.hasOwnProperty('armor')) { htmlContent += `<br><span class="info-line">Armor: ${unitStats.armor}</span>`; } if (unitStats.hasOwnProperty('dayVision') && unitStats.hasOwnProperty('nightVision')) { htmlContent += `<br><span class="info-line">Vision: ${unitStats.dayVision}/${unitStats.nightVision}</span>`; } } htmlContent += '</span></div>'; return htmlContent; }; export default getPopupContent;
devilesk/dota-interactive-map
src/js/getPopupContent.js
JavaScript
isc
2,819
package br.com.gestaoigrejas.sgi.model; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import br.com.gestaoigrejas.sgi.enums.Status; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter @Table(name = "TB_TASK") public class Task { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "task_id") private Long id; @Basic(optional = false) @Column(name = "name", unique = false, length = 255) private String name; @Basic(optional = false) @Column(name = "description", unique = false, length = 5000) private String description; @Basic(optional = false) @Temporal(TemporalType.TIMESTAMP) @Column(name = "start_date", unique = false, length = 255) private Date startDate; @Basic(optional = false) @Temporal(TemporalType.TIMESTAMP) @Column(name = "end_date", unique = false, length = 255) private Date endDate; @Basic(optional = false) @Column(name = "completion_percentage", unique = false, length = 255) private Integer completionPercentage; @ManyToOne @JoinColumn(name = "project_id") private Project project; @OneToMany(mappedBy = "task") private List<Attachment> attachments; @Basic(optional = true) @Column(name = "observation", unique = false, length = 5000) private String observation; @Basic(optional = false) @Enumerated(EnumType.STRING) @Column(name = "status", unique = false, length = 50) private Status status; @Basic(optional = false) @Temporal(TemporalType.TIMESTAMP) @Column(name = "registration", unique = false, length = 50) private Date registration; @Basic(optional = false) @Temporal(TemporalType.TIMESTAMP) @Column(name = "last_update", unique = false, length = 50) private Date lastUpdate; @OneToOne @JoinColumn(name = "responsible_change_id") private Collaborator responsibleChange; }
danielpinna/sgi-back
src/main/java/br/com/gestaoigrejas/sgi/model/Task.java
Java
isc
2,343
package main import ( "log" "net/http" "github.com/dim13/gold/articles" ) type rss struct { URL string Title string Subtitle string Articles articles.Articles } func rssHandler(w http.ResponseWriter, r *http.Request) { app := conf.Blog.ArticlesPerPage a := art.Enabled().Limit(app) rss := rss{ URL: "http://" + r.Host, Title: conf.Blog.Title, Subtitle: conf.Blog.Subtitle, Articles: a, } err := tmpl.ExecuteTemplate(w, "rss.tmpl", rss) if err != nil { log.Println(err) } }
dim13/gold
rss.go
GO
isc
518
/** Markup under cursor and editing */ var Reflux=require("reflux"); var docfilestore=require("./docfile"); var markupNav=require("../markup/nav"); var markupStore=Reflux.createStore({ listenables:[require("../actions/markup")] ,markupsUnderCursor:[] ,ctrl_m_handler:null ,editing:null ,hovering:null ,onMarkupsUnderCursor:function(markupsUnderCursor) { //this.editing=null; if (this.markupsUnderCursor==markupsUnderCursor) return; this.markupsUnderCursor=markupsUnderCursor||[]; this.trigger(this.markupsUnderCursor,{cursor:true}); } ,getEditing:function() { return this.editing; } ,getNext:function() { if (!this.editing) return; return markupNav.next(this.editing.markup); } ,getPrev:function() { if (!this.editing) return; return markupNav.prev(this.editing.markup); } ,cancelEdit:function() { this.editing=null; this.ctrl_m_handler=null; } ,freeEditing:function() { if (!this.editing) return; this.editing.doc=null;//to notify markupselector shouldComponentUpdate } ,onEditMarkup:function(markup) { this.cancelEdit(); this.editing=markup; this.ctrl_m_handler=null; this.trigger([{doc:markup.handle.doc,key:markup.key,markup:markup}],{cursor:true}); } ,setEditing:function(markup,handler) { this.cancelEdit(); this.editing=markup; this.ctrl_m_handler=handler; //this.trigger([],{cursor:true}); this.trigger(markup,{editing:true}); } ,onSetHotkey:function(handler) { this.ctrl_m_handler=handler; //console.log("handler",handler,this); } ,remove:function(markup) { //console.log("remove markup",markup); this.cancelEdit(); var doc=markup.handle.doc; doc.getEditor().react.removeMarkup(markup.key); this.trigger([],{cursor:true}); } ,removeByMid:function(mid,file){ //console.log("remove mid in file",mid,file); var doc=docfilestore.docOf(file); doc.getEditor().react.removeMarkup(mid); this.trigger([],{cursor:true}); } ,onToggleMarkup:function(){ if (this.ctrl_m_handler) { this.ctrl_m_handler(); this.ctrl_m_handler=null;//fire once } } ,getHovering:function() { return this.hovering; } ,onHovering:function(m) { this.hovering=m; this.trigger(m,{hovering:true}); } ,onCreateMarkup:function(obj,cb) { if (!obj.typedef || !obj.typedef.mark) { console.log(obj); throw "cannot create markup" } this.editing=null; obj.typedef.mark(obj, docfilestore.docOf ,function(err,newmarkup){ this.markupsUnderCursor=newmarkup; this.trigger( this.markupsUnderCursor,{newly:true}); if (cb) cb(); }.bind(this)); } }) module.exports=markupStore;
ksanaforge/pannaloka
src/stores/markup.js
JavaScript
isc
2,579
/*jslint node: true*/ "use strict"; var fs = require('fs'), path = require('path'), util = require('util'), protocolHandler = {}, moment = require('moment'); protocolHandler.http = require('http'); protocolHandler.https = require('https'); function asArray(a) { if (Array.isArray(a)) { return a; } // else if (a === null || a === undefined) { return []; } // else return [a]; } function Client(settings) { var protocol = settings.protocol || "http"; this.handler = protocolHandler[protocol]; this.verbose = !!settings.verbose; // false if not set this.server = settings.server || "win-api.westtoer.be"; this.version = settings.version || "v1"; this.clientid = settings.clientid || "westtoer"; this.secret = settings.secret || "no-secret"; this.baseURI = protocol + "://" + this.server + "/api/" + this.version + "/"; this.authURI = protocol + "://" + this.server + "/oauth/v2/token?grant_type=client_credentials&client_id=" + encodeURIComponent(this.clientid) + "&client_secret=" + encodeURIComponent(this.secret); // we initialize in a stopped modus this.stop(); } Client.DEFAULT_PAGE = 1; Client.DEFAULT_SIZE = 10; function GenericQuery(tpl) { if (tpl !== undefined && tpl.constructor === GenericQuery) { // clone - constructor this.format = tpl.format; this.resources = tpl.resources.slice(0); this.touristictypes = tpl.touristictypes.slice(0); this.sizeVal = tpl.sizeVal; this.pageNum = tpl.pageNum; this.channels = tpl.channels.slice(0); this.lastmodRange = tpl.lastmodRange; this.softDelState = tpl.softDelState; this.pubState = tpl.pubState; this.bulkMode = tpl.bulkMode; this.partnerId = tpl.partnerId; this.keyvalset = tpl.keyvalset.slice(0); this.ownerEmail = tpl.ownerEmail; this.requiredFields = tpl.requiredFields.slice(0); this.selectId = tpl.selectId; this.selectMunicipal = tpl.selectMunicipal; this.machineName = tpl.machineName; this.anyTerm = tpl.anyTerm; } else { // nothing to clone, use defaults this.format = 'xml'; this.resources = ['accommodation']; //default zou alle types moeten kunnen bevatten this.touristictypes = []; this.sizeVal = Client.DEFAULT_SIZE; this.pageNum = Client.DEFAULT_PAGE; this.channels = []; this.requiredFields = []; this.keyvalset = []; this.bulkMode = false; } } GenericQuery.prototype.clone = function () { return new GenericQuery(this); }; // paging GenericQuery.prototype.page = function (page) { this.pageNum = Number(page) || Client.DEFAULT_PAGE; return this; }; GenericQuery.prototype.size = function (size) { this.sizeVal = Number(size) || 10; return this; }; // qrybuilder formats GenericQuery.prototype.asJSON_HAL = function () { this.format = 'json+hal'; return this; }; GenericQuery.prototype.asJSON = function () { this.format = 'json'; return this; }; GenericQuery.prototype.asXML = function () { this.format = 'xml'; return this; }; GenericQuery.prototype.bulk = function () { this.bulkMode = true; return this; }; //qrybuilder resource filter GenericQuery.prototype.forResources = function (newRsrc) { this.resources = asArray(newRsrc); return this; }; GenericQuery.prototype.andResource = function (singleRsrc) { this.resources.push(singleRsrc); return this; }; //qrybuilder type filter -- product queries GenericQuery.prototype.forTypes = function (newtypes) { return this.forResources(newtypes); }; GenericQuery.prototype.andType = function (singletype) { return this.andResource(singletype); }; //qrybuilder type filter -- vocabularies queries GenericQuery.prototype.forVocs = function () { return this.forResources(['vocabulary']); }; //qrybuilder type filter -- claims queries GenericQuery.prototype.forClaims = function () { return this.forResources(['product_claim']); }; //qrybuilder type filter -- statistical queries GenericQuery.prototype.forStats = function () { return this.forResources(['product_statistical_data']); }; //qrybuilder touristic_type filter GenericQuery.prototype.forTouristicTypes = function (newtypes) { this.touristictypes = asArray(newtypes); return this; }; GenericQuery.prototype.andTouristicType = function (singletype) { this.touristictypes.push(singletype); return this; }; //qrybuilder generic keyvals filter GenericQuery.prototype.andKeyVal = function (key, val) { this.keyvalset.push({"key": key, "val": val}); return this; }; //qrybuilder lastmod filter GenericQuery.prototype.lastmod = function (range) { this.lastmodRange = range; return this; }; function dateFormat(s) { if (s === undefined || s === null) { return "*"; } return moment(s).format('YYYY-MM-DD'); } GenericQuery.prototype.lastmodBetween = function (from, to) { var range = {}; if (from !== undefined && from !== null) { range.gte = dateFormat(from); } if (to !== undefined && to !== null) { range.lt = dateFormat(to); } return this.lastmod(range); // start boundary is inclusive, end-boundary is exclusive }; //qrybuilder delete filter GenericQuery.prototype.removed = function () { this.softDelState = true; return this; }; GenericQuery.prototype.active = function () { this.softDelState = false; return this; }; GenericQuery.prototype.ignoreRemoved = function () { this.softDelState = undefined; return this; }; //qrybuilder pubchannel filter GenericQuery.prototype.forChannels = function (chs) { this.channels = asArray(chs); return this; }; GenericQuery.prototype.andChannel = function (ch) { this.channels.push(ch); return this; }; GenericQuery.prototype.requirePubChannel = function () { return this.andChannel(".*"); }; //qrybuilder published filter GenericQuery.prototype.published = function () { this.pubState = true; return this; }; GenericQuery.prototype.hidden = function () { this.pubState = false; return this; }; GenericQuery.prototype.ignorePublished = function () { this.pubState = undefined; return this; }; //qrybuilder owner-email filtering GenericQuery.prototype.owner = function (email) { this.ownerEmail = email; return this; }; //qrybuilder partner-id filtering GenericQuery.prototype.partner = function (id) { this.partnerId = id; return this; }; //qrybuilder id filtering GenericQuery.prototype.id = function (id) { this.selectId = id; return this; }; //qrybuilder municipality filtering GenericQuery.prototype.municipality = function (muni) { this.selectMunicipal = muni; return this; }; //qrybuilder existingfields filter GenericQuery.prototype.requireFields = function (flds) { this.requiredFields = asArray(flds); return this; }; GenericQuery.prototype.andField = function (fld) { this.requiredFields.push(fld); return this; }; //qrybuilder vocname filtering GenericQuery.prototype.vocname = function (name) { this.machineName = name; return this; }; //qrybuilder stats-year filtering GenericQuery.prototype.statsyear = function (year) { this.statsYear = Number(year); return this; }; //qrybuilder any field matching GenericQuery.prototype.match = function (term) { this.anyTerm = term; return this; }; GenericQuery.addURI = function (key, value, unsetVal) { if (value === unsetVal) { return ""; } // else return "&" + key + "=" + encodeURIComponent(value); }; GenericQuery.addQuery = function (set, type, key, value) { if (Array.isArray(value)) { value = value.join(" "); } if (value === undefined || value === null || value === "") { return; } // else var rule = {}, qry = {}; rule[key] = value; qry[type] = rule; set.push(qry); }; GenericQuery.addMatchQuery = function (set, key, value) { GenericQuery.addQuery(set, "match", key, value); }; GenericQuery.addFuzzyQuery = function (set, key, value) { GenericQuery.addQuery(set, "fuzzy", key, value); }; GenericQuery.addTermsQuery = function (set, key, value) { GenericQuery.addQuery(set, "terms", key, value.split(/\s/)); }; GenericQuery.addRegExpQuery = function (set, key, value) { GenericQuery.addQuery(set, "regexp", key, value); }; GenericQuery.addRangeQuery = function (set, key, range) { GenericQuery.addQuery(set, "range", key, range); }; GenericQuery.addNestedQuery = function (set, path, subfn) { if (path === undefined) { return; } // else var subset = [], qry = {"bool": {"must": subset}}; subfn(subset); set.push({"nested": {"path": path, "query": qry}}); }; GenericQuery.addExistsFilters = function (set, fields) { fields.forEach(function (field) { if (field === undefined || field === null || field === "") { return; } set.push({"exists": {"field": field}}); }); }; GenericQuery.prototype.getURI = function (client, notoken) { notoken = notoken || false; var me = this, uri, esq = [], esf = [], query, queryNeeded = false, expired = client.token_expires < Date.now(); if (!notoken && (client.token === null || expired)) { throw new Error("client has no active (" + !expired + ") token (" + client.token + ")"); } if (this.resources === undefined || this.resources === null || this.resources.length === 0) { throw new Error("no types specified for fetch"); } uri = client.baseURI + (this.bulkMode ? "bulk/" : "") + this.resources.join(',') + "?format=" + this.format + "&access_token=" + (notoken ? "***" : encodeURIComponent(client.token)); if (!this.bulkMode) { // paging is meaningless in bulk mode uri += GenericQuery.addURI("size", this.sizeVal, Client.DEFAULT_SIZE); uri += GenericQuery.addURI("page", this.pageNum, Client.DEFAULT_PAGE); } GenericQuery.addRangeQuery(esq, "metadata.update_date", this.lastmodRange); GenericQuery.addMatchQuery(esq, "metadata.deleted", this.softDelState); GenericQuery.addMatchQuery(esq, "publishing_channels.published", this.pubState); GenericQuery.addMatchQuery(esq, "metadata.id", this.selectId); GenericQuery.addMatchQuery(esq, "location_info.address.municipality", this.selectMunicipal); this.keyvalset.forEach( function(kv) { GenericQuery.addMatchQuery(esq, kv.key, kv.val); }); GenericQuery.addFuzzyQuery(esq, "_all", this.anyTerm); GenericQuery.addExistsFilters(esf, this.requiredFields); if (this.channels.length > 0) { GenericQuery.addNestedQuery( esq, "publishing_channels.publishing_channel", function (subset) { GenericQuery.addRegExpQuery(subset, "publishing_channels.publishing_channel.code", me.channels); GenericQuery.addMatchQuery(subset, "publishing_channels.publishing_channel.published", true); } ); } GenericQuery.addMatchQuery(esq, "metadata.touristic_product_type.code", this.touristictypes); // specific for claims GenericQuery.addRegExpQuery(esq, "claims.claim.owner.email_address", this.ownerEmail); GenericQuery.addMatchQuery(esq, "metadata.partner_id", this.partnerId); // specific for vocabs GenericQuery.addMatchQuery(esq, "machine_name", this.machineName); // specific for stats GenericQuery.addMatchQuery(esq, "statistical_data_collection.year", this.statsYear); query = {"query" : {"filtered": {}}}; if (esq.length > 0) { queryNeeded = true; query.query.filtered.query = {"bool" : {"must": esq}}; } if (esf.length > 0) { queryNeeded = true; query.query.filtered.filter = {"bool" : {"must": esf}}; } if (queryNeeded) { uri += "&_query=" + encodeURIComponent(JSON.stringify(query)); } return uri; }; function getResponse(client, uri, cb, verbose) { verbose = verbose || false; if (verbose) { console.log("call uri [%s]", uri); } client.get(uri, function (res) { cb(null, res); }).on('error', function (e) { cb(e); }); } function streamData(client, uri, sink, cb, verbose) { getResponse(client, uri, function (e, res) { var stream; if (e) { sink.emit('error', e); } else if (res === undefined || res === null) { sink.emit('error', new Error("error reading uri [" + uri + "] - no response object.")); } else if (res.statusCode !== 200) { sink.emit('error', new Error("error reading uri [" + uri + "] to stream - response.status == " + res.statusCode)); } else { // all is well, so try sinking this data stream = res.pipe(sink); } cb(e, res, stream); }, verbose); } function getData(client, uri, cb, verbose) { getResponse(client, uri, function (e, res) { var data = ""; if (e) { return cb(e); } //else if (res === undefined || res === null) { return cb(new Error("error reading uri [" + uri + "] - no response object.")); } if (res.statusCode !== 200) { return cb(new Error("error reading uri [" + uri + "] - status == " + res.statusCode)); } // else res .on('data', function (chunk) { data += chunk; }) .on('end', function () { cb(null, data); }) .on('error', cb); }, verbose); } function getJSON(client, uri, cb, verbose) { getData(client, uri, function (e, data) { if (e) { return cb(e); } //else cb(null, JSON.parse(data)); }, verbose); } function getXML(client, uri, cb, verbose) { //TODO parse XML to DOM ? getData(client, uri, cb, verbose); } Client.prototype.stop = function () { clearTimeout(this.token_refresh); this.token = null; this.token_expires = Date.now(); this.token_refresh = null; }; Client.prototype.start = function (cb) { cb = cb || function () {return; }; var me = this, SLACK_MILLIS = 1000, exp_in_millis; if (me.token_refresh !== null) { // already started... if (cb) { return cb(null); // no errors, but no token object either } return; } // else getJSON(this.handler, this.authURI, function (e, resp) { if (e) { console.error("getjson ERROR: %j", e); return cb(e); } me.token = resp.access_token; exp_in_millis = resp.expires_in * 1000; me.token_expires = Date.now() + exp_in_millis; if (exp_in_millis > SLACK_MILLIS) { // we assume at least 1s slack to operate me.token_refresh = setTimeout(function () { me.start(); }, exp_in_millis - SLACK_MILLIS); } else { console.warn("token validity too short to organize self-refresh"); } if (me.verbose) { console.log("got token %s - valid for %d - till %s", me.token, resp.expires_in, moment(me.token_expires)); } cb(e, resp); }, this.verbose); }; Client.prototype.fetch = function (qry, cb) { if (arguments.length < 2) { cb = qry; qry = new GenericQuery(); } try { if (qry.format === 'json') { getJSON(this.handler, qry.getURI(this), function (e, resp) { cb(e, resp); }, this.verbose); } else if (qry.format === 'json+hal') { getJSON(this.handler, qry.getURI(this), function (e, resp) { if (e) { return cb(e); } // else var meta = resp, EMB = "_embedded", emb = meta[EMB]; resp = emb.items; delete emb.items; cb(e, resp, meta); }, this.verbose); } else if (qry.format === 'xml') { getXML(this.handler, qry.getURI(this), function (e, resp) { cb(e, resp); }, this.verbose); } } catch (e) { cb(e); } }; Client.prototype.stream = function (qry, sink, cb) { if (arguments.length < 2) { sink = qry; qry = new GenericQuery(); } cb = cb || function () { return; }; // do nothing callback try { streamData(this.handler, qry.getURI(this), sink, cb, this.verbose); } catch (e) { cb(e, null); } }; Client.prototype.parseVocabularyCodes = function (vocabs, onlyNames) { return vocabs.reduce(function (byName, voc) { var name = voc.machine_name; if (onlyNames === undefined || onlyNames.indexOf(name) !== -1) { if (byName.hasOwnProperty(name)) { throw new Error("duplicate key machine_name : " + name); } if (voc && voc.terms && voc.terms.term) { byName[name] = Object.keys(voc.terms.term.reduce(function (res, term) { var code = term.code || ""; if (code.length === 0) { throw new Error("invalid empty code '' for vocabulary: " + name); } if (res.hasOwnProperty(code)) { throw new Error("duplicate code '" + code + "' for vocabulary: " + name); } res[code] = term; return res; }, {})); // byName[name] = voc.terms.term.map(function (term) { // var code = term.code || ""; // if (code.length === 0) { // throw new Error("invalid empty code '' for vocabulary: " + name); // } // return code; // }); } else { byName[name] = []; } } return byName; }, {}); }; Client.prototype.parseVocabularyTrees = function (vocabs, onlyNames) { return vocabs.reduce(function (byName, voc) { var name = voc.machine_name, termRoot = {children: []}, termNodes; if (onlyNames === undefined || onlyNames.indexOf(name) !== -1) { if (byName.hasOwnProperty(name)) { throw new Error("duplicate key machine_name : " + name); } if (voc && voc.terms && voc.terms.term && voc.hierarchy) { // list all linkable nodes termNodes = voc.terms.term.reduce(function (tns, term) { var code = term.code || "", pcode = term.parent_code || ""; if (code.length === 0) { throw new Error("invalid empty code '' for vocabulary: " + name); } if (tns.hasOwnProperty(code)) { throw new Error("duplicate code '" + code + "' for vocabulary: " + name); } tns[code] = { code: code, parent: pcode, children: [] }; return tns; }, {}); // link parents and children Object.keys(termNodes).forEach(function (code) { var tn = termNodes[code], pn = tn.parent === "" ? termRoot : termNodes[tn.parent]; if (pn === null || pn === undefined) { throw new Error("not found node for parent_code '" + tn.parent + "' in voc named: " + name); } tn.parent = pn; pn.children.push(tn); }); byName[name] = termRoot.children; } else { byName[name] = null; } } return byName; }, {}); }; module.exports.client = function (settings) { return new Client(settings); }; module.exports.query = function (service) { service = service || 'product'; if (service === 'product') { return new GenericQuery(); } if (service === 'vocabulary') { return new GenericQuery().forVocs(); } if (service === 'claim') { return new GenericQuery().forClaims(); } if (service === 'statistics') { return new GenericQuery().forStats(); } throw "unknown service request"; };
westtoer/node-winapi
lib/winapi.js
JavaScript
isc
20,578
<?php namespace MooPhp\MooInterface\Request; use MooPhp\Api; use MooPhp\MooInterface\Data\ImageBasket; use MooPhp\MooInterface\Data\Side; /** * @package MooPhp * @author Jonathan Oddy <jonathan@moo.com> * @copyright Copyright (c) 2012, Moo Print Ltd. */ class RenderSideUrl extends CommonRenderSide { public function __construct() { parent::__construct("moo.pack.renderSideUrl", self::HTTP_POST); } }
moodev/moo-php
lib/MooPhp/MooInterface/Request/RenderSideUrl.php
PHP
isc
429
/* * Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com> * Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com> * Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com> * Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com> * Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net> * Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com> * Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "SolutionALG.hh" #include "RestrictionALG.hh" #include "ConstraintSystemALG.hh" #include "EvaluationSystemALG.hh" #include <list> const SolutionALG::MachineId SolutionALG::unassigned = -1; const SolutionALG::MachineId SolutionALG::failToAssign = -2; SolutionALG::SolutionALG(size_t nbProcesses_p) :assignment_m(nbProcesses_p,unassigned),incrementalValue_m(0.0) { } SolutionALG::~SolutionALG() { for (RestrictionPool::const_iterator it_l = restrictions_m.begin(); it_l != restrictions_m.end(); ++it_l) { RestrictionALG * pRestriction_l = *it_l; if (pRestriction_l != pConstraintSystem_m) delete pRestriction_l; } } void SolutionALG::unassign(ProcessId process_p) { pConstraintSystem_m->unassign(process_p, assignment_m[process_p]); assignment_m[process_p] = unassigned; } void SolutionALG::assign(ProcessId process_p, MachineId machine_p) { assignment_m[process_p] = machine_p; pConstraintSystem_m->assign(process_p, machine_p); } double SolutionALG::evaluate() { return pEvaluationSystem_m->evaluate(assignment_m); } std::vector<SolutionALG::ProcessId> SolutionALG::getAvaiableProcesses() const { std::vector<SolutionALG::ProcessId> return_l; std::vector<ProcessId> unassigned_l; ProcessId current_l = 0; ProcessId end_l = assignment_m.size(); for( ; current_l < end_l; ++current_l) { if (assignment_m[current_l] == unassigned) { unassigned_l.push_back(current_l); } } for (RestrictionPool::const_iterator it_l = restrictions_m.begin(); it_l != restrictions_m.end(); ++it_l) { RestrictionALG * pRestriction_l = *it_l; pRestriction_l->filter(unassigned_l); } return_l.insert(return_l.begin(), unassigned_l.begin(), unassigned_l.end()); return return_l; } std::vector<SolutionALG::MachineId> SolutionALG::getAvaiableMachines(ProcessId process_p) const { std::vector<SolutionALG::MachineId> return_l; std::vector<MachineId> possibles_l = pConstraintSystem_m->getLegalMachinePool(process_p); for (RestrictionPool::const_iterator it_l = restrictions_m.begin(); it_l != restrictions_m.end(); ++it_l) { RestrictionALG * pRestriction_l = *it_l; pRestriction_l->filter(process_p,possibles_l); } return_l.insert(return_l.begin(), possibles_l.begin(), possibles_l.end()); return return_l; } void SolutionALG::addRestriction(RestrictionALG * pRestriction_p) { restrictions_m.push_back(pRestriction_p); } void SolutionALG::setpConstraintSystem(ConstraintSystemALG * pSystem_p) { pConstraintSystem_m = pSystem_p; addRestriction(pConstraintSystem_m); } void SolutionALG::setpEvaluationSystem(EvaluationSystemALG * pSystem_p) { pEvaluationSystem_m = pSystem_p; }
gturri/roadef2012
src/alg/MCTS/SolutionALG.cc
C++
isc
4,222
package parser_test import ( "testing" "github.com/tmc/graphql/parser" ) func TestMalformedQuery(t *testing.T) { op, err := parser.ParseOperation(nil) if !parser.IsMalformedOperation(err) { t.Error("Expected malformed operation") } if op != nil { t.Error("Expected nil result") } if es := err.Error(); es != "parser: malformed graphql operation: 1:1 (0): no match found" { t.Errorf("got unexpected error: '%v'", es) } } func TestMultipleOperations(t *testing.T) { multi := ` {foo} {bar} ` op, err := parser.ParseOperation([]byte(multi)) if err != parser.ErrMultipleOperations { t.Error("Expected multiple operations error") } if op != nil { t.Error("Expected nil result") } }
tmc/graphql
parser/parser_test.go
GO
isc
708
// Copyright (c) 2014 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package btcjson_test import ( "encoding/json" "reflect" "testing" "github.com/adiabat/btcd/btcjson" ) // TestIsValidIDType ensures the IsValidIDType function behaves as expected. func TestIsValidIDType(t *testing.T) { t.Parallel() tests := []struct { name string id interface{} isValid bool }{ {"int", int(1), true}, {"int8", int8(1), true}, {"int16", int16(1), true}, {"int32", int32(1), true}, {"int64", int64(1), true}, {"uint", uint(1), true}, {"uint8", uint8(1), true}, {"uint16", uint16(1), true}, {"uint32", uint32(1), true}, {"uint64", uint64(1), true}, {"string", "1", true}, {"nil", nil, true}, {"float32", float32(1), true}, {"float64", float64(1), true}, {"bool", true, false}, {"chan int", make(chan int), false}, {"complex64", complex64(1), false}, {"complex128", complex128(1), false}, {"func", func() {}, false}, } t.Logf("Running %d tests", len(tests)) for i, test := range tests { if btcjson.IsValidIDType(test.id) != test.isValid { t.Errorf("Test #%d (%s) valid mismatch - got %v, "+ "want %v", i, test.name, !test.isValid, test.isValid) continue } } } // TestMarshalResponse ensures the MarshalResponse function works as expected. func TestMarshalResponse(t *testing.T) { t.Parallel() testID := 1 tests := []struct { name string result interface{} jsonErr *btcjson.RPCError expected []byte }{ { name: "ordinary bool result with no error", result: true, jsonErr: nil, expected: []byte(`{"result":true,"error":null,"id":1}`), }, { name: "result with error", result: nil, jsonErr: func() *btcjson.RPCError { return btcjson.NewRPCError(btcjson.ErrRPCBlockNotFound, "123 not found") }(), expected: []byte(`{"result":null,"error":{"code":-5,"message":"123 not found"},"id":1}`), }, } t.Logf("Running %d tests", len(tests)) for i, test := range tests { _, _ = i, test marshalled, err := btcjson.MarshalResponse(testID, test.result, test.jsonErr) if err != nil { t.Errorf("Test #%d (%s) unexpected error: %v", i, test.name, err) continue } if !reflect.DeepEqual(marshalled, test.expected) { t.Errorf("Test #%d (%s) mismatched result - got %s, "+ "want %s", i, test.name, marshalled, test.expected) } } } // TestMiscErrors tests a few error conditions not covered elsewhere. func TestMiscErrors(t *testing.T) { t.Parallel() // Force an error in NewRequest by giving it a parameter type that is // not supported. _, err := btcjson.NewRequest(nil, "test", []interface{}{make(chan int)}) if err == nil { t.Error("NewRequest: did not receive error") return } // Force an error in MarshalResponse by giving it an id type that is not // supported. wantErr := btcjson.Error{ErrorCode: btcjson.ErrInvalidType} _, err = btcjson.MarshalResponse(make(chan int), nil, nil) if jerr, ok := err.(btcjson.Error); !ok || jerr.ErrorCode != wantErr.ErrorCode { t.Errorf("MarshalResult: did not receive expected error - got "+ "%v (%[1]T), want %v (%[2]T)", err, wantErr) return } // Force an error in MarshalResponse by giving it a result type that // can't be marshalled. _, err = btcjson.MarshalResponse(1, make(chan int), nil) if _, ok := err.(*json.UnsupportedTypeError); !ok { wantErr := &json.UnsupportedTypeError{} t.Errorf("MarshalResult: did not receive expected error - got "+ "%v (%[1]T), want %T", err, wantErr) return } } // TestRPCError tests the error output for the RPCError type. func TestRPCError(t *testing.T) { t.Parallel() tests := []struct { in *btcjson.RPCError want string }{ { btcjson.ErrRPCInvalidRequest, "-32600: Invalid request", }, { btcjson.ErrRPCMethodNotFound, "-32601: Method not found", }, } t.Logf("Running %d tests", len(tests)) for i, test := range tests { result := test.in.Error() if result != test.want { t.Errorf("Error #%d\n got: %s want: %s", i, result, test.want) continue } } }
adiabat/btcd
btcjson/jsonrpc_test.go
GO
isc
4,149
//////////////////////////////////////////////////////////////////////////////// // GaProject.cpp // Includes #include "GaProject.h" // Games #include "PgMain.h" pgMain project; //////////////////////////////////////////////////////////////////////////////// // Init void GaProject::Create() { project.Create(); } //////////////////////////////////////////////////////////////////////////////// // Init void GaProject::Init() { project.Init(); } //////////////////////////////////////////////////////////////////////////////// // Reset void GaProject::Reset() { project.Reset(); } //////////////////////////////////////////////////////////////////////////////// // Update void GaProject::Update() { project.Update(); } //////////////////////////////////////////////////////////////////////////////// // Render void GaProject::Render() { project.Render(); } //////////////////////////////////////////////////////////////////////////////// // Destroy void GaProject::Destroy() { project.Destroy(); } //////////////////////////////////////////////////////////////////////////////// // SetClosing void GaProject::SetClosing() { project.SetClosing(); } //////////////////////////////////////////////////////////////////////////////// // IsClosed BtBool GaProject::IsClosed() { return project.IsClosed(); } //////////////////////////////////////////////////////////////////////////////// // IsClosing BtBool GaProject::IsClosing() { return project.IsClosing(); }
thecreativeexchange/labella
OpenLab_Apps/LabellaApp/Mirror/GaProject.cpp
C++
isc
1,487
// Generated by typings // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/e0abafb1a6ff652f7ff967120e312d5c1916eaef/lodash/lodash.d.ts declare var _: _.LoDashStatic; declare module _ { interface LoDashStatic { /** * Creates a lodash object which wraps the given value to enable intuitive method chaining. * * In addition to Lo-Dash methods, wrappers also have the following Array methods: * concat, join, pop, push, reverse, shift, slice, sort, splice, and unshift * * Chaining is supported in custom builds as long as the value method is implicitly or * explicitly included in the build. * * The chainable wrapper functions are: * after, assign, bind, bindAll, bindKey, chain, chunk, compact, compose, concat, countBy, * createCallback, curry, debounce, defaults, defer, delay, difference, filter, flatten, * forEach, forEachRight, forIn, forInRight, forOwn, forOwnRight, functions, groupBy, * keyBy, initial, intersection, invert, invoke, keys, map, max, memoize, merge, min, * object, omit, once, pairs, partial, partialRight, pick, pluck, pull, push, range, reject, * remove, rest, reverse, sample, shuffle, slice, sort, sortBy, splice, tap, throttle, times, * toArray, transform, union, uniq, unset, unshift, unzip, values, where, without, wrap, and zip * * The non-chainable wrapper functions are: * clone, cloneDeep, contains, escape, every, find, findIndex, findKey, findLast, * findLastIndex, findLastKey, has, identity, indexOf, isArguments, isArray, isBoolean, * isDate, isElement, isEmpty, isEqual, isFinite, isFunction, isNaN, isNull, isNumber, * isObject, isPlainObject, isRegExp, isString, isUndefined, join, lastIndexOf, mixin, * noConflict, parseInt, pop, random, reduce, reduceRight, result, shift, size, some, * sortedIndex, runInContext, template, unescape, uniqueId, and value * * The wrapper functions first and last return wrapped values when n is provided, otherwise * they return unwrapped values. * * Explicit chaining can be enabled by using the _.chain method. **/ (value: number): LoDashImplicitWrapper<number>; (value: string): LoDashImplicitStringWrapper; (value: boolean): LoDashImplicitWrapper<boolean>; (value: Array<number>): LoDashImplicitNumberArrayWrapper; <T>(value: Array<T>): LoDashImplicitArrayWrapper<T>; <T extends {}>(value: T): LoDashImplicitObjectWrapper<T>; (value: any): LoDashImplicitWrapper<any>; /** * The semantic version number. **/ VERSION: string; /** * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby * (ERB). Change the following template settings to use alternative delimiters. **/ templateSettings: TemplateSettings; } /** * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby * (ERB). Change the following template settings to use alternative delimiters. **/ interface TemplateSettings { /** * The "escape" delimiter. **/ escape?: RegExp; /** * The "evaluate" delimiter. **/ evaluate?: RegExp; /** * An object to import into the template as local variables. **/ imports?: Dictionary<any>; /** * The "interpolate" delimiter. **/ interpolate?: RegExp; /** * Used to reference the data object in the template text. **/ variable?: string; } /** * Creates a cache object to store key/value pairs. */ interface MapCache { /** * Removes `key` and its value from the cache. * @param key The key of the value to remove. * @return Returns `true` if the entry was removed successfully, else `false`. */ delete(key: string): boolean; /** * Gets the cached value for `key`. * @param key The key of the value to get. * @return Returns the cached value. */ get(key: string): any; /** * Checks if a cached value for `key` exists. * @param key The key of the entry to check. * @return Returns `true` if an entry for `key` exists, else `false`. */ has(key: string): boolean; /** * Sets `value` to `key` of the cache. * @param key The key of the value to cache. * @param value The value to cache. * @return Returns the cache object. */ set(key: string, value: any): _.Dictionary<any>; } interface LoDashWrapperBase<T, TWrapper> { } interface LoDashImplicitWrapperBase<T, TWrapper> extends LoDashWrapperBase<T, TWrapper> { } interface LoDashExplicitWrapperBase<T, TWrapper> extends LoDashWrapperBase<T, TWrapper> { } interface LoDashImplicitWrapper<T> extends LoDashImplicitWrapperBase<T, LoDashImplicitWrapper<T>> { } interface LoDashExplicitWrapper<T> extends LoDashExplicitWrapperBase<T, LoDashExplicitWrapper<T>> { } interface LoDashImplicitStringWrapper extends LoDashImplicitWrapper<string> { } interface LoDashExplicitStringWrapper extends LoDashExplicitWrapper<string> { } interface LoDashImplicitObjectWrapper<T> extends LoDashImplicitWrapperBase<T, LoDashImplicitObjectWrapper<T>> { } interface LoDashExplicitObjectWrapper<T> extends LoDashExplicitWrapperBase<T, LoDashExplicitObjectWrapper<T>> { } interface LoDashImplicitArrayWrapper<T> extends LoDashImplicitWrapperBase<T[], LoDashImplicitArrayWrapper<T>> { pop(): T; push(...items: T[]): LoDashImplicitArrayWrapper<T>; shift(): T; sort(compareFn?: (a: T, b: T) => number): LoDashImplicitArrayWrapper<T>; splice(start: number): LoDashImplicitArrayWrapper<T>; splice(start: number, deleteCount: number, ...items: any[]): LoDashImplicitArrayWrapper<T>; unshift(...items: T[]): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> extends LoDashExplicitWrapperBase<T[], LoDashExplicitArrayWrapper<T>> { } interface LoDashImplicitNumberArrayWrapper extends LoDashImplicitArrayWrapper<number> { } interface LoDashExplicitNumberArrayWrapper extends LoDashExplicitArrayWrapper<number> { } /********* * Array * *********/ //_.chunk interface LoDashStatic { /** * Creates an array of elements split into groups the length of size. If collection can’t be split evenly, the * final chunk will be the remaining elements. * * @param array The array to process. * @param size The length of each chunk. * @return Returns the new array containing chunks. */ chunk<T>( array: List<T>, size?: number ): T[][]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.chunk */ chunk(size?: number): LoDashImplicitArrayWrapper<T[]>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.chunk */ chunk<TResult>(size?: number): LoDashImplicitArrayWrapper<TResult[]>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.chunk */ chunk(size?: number): LoDashExplicitArrayWrapper<T[]>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.chunk */ chunk<TResult>(size?: number): LoDashExplicitArrayWrapper<TResult[]>; } //_.compact interface LoDashStatic { /** * Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are * falsey. * * @param array The array to compact. * @return (Array) Returns the new array of filtered values. */ compact<T>(array?: List<T>): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.compact */ compact(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.compact */ compact<TResult>(): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.compact */ compact(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.compact */ compact<TResult>(): LoDashExplicitArrayWrapper<TResult>; } //_.concat DUMMY interface LoDashStatic { /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ concat<T>(...values: (T[]|List<T>)[]) : T[]; } //_.difference interface LoDashStatic { /** * Creates an array of unique array values not included in the other provided arrays using SameValueZero for * equality comparisons. * * @param array The array to inspect. * @param values The arrays of values to exclude. * @return Returns the new array of filtered values. */ difference<T>( array: T[]|List<T>, ...values: Array<T[]|List<T>> ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.difference */ difference(...values: (T[]|List<T>)[]): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.difference */ difference<TValue>(...values: (TValue[]|List<TValue>)[]): LoDashImplicitArrayWrapper<TValue>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.difference */ difference(...values: (T[]|List<T>)[]): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.difference */ difference<TValue>(...values: (TValue[]|List<TValue>)[]): LoDashExplicitArrayWrapper<TValue>; } //_.differenceBy interface LoDashStatic { /** * This method is like _.difference except that it accepts iteratee which is invoked for each element of array * and values to generate the criterion by which uniqueness is computed. The iteratee is invoked with one * argument: (value). * * @param array The array to inspect. * @param values The values to exclude. * @param iteratee The iteratee invoked per element. * @returns Returns the new array of filtered values. */ differenceBy<T>( array: T[]|List<T>, values?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): T[]; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( array: T[]|List<T>, values?: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.differenceBy */ differenceBy<T>( array: T[]|List<T>, values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): T[]; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( array: T[]|List<T>, values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.differenceBy */ differenceBy<T>( array: T[]|List<T>, values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): T[]; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( array: T[]|List<T>, values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( array: T[]|List<T>, values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.differenceBy */ differenceBy<T>( array: T[]|List<T>, values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): T[]; /** * @see _.differenceBy */ differenceBy<T>( array: T[]|List<T>, values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): T[]; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( array: T[]|List<T>, values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.differenceBy */ differenceBy<T>( array: T[]|List<T>, ...values: any[] ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.differenceBy */ differenceBy<T>( values?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( ...values: any[] ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.differenceBy */ differenceBy<T>( values?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( ...values: any[] ): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.differenceBy */ differenceBy<T>( values?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( ...values: any[] ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.differenceBy */ differenceBy<T>( values?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: ((value: T) => any)|string ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T, W extends Object>( values1?: T[]|List<T>, values2?: T[]|List<T>, values3?: T[]|List<T>, values4?: T[]|List<T>, values5?: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.differenceBy */ differenceBy<T>( ...values: any[] ): LoDashExplicitArrayWrapper<T>; } //_.differenceWith DUMMY interface LoDashStatic { /** * Creates an array of unique `array` values not included in the other * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @example * * _.difference([3, 2, 1], [4, 2]); * // => [3, 1] */ differenceWith( array: any[]|List<any>, ...values: any[] ): any[]; } //_.drop interface LoDashStatic { /** * Creates a slice of array with n elements dropped from the beginning. * * @param array The array to query. * @param n The number of elements to drop. * @return Returns the slice of array. */ drop<T>(array: T[]|List<T>, n?: number): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.drop */ drop(n?: number): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.drop */ drop<T>(n?: number): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.drop */ drop(n?: number): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.drop */ drop<T>(n?: number): LoDashExplicitArrayWrapper<T>; } //_.dropRight interface LoDashStatic { /** * Creates a slice of array with n elements dropped from the end. * * @param array The array to query. * @param n The number of elements to drop. * @return Returns the slice of array. */ dropRight<T>( array: List<T>, n?: number ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.dropRight */ dropRight(n?: number): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.dropRight */ dropRight<TResult>(n?: number): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.dropRight */ dropRight(n?: number): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.dropRight */ dropRight<TResult>(n?: number): LoDashExplicitArrayWrapper<TResult>; } //_.dropRightWhile interface LoDashStatic { /** * Creates a slice of array excluding elements dropped from the end. Elements are dropped until predicate * returns falsey. The predicate is bound to thisArg and invoked with three arguments: (value, index, array). * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * match the properties of the given object, else false. * * @param array The array to query. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the slice of array. */ dropRightWhile<TValue>( array: List<TValue>, predicate?: ListIterator<TValue, boolean> ): TValue[]; /** * @see _.dropRightWhile */ dropRightWhile<TValue>( array: List<TValue>, predicate?: string ): TValue[]; /** * @see _.dropRightWhile */ dropRightWhile<TWhere, TValue>( array: List<TValue>, predicate?: TWhere ): TValue[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.dropRightWhile */ dropRightWhile( predicate?: ListIterator<T, boolean> ): LoDashImplicitArrayWrapper<T>; /** * @see _.dropRightWhile */ dropRightWhile( predicate?: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.dropRightWhile */ dropRightWhile<TWhere>( predicate?: TWhere ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.dropRightWhile */ dropRightWhile<TValue>( predicate?: ListIterator<TValue, boolean> ): LoDashImplicitArrayWrapper<TValue>; /** * @see _.dropRightWhile */ dropRightWhile<TValue>( predicate?: string ): LoDashImplicitArrayWrapper<TValue>; /** * @see _.dropRightWhile */ dropRightWhile<TWhere, TValue>( predicate?: TWhere ): LoDashImplicitArrayWrapper<TValue>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.dropRightWhile */ dropRightWhile( predicate?: ListIterator<T, boolean> ): LoDashExplicitArrayWrapper<T>; /** * @see _.dropRightWhile */ dropRightWhile( predicate?: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.dropRightWhile */ dropRightWhile<TWhere>( predicate?: TWhere ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.dropRightWhile */ dropRightWhile<TValue>( predicate?: ListIterator<TValue, boolean> ): LoDashExplicitArrayWrapper<TValue>; /** * @see _.dropRightWhile */ dropRightWhile<TValue>( predicate?: string ): LoDashExplicitArrayWrapper<TValue>; /** * @see _.dropRightWhile */ dropRightWhile<TWhere, TValue>( predicate?: TWhere ): LoDashExplicitArrayWrapper<TValue>; } //_.dropWhile interface LoDashStatic { /** * Creates a slice of array excluding elements dropped from the beginning. Elements are dropped until predicate * returns falsey. The predicate is bound to thisArg and invoked with three arguments: (value, index, array). * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param array The array to query. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the slice of array. */ dropWhile<TValue>( array: List<TValue>, predicate?: ListIterator<TValue, boolean> ): TValue[]; /** * @see _.dropWhile */ dropWhile<TValue>( array: List<TValue>, predicate?: string ): TValue[]; /** * @see _.dropWhile */ dropWhile<TWhere, TValue>( array: List<TValue>, predicate?: TWhere ): TValue[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.dropWhile */ dropWhile( predicate?: ListIterator<T, boolean> ): LoDashImplicitArrayWrapper<T>; /** * @see _.dropWhile */ dropWhile( predicate?: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.dropWhile */ dropWhile<TWhere>( predicate?: TWhere ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.dropWhile */ dropWhile<TValue>( predicate?: ListIterator<TValue, boolean> ): LoDashImplicitArrayWrapper<TValue>; /** * @see _.dropWhile */ dropWhile<TValue>( predicate?: string ): LoDashImplicitArrayWrapper<TValue>; /** * @see _.dropWhile */ dropWhile<TWhere, TValue>( predicate?: TWhere ): LoDashImplicitArrayWrapper<TValue>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.dropWhile */ dropWhile( predicate?: ListIterator<T, boolean> ): LoDashExplicitArrayWrapper<T>; /** * @see _.dropWhile */ dropWhile( predicate?: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.dropWhile */ dropWhile<TWhere>( predicate?: TWhere ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.dropWhile */ dropWhile<TValue>( predicate?: ListIterator<TValue, boolean> ): LoDashExplicitArrayWrapper<TValue>; /** * @see _.dropWhile */ dropWhile<TValue>( predicate?: string ): LoDashExplicitArrayWrapper<TValue>; /** * @see _.dropWhile */ dropWhile<TWhere, TValue>( predicate?: TWhere ): LoDashExplicitArrayWrapper<TValue>; } //_.fill interface LoDashStatic { /** * Fills elements of array with value from start up to, but not including, end. * * Note: This method mutates array. * * @param array The array to fill. * @param value The value to fill array with. * @param start The start position. * @param end The end position. * @return Returns array. */ fill<T>( array: any[], value: T, start?: number, end?: number ): T[]; /** * @see _.fill */ fill<T>( array: List<any>, value: T, start?: number, end?: number ): List<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.fill */ fill<T>( value: T, start?: number, end?: number ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.fill */ fill<T>( value: T, start?: number, end?: number ): LoDashImplicitObjectWrapper<List<T>>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.fill */ fill<T>( value: T, start?: number, end?: number ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.fill */ fill<T>( value: T, start?: number, end?: number ): LoDashExplicitObjectWrapper<List<T>>; } //_.findIndex interface LoDashStatic { /** * This method is like _.find except that it returns the index of the first element predicate returns truthy * for instead of the element itself. * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param array The array to search. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the index of the found element, else -1. */ findIndex<T>( array: List<T>, predicate?: ListIterator<T, boolean> ): number; /** * @see _.findIndex */ findIndex<T>( array: List<T>, predicate?: string ): number; /** * @see _.findIndex */ findIndex<W, T>( array: List<T>, predicate?: W ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.findIndex */ findIndex( predicate?: ListIterator<T, boolean> ): number; /** * @see _.findIndex */ findIndex( predicate?: string ): number; /** * @see _.findIndex */ findIndex<W>( predicate?: W ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.findIndex */ findIndex<TResult>( predicate?: ListIterator<TResult, boolean> ): number; /** * @see _.findIndex */ findIndex( predicate?: string ): number; /** * @see _.findIndex */ findIndex<W>( predicate?: W ): number; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.findIndex */ findIndex( predicate?: ListIterator<T, boolean> ): LoDashExplicitWrapper<number>; /** * @see _.findIndex */ findIndex( predicate?: string ): LoDashExplicitWrapper<number>; /** * @see _.findIndex */ findIndex<W>( predicate?: W ): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.findIndex */ findIndex<TResult>( predicate?: ListIterator<TResult, boolean> ): LoDashExplicitWrapper<number>; /** * @see _.findIndex */ findIndex( predicate?: string ): LoDashExplicitWrapper<number>; /** * @see _.findIndex */ findIndex<W>( predicate?: W ): LoDashExplicitWrapper<number>; } //_.findLastIndex interface LoDashStatic { /** * This method is like _.findIndex except that it iterates over elements of collection from right to left. * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param array The array to search. * @param predicate The function invoked per iteration. * @param thisArg The function invoked per iteration. * @return Returns the index of the found element, else -1. */ findLastIndex<T>( array: List<T>, predicate?: ListIterator<T, boolean> ): number; /** * @see _.findLastIndex */ findLastIndex<T>( array: List<T>, predicate?: string ): number; /** * @see _.findLastIndex */ findLastIndex<W, T>( array: List<T>, predicate?: W ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.findLastIndex */ findLastIndex( predicate?: ListIterator<T, boolean> ): number; /** * @see _.findLastIndex */ findLastIndex( predicate?: string ): number; /** * @see _.findLastIndex */ findLastIndex<W>( predicate?: W ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.findLastIndex */ findLastIndex<TResult>( predicate?: ListIterator<TResult, boolean> ): number; /** * @see _.findLastIndex */ findLastIndex( predicate?: string ): number; /** * @see _.findLastIndex */ findLastIndex<W>( predicate?: W ): number; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.findLastIndex */ findLastIndex( predicate?: ListIterator<T, boolean> ): LoDashExplicitWrapper<number>; /** * @see _.findLastIndex */ findLastIndex( predicate?: string ): LoDashExplicitWrapper<number>; /** * @see _.findLastIndex */ findLastIndex<W>( predicate?: W ): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.findLastIndex */ findLastIndex<TResult>( predicate?: ListIterator<TResult, boolean> ): LoDashExplicitWrapper<number>; /** * @see _.findLastIndex */ findLastIndex( predicate?: string ): LoDashExplicitWrapper<number>; /** * @see _.findLastIndex */ findLastIndex<W>( predicate?: W ): LoDashExplicitWrapper<number>; } //_.first interface LoDashStatic { /** * @see _.head */ first<T>(array: List<T>): T; } interface LoDashImplicitWrapper<T> { /** * @see _.head */ first(): string; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.head */ first(): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.head */ first<T>(): T; } interface LoDashExplicitWrapper<T> { /** * @see _.head */ first(): LoDashExplicitWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.head */ first<T>(): T; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.head */ first<T>(): T; } interface RecursiveArray<T> extends Array<T|RecursiveArray<T>> {} interface ListOfRecursiveArraysOrValues<T> extends List<T|RecursiveArray<T>> {} //_.flatten interface LoDashStatic { /** * Flattens a nested array. If isDeep is true the array is recursively flattened, otherwise it’s only * flattened a single level. * * @param array The array to flatten. * @param isDeep Specify a deep flatten. * @return Returns the new flattened array. */ flatten<T>(array: ListOfRecursiveArraysOrValues<T>, isDeep: boolean): T[]; /** * @see _.flatten */ flatten<T>(array: List<T|T[]>): T[]; /** * @see _.flatten */ flatten<T>(array: ListOfRecursiveArraysOrValues<T>): RecursiveArray<T>; } interface LoDashImplicitWrapper<T> { /** * @see _.flatten */ flatten(): LoDashImplicitArrayWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.flatten */ flatten<TResult>(isDeep?: boolean): LoDashImplicitArrayWrapper<TResult>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.flatten */ flatten<TResult>(isDeep?: boolean): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitWrapper<T> { /** * @see _.flatten */ flatten(): LoDashExplicitArrayWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.flatten */ flatten<TResult>(isDeep?: boolean): LoDashExplicitArrayWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.flatten */ flatten<TResult>(isDeep?: boolean): LoDashExplicitArrayWrapper<TResult>; } //_.flattenDeep interface LoDashStatic { /** * Recursively flattens a nested array. * * @param array The array to recursively flatten. * @return Returns the new flattened array. */ flattenDeep<T>(array: ListOfRecursiveArraysOrValues<T>): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.flattenDeep */ flattenDeep(): LoDashImplicitArrayWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.flattenDeep */ flattenDeep<T>(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.flattenDeep */ flattenDeep<T>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.flattenDeep */ flattenDeep(): LoDashExplicitArrayWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.flattenDeep */ flattenDeep<T>(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.flattenDeep */ flattenDeep<T>(): LoDashExplicitArrayWrapper<T>; } //_.fromPairs DUMMY interface LoDashStatic { /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['fred', 30], ['barney', 40]]); * // => { 'fred': 30, 'barney': 40 } */ fromPairs( array: any[]|List<any> ): Dictionary<any>; } //_.fromPairs DUMMY interface LoDashImplicitArrayWrapper<T> { /** * @see _.fromPairs */ fromPairs(): LoDashImplicitObjectWrapper<any>; } //_.fromPairs DUMMY interface LoDashExplicitArrayWrapper<T> { /** * @see _.fromPairs */ fromPairs(): LoDashExplicitObjectWrapper<any>; } //_.head interface LoDashStatic { /** * Gets the first element of array. * * @alias _.first * * @param array The array to query. * @return Returns the first element of array. */ head<T>(array: List<T>): T; } interface LoDashImplicitWrapper<T> { /** * @see _.head */ head(): string; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.head */ head(): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.head */ head<T>(): T; } interface LoDashExplicitWrapper<T> { /** * @see _.head */ head(): LoDashExplicitWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.head */ head<T>(): T; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.head */ head<T>(): T; } //_.indexOf interface LoDashStatic { /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the offset * from the end of `array`. If `array` is sorted providing `true` for `fromIndex` * performs a faster binary search. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // using `fromIndex` * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ indexOf<T>( array: List<T>, value: T, fromIndex?: boolean|number ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.indexOf */ indexOf( value: T, fromIndex?: boolean|number ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.indexOf */ indexOf<TValue>( value: TValue, fromIndex?: boolean|number ): number; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.indexOf */ indexOf( value: T, fromIndex?: boolean|number ): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.indexOf */ indexOf<TValue>( value: TValue, fromIndex?: boolean|number ): LoDashExplicitWrapper<number>; } //_.intersectionBy DUMMY interface LoDashStatic { /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which uniqueness is computed. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of shared values. * @example * * _.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor); * // => [2.1] * * // using the `_.property` iteratee shorthand * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ intersectionBy( array: any[]|List<any>, ...values: any[] ): any[]; } //_.intersectionWith DUMMY interface LoDashStatic { /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ intersectionWith( array: any[]|List<any>, ...values: any[] ): any[]; } //_.join interface LoDashStatic { /** * Converts all elements in `array` into a string separated by `separator`. * * @param array The array to convert. * @param separator The element separator. * @returns Returns the joined string. */ join( array: List<any>, separator?: string ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.join */ join(separator?: string): string; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.join */ join(separator?: string): string; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.join */ join(separator?: string): string; } interface LoDashExplicitWrapper<T> { /** * @see _.join */ join(separator?: string): LoDashExplicitWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.join */ join(separator?: string): LoDashExplicitWrapper<string>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.join */ join(separator?: string): LoDashExplicitWrapper<string>; } //_.pullAll DUMMY interface LoDashStatic { /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3, 1, 2, 3]; * * _.pull(array, [2, 3]); * console.log(array); * // => [1, 1] */ pullAll( array: any[]|List<any>, ...values: any[] ): any[]; } //_.pullAllBy DUMMY interface LoDashStatic { /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to to generate the criterion * by which uniqueness is computed. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ pullAllBy( array: any[]|List<any>, ...values: any[] ): any[]; } //_.reverse DUMMY interface LoDashStatic { /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @memberOf _ * @category Array * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ reverse( array: any[]|List<any>, ...values: any[] ): any[]; } //_.sortedIndexOf interface LoDashStatic { /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([1, 1, 2, 2], 2); * // => 2 */ sortedIndexOf<T>( array: List<T>, value: T ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sortedIndexOf */ sortedIndexOf( value: T ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sortedIndexOf */ sortedIndexOf<TValue>( value: TValue ): number; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sortedIndexOf */ sortedIndexOf( value: T ): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sortedIndexOf */ sortedIndexOf<TValue>( value: TValue ): LoDashExplicitWrapper<number>; } //_.initial interface LoDashStatic { /** * Gets all but the last element of array. * * @param array The array to query. * @return Returns the slice of array. */ initial<T>(array: List<T>): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.initial */ initial(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.initial */ initial<T>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.initial */ initial(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.initial */ initial<T>(): LoDashExplicitArrayWrapper<T>; } //_.intersection interface LoDashStatic { /** * Creates an array of unique values that are included in all of the provided arrays using SameValueZero for * equality comparisons. * * @param arrays The arrays to inspect. * @return Returns the new array of shared values. */ intersection<T>(...arrays: (T[]|List<T>)[]): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.intersection */ intersection<TResult>(...arrays: (TResult[]|List<TResult>)[]): LoDashImplicitArrayWrapper<TResult>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.intersection */ intersection<TResult>(...arrays: (TResult[]|List<TResult>)[]): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.intersection */ intersection<TResult>(...arrays: (TResult[]|List<TResult>)[]): LoDashExplicitArrayWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.intersection */ intersection<TResult>(...arrays: (TResult[]|List<TResult>)[]): LoDashExplicitArrayWrapper<TResult>; } //_.last interface LoDashStatic { /** * Gets the last element of array. * * @param array The array to query. * @return Returns the last element of array. */ last<T>(array: List<T>): T; } interface LoDashImplicitWrapper<T> { /** * @see _.last */ last(): string; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.last */ last(): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.last */ last<T>(): T; } interface LoDashExplicitWrapper<T> { /** * @see _.last */ last(): LoDashExplicitWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.last */ last<T>(): T; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.last */ last<T>(): T; } //_.lastIndexOf interface LoDashStatic { /** * This method is like _.indexOf except that it iterates over elements of array from right to left. * * @param array The array to search. * @param value The value to search for. * @param fromIndex The index to search from or true to perform a binary search on a sorted array. * @return Returns the index of the matched value, else -1. */ lastIndexOf<T>( array: List<T>, value: T, fromIndex?: boolean|number ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.lastIndexOf */ lastIndexOf( value: T, fromIndex?: boolean|number ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.lastIndexOf */ lastIndexOf<TResult>( value: TResult, fromIndex?: boolean|number ): number; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.lastIndexOf */ lastIndexOf( value: T, fromIndex?: boolean|number ): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.lastIndexOf */ lastIndexOf<TResult>( value: TResult, fromIndex?: boolean|number ): LoDashExplicitWrapper<number>; } //_.pull interface LoDashStatic { /** * Removes all provided values from array using SameValueZero for equality comparisons. * * Note: Unlike _.without, this method mutates array. * * @param array The array to modify. * @param values The values to remove. * @return Returns array. */ pull<T>( array: T[], ...values: T[] ): T[]; /** * @see _.pull */ pull<T>( array: List<T>, ...values: T[] ): List<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.pull */ pull(...values: T[]): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.pull */ pull<TValue>(...values: TValue[]): LoDashImplicitObjectWrapper<List<TValue>>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.pull */ pull(...values: T[]): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.pull */ pull<TValue>(...values: TValue[]): LoDashExplicitObjectWrapper<List<TValue>>; } //_.pullAt interface LoDashStatic { /** * Removes elements from array corresponding to the given indexes and returns an array of the removed elements. * Indexes may be specified as an array of indexes or as individual arguments. * * Note: Unlike _.at, this method mutates array. * * @param array The array to modify. * @param indexes The indexes of elements to remove, specified as individual indexes or arrays of indexes. * @return Returns the new array of removed elements. */ pullAt<T>( array: List<T>, ...indexes: (number|number[])[] ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.pullAt */ pullAt(...indexes: (number|number[])[]): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.pullAt */ pullAt<T>(...indexes: (number|number[])[]): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.pullAt */ pullAt(...indexes: (number|number[])[]): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.pullAt */ pullAt<T>(...indexes: (number|number[])[]): LoDashExplicitArrayWrapper<T>; } //_.remove interface LoDashStatic { /** * Removes all elements from array that predicate returns truthy for and returns an array of the removed * elements. The predicate is bound to thisArg and invoked with three arguments: (value, index, array). * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * Note: Unlike _.filter, this method mutates array. * * @param array The array to modify. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the new array of removed elements. */ remove<T>( array: List<T>, predicate?: ListIterator<T, boolean> ): T[]; /** * @see _.remove */ remove<T>( array: List<T>, predicate?: string ): T[]; /** * @see _.remove */ remove<W, T>( array: List<T>, predicate?: W ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.remove */ remove( predicate?: ListIterator<T, boolean> ): LoDashImplicitArrayWrapper<T>; /** * @see _.remove */ remove( predicate?: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.remove */ remove<W>( predicate?: W ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.remove */ remove<TResult>( predicate?: ListIterator<TResult, boolean> ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.remove */ remove<TResult>( predicate?: string ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.remove */ remove<W, TResult>( predicate?: W ): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.remove */ remove( predicate?: ListIterator<T, boolean> ): LoDashExplicitArrayWrapper<T>; /** * @see _.remove */ remove( predicate?: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.remove */ remove<W>( predicate?: W ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.remove */ remove<TResult>( predicate?: ListIterator<TResult, boolean> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.remove */ remove<TResult>( predicate?: string ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.remove */ remove<W, TResult>( predicate?: W ): LoDashExplicitArrayWrapper<TResult>; } //_.tail interface LoDashStatic { /** * Gets all but the first element of array. * * @alias _.tail * * @param array The array to query. * @return Returns the slice of array. */ tail<T>(array: List<T>): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.tail */ tail(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.tail */ tail<T>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.tail */ tail(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.tail */ tail<T>(): LoDashExplicitArrayWrapper<T>; } //_.slice interface LoDashStatic { /** * Creates a slice of array from start up to, but not including, end. * * @param array The array to slice. * @param start The start position. * @param end The end position. * @return Returns the slice of array. */ slice<T>( array: T[], start?: number, end?: number ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.slice */ slice( start?: number, end?: number ): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.slice */ slice( start?: number, end?: number ): LoDashExplicitArrayWrapper<T>; } //_.sortedIndex interface LoDashStatic { /** * Uses a binary search to determine the lowest index at which `value` should * be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 * * _.sortedIndex([4, 5], 4); * // => 0 */ sortedIndex<T, TSort>( array: List<T>, value: T ): number; /** * @see _.sortedIndex */ sortedIndex<T>( array: List<T>, value: T ): number; /** * @see _.sortedIndex */ sortedIndex<T>( array: List<T>, value: T ): number; /** * @see _.sortedIndex */ sortedIndex<W, T>( array: List<T>, value: T ): number; /** * @see _.sortedIndex */ sortedIndex<T>( array: List<T>, value: T ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.sortedIndex */ sortedIndex<TSort>( value: string ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sortedIndex */ sortedIndex<TSort>( value: T ): number; /** * @see _.sortedIndex */ sortedIndex( value: T ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sortedIndex */ sortedIndex<T, TSort>( value: T ): number; /** * @see _.sortedIndex */ sortedIndex<T>( value: T ): number; /** * @see _.sortedIndex */ sortedIndex<W, T>( value: T ): number; } interface LoDashExplicitWrapper<T> { /** * @see _.sortedIndex */ sortedIndex<TSort>( value: string ): LoDashExplicitWrapper<number>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sortedIndex */ sortedIndex<TSort>( value: T ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndex */ sortedIndex( value: T ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndex */ sortedIndex<W>( value: T ): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sortedIndex */ sortedIndex<T, TSort>( value: T ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndex */ sortedIndex<T>( value: T ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndex */ sortedIndex<W, T>( value: T ): LoDashExplicitWrapper<number>; } //_.sortedIndexBy interface LoDashStatic { /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted into `array`. * @example * * var dict = { 'thirty': 30, 'forty': 40, 'fifty': 50 }; * * _.sortedIndexBy(['thirty', 'fifty'], 'forty', _.propertyOf(dict)); * // => 1 * * // using the `_.property` iteratee shorthand * _.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); * // => 0 */ sortedIndexBy<T, TSort>( array: List<T>, value: T, iteratee: (x: T) => TSort ): number; /** * @see _.sortedIndexBy */ sortedIndexBy<T>( array: List<T>, value: T, iteratee: (x: T) => any ): number; /** * @see _.sortedIndexBy */ sortedIndexBy<T>( array: List<T>, value: T, iteratee: string ): number; /** * @see _.sortedIndexBy */ sortedIndexBy<W, T>( array: List<T>, value: T, iteratee: W ): number; /** * @see _.sortedIndexBy */ sortedIndexBy<T>( array: List<T>, value: T, iteratee: Object ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.sortedIndexBy */ sortedIndexBy<TSort>( value: string, iteratee: (x: string) => TSort ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sortedIndexBy */ sortedIndexBy<TSort>( value: T, iteratee: (x: T) => TSort ): number; /** * @see _.sortedIndexBy */ sortedIndexBy( value: T, iteratee: string ): number; /** * @see _.sortedIndexBy */ sortedIndexBy<W>( value: T, iteratee: W ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sortedIndexBy */ sortedIndexBy<T, TSort>( value: T, iteratee: (x: T) => TSort ): number; /** * @see _.sortedIndexBy */ sortedIndexBy<T>( value: T, iteratee: (x: T) => any ): number; /** * @see _.sortedIndexBy */ sortedIndexBy<T>( value: T, iteratee: string ): number; /** * @see _.sortedIndexBy */ sortedIndexBy<W, T>( value: T, iteratee: W ): number; /** * @see _.sortedIndexBy */ sortedIndexBy<T>( value: T, iteratee: Object ): number; } interface LoDashExplicitWrapper<T> { /** * @see _.sortedIndexBy */ sortedIndexBy<TSort>( value: string, iteratee: (x: string) => TSort ): LoDashExplicitWrapper<number>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sortedIndexBy */ sortedIndexBy<TSort>( value: T, iteratee: (x: T) => TSort ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndexBy */ sortedIndexBy( value: T, iteratee: string ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndexBy */ sortedIndexBy<W>( value: T, iteratee: W ): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sortedIndexBy */ sortedIndexBy<T, TSort>( value: T, iteratee: (x: T) => TSort ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndexBy */ sortedIndexBy<T>( value: T, iteratee: (x: T) => any ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndexBy */ sortedIndexBy<T>( value: T, iteratee: string ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndexBy */ sortedIndexBy<W, T>( value: T, iteratee: W ): LoDashExplicitWrapper<number>; /** * @see _.sortedIndexBy */ sortedIndexBy<T>( value: T, iteratee: Object ): LoDashExplicitWrapper<number>; } //_.sortedLastIndex interface LoDashStatic { /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted into `array`. * @example * * _.sortedLastIndex([4, 5], 4); * // => 1 */ sortedLastIndex<T, TSort>( array: List<T>, value: T ): number; /** * @see _.sortedLastIndex */ sortedLastIndex<T>( array: List<T>, value: T ): number; /** * @see _.sortedLastIndex */ sortedLastIndex<T>( array: List<T>, value: T ): number; /** * @see _.sortedLastIndex */ sortedLastIndex<W, T>( array: List<T>, value: T ): number; /** * @see _.sortedLastIndex */ sortedLastIndex<T>( array: List<T>, value: T ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.sortedLastIndex */ sortedLastIndex<TSort>( value: string ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sortedLastIndex */ sortedLastIndex<TSort>( value: T ): number; /** * @see _.sortedLastIndex */ sortedLastIndex( value: T ): number; /** * @see _.sortedLastIndex */ sortedLastIndex<W>( value: T ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sortedLastIndex */ sortedLastIndex<T, TSort>( value: T ): number; /** * @see _.sortedLastIndex */ sortedLastIndex<T>( value: T ): number; /** * @see _.sortedLastIndex */ sortedLastIndex<W, T>( value: T ): number; } interface LoDashExplicitWrapper<T> { /** * @see _.sortedLastIndex */ sortedLastIndex<TSort>( value: string ): LoDashExplicitWrapper<number>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sortedLastIndex */ sortedLastIndex<TSort>( value: T ): LoDashExplicitWrapper<number>; /** * @see _.sortedLastIndex */ sortedLastIndex( value: T ): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sortedLastIndex */ sortedLastIndex<T, TSort>( value: T ): LoDashExplicitWrapper<number>; /** * @see _.sortedLastIndex */ sortedLastIndex<T>( value: T ): LoDashExplicitWrapper<number>; /** * @see _.sortedLastIndex */ sortedLastIndex<W, T>( value: T ): LoDashExplicitWrapper<number>; } //_.sortedLastIndexBy interface LoDashStatic { /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted into `array`. * @example * * // using the `_.property` iteratee shorthand * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); * // => 1 */ sortedLastIndexBy<T, TSort>( array: List<T>, value: T, iteratee: (x: T) => TSort ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T>( array: List<T>, value: T, iteratee: (x: T) => any ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T>( array: List<T>, value: T, iteratee: string ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<W, T>( array: List<T>, value: T, iteratee: W ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T>( array: List<T>, value: T, iteratee: Object ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<TSort>( value: string, iteratee: (x: string) => TSort ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<TSort>( value: T, iteratee: (x: T) => TSort ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy( value: T, iteratee: string ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<W>( value: T, iteratee: W ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T, TSort>( value: T, iteratee: (x: T) => TSort ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T>( value: T, iteratee: (x: T) => any ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T>( value: T, iteratee: string ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<W, T>( value: T, iteratee: W ): number; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T>( value: T, iteratee: Object ): number; } interface LoDashExplicitWrapper<T> { /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<TSort>( value: string, iteratee: (x: string) => TSort ): LoDashExplicitWrapper<number>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<TSort>( value: T, iteratee: (x: T) => TSort ): LoDashExplicitWrapper<number>; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy( value: T, iteratee: string ): LoDashExplicitWrapper<number>; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<W>( value: T, iteratee: W ): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T, TSort>( value: T, iteratee: (x: T) => TSort ): LoDashExplicitWrapper<number>; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T>( value: T, iteratee: (x: T) => any ): LoDashExplicitWrapper<number>; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T>( value: T, iteratee: string ): LoDashExplicitWrapper<number>; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<W, T>( value: T, iteratee: W ): LoDashExplicitWrapper<number>; /** * @see _.sortedLastIndexBy */ sortedLastIndexBy<T>( value: T, iteratee: Object ): LoDashExplicitWrapper<number>; } //_.sortedLastIndexOf DUMMY interface LoDashStatic { /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([1, 1, 2, 2], 2); * // => 3 */ sortedLastIndexOf( array: any[]|List<any>, ...values: any[] ): any[]; } //_.tail interface LoDashStatic { /** * @see _.rest */ tail<T>(array: List<T>): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.rest */ tail(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.rest */ tail<T>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.rest */ tail(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.rest */ tail<T>(): LoDashExplicitArrayWrapper<T>; } //_.take interface LoDashStatic { /** * Creates a slice of array with n elements taken from the beginning. * * @param array The array to query. * @param n The number of elements to take. * @return Returns the slice of array. */ take<T>( array: List<T>, n?: number ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.take */ take(n?: number): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.take */ take<TResult>(n?: number): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.take */ take(n?: number): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.take */ take<TResult>(n?: number): LoDashExplicitArrayWrapper<TResult>; } //_.takeRight interface LoDashStatic { /** * Creates a slice of array with n elements taken from the end. * * @param array The array to query. * @param n The number of elements to take. * @return Returns the slice of array. */ takeRight<T>( array: List<T>, n?: number ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.takeRight */ takeRight(n?: number): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.takeRight */ takeRight<TResult>(n?: number): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.takeRight */ takeRight(n?: number): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.takeRight */ takeRight<TResult>(n?: number): LoDashExplicitArrayWrapper<TResult>; } //_.takeRightWhile interface LoDashStatic { /** * Creates a slice of array with elements taken from the end. Elements are taken until predicate returns * falsey. The predicate is bound to thisArg and invoked with three arguments: (value, index, array). * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param array The array to query. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the slice of array. */ takeRightWhile<TValue>( array: List<TValue>, predicate?: ListIterator<TValue, boolean> ): TValue[]; /** * @see _.takeRightWhile */ takeRightWhile<TValue>( array: List<TValue>, predicate?: string ): TValue[]; /** * @see _.takeRightWhile */ takeRightWhile<TWhere, TValue>( array: List<TValue>, predicate?: TWhere ): TValue[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.takeRightWhile */ takeRightWhile( predicate?: ListIterator<T, boolean> ): LoDashImplicitArrayWrapper<T>; /** * @see _.takeRightWhile */ takeRightWhile( predicate?: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.takeRightWhile */ takeRightWhile<TWhere>( predicate?: TWhere ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.takeRightWhile */ takeRightWhile<TValue>( predicate?: ListIterator<TValue, boolean> ): LoDashImplicitArrayWrapper<TValue>; /** * @see _.takeRightWhile */ takeRightWhile<TValue>( predicate?: string ): LoDashImplicitArrayWrapper<TValue>; /** * @see _.takeRightWhile */ takeRightWhile<TWhere, TValue>( predicate?: TWhere ): LoDashImplicitArrayWrapper<TValue>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.takeRightWhile */ takeRightWhile( predicate?: ListIterator<T, boolean> ): LoDashExplicitArrayWrapper<T>; /** * @see _.takeRightWhile */ takeRightWhile( predicate?: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.takeRightWhile */ takeRightWhile<TWhere>( predicate?: TWhere ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.takeRightWhile */ takeRightWhile<TValue>( predicate?: ListIterator<TValue, boolean> ): LoDashExplicitArrayWrapper<TValue>; /** * @see _.takeRightWhile */ takeRightWhile<TValue>( predicate?: string ): LoDashExplicitArrayWrapper<TValue>; /** * @see _.takeRightWhile */ takeRightWhile<TWhere, TValue>( predicate?: TWhere ): LoDashExplicitArrayWrapper<TValue>; } //_.takeWhile interface LoDashStatic { /** * Creates a slice of array with elements taken from the beginning. Elements are taken until predicate returns * falsey. The predicate is bound to thisArg and invoked with three arguments: (value, index, array). * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param array The array to query. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the slice of array. */ takeWhile<TValue>( array: List<TValue>, predicate?: ListIterator<TValue, boolean> ): TValue[]; /** * @see _.takeWhile */ takeWhile<TValue>( array: List<TValue>, predicate?: string ): TValue[]; /** * @see _.takeWhile */ takeWhile<TWhere, TValue>( array: List<TValue>, predicate?: TWhere ): TValue[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.takeWhile */ takeWhile( predicate?: ListIterator<T, boolean> ): LoDashImplicitArrayWrapper<T>; /** * @see _.takeWhile */ takeWhile( predicate?: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.takeWhile */ takeWhile<TWhere>( predicate?: TWhere ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.takeWhile */ takeWhile<TValue>( predicate?: ListIterator<TValue, boolean> ): LoDashImplicitArrayWrapper<TValue>; /** * @see _.takeWhile */ takeWhile<TValue>( predicate?: string ): LoDashImplicitArrayWrapper<TValue>; /** * @see _.takeWhile */ takeWhile<TWhere, TValue>( predicate?: TWhere ): LoDashImplicitArrayWrapper<TValue>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.takeWhile */ takeWhile( predicate?: ListIterator<T, boolean> ): LoDashExplicitArrayWrapper<T>; /** * @see _.takeWhile */ takeWhile( predicate?: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.takeWhile */ takeWhile<TWhere>( predicate?: TWhere ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.takeWhile */ takeWhile<TValue>( predicate?: ListIterator<TValue, boolean> ): LoDashExplicitArrayWrapper<TValue>; /** * @see _.takeWhile */ takeWhile<TValue>( predicate?: string ): LoDashExplicitArrayWrapper<TValue>; /** * @see _.takeWhile */ takeWhile<TWhere, TValue>( predicate?: TWhere ): LoDashExplicitArrayWrapper<TValue>; } //_.union interface LoDashStatic { /** * Creates an array of unique values, in order, from all of the provided arrays using SameValueZero for * equality comparisons. * * @param arrays The arrays to inspect. * @return Returns the new array of combined values. */ union<T>(...arrays: List<T>[]): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.union */ union(...arrays: List<T>[]): LoDashImplicitArrayWrapper<T>; /** * @see _.union */ union<T>(...arrays: List<T>[]): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.union */ union<T>(...arrays: List<T>[]): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.union */ union(...arrays: List<T>[]): LoDashExplicitArrayWrapper<T>; /** * @see _.union */ union<T>(...arrays: List<T>[]): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.union */ union<T>(...arrays: List<T>[]): LoDashExplicitArrayWrapper<T>; } //_.unionBy interface LoDashStatic { /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by which * uniqueness is computed. The iteratee is invoked with one argument: (value). * * @param arrays The arrays to inspect. * @param iteratee The iteratee invoked per element. * @return Returns the new array of combined values. */ unionBy<T>( arrays: T[]|List<T>, iteratee?: (value: T) => any ): T[]; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.unionBy */ unionBy<T>( arrays1: T[]|List<T>, arrays2: T[]|List<T>, iteratee?: (value: T) => any ): T[]; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays1: T[]|List<T>, arrays2: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.unionBy */ unionBy<T>( arrays1: T[]|List<T>, arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: (value: T) => any ): T[]; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays1: T[]|List<T>, arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.unionBy */ unionBy<T>( arrays1: T[]|List<T>, arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: (value: T) => any ): T[]; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays1: T[]|List<T>, arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.unionBy */ unionBy<T>( arrays1: T[]|List<T>, arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: (value: T) => any ): T[]; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays1: T[]|List<T>, arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: W ): T[]; /** * @see _.unionBy */ unionBy<T>( arrays: T[]|List<T>, ...iteratee: any[] ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.unionBy */ unionBy<T>( iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( ...iteratee: any[] ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.unionBy */ unionBy<T>( iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: (value: T) => any ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: W ): LoDashImplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( ...iteratee: any[] ): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.unionBy */ unionBy<T>( iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( ...iteratee: any[] ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.unionBy */ unionBy<T>( iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: (value: T) => any ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T, W extends Object>( arrays2: T[]|List<T>, arrays3: T[]|List<T>, arrays4: T[]|List<T>, arrays5: T[]|List<T>, iteratee?: W ): LoDashExplicitArrayWrapper<T>; /** * @see _.unionBy */ unionBy<T>( ...iteratee: any[] ): LoDashExplicitArrayWrapper<T>; } //_.uniq interface LoDashStatic { /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. * * @static * @memberOf _ * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ uniq<T>( array: List<T> ): T[]; /** * @see _.uniq */ uniq<T, TSort>( array: List<T> ): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.uniq */ uniq<TSort>(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.uniq */ uniq<TSort>(): LoDashImplicitArrayWrapper<T>; /** * @see _.uniq */ uniq(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { uniq<T>(): LoDashImplicitArrayWrapper<T>; /** * @see _.uniq */ uniq<T, TSort>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.uniq */ uniq<TSort>(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.uniq */ uniq<TSort>(): LoDashExplicitArrayWrapper<T>; /** * @see _.uniq */ uniq(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.uniq */ uniq<T>(): LoDashExplicitArrayWrapper<T>; /** * @see _.uniq */ uniq<T, TSort>(): LoDashExplicitArrayWrapper<T>; } //_.uniqBy interface LoDashStatic { /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Array * @param {Array} array The array to inspect. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // using the `_.property` iteratee shorthand * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ uniqBy<T>( array: List<T>, iteratee: ListIterator<T, any> ): T[]; /** * @see _.uniqBy */ uniqBy<T, TSort>( array: List<T>, iteratee: ListIterator<T, TSort> ): T[]; /** * @see _.uniqBy */ uniqBy<T>( array: List<T>, iteratee: string ): T[]; /** * @see _.uniqBy */ uniqBy<T>( array: List<T>, iteratee: Object ): T[]; /** * @see _.uniqBy */ uniqBy<TWhere extends {}, T>( array: List<T>, iteratee: TWhere ): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.uniqBy */ uniqBy<TSort>( iteratee: ListIterator<T, TSort> ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.uniqBy */ uniqBy<TSort>( iteratee: ListIterator<T, TSort> ): LoDashImplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy( iteratee: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<TWhere extends {}>( iteratee: TWhere ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.uniqBy */ uniqBy<T>( iteratee: ListIterator<T, any> ): LoDashImplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<T, TSort>( iteratee: ListIterator<T, TSort> ): LoDashImplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<T>( iteratee: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<T>( iteratee: Object ): LoDashImplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<TWhere extends {}, T>( iteratee: TWhere ): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.uniqBy */ uniqBy<TSort>( iteratee: ListIterator<T, TSort> ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.uniqBy */ uniqBy<TSort>( iteratee: ListIterator<T, TSort> ): LoDashExplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy( iteratee: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<TWhere extends {}>( iteratee: TWhere ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.uniqBy */ uniqBy<T>( iteratee: ListIterator<T, any> ): LoDashExplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<T, TSort>( iteratee: ListIterator<T, TSort> ): LoDashExplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<T>( iteratee: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<T>( iteratee: Object ): LoDashExplicitArrayWrapper<T>; /** * @see _.uniqBy */ uniqBy<TWhere extends {}, T>( iteratee: TWhere ): LoDashExplicitArrayWrapper<T>; } //_.sortedUniq interface LoDashStatic { /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ sortedUniq<T>( array: List<T> ): T[]; /** * @see _.sortedUniq */ sortedUniq<T, TSort>( array: List<T> ): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.sortedUniq */ sortedUniq<TSort>(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sortedUniq */ sortedUniq<TSort>(): LoDashImplicitArrayWrapper<T>; /** * @see _.sortedUniq */ sortedUniq(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { sortedUniq<T>(): LoDashImplicitArrayWrapper<T>; /** * @see _.sortedUniq */ sortedUniq<T, TSort>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.sortedUniq */ sortedUniq<TSort>(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sortedUniq */ sortedUniq<TSort>(): LoDashExplicitArrayWrapper<T>; /** * @see _.sortedUniq */ sortedUniq(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sortedUniq */ sortedUniq<T>(): LoDashExplicitArrayWrapper<T>; /** * @see _.sortedUniq */ sortedUniq<T, TSort>(): LoDashExplicitArrayWrapper<T>; } //_.sortedUniqBy interface LoDashStatic { /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.2] */ sortedUniqBy<T>( array: List<T>, iteratee: ListIterator<T, any> ): T[]; /** * @see _.sortedUniqBy */ sortedUniqBy<T, TSort>( array: List<T>, iteratee: ListIterator<T, TSort> ): T[]; /** * @see _.sortedUniqBy */ sortedUniqBy<T>( array: List<T>, iteratee: string ): T[]; /** * @see _.sortedUniqBy */ sortedUniqBy<T>( array: List<T>, iteratee: Object ): T[]; /** * @see _.sortedUniqBy */ sortedUniqBy<TWhere extends {}, T>( array: List<T>, iteratee: TWhere ): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.sortedUniqBy */ sortedUniqBy<TSort>( iteratee: ListIterator<T, TSort> ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sortedUniqBy */ sortedUniqBy<TSort>( iteratee: ListIterator<T, TSort> ): LoDashImplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy( iteratee: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<TWhere extends {}>( iteratee: TWhere ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sortedUniqBy */ sortedUniqBy<T>( iteratee: ListIterator<T, any> ): LoDashImplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<T, TSort>( iteratee: ListIterator<T, TSort> ): LoDashImplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<T>( iteratee: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<T>( iteratee: Object ): LoDashImplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<TWhere extends {}, T>( iteratee: TWhere ): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.sortedUniqBy */ sortedUniqBy<TSort>( iteratee: ListIterator<T, TSort> ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sortedUniqBy */ sortedUniqBy<TSort>( iteratee: ListIterator<T, TSort> ): LoDashExplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy( iteratee: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<TWhere extends {}>( iteratee: TWhere ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sortedUniqBy */ sortedUniqBy<T>( iteratee: ListIterator<T, any> ): LoDashExplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<T, TSort>( iteratee: ListIterator<T, TSort> ): LoDashExplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<T>( iteratee: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<T>( iteratee: Object ): LoDashExplicitArrayWrapper<T>; /** * @see _.sortedUniqBy */ sortedUniqBy<TWhere extends {}, T>( iteratee: TWhere ): LoDashExplicitArrayWrapper<T>; } //_.unionWith DUMMY interface LoDashStatic { /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ unionWith( array: any[]|List<any>, ...values: any[] ): any[]; } //_.uniqWith DUMMY interface LoDashStatic { /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The comparator is invoked with * two arguments: (arrVal, othVal). * * @static * @memberOf _ * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ uniqWith( array: any[]|List<any>, ...values: any[] ): any[]; } //_.unzip interface LoDashStatic { /** * This method is like _.zip except that it accepts an array of grouped elements and creates an array * regrouping the elements to their pre-zip configuration. * * @param array The array of grouped elements to process. * @return Returns the new array of regrouped elements. */ unzip<T>(array: List<List<T>>): T[][]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.unzip */ unzip<T>(): LoDashImplicitArrayWrapper<T[]>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.unzip */ unzip<T>(): LoDashImplicitArrayWrapper<T[]>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.unzip */ unzip<T>(): LoDashExplicitArrayWrapper<T[]>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.unzip */ unzip<T>(): LoDashExplicitArrayWrapper<T[]>; } //_.unzipWith interface LoDashStatic { /** * This method is like _.unzip except that it accepts an iteratee to specify how regrouped values should be * combined. The iteratee is bound to thisArg and invoked with four arguments: (accumulator, value, index, * group). * * @param array The array of grouped elements to process. * @param iteratee The function to combine regrouped values. * @param thisArg The this binding of iteratee. * @return Returns the new array of regrouped elements. */ unzipWith<TArray, TResult>( array: List<List<TArray>>, iteratee?: MemoIterator<TArray, TResult> ): TResult[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.unzipWith */ unzipWith<TArr, TResult>( iteratee?: MemoIterator<TArr, TResult> ): LoDashImplicitArrayWrapper<TResult>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.unzipWith */ unzipWith<TArr, TResult>( iteratee?: MemoIterator<TArr, TResult> ): LoDashImplicitArrayWrapper<TResult>; } //_.without interface LoDashStatic { /** * Creates an array excluding all provided values using SameValueZero for equality comparisons. * * @param array The array to filter. * @param values The values to exclude. * @return Returns the new array of filtered values. */ without<T>( array: List<T>, ...values: T[] ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.without */ without(...values: T[]): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.without */ without<T>(...values: T[]): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.without */ without(...values: T[]): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.without */ without<T>(...values: T[]): LoDashExplicitArrayWrapper<T>; } //_.xor interface LoDashStatic { /** * Creates an array of unique values that is the symmetric difference of the provided arrays. * * @param arrays The arrays to inspect. * @return Returns the new array of values. */ xor<T>(...arrays: List<T>[]): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.xor */ xor(...arrays: List<T>[]): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.xor */ xor<T>(...arrays: List<T>[]): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.xor */ xor(...arrays: List<T>[]): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.xor */ xor<T>(...arrays: List<T>[]): LoDashExplicitArrayWrapper<T>; } //_.xorBy DUMMY interface LoDashStatic { /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by which * uniqueness is computed. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of values. * @example * * _.xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); * // => [1.2, 4.3] * * // using the `_.property` iteratee shorthand * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ xorBy( array: any[]|List<any>, ...values: any[] ): any[]; } //_.xorWith DUMMY interface LoDashStatic { /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The comparator is invoked with * two arguments: (arrVal, othVal). * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ xorWith( array: any[]|List<any>, ...values: any[] ): any[]; } //_.zip interface LoDashStatic { /** * Creates an array of grouped elements, the first of which contains the first elements of the given arrays, * the second of which contains the second elements of the given arrays, and so on. * * @param arrays The arrays to process. * @return Returns the new array of grouped elements. */ zip<T>(...arrays: List<T>[]): T[][]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.zip */ zip<T>(...arrays: List<T>[]): _.LoDashImplicitArrayWrapper<T[]>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.zip */ zip<T>(...arrays: List<T>[]): _.LoDashImplicitArrayWrapper<T[]>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.zip */ zip<T>(...arrays: List<T>[]): _.LoDashExplicitArrayWrapper<T[]>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.zip */ zip<T>(...arrays: List<T>[]): _.LoDashExplicitArrayWrapper<T[]>; } //_.zipObject interface LoDashStatic { /** * The inverse of _.pairs; this method returns an object composed from arrays of property names and values. * Provide either a single two dimensional array, e.g. [[key1, value1], [key2, value2]] or two arrays, one of * property names and one of corresponding values. * * @param props The property names. * @param values The property values. * @return Returns the new object. */ zipObject<TValues, TResult extends {}>( props: List<StringRepresentable>|List<List<any>>, values?: List<TValues> ): TResult; /** * @see _.zipObject */ zipObject<TResult extends {}>( props: List<StringRepresentable>|List<List<any>>, values?: List<any> ): TResult; /** * @see _.zipObject */ zipObject( props: List<StringRepresentable>|List<List<any>>, values?: List<any> ): _.Dictionary<any>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.zipObject */ zipObject<TValues, TResult extends {}>( values?: List<TValues> ): _.LoDashImplicitObjectWrapper<TResult>; /** * @see _.zipObject */ zipObject<TResult extends {}>( values?: List<any> ): _.LoDashImplicitObjectWrapper<TResult>; /** * @see _.zipObject */ zipObject( values?: List<any> ): _.LoDashImplicitObjectWrapper<_.Dictionary<any>>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.zipObject */ zipObject<TValues, TResult extends {}>( values?: List<TValues> ): _.LoDashImplicitObjectWrapper<TResult>; /** * @see _.zipObject */ zipObject<TResult extends {}>( values?: List<any> ): _.LoDashImplicitObjectWrapper<TResult>; /** * @see _.zipObject */ zipObject( values?: List<any> ): _.LoDashImplicitObjectWrapper<_.Dictionary<any>>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.zipObject */ zipObject<TValues, TResult extends {}>( values?: List<TValues> ): _.LoDashExplicitObjectWrapper<TResult>; /** * @see _.zipObject */ zipObject<TResult extends {}>( values?: List<any> ): _.LoDashExplicitObjectWrapper<TResult>; /** * @see _.zipObject */ zipObject( values?: List<any> ): _.LoDashExplicitObjectWrapper<_.Dictionary<any>>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.zipObject */ zipObject<TValues, TResult extends {}>( values?: List<TValues> ): _.LoDashExplicitObjectWrapper<TResult>; /** * @see _.zipObject */ zipObject<TResult extends {}>( values?: List<any> ): _.LoDashExplicitObjectWrapper<TResult>; /** * @see _.zipObject */ zipObject( values?: List<any> ): _.LoDashExplicitObjectWrapper<_.Dictionary<any>>; } //_.zipWith interface LoDashStatic { /** * This method is like _.zip except that it accepts an iteratee to specify how grouped values should be * combined. The iteratee is bound to thisArg and invoked with four arguments: (accumulator, value, index, * group). * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee] The function to combine grouped values. * @param {*} [thisArg] The `this` binding of `iteratee`. * @return Returns the new array of grouped elements. */ zipWith<TResult>(...args: any[]): TResult[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.zipWith */ zipWith<TResult>(...args: any[]): LoDashImplicitArrayWrapper<TResult>; } /********* * Chain * *********/ //_.chain interface LoDashStatic { /** * Creates a lodash object that wraps value with explicit method chaining enabled. * * @param value The value to wrap. * @return Returns the new lodash wrapper instance. */ chain(value: number): LoDashExplicitWrapper<number>; chain(value: string): LoDashExplicitWrapper<string>; chain(value: boolean): LoDashExplicitWrapper<boolean>; chain<T>(value: T[]): LoDashExplicitArrayWrapper<T>; chain<T extends {}>(value: T): LoDashExplicitObjectWrapper<T>; chain(value: any): LoDashExplicitWrapper<any>; } interface LoDashImplicitWrapper<T> { /** * @see _.chain */ chain(): LoDashExplicitWrapper<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.chain */ chain(): LoDashExplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.chain */ chain(): LoDashExplicitObjectWrapper<T>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.chain */ chain(): TWrapper; } //_.tap interface LoDashStatic { /** * This method invokes interceptor and returns value. The interceptor is bound to thisArg and invoked with one * argument; (value). The purpose of this method is to "tap into" a method chain in order to perform operations * on intermediate results within the chain. * * @param value The value to provide to interceptor. * @param interceptor The function to invoke. * @parem thisArg The this binding of interceptor. * @return Returns value. **/ tap<T>( value: T, interceptor: (value: T) => void ): T; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.tap */ tap( interceptor: (value: T) => void ): TWrapper; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.tap */ tap( interceptor: (value: T) => void ): TWrapper; } //_.thru interface LoDashStatic { /** * This method is like _.tap except that it returns the result of interceptor. * * @param value The value to provide to interceptor. * @param interceptor The function to invoke. * @param thisArg The this binding of interceptor. * @return Returns the result of interceptor. */ thru<T, TResult>( value: T, interceptor: (value: T) => TResult ): TResult; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.thru */ thru<TResult extends number>( interceptor: (value: T) => TResult): LoDashImplicitWrapper<TResult>; /** * @see _.thru */ thru<TResult extends string>( interceptor: (value: T) => TResult): LoDashImplicitWrapper<TResult>; /** * @see _.thru */ thru<TResult extends boolean>( interceptor: (value: T) => TResult): LoDashImplicitWrapper<TResult>; /** * @see _.thru */ thru<TResult extends {}>( interceptor: (value: T) => TResult): LoDashImplicitObjectWrapper<TResult>; /** * @see _.thru */ thru<TResult>( interceptor: (value: T) => TResult[]): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.thru */ thru<TResult extends number>( interceptor: (value: T) => TResult ): LoDashExplicitWrapper<TResult>; /** * @see _.thru */ thru<TResult extends string>( interceptor: (value: T) => TResult ): LoDashExplicitWrapper<TResult>; /** * @see _.thru */ thru<TResult extends boolean>( interceptor: (value: T) => TResult ): LoDashExplicitWrapper<TResult>; /** * @see _.thru */ thru<TResult extends {}>( interceptor: (value: T) => TResult ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.thru */ thru<TResult>( interceptor: (value: T) => TResult[] ): LoDashExplicitArrayWrapper<TResult>; } //_.prototype.commit interface LoDashImplicitWrapperBase<T, TWrapper> { /** * Executes the chained sequence and returns the wrapped result. * * @return Returns the new lodash wrapper instance. */ commit(): TWrapper; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.commit */ commit(): TWrapper; } //_.prototype.concat interface LoDashImplicitWrapperBase<T, TWrapper> { /** * Creates a new array joining a wrapped array with any additional arrays and/or values. * * @param items * @return Returns the new concatenated array. */ concat<TItem>(...items: Array<TItem|Array<TItem>>): LoDashImplicitArrayWrapper<TItem>; /** * @see _.concat */ concat(...items: Array<T|Array<T>>): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.concat */ concat<TItem>(...items: Array<TItem|Array<TItem>>): LoDashExplicitArrayWrapper<TItem>; /** * @see _.concat */ concat(...items: Array<T|Array<T>>): LoDashExplicitArrayWrapper<T>; } //_.prototype.plant interface LoDashImplicitWrapperBase<T, TWrapper> { /** * Creates a clone of the chained sequence planting value as the wrapped value. * @param value The value to plant as the wrapped value. * @return Returns the new lodash wrapper instance. */ plant(value: number): LoDashImplicitWrapper<number>; /** * @see _.plant */ plant(value: string): LoDashImplicitStringWrapper; /** * @see _.plant */ plant(value: boolean): LoDashImplicitWrapper<boolean>; /** * @see _.plant */ plant(value: number[]): LoDashImplicitNumberArrayWrapper; /** * @see _.plant */ plant<T>(value: T[]): LoDashImplicitArrayWrapper<T>; /** * @see _.plant */ plant<T extends {}>(value: T): LoDashImplicitObjectWrapper<T>; /** * @see _.plant */ plant(value: any): LoDashImplicitWrapper<any>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.plant */ plant(value: number): LoDashExplicitWrapper<number>; /** * @see _.plant */ plant(value: string): LoDashExplicitStringWrapper; /** * @see _.plant */ plant(value: boolean): LoDashExplicitWrapper<boolean>; /** * @see _.plant */ plant(value: number[]): LoDashExplicitNumberArrayWrapper; /** * @see _.plant */ plant<T>(value: T[]): LoDashExplicitArrayWrapper<T>; /** * @see _.plant */ plant<T extends {}>(value: T): LoDashExplicitObjectWrapper<T>; /** * @see _.plant */ plant(value: any): LoDashExplicitWrapper<any>; } //_.prototype.reverse interface LoDashImplicitArrayWrapper<T> { /** * Reverses the wrapped array so the first element becomes the last, the second element becomes the second to * last, and so on. * * Note: This method mutates the wrapped array. * * @return Returns the new reversed lodash wrapper instance. */ reverse(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.reverse */ reverse(): LoDashExplicitArrayWrapper<T>; } //_.prototype.toJSON interface LoDashWrapperBase<T, TWrapper> { /** * @see _.value */ toJSON(): T; } //_.prototype.toString interface LoDashWrapperBase<T, TWrapper> { /** * Produces the result of coercing the unwrapped value to a string. * * @return Returns the coerced string value. */ toString(): string; } //_.prototype.value interface LoDashWrapperBase<T, TWrapper> { /** * Executes the chained sequence to extract the unwrapped value. * * @alias _.toJSON, _.valueOf * * @return Returns the resolved unwrapped value. */ value(): T; } //_.valueOf interface LoDashWrapperBase<T, TWrapper> { /** * @see _.value */ valueOf(): T; } /************** * Collection * **************/ //_.at interface LoDashStatic { /** * Creates an array of elements corresponding to the given keys, or indexes, of collection. Keys may be * specified as individual arguments or as arrays of keys. * * @param collection The collection to iterate over. * @param props The property names or indexes of elements to pick, specified individually or in arrays. * @return Returns the new array of picked elements. */ at<T>( collection: List<T>|Dictionary<T>, ...props: (number|string|(number|string)[])[] ): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.at */ at(...props: (number|string|(number|string)[])[]): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.at */ at<T>(...props: (number|string|(number|string)[])[]): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.at */ at(...props: (number|string|(number|string)[])[]): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.at */ at<T>(...props: (number|string|(number|string)[])[]): LoDashExplicitArrayWrapper<T>; } //_.countBy interface LoDashStatic { /** * Creates an object composed of keys generated from the results of running each element of collection through * iteratee. The corresponding value of each key is the number of times the key was returned by iteratee. The * iteratee is bound to thisArg and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for iteratee the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for iteratee the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param collection The collection to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ countBy<T>( collection: List<T>, iteratee?: ListIterator<T, any> ): Dictionary<number>; /** * @see _.countBy */ countBy<T>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<number>; /** * @see _.countBy */ countBy<T>( collection: NumericDictionary<T>, iteratee?: NumericDictionaryIterator<T, any> ): Dictionary<number>; /** * @see _.countBy */ countBy<T>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, iteratee?: string ): Dictionary<number>; /** * @see _.countBy */ countBy<W, T>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, iteratee?: W ): Dictionary<number>; /** * @see _.countBy */ countBy<T>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, iteratee?: Object ): Dictionary<number>; } interface LoDashImplicitWrapper<T> { /** * @see _.countBy */ countBy( iteratee?: ListIterator<T, any> ): LoDashImplicitObjectWrapper<Dictionary<number>>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.countBy */ countBy( iteratee?: ListIterator<T, any> ): LoDashImplicitObjectWrapper<Dictionary<number>>; /** * @see _.countBy */ countBy( iteratee?: string ): LoDashImplicitObjectWrapper<Dictionary<number>>; /** * @see _.countBy */ countBy<W>( iteratee?: W ): LoDashImplicitObjectWrapper<Dictionary<number>>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.countBy */ countBy<T>( iteratee?: ListIterator<T, any>|DictionaryIterator<T, any>|NumericDictionaryIterator<T, any> ): LoDashImplicitObjectWrapper<Dictionary<number>>; /** * @see _.countBy */ countBy( iteratee?: string ): LoDashImplicitObjectWrapper<Dictionary<number>>; /** * @see _.countBy */ countBy<W>( iteratee?: W ): LoDashImplicitObjectWrapper<Dictionary<number>>; } interface LoDashExplicitWrapper<T> { /** * @see _.countBy */ countBy( iteratee?: ListIterator<T, any> ): LoDashExplicitObjectWrapper<Dictionary<number>>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.countBy */ countBy( iteratee?: ListIterator<T, any> ): LoDashExplicitObjectWrapper<Dictionary<number>>; /** * @see _.countBy */ countBy( iteratee?: string ): LoDashExplicitObjectWrapper<Dictionary<number>>; /** * @see _.countBy */ countBy<W>( iteratee?: W ): LoDashExplicitObjectWrapper<Dictionary<number>>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.countBy */ countBy<T>( iteratee?: ListIterator<T, any>|DictionaryIterator<T, any>|NumericDictionaryIterator<T, any> ): LoDashExplicitObjectWrapper<Dictionary<number>>; /** * @see _.countBy */ countBy( iteratee?: string ): LoDashExplicitObjectWrapper<Dictionary<number>>; /** * @see _.countBy */ countBy<W>( iteratee?: W ): LoDashExplicitObjectWrapper<Dictionary<number>>; } //_.each interface LoDashStatic { /** * @see _.forEach */ each<T>( collection: T[], iteratee?: ListIterator<T, any> ): T[]; /** * @see _.forEach */ each<T>( collection: List<T>, iteratee?: ListIterator<T, any> ): List<T>; /** * @see _.forEach */ each<T>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.forEach */ each<T extends {}>( collection: T, iteratee?: ObjectIterator<any, any> ): T; /** * @see _.forEach */ each<T extends {}, TValue>( collection: T, iteratee?: ObjectIterator<TValue, any> ): T; } interface LoDashImplicitWrapper<T> { /** * @see _.forEach */ each( iteratee: ListIterator<string, any> ): LoDashImplicitWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.forEach */ each( iteratee: ListIterator<T, any> ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.forEach */ each<TValue>( iteratee?: ListIterator<TValue, any>|DictionaryIterator<TValue, any> ): LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.forEach */ each( iteratee: ListIterator<string, any> ): LoDashExplicitWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.forEach */ each( iteratee: ListIterator<T, any> ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.forEach */ each<TValue>( iteratee?: ListIterator<TValue, any>|DictionaryIterator<TValue, any> ): LoDashExplicitObjectWrapper<T>; } //_.eachRight interface LoDashStatic { /** * @see _.forEachRight */ eachRight<T>( collection: T[], iteratee?: ListIterator<T, any> ): T[]; /** * @see _.forEachRight */ eachRight<T>( collection: List<T>, iteratee?: ListIterator<T, any> ): List<T>; /** * @see _.forEachRight */ eachRight<T>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.forEachRight */ eachRight<T extends {}>( collection: T, iteratee?: ObjectIterator<any, any> ): T; /** * @see _.forEachRight */ eachRight<T extends {}, TValue>( collection: T, iteratee?: ObjectIterator<TValue, any> ): T; } interface LoDashImplicitWrapper<T> { /** * @see _.forEachRight */ eachRight( iteratee: ListIterator<string, any> ): LoDashImplicitWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.forEachRight */ eachRight( iteratee: ListIterator<T, any> ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.forEachRight */ eachRight<TValue>( iteratee?: ListIterator<TValue, any>|DictionaryIterator<TValue, any> ): LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.forEachRight */ eachRight( iteratee: ListIterator<string, any> ): LoDashExplicitWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.forEachRight */ eachRight( iteratee: ListIterator<T, any> ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.forEachRight */ eachRight<TValue>( iteratee?: ListIterator<TValue, any>|DictionaryIterator<TValue, any> ): LoDashExplicitObjectWrapper<T>; } //_.every interface LoDashStatic { /** * Checks if predicate returns truthy for all elements of collection. Iteration is stopped once predicate * returns falsey. The predicate is invoked with three arguments: (value, index|key, collection). * * @param collection The collection to iterate over. * @param predicate The function invoked per iteration. * @return Returns true if all elements pass the predicate check, else false. */ every<T>( collection: List<T>, predicate?: ListIterator<T, boolean> ): boolean; /** * @see _.every */ every<T>( collection: Dictionary<T>, predicate?: DictionaryIterator<T, boolean> ): boolean; /** * @see _.every */ every<T>( collection: NumericDictionary<T>, predicate?: NumericDictionaryIterator<T, boolean> ): boolean; /** * @see _.every */ every<T>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, predicate?: string|any[] ): boolean; /** * @see _.every */ every<TObject extends {}, T>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, predicate?: TObject ): boolean; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.every */ every( predicate?: ListIterator<T, boolean>|NumericDictionaryIterator<T, boolean> ): boolean; /** * @see _.every */ every( predicate?: string|any[] ): boolean; /** * @see _.every */ every<TObject extends {}>( predicate?: TObject ): boolean; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.every */ every<TResult>( predicate?: ListIterator<TResult, boolean>|DictionaryIterator<TResult, boolean>|NumericDictionaryIterator<T, boolean> ): boolean; /** * @see _.every */ every( predicate?: string|any[] ): boolean; /** * @see _.every */ every<TObject extends {}>( predicate?: TObject ): boolean; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.every */ every( predicate?: ListIterator<T, boolean>|NumericDictionaryIterator<T, boolean> ): LoDashExplicitWrapper<boolean>; /** * @see _.every */ every( predicate?: string|any[] ): LoDashExplicitWrapper<boolean>; /** * @see _.every */ every<TObject extends {}>( predicate?: TObject ): LoDashExplicitWrapper<boolean>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.every */ every<TResult>( predicate?: ListIterator<TResult, boolean>|DictionaryIterator<TResult, boolean>|NumericDictionaryIterator<T, boolean> ): LoDashExplicitWrapper<boolean>; /** * @see _.every */ every( predicate?: string|any[] ): LoDashExplicitWrapper<boolean>; /** * @see _.every */ every<TObject extends {}>( predicate?: TObject ): LoDashExplicitWrapper<boolean>; } //_.filter interface LoDashStatic { /** * Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The * predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection). * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param collection The collection to iterate over. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the new filtered array. */ filter<T>( collection: List<T>, predicate?: ListIterator<T, boolean> ): T[]; /** * @see _.filter */ filter<T>( collection: Dictionary<T>, predicate?: DictionaryIterator<T, boolean> ): T[]; /** * @see _.filter */ filter( collection: string, predicate?: StringIterator<boolean> ): string[]; /** * @see _.filter */ filter<T>( collection: List<T>|Dictionary<T>, predicate: string ): T[]; /** * @see _.filter */ filter<W extends {}, T>( collection: List<T>|Dictionary<T>, predicate: W ): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.filter */ filter( predicate?: StringIterator<boolean> ): LoDashImplicitArrayWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.filter */ filter( predicate: ListIterator<T, boolean> ): LoDashImplicitArrayWrapper<T>; /** * @see _.filter */ filter( predicate: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.filter */ filter<W>(predicate: W): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.filter */ filter<T>( predicate: ListIterator<T, boolean>|DictionaryIterator<T, boolean> ): LoDashImplicitArrayWrapper<T>; /** * @see _.filter */ filter<T>( predicate: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.filter */ filter<W, T>(predicate: W): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.filter */ filter( predicate?: StringIterator<boolean> ): LoDashExplicitArrayWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.filter */ filter( predicate: ListIterator<T, boolean> ): LoDashExplicitArrayWrapper<T>; /** * @see _.filter */ filter( predicate: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.filter */ filter<W>(predicate: W): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.filter */ filter<T>( predicate: ListIterator<T, boolean>|DictionaryIterator<T, boolean> ): LoDashExplicitArrayWrapper<T>; /** * @see _.filter */ filter<T>( predicate: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.filter */ filter<W, T>(predicate: W): LoDashExplicitArrayWrapper<T>; } //_.find interface LoDashStatic { /** * Iterates over elements of collection, returning the first element predicate returns truthy for. * The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection). * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param collection The collection to search. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the matched element, else undefined. */ find<T>( collection: List<T>, predicate?: ListIterator<T, boolean> ): T; /** * @see _.find */ find<T>( collection: Dictionary<T>, predicate?: DictionaryIterator<T, boolean> ): T; /** * @see _.find */ find<T>( collection: List<T>|Dictionary<T>, predicate?: string ): T; /** * @see _.find */ find<TObject extends {}, T>( collection: List<T>|Dictionary<T>, predicate?: TObject ): T; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.find */ find( predicate?: ListIterator<T, boolean> ): T; /** * @see _.find */ find( predicate?: string ): T; /** * @see _.find */ find<TObject extends {}>( predicate?: TObject ): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.find */ find<TResult>( predicate?: ListIterator<TResult, boolean>|DictionaryIterator<TResult, boolean> ): TResult; /** * @see _.find */ find<TResult>( predicate?: string ): TResult; /** * @see _.find */ find<TObject extends {}, TResult>( predicate?: TObject ): TResult; } //_.findLast interface LoDashStatic { /** * This method is like _.find except that it iterates over elements of a collection from * right to left. * @param collection Searches for a value in this list. * @param callback The function called per iteration. * @param thisArg The this binding of callback. * @return The found element, else undefined. **/ findLast<T>( collection: Array<T>, callback: ListIterator<T, boolean>): T; /** * @see _.find **/ findLast<T>( collection: List<T>, callback: ListIterator<T, boolean>): T; /** * @see _.find **/ findLast<T>( collection: Dictionary<T>, callback: DictionaryIterator<T, boolean>): T; /** * @see _.find * @param _.pluck style callback **/ findLast<W, T>( collection: Array<T>, whereValue: W): T; /** * @see _.find * @param _.pluck style callback **/ findLast<W, T>( collection: List<T>, whereValue: W): T; /** * @see _.find * @param _.pluck style callback **/ findLast<W, T>( collection: Dictionary<T>, whereValue: W): T; /** * @see _.find * @param _.where style callback **/ findLast<T>( collection: Array<T>, pluckValue: string): T; /** * @see _.find * @param _.where style callback **/ findLast<T>( collection: List<T>, pluckValue: string): T; /** * @see _.find * @param _.where style callback **/ findLast<T>( collection: Dictionary<T>, pluckValue: string): T; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.findLast */ findLast( callback: ListIterator<T, boolean>): T; /** * @see _.findLast * @param _.where style callback */ findLast<W>( whereValue: W): T; /** * @see _.findLast * @param _.where style callback */ findLast( pluckValue: string): T; } //_.flatMap interface LoDashStatic { /** * Creates an array of flattened values by running each element in collection through iteratee * and concating its result to the other mapped values. The iteratee is invoked with three arguments: * (value, index|key, collection). * * @param collection The collection to iterate over. * @param iteratee The function invoked per iteration. * @return Returns the new flattened array. */ flatMap<T, TResult>( collection: List<T>, iteratee?: ListIterator<T, TResult|TResult[]> ): TResult[]; /** * @see _.flatMap */ flatMap<TResult>( collection: List<any>, iteratee?: ListIterator<any, TResult|TResult[]> ): TResult[]; /** * @see _.flatMap */ flatMap<T, TResult>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, TResult|TResult[]> ): TResult[]; /** * @see _.flatMap */ flatMap<TResult>( collection: Dictionary<any>, iteratee?: DictionaryIterator<any, TResult|TResult[]> ): TResult[]; /** * @see _.flatMap */ flatMap<T, TResult>( collection: NumericDictionary<T>, iteratee?: NumericDictionaryIterator<T, TResult|TResult[]> ): TResult[]; /** * @see _.flatMap */ flatMap<TResult>( collection: NumericDictionary<any>, iteratee?: NumericDictionaryIterator<any, TResult|TResult[]> ): TResult[]; /** * @see _.flatMap */ flatMap<TObject extends Object, TResult>( collection: TObject, iteratee?: ObjectIterator<any, TResult|TResult[]> ): TResult[]; /** * @see _.flatMap */ flatMap<TResult>( collection: Object, iteratee?: ObjectIterator<any, TResult|TResult[]> ): TResult[]; /** * @see _.flatMap */ flatMap<TWhere extends Object, TObject extends Object>( collection: TObject, iteratee: TWhere ): boolean[]; /** * @see _.flatMap */ flatMap<TObject extends Object, TResult>( collection: TObject, iteratee: Object|string ): TResult[]; /** * @see _.flatMap */ flatMap<TObject extends Object>( collection: TObject, iteratee: [string, any] ): boolean[]; /** * @see _.flatMap */ flatMap<TResult>( collection: string ): string[]; /** * @see _.flatMap */ flatMap<TResult>( collection: Object, iteratee?: Object|string ): TResult[]; } interface LoDashImplicitWrapper<T> { /** * @see _.flatMap */ flatMap<TResult>( iteratee: ListIterator<string, TResult|TResult[]> ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.flatMap */ flatMap(): LoDashImplicitArrayWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.flatMap */ flatMap<TResult>( iteratee: ListIterator<T, TResult|TResult[]>|string ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.flatMap */ flatMap<TWhere extends Object>( iteratee: TWhere ): LoDashImplicitArrayWrapper<boolean>; /** * @see _.flatMap */ flatMap( iteratee: [string, any] ): LoDashImplicitArrayWrapper<boolean>; /** * @see _.flatMap */ flatMap<TResult>(): LoDashImplicitArrayWrapper<TResult>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.flatMap */ flatMap<T, TResult>( iteratee: ListIterator<T, TResult|TResult[]>|DictionaryIterator<T, TResult|TResult[]>|NumericDictionaryIterator<T, TResult|TResult[]> ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.flatMap */ flatMap<TResult>( iteratee: ObjectIterator<any, TResult|TResult[]>|string ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.flatMap */ flatMap<TWhere extends Object>( iteratee: TWhere ): LoDashImplicitArrayWrapper<boolean>; /** * @see _.flatMap */ flatMap( iteratee: [string, any] ): LoDashImplicitArrayWrapper<boolean>; /** * @see _.flatMap */ flatMap<TResult>(): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitWrapper<T> { /** * @see _.flatMap */ flatMap<TResult>( iteratee: ListIterator<string, TResult|TResult[]> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.flatMap */ flatMap(): LoDashExplicitArrayWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.flatMap */ flatMap<TResult>( iteratee: ListIterator<T, TResult|TResult[]>|string ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.flatMap */ flatMap<TWhere extends Object>( iteratee: TWhere ): LoDashExplicitArrayWrapper<boolean>; /** * @see _.flatMap */ flatMap( iteratee: [string, any] ): LoDashExplicitArrayWrapper<boolean>; /** * @see _.flatMap */ flatMap<TResult>(): LoDashExplicitArrayWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.flatMap */ flatMap<T, TResult>( iteratee: ListIterator<T, TResult|TResult[]>|DictionaryIterator<T, TResult|TResult[]>|NumericDictionaryIterator<T, TResult|TResult[]> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.flatMap */ flatMap<TResult>( iteratee: ObjectIterator<any, TResult|TResult[]>|string ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.flatMap */ flatMap<TWhere extends Object>( iteratee: TWhere ): LoDashExplicitArrayWrapper<boolean>; /** * @see _.flatMap */ flatMap( iteratee: [string, any] ): LoDashExplicitArrayWrapper<boolean>; /** * @see _.flatMap */ flatMap<TResult>(): LoDashExplicitArrayWrapper<TResult>; } //_.forEach interface LoDashStatic { /** * Iterates over elements of collection invoking iteratee for each element. The iteratee is bound to thisArg * and invoked with three arguments: * (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false. * * Note: As with other "Collections" methods, objects with a "length" property are iterated like arrays. To * avoid this behavior _.forIn or _.forOwn may be used for object iteration. * * @alias _.each * * @param collection The collection to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. */ forEach<T>( collection: T[], iteratee?: ListIterator<T, any> ): T[]; /** * @see _.forEach */ forEach<T>( collection: List<T>, iteratee?: ListIterator<T, any> ): List<T>; /** * @see _.forEach */ forEach<T>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.forEach */ forEach<T extends {}>( collection: T, iteratee?: ObjectIterator<any, any> ): T; /** * @see _.forEach */ forEach<T extends {}, TValue>( collection: T, iteratee?: ObjectIterator<TValue, any> ): T; } interface LoDashImplicitWrapper<T> { /** * @see _.forEach */ forEach( iteratee: ListIterator<string, any> ): LoDashImplicitWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.forEach */ forEach( iteratee: ListIterator<T, any> ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.forEach */ forEach<TValue>( iteratee?: ListIterator<TValue, any>|DictionaryIterator<TValue, any> ): LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.forEach */ forEach( iteratee: ListIterator<string, any> ): LoDashExplicitWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.forEach */ forEach( iteratee: ListIterator<T, any> ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.forEach */ forEach<TValue>( iteratee?: ListIterator<TValue, any>|DictionaryIterator<TValue, any> ): LoDashExplicitObjectWrapper<T>; } //_.forEachRight interface LoDashStatic { /** * This method is like _.forEach except that it iterates over elements of collection from right to left. * * @alias _.eachRight * * @param collection The collection to iterate over. * @param iteratee The function called per iteration. * @param thisArg The this binding of callback. */ forEachRight<T>( collection: T[], iteratee?: ListIterator<T, any> ): T[]; /** * @see _.forEachRight */ forEachRight<T>( collection: List<T>, iteratee?: ListIterator<T, any> ): List<T>; /** * @see _.forEachRight */ forEachRight<T>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.forEachRight */ forEachRight<T extends {}>( collection: T, iteratee?: ObjectIterator<any, any> ): T; /** * @see _.forEachRight */ forEachRight<T extends {}, TValue>( collection: T, iteratee?: ObjectIterator<TValue, any> ): T; } interface LoDashImplicitWrapper<T> { /** * @see _.forEachRight */ forEachRight( iteratee: ListIterator<string, any> ): LoDashImplicitWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.forEachRight */ forEachRight( iteratee: ListIterator<T, any> ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.forEachRight */ forEachRight<TValue>( iteratee?: ListIterator<TValue, any>|DictionaryIterator<TValue, any> ): LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.forEachRight */ forEachRight( iteratee: ListIterator<string, any> ): LoDashExplicitWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.forEachRight */ forEachRight( iteratee: ListIterator<T, any> ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.forEachRight */ forEachRight<TValue>( iteratee?: ListIterator<TValue, any>|DictionaryIterator<TValue, any> ): LoDashExplicitObjectWrapper<T>; } //_.groupBy interface LoDashStatic { /** * Creates an object composed of keys generated from the results of running each element of collection through * iteratee. The corresponding value of each key is an array of the elements responsible for generating the * key. The iteratee is bound to thisArg and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for iteratee the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for iteratee the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param collection The collection to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ groupBy<T, TKey>( collection: List<T>, iteratee?: ListIterator<T, TKey> ): Dictionary<T[]>; /** * @see _.groupBy */ groupBy<T>( collection: List<any>, iteratee?: ListIterator<T, any> ): Dictionary<T[]>; /** * @see _.groupBy */ groupBy<T, TKey>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, TKey> ): Dictionary<T[]>; /** * @see _.groupBy */ groupBy<T>( collection: Dictionary<any>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T[]>; /** * @see _.groupBy */ groupBy<T, TValue>( collection: List<T>|Dictionary<T>, iteratee?: string ): Dictionary<T[]>; /** * @see _.groupBy */ groupBy<T>( collection: List<T>|Dictionary<T>, iteratee?: string ): Dictionary<T[]>; /** * @see _.groupBy */ groupBy<TWhere, T>( collection: List<T>|Dictionary<T>, iteratee?: TWhere ): Dictionary<T[]>; /** * @see _.groupBy */ groupBy<T>( collection: List<T>|Dictionary<T>, iteratee?: Object ): Dictionary<T[]>; } interface LoDashImplicitWrapper<T> { /** * @see _.groupBy */ groupBy<TKey>( iteratee?: ListIterator<T, TKey> ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.groupBy */ groupBy<TKey>( iteratee?: ListIterator<T, TKey> ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<TValue>( iteratee?: string ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<TWhere>( iteratee?: TWhere ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.groupBy */ groupBy<T, TKey>( iteratee?: ListIterator<T, TKey>|DictionaryIterator<T, TKey> ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<T>( iteratee?: ListIterator<T, any>|DictionaryIterator<T, any> ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<T, TValue>( iteratee?: string ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<T>( iteratee?: string ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<TWhere, T>( iteratee?: TWhere ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<T>( iteratee?: Object ): LoDashImplicitObjectWrapper<Dictionary<T[]>>; } interface LoDashExplicitWrapper<T> { /** * @see _.groupBy */ groupBy<TKey>( iteratee?: ListIterator<T, TKey> ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.groupBy */ groupBy<TKey>( iteratee?: ListIterator<T, TKey> ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<TValue>( iteratee?: string ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<TWhere>( iteratee?: TWhere ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.groupBy */ groupBy<T, TKey>( iteratee?: ListIterator<T, TKey>|DictionaryIterator<T, TKey> ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<T>( iteratee?: ListIterator<T, any>|DictionaryIterator<T, any> ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<T, TValue>( iteratee?: string ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<T>( iteratee?: string ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<TWhere, T>( iteratee?: TWhere ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; /** * @see _.groupBy */ groupBy<T>( iteratee?: Object ): LoDashExplicitObjectWrapper<Dictionary<T[]>>; } //_.includes interface LoDashStatic { /** * Checks if target is in collection using SameValueZero for equality comparisons. If fromIndex is negative, * it’s used as the offset from the end of collection. * * @param collection The collection to search. * @param target The value to search for. * @param fromIndex The index to search from. * @return True if the target element is found, else false. */ includes<T>( collection: List<T>|Dictionary<T>, target: T, fromIndex?: number ): boolean; /** * @see _.includes */ includes( collection: string, target: string, fromIndex?: number ): boolean; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.includes */ includes( target: T, fromIndex?: number ): boolean; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.includes */ includes<TValue>( target: TValue, fromIndex?: number ): boolean; } interface LoDashImplicitWrapper<T> { /** * @see _.includes */ includes( target: string, fromIndex?: number ): boolean; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.includes */ includes( target: T, fromIndex?: number ): LoDashExplicitWrapper<boolean>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.includes */ includes<TValue>( target: TValue, fromIndex?: number ): LoDashExplicitWrapper<boolean>; } interface LoDashExplicitWrapper<T> { /** * @see _.includes */ includes( target: string, fromIndex?: number ): LoDashExplicitWrapper<boolean>; } //_.keyBy interface LoDashStatic { /** * Creates an object composed of keys generated from the results of running each element of collection through * iteratee. The corresponding value of each key is the last element responsible for generating the key. The * iteratee function is bound to thisArg and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for iteratee the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for iteratee the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param collection The collection to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ keyBy<T>( collection: List<T>, iteratee?: ListIterator<T, any> ): Dictionary<T>; /** * @see _.keyBy */ keyBy<T>( collection: NumericDictionary<T>, iteratee?: NumericDictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.keyBy */ keyBy<T>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.keyBy */ keyBy<T>( collection: List<T>|NumericDictionary<T>|Dictionary<T>, iteratee?: string ): Dictionary<T>; /** * @see _.keyBy */ keyBy<W extends Object, T>( collection: List<T>|NumericDictionary<T>|Dictionary<T>, iteratee?: W ): Dictionary<T>; /** * @see _.keyBy */ keyBy<T>( collection: List<T>|NumericDictionary<T>|Dictionary<T>, iteratee?: Object ): Dictionary<T>; } interface LoDashImplicitWrapper<T> { /** * @see _.keyBy */ keyBy( iteratee?: ListIterator<T, any> ): LoDashImplicitObjectWrapper<Dictionary<T>>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.keyBy */ keyBy( iteratee?: ListIterator<T, any> ): LoDashImplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy( iteratee?: string ): LoDashImplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy<W extends Object>( iteratee?: W ): LoDashImplicitObjectWrapper<Dictionary<T>>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.keyBy */ keyBy<T>( iteratee?: ListIterator<T, any>|NumericDictionaryIterator<T, any>|DictionaryIterator<T, any> ): LoDashImplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy<T>( iteratee?: string ): LoDashImplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy<W extends Object, T>( iteratee?: W ): LoDashImplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy<T>( iteratee?: Object ): LoDashImplicitObjectWrapper<Dictionary<T>>; } interface LoDashExplicitWrapper<T> { /** * @see _.keyBy */ keyBy( iteratee?: ListIterator<T, any> ): LoDashExplicitObjectWrapper<Dictionary<T>>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.keyBy */ keyBy( iteratee?: ListIterator<T, any> ): LoDashExplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy( iteratee?: string ): LoDashExplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy<W extends Object>( iteratee?: W ): LoDashExplicitObjectWrapper<Dictionary<T>>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.keyBy */ keyBy<T>( iteratee?: ListIterator<T, any>|NumericDictionaryIterator<T, any>|DictionaryIterator<T, any> ): LoDashExplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy<T>( iteratee?: string ): LoDashExplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy<W extends Object, T>( iteratee?: W ): LoDashExplicitObjectWrapper<Dictionary<T>>; /** * @see _.keyBy */ keyBy<T>( iteratee?: Object ): LoDashExplicitObjectWrapper<Dictionary<T>>; } //_.invoke interface LoDashStatic { /** * Invokes the method at path of object. * @param object The object to query. * @param path The path of the method to invoke. * @param args The arguments to invoke the method with. **/ invoke<TObject extends Object, TResult>( object: TObject, path: StringRepresentable|StringRepresentable[], ...args: any[]): TResult; /** * @see _.invoke **/ invoke<TValue, TResult>( object: Dictionary<TValue>|TValue[], path: StringRepresentable|StringRepresentable[], ...args: any[]): TResult; /** * @see _.invoke **/ invoke<TResult>( object: any, path: StringRepresentable|StringRepresentable[], ...args: any[]): TResult; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.invoke **/ invoke<TResult>( path: StringRepresentable|StringRepresentable[], ...args: any[]): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.invoke **/ invoke<TResult>( path: StringRepresentable|StringRepresentable[], ...args: any[]): TResult; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.invoke **/ invoke<TResult>( path: StringRepresentable|StringRepresentable[], ...args: any[]): TResult; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.invoke **/ invoke<TResult>( path: StringRepresentable|StringRepresentable[], ...args: any[]): TResult; } //_.invokeMap interface LoDashStatic { /** * Invokes the method named by methodName on each element in the collection returning * an array of the results of each invoked method. Additional arguments will be provided * to each invoked method. If methodName is a function it will be invoked for, and this * bound to, each element in the collection. * @param collection The collection to iterate over. * @param methodName The name of the method to invoke. * @param args Arguments to invoke the method with. **/ invokeMap<TValue extends {}, TResult>( collection: TValue[], methodName: string, ...args: any[]): TResult[]; /** * @see _.invokeMap **/ invokeMap<TValue extends {}, TResult>( collection: Dictionary<TValue>, methodName: string, ...args: any[]): TResult[]; /** * @see _.invokeMap **/ invokeMap<TResult>( collection: {}[], methodName: string, ...args: any[]): TResult[]; /** * @see _.invokeMap **/ invokeMap<TResult>( collection: Dictionary<{}>, methodName: string, ...args: any[]): TResult[]; /** * @see _.invokeMap **/ invokeMap<TValue extends {}, TResult>( collection: TValue[], method: (...args: any[]) => TResult, ...args: any[]): TResult[]; /** * @see _.invokeMap **/ invokeMap<TValue extends {}, TResult>( collection: Dictionary<TValue>, method: (...args: any[]) => TResult, ...args: any[]): TResult[]; /** * @see _.invokeMap **/ invokeMap<TResult>( collection: {}[], method: (...args: any[]) => TResult, ...args: any[]): TResult[]; /** * @see _.invokeMap **/ invokeMap<TResult>( collection: Dictionary<{}>, method: (...args: any[]) => TResult, ...args: any[]): TResult[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.invokeMap **/ invokeMap<TResult>( methodName: string, ...args: any[]): LoDashImplicitArrayWrapper<TResult>; /** * @see _.invokeMap **/ invokeMap<TResult>( method: (...args: any[]) => TResult, ...args: any[]): LoDashImplicitArrayWrapper<TResult>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.invokeMap **/ invokeMap<TResult>( methodName: string, ...args: any[]): LoDashImplicitArrayWrapper<TResult>; /** * @see _.invokeMap **/ invokeMap<TResult>( method: (...args: any[]) => TResult, ...args: any[]): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.invokeMap **/ invokeMap<TResult>( methodName: string, ...args: any[]): LoDashExplicitArrayWrapper<TResult>; /** * @see _.invokeMap **/ invokeMap<TResult>( method: (...args: any[]) => TResult, ...args: any[]): LoDashExplicitArrayWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.invokeMap **/ invokeMap<TResult>( methodName: string, ...args: any[]): LoDashExplicitArrayWrapper<TResult>; /** * @see _.invokeMap **/ invokeMap<TResult>( method: (...args: any[]) => TResult, ...args: any[]): LoDashExplicitArrayWrapper<TResult>; } //_.map interface LoDashStatic { /** * Creates an array of values by running each element in collection through iteratee. The iteratee is bound to * thisArg and invoked with three arguments: (value, index|key, collection). * * If a property name is provided for iteratee the created _.property style callback returns the property value * of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for iteratee the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * Many lodash methods are guarded to work as iteratees for methods like _.every, _.filter, _.map, _.mapValues, * _.reject, and _.some. * * The guarded methods are: * ary, callback, chunk, clone, create, curry, curryRight, drop, dropRight, every, fill, flatten, invert, max, * min, parseInt, slice, sortBy, take, takeRight, template, trim, trimLeft, trimRight, trunc, random, range, * sample, some, sum, uniq, and words * * @param collection The collection to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. * @return Returns the new mapped array. */ map<T, TResult>( collection: List<T>, iteratee?: ListIterator<T, TResult> ): TResult[]; /** * @see _.map */ map<T extends {}, TResult>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, TResult> ): TResult[]; map<T extends {}, TResult>( collection: NumericDictionary<T>, iteratee?: NumericDictionaryIterator<T, TResult> ): TResult[]; /** * @see _.map */ map<T, TResult>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, iteratee?: string ): TResult[]; /** * @see _.map */ map<T, TObject extends {}>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, iteratee?: TObject ): boolean[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.map */ map<TResult>( iteratee?: ListIterator<T, TResult> ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.map */ map<TResult>( iteratee?: string ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.map */ map<TObject extends {}>( iteratee?: TObject ): LoDashImplicitArrayWrapper<boolean>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.map */ map<TValue, TResult>( iteratee?: ListIterator<TValue, TResult>|DictionaryIterator<TValue, TResult> ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.map */ map<TValue, TResult>( iteratee?: string ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.map */ map<TObject extends {}>( iteratee?: TObject ): LoDashImplicitArrayWrapper<boolean>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.map */ map<TResult>( iteratee?: ListIterator<T, TResult> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.map */ map<TResult>( iteratee?: string ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.map */ map<TObject extends {}>( iteratee?: TObject ): LoDashExplicitArrayWrapper<boolean>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.map */ map<TValue, TResult>( iteratee?: ListIterator<TValue, TResult>|DictionaryIterator<TValue, TResult> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.map */ map<TValue, TResult>( iteratee?: string ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.map */ map<TObject extends {}>( iteratee?: TObject ): LoDashExplicitArrayWrapper<boolean>; } //_.partition interface LoDashStatic { /** * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for, * while the second of which contains elements predicate returns falsey for. * The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection). * * If a property name is provided for predicate the created _.property style callback * returns the property value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback * returns true for elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns * true for elements that have the properties of the given object, else false. * * @param collection The collection to iterate over. * @param callback The function called per iteration. * @param thisArg The this binding of predicate. * @return Returns the array of grouped elements. **/ partition<T>( collection: List<T>, callback: ListIterator<T, boolean>): T[][]; /** * @see _.partition **/ partition<T>( collection: Dictionary<T>, callback: DictionaryIterator<T, boolean>): T[][]; /** * @see _.partition **/ partition<W, T>( collection: List<T>, whereValue: W): T[][]; /** * @see _.partition **/ partition<W, T>( collection: Dictionary<T>, whereValue: W): T[][]; /** * @see _.partition **/ partition<T>( collection: List<T>, path: string, srcValue: any): T[][]; /** * @see _.partition **/ partition<T>( collection: Dictionary<T>, path: string, srcValue: any): T[][]; /** * @see _.partition **/ partition<T>( collection: List<T>, pluckValue: string): T[][]; /** * @see _.partition **/ partition<T>( collection: Dictionary<T>, pluckValue: string): T[][]; } interface LoDashImplicitStringWrapper { /** * @see _.partition */ partition( callback: ListIterator<string, boolean>): LoDashImplicitArrayWrapper<string[]>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.partition */ partition( callback: ListIterator<T, boolean>): LoDashImplicitArrayWrapper<T[]>; /** * @see _.partition */ partition<W>( whereValue: W): LoDashImplicitArrayWrapper<T[]>; /** * @see _.partition */ partition( path: string, srcValue: any): LoDashImplicitArrayWrapper<T[]>; /** * @see _.partition */ partition( pluckValue: string): LoDashImplicitArrayWrapper<T[]>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.partition */ partition<TResult>( callback: ListIterator<TResult, boolean>): LoDashImplicitArrayWrapper<TResult[]>; /** * @see _.partition */ partition<TResult>( callback: DictionaryIterator<TResult, boolean>): LoDashImplicitArrayWrapper<TResult[]>; /** * @see _.partition */ partition<W, TResult>( whereValue: W): LoDashImplicitArrayWrapper<TResult[]>; /** * @see _.partition */ partition<TResult>( path: string, srcValue: any): LoDashImplicitArrayWrapper<TResult[]>; /** * @see _.partition */ partition<TResult>( pluckValue: string): LoDashImplicitArrayWrapper<TResult[]>; } //_.reduce interface LoDashStatic { /** * Reduces a collection to a value which is the accumulated result of running each * element in the collection through the callback, where each successive callback execution * consumes the return value of the previous execution. If accumulator is not provided the * first element of the collection will be used as the initial accumulator value. The callback * is bound to thisArg and invoked with four arguments; (accumulator, value, index|key, collection). * @param collection The collection to iterate over. * @param callback The function called per iteration. * @param accumulator Initial value of the accumulator. * @param thisArg The this binding of callback. * @return Returns the accumulated value. **/ reduce<T, TResult>( collection: Array<T>, callback: MemoIterator<T, TResult>, accumulator: TResult): TResult; /** * @see _.reduce **/ reduce<T, TResult>( collection: List<T>, callback: MemoIterator<T, TResult>, accumulator: TResult): TResult; /** * @see _.reduce **/ reduce<T, TResult>( collection: Dictionary<T>, callback: MemoIterator<T, TResult>, accumulator: TResult): TResult; /** * @see _.reduce **/ reduce<T, TResult>( collection: NumericDictionary<T>, callback: MemoIterator<T, TResult>, accumulator: TResult): TResult; /** * @see _.reduce **/ reduce<T, TResult>( collection: Array<T>, callback: MemoIterator<T, TResult>): TResult; /** * @see _.reduce **/ reduce<T, TResult>( collection: List<T>, callback: MemoIterator<T, TResult>): TResult; /** * @see _.reduce **/ reduce<T, TResult>( collection: Dictionary<T>, callback: MemoIterator<T, TResult>): TResult; /** * @see _.reduce **/ reduce<T, TResult>( collection: NumericDictionary<T>, callback: MemoIterator<T, TResult>): TResult; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.reduce **/ reduce<TResult>( callback: MemoIterator<T, TResult>, accumulator: TResult): TResult; /** * @see _.reduce **/ reduce<TResult>( callback: MemoIterator<T, TResult>): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.reduce **/ reduce<TValue, TResult>( callback: MemoIterator<TValue, TResult>, accumulator: TResult): TResult; /** * @see _.reduce **/ reduce<TValue, TResult>( callback: MemoIterator<TValue, TResult>): TResult; } //_.reduceRight interface LoDashStatic { /** * This method is like _.reduce except that it iterates over elements of a collection from * right to left. * @param collection The collection to iterate over. * @param callback The function called per iteration. * @param accumulator Initial value of the accumulator. * @param thisArg The this binding of callback. * @return The accumulated value. **/ reduceRight<T, TResult>( collection: Array<T>, callback: MemoIterator<T, TResult>, accumulator: TResult): TResult; /** * @see _.reduceRight **/ reduceRight<T, TResult>( collection: List<T>, callback: MemoIterator<T, TResult>, accumulator: TResult): TResult; /** * @see _.reduceRight **/ reduceRight<T, TResult>( collection: Dictionary<T>, callback: MemoIterator<T, TResult>, accumulator: TResult): TResult; /** * @see _.reduceRight **/ reduceRight<T, TResult>( collection: Array<T>, callback: MemoIterator<T, TResult>): TResult; /** * @see _.reduceRight **/ reduceRight<T, TResult>( collection: List<T>, callback: MemoIterator<T, TResult>): TResult; /** * @see _.reduceRight **/ reduceRight<T, TResult>( collection: Dictionary<T>, callback: MemoIterator<T, TResult>): TResult; } //_.reject interface LoDashStatic { /** * The opposite of _.filter; this method returns the elements of collection that predicate does not return * truthy for. * * @param collection The collection to iterate over. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the new filtered array. */ reject<T>( collection: List<T>, predicate?: ListIterator<T, boolean> ): T[]; /** * @see _.reject */ reject<T>( collection: Dictionary<T>, predicate?: DictionaryIterator<T, boolean> ): T[]; /** * @see _.reject */ reject( collection: string, predicate?: StringIterator<boolean> ): string[]; /** * @see _.reject */ reject<T>( collection: List<T>|Dictionary<T>, predicate: string ): T[]; /** * @see _.reject */ reject<W extends {}, T>( collection: List<T>|Dictionary<T>, predicate: W ): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.reject */ reject( predicate?: StringIterator<boolean> ): LoDashImplicitArrayWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.reject */ reject( predicate: ListIterator<T, boolean> ): LoDashImplicitArrayWrapper<T>; /** * @see _.reject */ reject( predicate: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.reject */ reject<W>(predicate: W): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.reject */ reject<T>( predicate: ListIterator<T, boolean>|DictionaryIterator<T, boolean> ): LoDashImplicitArrayWrapper<T>; /** * @see _.reject */ reject<T>( predicate: string ): LoDashImplicitArrayWrapper<T>; /** * @see _.reject */ reject<W, T>(predicate: W): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.reject */ reject( predicate?: StringIterator<boolean> ): LoDashExplicitArrayWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.reject */ reject( predicate: ListIterator<T, boolean> ): LoDashExplicitArrayWrapper<T>; /** * @see _.reject */ reject( predicate: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.reject */ reject<W>(predicate: W): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.reject */ reject<T>( predicate: ListIterator<T, boolean>|DictionaryIterator<T, boolean> ): LoDashExplicitArrayWrapper<T>; /** * @see _.reject */ reject<T>( predicate: string ): LoDashExplicitArrayWrapper<T>; /** * @see _.reject */ reject<W, T>(predicate: W): LoDashExplicitArrayWrapper<T>; } //_.sample interface LoDashStatic { /** * Gets a random element from collection. * * @param collection The collection to sample. * @return Returns the random element. */ sample<T>( collection: List<T>|Dictionary<T>|NumericDictionary<T> ): T; /** * @see _.sample */ sample<O extends Object, T>( collection: O ): T; /** * @see _.sample */ sample<T>( collection: Object ): T; } interface LoDashImplicitWrapper<T> { /** * @see _.sample */ sample(): string; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sample */ sample(): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sample */ sample<T>(): T; } interface LoDashExplicitWrapper<T> { /** * @see _.sample */ sample(): LoDashExplicitWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sample */ sample<TWrapper>(): TWrapper; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sample */ sample<TWrapper>(): TWrapper; } //_.sampleSize interface LoDashStatic { /** * Gets n random elements at unique keys from collection up to the size of collection. * * @param collection The collection to sample. * @param n The number of elements to sample. * @return Returns the random elements. */ sampleSize<T>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, n?: number ): T[]; /** * @see _.sampleSize */ sampleSize<O extends Object, T>( collection: O, n?: number ): T[]; /** * @see _.sampleSize */ sampleSize<T>( collection: Object, n?: number ): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.sampleSize */ sampleSize( n?: number ): LoDashImplicitArrayWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sampleSize */ sampleSize( n?: number ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sampleSize */ sampleSize<T>( n?: number ): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.sampleSize */ sampleSize( n?: number ): LoDashExplicitArrayWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sampleSize */ sampleSize( n?: number ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sampleSize */ sampleSize<T>( n?: number ): LoDashExplicitArrayWrapper<T>; } //_.shuffle interface LoDashStatic { /** * Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. * * @param collection The collection to shuffle. * @return Returns the new shuffled array. */ shuffle<T>(collection: List<T>|Dictionary<T>): T[]; /** * @see _.shuffle */ shuffle(collection: string): string[]; } interface LoDashImplicitWrapper<T> { /** * @see _.shuffle */ shuffle(): LoDashImplicitArrayWrapper<string>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.shuffle */ shuffle(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.shuffle */ shuffle<T>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.shuffle */ shuffle(): LoDashExplicitArrayWrapper<string>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.shuffle */ shuffle(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.shuffle */ shuffle<T>(): LoDashExplicitArrayWrapper<T>; } //_.size interface LoDashStatic { /** * Gets the size of collection by returning its length for array-like values or the number of own enumerable * properties for objects. * * @param collection The collection to inspect. * @return Returns the size of collection. */ size<T>(collection: List<T>|Dictionary<T>): number; /** * @see _.size */ size(collection: string): number; } interface LoDashImplicitWrapper<T> { /** * @see _.size */ size(): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.size */ size(): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.size */ size(): number; } interface LoDashExplicitWrapper<T> { /** * @see _.size */ size(): LoDashExplicitWrapper<number>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.size */ size(): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.size */ size(): LoDashExplicitWrapper<number>; } //_.some interface LoDashStatic { /** * Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate * returns truthy. The predicate is invoked with three arguments: (value, index|key, collection). * * @param collection The collection to iterate over. * @param predicate The function invoked per iteration. * @return Returns true if any element passes the predicate check, else false. */ some<T>( collection: List<T>, predicate?: ListIterator<T, boolean> ): boolean; /** * @see _.some */ some<T>( collection: Dictionary<T>, predicate?: DictionaryIterator<T, boolean> ): boolean; /** * @see _.some */ some<T>( collection: NumericDictionary<T>, predicate?: NumericDictionaryIterator<T, boolean> ): boolean; /** * @see _.some */ some( collection: Object, predicate?: ObjectIterator<any, boolean> ): boolean; /** * @see _.some */ some<T>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, predicate?: string|[string, any] ): boolean; /** * @see _.some */ some( collection: Object, predicate?: string|[string, any] ): boolean; /** * @see _.some */ some<TObject extends {}, T>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, predicate?: TObject ): boolean; /** * @see _.some */ some<T>( collection: List<T>|Dictionary<T>|NumericDictionary<T>, predicate?: Object ): boolean; /** * @see _.some */ some<TObject extends {}>( collection: Object, predicate?: TObject ): boolean; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.some */ some( predicate?: ListIterator<T, boolean>|NumericDictionaryIterator<T, boolean> ): boolean; /** * @see _.some */ some( predicate?: string|[string, any] ): boolean; /** * @see _.some */ some<TObject extends {}>( predicate?: TObject ): boolean; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.some */ some<TResult>( predicate?: ListIterator<TResult, boolean>|DictionaryIterator<TResult, boolean>|NumericDictionaryIterator<T, boolean>|ObjectIterator<any, boolean> ): boolean; /** * @see _.some */ some( predicate?: string|[string, any] ): boolean; /** * @see _.some */ some<TObject extends {}>( predicate?: TObject ): boolean; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.some */ some( predicate?: ListIterator<T, boolean>|NumericDictionaryIterator<T, boolean> ): LoDashExplicitWrapper<boolean>; /** * @see _.some */ some( predicate?: string|[string, any] ): LoDashExplicitWrapper<boolean>; /** * @see _.some */ some<TObject extends {}>( predicate?: TObject ): LoDashExplicitWrapper<boolean>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.some */ some<TResult>( predicate?: ListIterator<TResult, boolean>|DictionaryIterator<TResult, boolean>|NumericDictionaryIterator<T, boolean>|ObjectIterator<any, boolean> ): LoDashExplicitWrapper<boolean>; /** * @see _.some */ some( predicate?: string|[string, any] ): LoDashExplicitWrapper<boolean>; /** * @see _.some */ some<TObject extends {}>( predicate?: TObject ): LoDashExplicitWrapper<boolean>; } //_.sortBy interface LoDashStatic { /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection through each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[]|Object|Object[]|string|string[])} [iteratees=[_.identity]] * The iteratees to sort by, specified individually or in arrays. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 42 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, function(o) { return o.user; }); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] * * _.sortBy(users, 'user', function(o) { * return Math.floor(o.age / 10); * }); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ sortBy<T, TSort>( collection: List<T>, iteratee?: ListIterator<T, TSort> ): T[]; /** * @see _.sortBy */ sortBy<T, TSort>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, TSort> ): T[]; /** * @see _.sortBy */ sortBy<T>( collection: List<T>|Dictionary<T>, iteratee: string ): T[]; /** * @see _.sortBy */ sortBy<W extends {}, T>( collection: List<T>|Dictionary<T>, whereValue: W ): T[]; /** * @see _.sortBy */ sortBy<T>( collection: List<T>|Dictionary<T> ): T[]; /** * @see _.sortBy */ sortBy<T>( collection: (Array<T>|List<T>), iteratees: (ListIterator<T, any>|string|Object)[]): T[]; /** * @see _.sortBy */ sortBy<T>( collection: (Array<T>|List<T>), ...iteratees: (ListIterator<T, boolean>|Object|string)[]): T[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sortBy */ sortBy<TSort>( iteratee?: ListIterator<T, TSort> ): LoDashImplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy(iteratee: string): LoDashImplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy<W extends {}>(whereValue: W): LoDashImplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy(): LoDashImplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy(...iteratees: (ListIterator<T, boolean>|Object|string)[]): LoDashImplicitArrayWrapper<T>; /** * @see _.sortBy **/ sortBy(iteratees: (ListIterator<T, any>|string|Object)[]): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sortBy */ sortBy<T, TSort>( iteratee?: ListIterator<T, TSort>|DictionaryIterator<T, TSort> ): LoDashImplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy<T>(iteratee: string): LoDashImplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy<W extends {}, T>(whereValue: W): LoDashImplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy<T>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sortBy */ sortBy<TSort>( iteratee?: ListIterator<T, TSort> ): LoDashExplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy(iteratee: string): LoDashExplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy<W extends {}>(whereValue: W): LoDashExplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sortBy */ sortBy<T, TSort>( iteratee?: ListIterator<T, TSort>|DictionaryIterator<T, TSort> ): LoDashExplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy<T>(iteratee: string): LoDashExplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy<W extends {}, T>(whereValue: W): LoDashExplicitArrayWrapper<T>; /** * @see _.sortBy */ sortBy<T>(): LoDashExplicitArrayWrapper<T>; } //_.orderBy interface LoDashStatic { /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} [iteratees=[_.identity]] The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for functions like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 42 }, * { 'user': 'barney', 'age': 36 } * ]; * * // sort by `user` in ascending order and by `age` in descending order * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ orderBy<W extends Object, T>( collection: List<T>, iteratees: ListIterator<T, any>|string|W|(ListIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): T[]; /** * @see _.orderBy */ orderBy<T>( collection: List<T>, iteratees: ListIterator<T, any>|string|Object|(ListIterator<T, any>|string|Object)[], orders?: boolean|string|(boolean|string)[] ): T[]; /** * @see _.orderBy */ orderBy<W extends Object, T>( collection: NumericDictionary<T>, iteratees: NumericDictionaryIterator<T, any>|string|W|(NumericDictionaryIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): T[]; /** * @see _.orderBy */ orderBy<T>( collection: NumericDictionary<T>, iteratees: NumericDictionaryIterator<T, any>|string|Object|(NumericDictionaryIterator<T, any>|string|Object)[], orders?: boolean|string|(boolean|string)[] ): T[]; /** * @see _.orderBy */ orderBy<W extends Object, T>( collection: Dictionary<T>, iteratees: DictionaryIterator<T, any>|string|W|(DictionaryIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): T[]; /** * @see _.orderBy */ orderBy<T>( collection: Dictionary<T>, iteratees: DictionaryIterator<T, any>|string|Object|(DictionaryIterator<T, any>|string|Object)[], orders?: boolean|string|(boolean|string)[] ): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.orderBy */ orderBy( iteratees: ListIterator<T, any>|string|(ListIterator<T, any>|string)[], orders?: boolean|string|(boolean|string)[] ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.orderBy */ orderBy<W extends Object>( iteratees: ListIterator<T, any>|string|W|(ListIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.orderBy */ orderBy<W extends Object, T>( iteratees: ListIterator<T, any>|string|W|(ListIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): LoDashImplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<T>( iteratees: ListIterator<T, any>|string|Object|(ListIterator<T, any>|string|Object)[], orders?: boolean|string|(boolean|string)[] ): LoDashImplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<W extends Object, T>( iteratees: NumericDictionaryIterator<T, any>|string|W|(NumericDictionaryIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): LoDashImplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<T>( iteratees: NumericDictionaryIterator<T, any>|string|Object|(NumericDictionaryIterator<T, any>|string|Object)[], orders?: boolean|string|(boolean|string)[] ): LoDashImplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<W extends Object, T>( iteratees: DictionaryIterator<T, any>|string|W|(DictionaryIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): LoDashImplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<T>( iteratees: DictionaryIterator<T, any>|string|Object|(DictionaryIterator<T, any>|string|Object)[], orders?: boolean|string|(boolean|string)[] ): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.orderBy */ orderBy( iteratees: ListIterator<T, any>|string|(ListIterator<T, any>|string)[], orders?: boolean|string|(boolean|string)[] ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.orderBy */ orderBy<W extends Object>( iteratees: ListIterator<T, any>|string|W|(ListIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.orderBy */ orderBy<W extends Object, T>( iteratees: ListIterator<T, any>|string|W|(ListIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): LoDashExplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<T>( iteratees: ListIterator<T, any>|string|Object|(ListIterator<T, any>|string|Object)[], orders?: boolean|string|(boolean|string)[] ): LoDashExplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<W extends Object, T>( iteratees: NumericDictionaryIterator<T, any>|string|W|(NumericDictionaryIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): LoDashExplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<T>( iteratees: NumericDictionaryIterator<T, any>|string|Object|(NumericDictionaryIterator<T, any>|string|Object)[], orders?: boolean|string|(boolean|string)[] ): LoDashExplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<W extends Object, T>( iteratees: DictionaryIterator<T, any>|string|W|(DictionaryIterator<T, any>|string|W)[], orders?: boolean|string|(boolean|string)[] ): LoDashExplicitArrayWrapper<T>; /** * @see _.orderBy */ orderBy<T>( iteratees: DictionaryIterator<T, any>|string|Object|(DictionaryIterator<T, any>|string|Object)[], orders?: boolean|string|(boolean|string)[] ): LoDashExplicitArrayWrapper<T>; } /******** * Date * ********/ //_.now interface LoDashStatic { /** * Gets the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC). * * @return The number of milliseconds. */ now(): number; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.now */ now(): number; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.now */ now(): LoDashExplicitWrapper<number>; } /************* * Functions * *************/ //_.after interface LoDashStatic { /** * The opposite of _.before; this method creates a function that invokes func once it’s called n or more times. * * @param n The number of calls before func is invoked. * @param func The function to restrict. * @return Returns the new restricted function. */ after<TFunc extends Function>( n: number, func: TFunc ): TFunc; } interface LoDashImplicitWrapper<T> { /** * @see _.after **/ after<TFunc extends Function>(func: TFunc): LoDashImplicitObjectWrapper<TFunc>; } interface LoDashExplicitWrapper<T> { /** * @see _.after **/ after<TFunc extends Function>(func: TFunc): LoDashExplicitObjectWrapper<TFunc>; } //_.ary interface LoDashStatic { /** * Creates a function that accepts up to n arguments ignoring any additional arguments. * * @param func The function to cap arguments for. * @param n The arity cap. * @returns Returns the new function. */ ary<TResult extends Function>( func: Function, n?: number ): TResult; ary<T extends Function, TResult extends Function>( func: T, n?: number ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.ary */ ary<TResult extends Function>(n?: number): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.ary */ ary<TResult extends Function>(n?: number): LoDashExplicitObjectWrapper<TResult>; } //_.before interface LoDashStatic { /** * Creates a function that invokes func, with the this binding and arguments of the created function, while * it’s called less than n times. Subsequent calls to the created function return the result of the last func * invocation. * * @param n The number of calls at which func is no longer invoked. * @param func The function to restrict. * @return Returns the new restricted function. */ before<TFunc extends Function>( n: number, func: TFunc ): TFunc; } interface LoDashImplicitWrapper<T> { /** * @see _.before **/ before<TFunc extends Function>(func: TFunc): LoDashImplicitObjectWrapper<TFunc>; } interface LoDashExplicitWrapper<T> { /** * @see _.before **/ before<TFunc extends Function>(func: TFunc): LoDashExplicitObjectWrapper<TFunc>; } //_.bind interface FunctionBind { placeholder: any; <T extends Function, TResult extends Function>( func: T, thisArg: any, ...partials: any[] ): TResult; <TResult extends Function>( func: Function, thisArg: any, ...partials: any[] ): TResult; } interface LoDashStatic { /** * Creates a function that invokes func with the this binding of thisArg and prepends any additional _.bind * arguments to those provided to the bound function. * * The _.bind.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for * partially applied arguments. * * Note: Unlike native Function#bind this method does not set the "length" property of bound functions. * * @param func The function to bind. * @param thisArg The this binding of func. * @param partials The arguments to be partially applied. * @return Returns the new bound function. */ bind: FunctionBind; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.bind */ bind<TResult extends Function>( thisArg: any, ...partials: any[] ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.bind */ bind<TResult extends Function>( thisArg: any, ...partials: any[] ): LoDashExplicitObjectWrapper<TResult>; } //_.bindAll interface LoDashStatic { /** * Binds methods of an object to the object itself, overwriting the existing method. Method names may be * specified as individual arguments or as arrays of method names. If no method names are provided all * enumerable function properties, own and inherited, of object are bound. * * Note: This method does not set the "length" property of bound functions. * * @param object The object to bind and assign the bound methods to. * @param methodNames The object method names to bind, specified as individual method names or arrays of * method names. * @return Returns object. */ bindAll<T>( object: T, ...methodNames: (string|string[])[] ): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.bindAll */ bindAll(...methodNames: (string|string[])[]): LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.bindAll */ bindAll(...methodNames: (string|string[])[]): LoDashExplicitObjectWrapper<T>; } //_.bindKey interface FunctionBindKey { placeholder: any; <T extends Object, TResult extends Function>( object: T, key: any, ...partials: any[] ): TResult; <TResult extends Function>( object: Object, key: any, ...partials: any[] ): TResult; } interface LoDashStatic { /** * Creates a function that invokes the method at object[key] and prepends any additional _.bindKey arguments * to those provided to the bound function. * * This method differs from _.bind by allowing bound functions to reference methods that may be redefined * or don’t yet exist. See Peter Michaux’s article for more details. * * The _.bindKey.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder * for partially applied arguments. * * @param object The object the method belongs to. * @param key The key of the method. * @param partials The arguments to be partially applied. * @return Returns the new bound function. */ bindKey: FunctionBindKey; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.bindKey */ bindKey<TResult extends Function>( key: any, ...partials: any[] ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.bindKey */ bindKey<TResult extends Function>( key: any, ...partials: any[] ): LoDashExplicitObjectWrapper<TResult>; } //_.createCallback interface LoDashStatic { /** * Produces a callback bound to an optional thisArg. If func is a property name the created * callback will return the property value for a given element. If func is an object the created * callback will return true for elements that contain the equivalent object properties, * otherwise it will return false. * @param func The value to convert to a callback. * @param thisArg The this binding of the created callback. * @param argCount The number of arguments the callback accepts. * @return A callback function. **/ createCallback( func: string, argCount?: number): () => any; /** * @see _.createCallback **/ createCallback( func: Dictionary<any>, argCount?: number): () => boolean; } interface LoDashImplicitWrapper<T> { /** * @see _.createCallback **/ createCallback( argCount?: number): LoDashImplicitObjectWrapper<() => any>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.createCallback **/ createCallback( argCount?: number): LoDashImplicitObjectWrapper<() => any>; } //_.curry interface LoDashStatic { /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. * @return Returns the new curried function. */ curry<T1, R>(func: (t1: T1) => R): CurriedFunction1<T1, R>; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. * @return Returns the new curried function. */ curry<T1, T2, R>(func: (t1: T1, t2: T2) => R): CurriedFunction2<T1, T2, R>; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. * @return Returns the new curried function. */ curry<T1, T2, T3, R>(func: (t1: T1, t2: T2, t3: T3) => R): CurriedFunction3<T1, T2, T3, R>; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. * @return Returns the new curried function. */ curry<T1, T2, T3, T4, R>(func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): CurriedFunction4<T1, T2, T3, T4, R>; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. * @return Returns the new curried function. */ curry<T1, T2, T3, T4, T5, R>(func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): CurriedFunction5<T1, T2, T3, T4, T5, R>; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. * @param arity The arity of func. * @return Returns the new curried function. */ curry<TResult extends Function>( func: Function, arity?: number): TResult; } interface CurriedFunction1<T1, R> { (): CurriedFunction1<T1, R>; (t1: T1): R; } interface CurriedFunction2<T1, T2, R> { (): CurriedFunction2<T1, T2, R>; (t1: T1): CurriedFunction1<T2, R>; (t1: T1, t2: T2): R; } interface CurriedFunction3<T1, T2, T3, R> { (): CurriedFunction3<T1, T2, T3, R>; (t1: T1): CurriedFunction2<T2, T3, R>; (t1: T1, t2: T2): CurriedFunction1<T3, R>; (t1: T1, t2: T2, t3: T3): R; } interface CurriedFunction4<T1, T2, T3, T4, R> { (): CurriedFunction4<T1, T2, T3, T4, R>; (t1: T1): CurriedFunction3<T2, T3, T4, R>; (t1: T1, t2: T2): CurriedFunction2<T3, T4, R>; (t1: T1, t2: T2, t3: T3): CurriedFunction1<T4, R>; (t1: T1, t2: T2, t3: T3, t4: T4): R; } interface CurriedFunction5<T1, T2, T3, T4, T5, R> { (): CurriedFunction5<T1, T2, T3, T4, T5, R>; (t1: T1): CurriedFunction4<T2, T3, T4, T5, R>; (t1: T1, t2: T2): CurriedFunction3<T3, T4, T5, R>; (t1: T1, t2: T2, t3: T3): CurriedFunction2<T4, T5, R>; (t1: T1, t2: T2, t3: T3, t4: T4): CurriedFunction1<T5, R>; (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.curry **/ curry<TResult extends Function>(arity?: number): LoDashImplicitObjectWrapper<TResult>; } //_.curryRight interface LoDashStatic { /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. * @return Returns the new curried function. */ curryRight<T1, R>(func: (t1: T1) => R): CurriedFunction1<T1, R>; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. * @return Returns the new curried function. */ curryRight<T1, T2, R>(func: (t1: T1, t2: T2) => R): CurriedFunction2<T2, T1, R>; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. * @return Returns the new curried function. */ curryRight<T1, T2, T3, R>(func: (t1: T1, t2: T2, t3: T3) => R): CurriedFunction3<T3, T2, T1, R>; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. * @return Returns the new curried function. */ curryRight<T1, T2, T3, T4, R>(func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): CurriedFunction4<T4, T3, T2, T1, R>; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. * @return Returns the new curried function. */ curryRight<T1, T2, T3, T4, T5, R>(func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): CurriedFunction5<T5, T4, T3, T2, T1, R>; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. * @param arity The arity of func. * @return Returns the new curried function. */ curryRight<TResult extends Function>( func: Function, arity?: number): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.curryRight **/ curryRight<TResult extends Function>(arity?: number): LoDashImplicitObjectWrapper<TResult>; } //_.debounce interface DebounceSettings { /** * Specify invoking on the leading edge of the timeout. */ leading?: boolean; /** * The maximum time func is allowed to be delayed before it’s invoked. */ maxWait?: number; /** * Specify invoking on the trailing edge of the timeout. */ trailing?: boolean; } interface LoDashStatic { /** * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since * the last time the debounced function was invoked. The debounced function comes with a cancel method to * cancel delayed invocations. Provide an options object to indicate that func should be invoked on the * leading and/or trailing edge of the wait timeout. Subsequent calls to the debounced function return the * result of the last func invocation. * * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only * if the the debounced function is invoked more than once during the wait timeout. * * See David Corbacho’s article for details over the differences between _.debounce and _.throttle. * * @param func The function to debounce. * @param wait The number of milliseconds to delay. * @param options The options object. * @param options.leading Specify invoking on the leading edge of the timeout. * @param options.maxWait The maximum time func is allowed to be delayed before it’s invoked. * @param options.trailing Specify invoking on the trailing edge of the timeout. * @return Returns the new debounced function. */ debounce<T extends Function>( func: T, wait?: number, options?: DebounceSettings ): T & Cancelable; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.debounce */ debounce( wait?: number, options?: DebounceSettings ): LoDashImplicitObjectWrapper<T & Cancelable>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.debounce */ debounce( wait?: number, options?: DebounceSettings ): LoDashExplicitObjectWrapper<T & Cancelable>; } //_.defer interface LoDashStatic { /** * Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to * func when it’s invoked. * * @param func The function to defer. * @param args The arguments to invoke the function with. * @return Returns the timer id. */ defer<T extends Function>( func: T, ...args: any[] ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.defer */ defer(...args: any[]): LoDashImplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.defer */ defer(...args: any[]): LoDashExplicitWrapper<number>; } //_.delay interface LoDashStatic { /** * Invokes func after wait milliseconds. Any additional arguments are provided to func when it’s invoked. * * @param func The function to delay. * @param wait The number of milliseconds to delay invocation. * @param args The arguments to invoke the function with. * @return Returns the timer id. */ delay<T extends Function>( func: T, wait: number, ...args: any[] ): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.delay */ delay( wait: number, ...args: any[] ): LoDashImplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.delay */ delay( wait: number, ...args: any[] ): LoDashExplicitWrapper<number>; } interface LoDashStatic { /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ flip<T extends Function>(func: T): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.flip */ flip(): LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.flip */ flip(): LoDashExplicitObjectWrapper<T>; } //_.flow interface LoDashStatic { /** * Creates a function that returns the result of invoking the provided functions with the this binding of the * created function, where each successive invocation is supplied the return value of the previous. * * @param funcs Functions to invoke. * @return Returns the new function. */ flow<TResult extends Function>(...funcs: Function[]): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.flow */ flow<TResult extends Function>(...funcs: Function[]): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.flow */ flow<TResult extends Function>(...funcs: Function[]): LoDashExplicitObjectWrapper<TResult>; } //_.flowRight interface LoDashStatic { /** * This method is like _.flow except that it creates a function that invokes the provided functions from right * to left. * * @param funcs Functions to invoke. * @return Returns the new function. */ flowRight<TResult extends Function>(...funcs: Function[]): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.flowRight */ flowRight<TResult extends Function>(...funcs: Function[]): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.flowRight */ flowRight<TResult extends Function>(...funcs: Function[]): LoDashExplicitObjectWrapper<TResult>; } //_.memoize interface MemoizedFunction extends Function { cache: MapCache; } interface LoDashStatic { /** * Creates a function that memoizes the result of func. If resolver is provided it determines the cache key for * storing the result based on the arguments provided to the memoized function. By default, the first argument * provided to the memoized function is coerced to a string and used as the cache key. The func is invoked with * the this binding of the memoized function. * * @param func The function to have its output memoized. * @param resolver The function to resolve the cache key. * @return Returns the new memoizing function. */ memoize: { <T extends Function>(func: T, resolver?: Function): T & MemoizedFunction; Cache: MapCache; } } interface LoDashImplicitObjectWrapper<T> { /** * @see _.memoize */ memoize(resolver?: Function): LoDashImplicitObjectWrapper<T & MemoizedFunction>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.memoize */ memoize(resolver?: Function): LoDashExplicitObjectWrapper<T & MemoizedFunction>; } //_.overArgs (was _.modArgs) interface LoDashStatic { /** * Creates a function that runs each argument through a corresponding transform function. * * @param func The function to wrap. * @param transforms The functions to transform arguments, specified as individual functions or arrays * of functions. * @return Returns the new function. */ overArgs<T extends Function, TResult extends Function>( func: T, ...transforms: Function[] ): TResult; /** * @see _.overArgs */ overArgs<T extends Function, TResult extends Function>( func: T, transforms: Function[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.overArgs */ overArgs<TResult extends Function>(...transforms: Function[]): LoDashImplicitObjectWrapper<TResult>; /** * @see _.overArgs */ overArgs<TResult extends Function>(transforms: Function[]): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.overArgs */ overArgs<TResult extends Function>(...transforms: Function[]): LoDashExplicitObjectWrapper<TResult>; /** * @see _.overArgs */ overArgs<TResult extends Function>(transforms: Function[]): LoDashExplicitObjectWrapper<TResult>; } //_.negate interface LoDashStatic { /** * Creates a function that negates the result of the predicate func. The func predicate is invoked with * the this binding and arguments of the created function. * * @param predicate The predicate to negate. * @return Returns the new function. */ negate<T extends Function>(predicate: T): (...args: any[]) => boolean; /** * @see _.negate */ negate<T extends Function, TResult extends Function>(predicate: T): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.negate */ negate(): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; /** * @see _.negate */ negate<TResult extends Function>(): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.negate */ negate(): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; /** * @see _.negate */ negate<TResult extends Function>(): LoDashExplicitObjectWrapper<TResult>; } //_.once interface LoDashStatic { /** * Creates a function that is restricted to invoking func once. Repeat calls to the function return the value * of the first call. The func is invoked with the this binding and arguments of the created function. * * @param func The function to restrict. * @return Returns the new restricted function. */ once<T extends Function>(func: T): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.once */ once(): LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.once */ once(): LoDashExplicitObjectWrapper<T>; } //_.partial interface LoDashStatic { /** * Creates a function that, when called, invokes func with any additional partial arguments * prepended to those provided to the new function. This method is similar to _.bind except * it does not alter the this binding. * @param func The function to partially apply arguments to. * @param args Arguments to be partially applied. * @return The new partially applied function. **/ partial: Partial; } type PH = LoDashStatic; interface Function0<R> { (): R; } interface Function1<T1, R> { (t1: T1): R; } interface Function2<T1, T2, R> { (t1: T1, t2: T2): R; } interface Function3<T1, T2, T3, R> { (t1: T1, t2: T2, t3: T3): R; } interface Function4<T1, T2, T3, T4, R> { (t1: T1, t2: T2, t3: T3, t4: T4): R; } interface Partial { // arity 0 <R>(func: Function0<R>): Function0<R>; // arity 1 <T1, R>(func: Function1<T1, R>): Function1<T1, R>; <T1, R>(func: Function1<T1, R>, arg1: T1): Function0<R>; // arity 2 <T1, T2, R>(func: Function2<T1, T2, R>): Function2<T1, T2, R>; <T1, T2, R>(func: Function2<T1, T2, R>, arg1: T1): Function1< T2, R>; <T1, T2, R>(func: Function2<T1, T2, R>, plc1: PH, arg2: T2): Function1<T1, R>; <T1, T2, R>(func: Function2<T1, T2, R>, arg1: T1, arg2: T2): Function0< R>; // arity 3 <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>): Function3<T1, T2, T3, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1): Function2< T2, T3, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, plc1: PH, arg2: T2): Function2<T1, T3, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, arg2: T2): Function1< T3, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, plc1: PH, plc2: PH, arg3: T3): Function2<T1, T2, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, plc2: PH, arg3: T3): Function1< T2, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, plc1: PH, arg2: T2, arg3: T3): Function1<T1, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, arg2: T2, arg3: T3): Function0< R>; // arity 4 <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>): Function4<T1, T2, T3, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1): Function3< T2, T3, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: PH, arg2: T2): Function3<T1, T3, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2): Function2< T3, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: PH, plc2: PH, arg3: T3): Function3<T1, T2, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: PH, arg3: T3): Function2< T2, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: PH, arg2: T2, arg3: T3): Function2<T1, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, arg3: T3): Function1< T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: PH, plc2: PH, plc3: PH, arg4: T4): Function3<T1, T2, T3, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: PH, plc3: PH, arg4: T4): Function2< T2, T3, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: PH, arg2: T2, plc3: PH, arg4: T4): Function2<T1, T3, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, plc3: PH, arg4: T4): Function1< T3, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: PH, plc2: PH, arg3: T3, arg4: T4): Function2<T1, T2, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: PH, arg3: T3, arg4: T4): Function1< T2, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: PH, arg2: T2, arg3: T3, arg4: T4): Function1<T1, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): Function0< R>; // catch-all (func: Function, ...args: any[]): Function; } //_.partialRight interface LoDashStatic { /** * This method is like _.partial except that partial arguments are appended to those provided * to the new function. * @param func The function to partially apply arguments to. * @param args Arguments to be partially applied. * @return The new partially applied function. **/ partialRight: PartialRight } interface PartialRight { // arity 0 <R>(func: Function0<R>): Function0<R>; // arity 1 <T1, R>(func: Function1<T1, R>): Function1<T1, R>; <T1, R>(func: Function1<T1, R>, arg1: T1): Function0<R>; // arity 2 <T1, T2, R>(func: Function2<T1, T2, R>): Function2<T1, T2, R>; <T1, T2, R>(func: Function2<T1, T2, R>, arg1: T1, plc2: PH): Function1< T2, R>; <T1, T2, R>(func: Function2<T1, T2, R>, arg2: T2): Function1<T1, R>; <T1, T2, R>(func: Function2<T1, T2, R>, arg1: T1, arg2: T2): Function0< R>; // arity 3 <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>): Function3<T1, T2, T3, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, plc2: PH, plc3: PH): Function2< T2, T3, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg2: T2, plc3: PH): Function2<T1, T3, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, arg2: T2, plc3: PH): Function1< T3, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg3: T3): Function2<T1, T2, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, plc2: PH, arg3: T3): Function1< T2, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg2: T2, arg3: T3): Function1<T1, R>; <T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, arg2: T2, arg3: T3): Function0< R>; // arity 4 <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>): Function4<T1, T2, T3, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: PH, plc3: PH, plc4: PH): Function3< T2, T3, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg2: T2, plc3: PH, plc4: PH): Function3<T1, T3, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, plc3: PH, plc4: PH): Function2< T3, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg3: T3, plc4: PH): Function3<T1, T2, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: PH, arg3: T3, plc4: PH): Function2< T2, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg2: T2, arg3: T3, plc4: PH): Function2<T1, T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, arg3: T3, plc4: PH): Function1< T4, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg4: T4): Function3<T1, T2, T3, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: PH, plc3: PH, arg4: T4): Function2< T2, T3, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg2: T2, plc3: PH, arg4: T4): Function2<T1, T3, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, plc3: PH, arg4: T4): Function1< T3, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg3: T3, arg4: T4): Function2<T1, T2, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: PH, arg3: T3, arg4: T4): Function1< T2, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg2: T2, arg3: T3, arg4: T4): Function1<T1, R>; <T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): Function0< R>; // catch-all (func: Function, ...args: any[]): Function; } //_.rearg interface LoDashStatic { /** * Creates a function that invokes func with arguments arranged according to the specified indexes where the * argument value at the first index is provided as the first argument, the argument value at the second index * is provided as the second argument, and so on. * @param func The function to rearrange arguments for. * @param indexes The arranged argument indexes, specified as individual indexes or arrays of indexes. * @return Returns the new function. */ rearg<TResult extends Function>(func: Function, indexes: number[]): TResult; /** * @see _.rearg */ rearg<TResult extends Function>(func: Function, ...indexes: number[]): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.rearg */ rearg<TResult extends Function>(indexes: number[]): LoDashImplicitObjectWrapper<TResult>; /** * @see _.rearg */ rearg<TResult extends Function>(...indexes: number[]): LoDashImplicitObjectWrapper<TResult>; } //_.rest interface LoDashStatic { /** * Creates a function that invokes func with the this binding of the created function and arguments from start * and beyond provided as an array. * * Note: This method is based on the rest parameter. * * @param func The function to apply a rest parameter to. * @param start The start position of the rest parameter. * @return Returns the new function. */ rest<TResult extends Function>( func: Function, start?: number ): TResult; /** * @see _.rest */ rest<TResult extends Function, TFunc extends Function>( func: TFunc, start?: number ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.rest */ rest<TResult extends Function>(start?: number): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.rest */ rest<TResult extends Function>(start?: number): LoDashExplicitObjectWrapper<TResult>; } //_.spread interface LoDashStatic { /** * Creates a function that invokes func with the this binding of the created function and an array of arguments * much like Function#apply. * * Note: This method is based on the spread operator. * * @param func The function to spread arguments over. * @return Returns the new function. */ spread<F extends Function, T extends Function>(func: F): T; /** * @see _.spread */ spread<T extends Function>(func: Function): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.spread */ spread<T extends Function>(): LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.spread */ spread<T extends Function>(): LoDashExplicitObjectWrapper<T>; } //_.throttle interface ThrottleSettings { /** * If you'd like to disable the leading-edge call, pass this as false. */ leading?: boolean; /** * If you'd like to disable the execution on the trailing-edge, pass false. */ trailing?: boolean; } interface LoDashStatic { /** * Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled * function comes with a cancel method to cancel delayed invocations. Provide an options object to indicate * that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to * the throttled function return the result of the last func call. * * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if * the the throttled function is invoked more than once during the wait timeout. * * @param func The function to throttle. * @param wait The number of milliseconds to throttle invocations to. * @param options The options object. * @param options.leading Specify invoking on the leading edge of the timeout. * @param options.trailing Specify invoking on the trailing edge of the timeout. * @return Returns the new throttled function. */ throttle<T extends Function>( func: T, wait?: number, options?: ThrottleSettings ): T & Cancelable; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.throttle */ throttle( wait?: number, options?: ThrottleSettings ): LoDashImplicitObjectWrapper<T & Cancelable>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.throttle */ throttle( wait?: number, options?: ThrottleSettings ): LoDashExplicitObjectWrapper<T & Cancelable>; } //_.unary interface LoDashStatic { /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ unary<T extends Function>(func: T): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.unary */ unary(): LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.unary */ unary(): LoDashExplicitObjectWrapper<T>; } //_.wrap interface LoDashStatic { /** * Creates a function that provides value to the wrapper function as its first argument. Any additional * arguments provided to the function are appended to those provided to the wrapper function. The wrapper is * invoked with the this binding of the created function. * * @param value The value to wrap. * @param wrapper The wrapper function. * @return Returns the new function. */ wrap<V, W extends Function, R extends Function>( value: V, wrapper: W ): R; /** * @see _.wrap */ wrap<V, R extends Function>( value: V, wrapper: Function ): R; /** * @see _.wrap */ wrap<R extends Function>( value: any, wrapper: Function ): R; } interface LoDashImplicitWrapper<T> { /** * @see _.wrap */ wrap<W extends Function, R extends Function>(wrapper: W): LoDashImplicitObjectWrapper<R>; /** * @see _.wrap */ wrap<R extends Function>(wrapper: Function): LoDashImplicitObjectWrapper<R>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.wrap */ wrap<W extends Function, R extends Function>(wrapper: W): LoDashImplicitObjectWrapper<R>; /** * @see _.wrap */ wrap<R extends Function>(wrapper: Function): LoDashImplicitObjectWrapper<R>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.wrap */ wrap<W extends Function, R extends Function>(wrapper: W): LoDashImplicitObjectWrapper<R>; /** * @see _.wrap */ wrap<R extends Function>(wrapper: Function): LoDashImplicitObjectWrapper<R>; } interface LoDashExplicitWrapper<T> { /** * @see _.wrap */ wrap<W extends Function, R extends Function>(wrapper: W): LoDashExplicitObjectWrapper<R>; /** * @see _.wrap */ wrap<R extends Function>(wrapper: Function): LoDashExplicitObjectWrapper<R>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.wrap */ wrap<W extends Function, R extends Function>(wrapper: W): LoDashExplicitObjectWrapper<R>; /** * @see _.wrap */ wrap<R extends Function>(wrapper: Function): LoDashExplicitObjectWrapper<R>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.wrap */ wrap<W extends Function, R extends Function>(wrapper: W): LoDashExplicitObjectWrapper<R>; /** * @see _.wrap */ wrap<R extends Function>(wrapper: Function): LoDashExplicitObjectWrapper<R>; } /******** * Lang * ********/ //_.castArray interface LoDashStatic { /** * Casts value as an array if it’s not one. * * @param value The value to inspect. * @return Returns the cast array. */ castArray<T>(value: T): T[]; } interface LoDashImplicitWrapper<T> { /** * @see _.castArray */ castArray(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.castArray */ castArray(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.castArray */ castArray(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitWrapper<T> { /** * @see _.castArray */ castArray(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.castArray */ castArray(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.castArray */ castArray(): LoDashExplicitArrayWrapper<T>; } //_.clone interface LoDashStatic { /** * Creates a shallow clone of value. * * Note: This method is loosely based on the structured clone algorithm and supports cloning arrays, * array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, * and typed arrays. The own enumerable properties of arguments objects are cloned as plain objects. An empty * object is returned for uncloneable values such as error objects, functions, DOM nodes, and WeakMaps. * * @param value The value to clone. * @return Returns the cloned value. */ clone<T>(value: T): T; } interface LoDashImplicitWrapper<T> { /** * @see _.clone */ clone(): T; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.clone */ clone(): T[]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.clone */ clone(): T; } interface LoDashExplicitWrapper<T> { /** * @see _.clone */ clone(): LoDashExplicitWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.clone */ clone(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.clone */ clone(): LoDashExplicitObjectWrapper<T>; } //_.cloneDeep interface LoDashStatic { /** * This method is like _.clone except that it recursively clones value. * * @param value The value to recursively clone. * @return Returns the deep cloned value. */ cloneDeep<T>(value: T): T; } interface LoDashImplicitWrapper<T> { /** * @see _.cloneDeep */ cloneDeep(): T; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.cloneDeep */ cloneDeep(): T[]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.cloneDeep */ cloneDeep(): T; } interface LoDashExplicitWrapper<T> { /** * @see _.cloneDeep */ cloneDeep(): LoDashExplicitWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.cloneDeep */ cloneDeep(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.cloneDeep */ cloneDeep(): LoDashExplicitObjectWrapper<T>; } //_.cloneDeepWith interface CloneDeepWithCustomizer<TValue, TResult> { (value: TValue): TResult; } interface LoDashStatic { /** * This method is like _.cloneWith except that it recursively clones value. * * @param value The value to recursively clone. * @param customizer The function to customize cloning. * @return Returns the deep cloned value. */ cloneDeepWith<TResult>( value: any, customizer?: CloneDeepWithCustomizer<any, TResult> ): TResult; /** * @see _.clonDeepeWith */ cloneDeepWith<T, TResult>( value: T, customizer?: CloneDeepWithCustomizer<T, TResult> ): TResult; } interface LoDashImplicitWrapper<T> { /** * @see _.cloneDeepWith */ cloneDeepWith<TResult>( customizer?: CloneDeepWithCustomizer<T, TResult> ): TResult; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.cloneDeepWith */ cloneDeepWith<TResult>( customizer?: CloneDeepWithCustomizer<T[], TResult> ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.cloneDeepWith */ cloneDeepWith<TResult>( customizer?: CloneDeepWithCustomizer<T, TResult> ): TResult; } interface LoDashExplicitWrapper<T> { /** * @see _.cloneDeepWith */ cloneDeepWith<TResult extends (number|string|boolean)>( customizer?: CloneDeepWithCustomizer<T, TResult> ): LoDashExplicitWrapper<TResult>; /** * @see _.cloneDeepWith */ cloneDeepWith<TResult>( customizer?: CloneDeepWithCustomizer<T, TResult[]> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.cloneDeepWith */ cloneDeepWith<TResult extends Object>( customizer?: CloneDeepWithCustomizer<T, TResult> ): LoDashExplicitObjectWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.cloneDeepWith */ cloneDeepWith<TResult extends (number|string|boolean)>( customizer?: CloneDeepWithCustomizer<T[], TResult> ): LoDashExplicitWrapper<TResult>; /** * @see _.cloneDeepWith */ cloneDeepWith<TResult>( customizer?: CloneDeepWithCustomizer<T[], TResult[]> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.cloneDeepWith */ cloneDeepWith<TResult extends Object>( customizer?: CloneDeepWithCustomizer<T[], TResult> ): LoDashExplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.cloneDeepWith */ cloneDeepWith<TResult extends (number|string|boolean)>( customizer?: CloneDeepWithCustomizer<T, TResult> ): LoDashExplicitWrapper<TResult>; /** * @see _.cloneDeepWith */ cloneDeepWith<TResult>( customizer?: CloneDeepWithCustomizer<T, TResult[]> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.cloneDeepWith */ cloneDeepWith<TResult extends Object>( customizer?: CloneDeepWithCustomizer<T, TResult> ): LoDashExplicitObjectWrapper<TResult>; } //_.cloneWith interface CloneWithCustomizer<TValue, TResult> { (value: TValue): TResult; } interface LoDashStatic { /** * This method is like _.clone except that it accepts customizer which is invoked to produce the cloned value. * If customizer returns undefined cloning is handled by the method instead. * * @param value The value to clone. * @param customizer The function to customize cloning. * @return Returns the cloned value. */ cloneWith<TResult>( value: any, customizer?: CloneWithCustomizer<any, TResult> ): TResult; /** * @see _.cloneWith */ cloneWith<T, TResult>( value: T, customizer?: CloneWithCustomizer<T, TResult> ): TResult; } interface LoDashImplicitWrapper<T> { /** * @see _.cloneWith */ cloneWith<TResult>( customizer?: CloneWithCustomizer<T, TResult> ): TResult; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.cloneWith */ cloneWith<TResult>( customizer?: CloneWithCustomizer<T[], TResult> ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.cloneWith */ cloneWith<TResult>( customizer?: CloneWithCustomizer<T, TResult> ): TResult; } interface LoDashExplicitWrapper<T> { /** * @see _.cloneWith */ cloneWith<TResult extends (number|string|boolean)>( customizer?: CloneWithCustomizer<T, TResult> ): LoDashExplicitWrapper<TResult>; /** * @see _.cloneWith */ cloneWith<TResult>( customizer?: CloneWithCustomizer<T, TResult[]> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.cloneWith */ cloneWith<TResult extends Object>( customizer?: CloneWithCustomizer<T, TResult> ): LoDashExplicitObjectWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.cloneWith */ cloneWith<TResult extends (number|string|boolean)>( customizer?: CloneWithCustomizer<T[], TResult> ): LoDashExplicitWrapper<TResult>; /** * @see _.cloneWith */ cloneWith<TResult>( customizer?: CloneWithCustomizer<T[], TResult[]> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.cloneWith */ cloneWith<TResult extends Object>( customizer?: CloneWithCustomizer<T[], TResult> ): LoDashExplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.cloneWith */ cloneWith<TResult extends (number|string|boolean)>( customizer?: CloneWithCustomizer<T, TResult> ): LoDashExplicitWrapper<TResult>; /** * @see _.cloneWith */ cloneWith<TResult>( customizer?: CloneWithCustomizer<T, TResult[]> ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.cloneWith */ cloneWith<TResult extends Object>( customizer?: CloneWithCustomizer<T, TResult> ): LoDashExplicitObjectWrapper<TResult>; } //_.eq interface LoDashStatic { /** * Performs a [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ eq( value: any, other: any ): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isEqual */ eq( other: any ): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isEqual */ eq( other: any ): LoDashExplicitWrapper<boolean>; } //_.gt interface LoDashStatic { /** * Checks if value is greater than other. * * @param value The value to compare. * @param other The other value to compare. * @return Returns true if value is greater than other, else false. */ gt( value: any, other: any ): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.gt */ gt(other: any): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.gt */ gt(other: any): LoDashExplicitWrapper<boolean>; } //_.gte interface LoDashStatic { /** * Checks if value is greater than or equal to other. * * @param value The value to compare. * @param other The other value to compare. * @return Returns true if value is greater than or equal to other, else false. */ gte( value: any, other: any ): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.gte */ gte(other: any): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.gte */ gte(other: any): LoDashExplicitWrapper<boolean>; } //_.isArguments interface LoDashStatic { /** * Checks if value is classified as an arguments object. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isArguments(value?: any): value is IArguments; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isArguments */ isArguments(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isArguments */ isArguments(): LoDashExplicitWrapper<boolean>; } //_.isArray interface LoDashStatic { /** * Checks if value is classified as an Array object. * @param value The value to check. * * @return Returns true if value is correctly classified, else false. */ isArray<T>(value?: any): value is T[]; } interface LoDashImplicitWrapperBase<T,TWrapper> { /** * @see _.isArray */ isArray(): boolean; } interface LoDashExplicitWrapperBase<T,TWrapper> { /** * @see _.isArray */ isArray(): LoDashExplicitWrapper<boolean>; } //_.isArrayBuffer interface LoDashStatic { /** * Checks if value is classified as an ArrayBuffer object. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isArrayBuffer(value?: any): value is ArrayBuffer; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isArrayBuffer */ isArrayBuffer(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isArrayBuffer */ isArrayBuffer(): LoDashExplicitWrapper<boolean>; } //_.isArrayLike interface LoDashStatic { /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @type Function * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ isArrayLike<T>(value?: any): value is T[]; } interface LoDashImplicitWrapperBase<T,TWrapper> { /** * @see _.isArrayLike */ isArrayLike(): boolean; } interface LoDashExplicitWrapperBase<T,TWrapper> { /** * @see _.isArrayLike */ isArrayLike(): LoDashExplicitWrapper<boolean>; } //_.isArrayLikeObject interface LoDashStatic { /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @type Function * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ isArrayLikeObject<T>(value?: any): value is T[]; } interface LoDashImplicitWrapperBase<T,TWrapper> { /** * @see _.isArrayLikeObject */ isArrayLikeObject(): boolean; } interface LoDashExplicitWrapperBase<T,TWrapper> { /** * @see _.isArrayLikeObject */ isArrayLikeObject(): LoDashExplicitWrapper<boolean>; } //_.isBoolean interface LoDashStatic { /** * Checks if value is classified as a boolean primitive or object. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isBoolean(value?: any): value is boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isBoolean */ isBoolean(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isBoolean */ isBoolean(): LoDashExplicitWrapper<boolean>; } //_.isBuffer interface LoDashStatic { /** * Checks if value is a buffer. * * @param value The value to check. * @return Returns true if value is a buffer, else false. */ isBuffer(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isBuffer */ isBuffer(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isBuffer */ isBuffer(): LoDashExplicitWrapper<boolean>; } //_.isDate interface LoDashStatic { /** * Checks if value is classified as a Date object. * @param value The value to check. * * @return Returns true if value is correctly classified, else false. */ isDate(value?: any): value is Date; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isDate */ isDate(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isDate */ isDate(): LoDashExplicitWrapper<boolean>; } //_.isElement interface LoDashStatic { /** * Checks if value is a DOM element. * * @param value The value to check. * @return Returns true if value is a DOM element, else false. */ isElement(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isElement */ isElement(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isElement */ isElement(): LoDashExplicitWrapper<boolean>; } //_.isEmpty interface LoDashStatic { /** * Checks if value is empty. A value is considered empty unless it’s an arguments object, array, string, or * jQuery-like collection with a length greater than 0 or an object with own enumerable properties. * * @param value The value to inspect. * @return Returns true if value is empty, else false. */ isEmpty(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isEmpty */ isEmpty(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isEmpty */ isEmpty(): LoDashExplicitWrapper<boolean>; } //_.isEqual interface LoDashStatic { /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are **not** supported. * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ isEqual( value: any, other: any ): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isEqual */ isEqual( other: any ): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isEqual */ isEqual( other: any ): LoDashExplicitWrapper<boolean>; } // _.isEqualWith interface IsEqualCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; } interface LoDashStatic { /** * This method is like `_.isEqual` except that it accepts `customizer` which is * invoked to compare values. If `customizer` returns `undefined` comparisons are * handled by the method instead. The `customizer` is invoked with up to seven arguments: * (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ isEqualWith( value: any, other: any, customizer: IsEqualCustomizer ): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isEqualWith */ isEqualWith( other: any, customizer: IsEqualCustomizer ): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isEqualWith */ isEqualWith( other: any, customizer: IsEqualCustomizer ): LoDashExplicitWrapper<boolean>; } //_.isError interface LoDashStatic { /** * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError * object. * * @param value The value to check. * @return Returns true if value is an error object, else false. */ isError(value: any): value is Error; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isError */ isError(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isError */ isError(): LoDashExplicitWrapper<boolean>; } //_.isFinite interface LoDashStatic { /** * Checks if value is a finite primitive number. * * Note: This method is based on Number.isFinite. * * @param value The value to check. * @return Returns true if value is a finite number, else false. */ isFinite(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isFinite */ isFinite(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isFinite */ isFinite(): LoDashExplicitWrapper<boolean>; } //_.isFunction interface LoDashStatic { /** * Checks if value is classified as a Function object. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isFunction(value?: any): value is Function; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isFunction */ isFunction(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isFunction */ isFunction(): LoDashExplicitWrapper<boolean>; } //_.isInteger interface LoDashStatic { /** * Checks if `value` is an integer. * * **Note:** This method is based on [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ isInteger(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isInteger */ isInteger(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isInteger */ isInteger(): LoDashExplicitWrapper<boolean>; } //_.isLength interface LoDashStatic { /** * Checks if `value` is a valid array-like length. * * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ isLength(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isLength */ isLength(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isLength */ isLength(): LoDashExplicitWrapper<boolean>; } //_.isMap interface LoDashStatic { /** * Checks if value is classified as a Map object. * * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ isMap<K, V>(value?: any): value is Map<K, V>; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isMap */ isMap(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isMap */ isMap(): LoDashExplicitWrapper<boolean>; } //_.isMatch interface isMatchCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; } interface LoDashStatic { /** * Performs a deep comparison between `object` and `source` to determine if * `object` contains equivalent property values. * * **Note:** This method supports comparing the same values as `_.isEqual`. * * @static * @memberOf _ * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.isMatch(object, { 'age': 40 }); * // => true * * _.isMatch(object, { 'age': 36 }); * // => false */ isMatch(object: Object, source: Object): boolean; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.isMatch */ isMatch(source: Object): boolean; } //_.isMatchWith interface isMatchWithCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; } interface LoDashStatic { /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined` comparisons * are handled by the method instead. The `customizer` is invoked with three * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ isMatchWith(object: Object, source: Object, customizer: isMatchWithCustomizer): boolean; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.isMatchWith */ isMatchWith(source: Object, customizer: isMatchWithCustomizer): boolean; } //_.isNaN interface LoDashStatic { /** * Checks if value is NaN. * * Note: This method is not the same as isNaN which returns true for undefined and other non-numeric values. * * @param value The value to check. * @return Returns true if value is NaN, else false. */ isNaN(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isNaN */ isNaN(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isNaN */ isNaN(): LoDashExplicitWrapper<boolean>; } //_.isNative interface LoDashStatic { /** * Checks if value is a native function. * @param value The value to check. * * @retrun Returns true if value is a native function, else false. */ isNative(value: any): value is Function; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isNative */ isNative(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isNative */ isNative(): LoDashExplicitWrapper<boolean>; } //_.isNil interface LoDashStatic { /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ isNil(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isNil */ isNil(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isNil */ isNil(): LoDashExplicitWrapper<boolean>; } //_.isNull interface LoDashStatic { /** * Checks if value is null. * * @param value The value to check. * @return Returns true if value is null, else false. */ isNull(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isNull */ isNull(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isNull */ isNull(): LoDashExplicitWrapper<boolean>; } //_.isNumber interface LoDashStatic { /** * Checks if value is classified as a Number primitive or object. * * Note: To exclude Infinity, -Infinity, and NaN, which are classified as numbers, use the _.isFinite method. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isNumber(value?: any): value is number; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isNumber */ isNumber(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isNumber */ isNumber(): LoDashExplicitWrapper<boolean>; } //_.isObject interface LoDashStatic { /** * Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), * and new String('')) * * @param value The value to check. * @return Returns true if value is an object, else false. */ isObject(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isObject */ isObject(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isObject */ isObject(): LoDashExplicitWrapper<boolean>; } //_.isObjectLike interface LoDashStatic { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ isObjectLike(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isObjectLike */ isObjectLike(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isObjectLike */ isObjectLike(): LoDashExplicitWrapper<boolean>; } //_.isPlainObject interface LoDashStatic { /** * Checks if value is a plain object, that is, an object created by the Object constructor or one with a * [[Prototype]] of null. * * Note: This method assumes objects created by the Object constructor have no inherited enumerable properties. * * @param value The value to check. * @return Returns true if value is a plain object, else false. */ isPlainObject(value?: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isPlainObject */ isPlainObject(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isPlainObject */ isPlainObject(): LoDashExplicitWrapper<boolean>; } //_.isRegExp interface LoDashStatic { /** * Checks if value is classified as a RegExp object. * @param value The value to check. * * @return Returns true if value is correctly classified, else false. */ isRegExp(value?: any): value is RegExp; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isRegExp */ isRegExp(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isRegExp */ isRegExp(): LoDashExplicitWrapper<boolean>; } //_.isSafeInteger interface LoDashStatic { /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ isSafeInteger(value: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isSafeInteger */ isSafeInteger(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isSafeInteger */ isSafeInteger(): LoDashExplicitWrapper<boolean>; } //_.isSet interface LoDashStatic { /** * Checks if value is classified as a Set object. * * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ isSet<T>(value?: any): value is Set<T>; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isSet */ isSet(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isSet */ isSet(): LoDashExplicitWrapper<boolean>; } //_.isString interface LoDashStatic { /** * Checks if value is classified as a String primitive or object. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isString(value?: any): value is string; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isString */ isString(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isString */ isString(): LoDashExplicitWrapper<boolean>; } //_.isSymbol interface LoDashStatic { /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ isSymbol(value: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isSymbol */ isSymbol(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isSymbol */ isSymbol(): LoDashExplicitWrapper<boolean>; } //_.isTypedArray interface LoDashStatic { /** * Checks if value is classified as a typed array. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isTypedArray(value: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isTypedArray */ isTypedArray(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isTypedArray */ isTypedArray(): LoDashExplicitWrapper<boolean>; } //_.isUndefined interface LoDashStatic { /** * Checks if value is undefined. * * @param value The value to check. * @return Returns true if value is undefined, else false. */ isUndefined(value: any): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * see _.isUndefined */ isUndefined(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * see _.isUndefined */ isUndefined(): LoDashExplicitWrapper<boolean>; } //_.isWeakMap interface LoDashStatic { /** * Checks if value is classified as a WeakMap object. * * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ isWeakMap<K, V>(value?: any): value is WeakMap<K, V>; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isSet */ isWeakMap(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isSet */ isWeakMap(): LoDashExplicitWrapper<boolean>; } //_.isWeakSet interface LoDashStatic { /** * Checks if value is classified as a WeakSet object. * * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ isWeakSet<T>(value?: any): value is WeakSet<T>; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.isWeakSet */ isWeakSet(): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.isWeakSet */ isWeakSet(): LoDashExplicitWrapper<boolean>; } //_.lt interface LoDashStatic { /** * Checks if value is less than other. * * @param value The value to compare. * @param other The other value to compare. * @return Returns true if value is less than other, else false. */ lt( value: any, other: any ): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.lt */ lt(other: any): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.lt */ lt(other: any): LoDashExplicitWrapper<boolean>; } //_.lte interface LoDashStatic { /** * Checks if value is less than or equal to other. * * @param value The value to compare. * @param other The other value to compare. * @return Returns true if value is less than or equal to other, else false. */ lte( value: any, other: any ): boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.lte */ lte(other: any): boolean; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.lte */ lte(other: any): LoDashExplicitWrapper<boolean>; } //_.toArray interface LoDashStatic { /** * Converts value to an array. * * @param value The value to convert. * @return Returns the converted array. */ toArray<T>(value: List<T>|Dictionary<T>|NumericDictionary<T>): T[]; /** * @see _.toArray */ toArray<TValue, TResult>(value: TValue): TResult[]; /** * @see _.toArray */ toArray<TResult>(value?: any): TResult[]; } interface LoDashImplicitWrapper<T> { /** * @see _.toArray */ toArray<TResult>(): LoDashImplicitArrayWrapper<TResult>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.toArray */ toArray(): LoDashImplicitArrayWrapper<T>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.toArray */ toArray<TResult>(): LoDashImplicitArrayWrapper<TResult>; } interface LoDashExplicitWrapper<T> { /** * @see _.toArray */ toArray<TResult>(): LoDashExplicitArrayWrapper<TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.toArray */ toArray(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.toArray */ toArray<TResult>(): LoDashExplicitArrayWrapper<TResult>; } //_.toPlainObject interface LoDashStatic { /** * Converts value to a plain object flattening inherited enumerable properties of value to own properties * of the plain object. * * @param value The value to convert. * @return Returns the converted plain object. */ toPlainObject<TResult extends {}>(value?: any): TResult; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.toPlainObject */ toPlainObject<TResult extends {}>(): LoDashImplicitObjectWrapper<TResult>; } //_.toInteger interface LoDashStatic { /** * Converts `value` to an integer. * * **Note:** This function is loosely based on [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger). * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3'); * // => 3 */ toInteger(value: any): number; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.toInteger */ toInteger(): LoDashImplicitWrapper<number>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.toInteger */ toInteger(): LoDashExplicitWrapper<number>; } //_.toLength interface LoDashStatic { /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @return {number} Returns the converted integer. * @example * * _.toLength(3); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3'); * // => 3 */ toLength(value: any): number; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.toLength */ toLength(): LoDashImplicitWrapper<number>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.toLength */ toLength(): LoDashExplicitWrapper<number>; } //_.toNumber interface LoDashStatic { /** * Converts `value` to a number. * * @static * @memberOf _ * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3); * // => 3 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3'); * // => 3 */ toNumber(value: any): number; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.toNumber */ toNumber(): LoDashImplicitWrapper<number>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.toNumber */ toNumber(): LoDashExplicitWrapper<number>; } //_.toSafeInteger interface LoDashStatic { /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3'); * // => 3 */ toSafeInteger(value: any): number; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.toSafeInteger */ toSafeInteger(): LoDashImplicitWrapper<number>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.toSafeInteger */ toSafeInteger(): LoDashExplicitWrapper<number>; } //_.toString DUMMY interface LoDashStatic { /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ toString(value: any): string; } /******** * Math * ********/ //_.add interface LoDashStatic { /** * Adds two numbers. * * @param augend The first number to add. * @param addend The second number to add. * @return Returns the sum. */ add( augend: number, addend: number ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.add */ add(addend: number): number; } interface LoDashExplicitWrapper<T> { /** * @see _.add */ add(addend: number): LoDashExplicitWrapper<number>; } //_.ceil interface LoDashStatic { /** * Calculates n rounded up to precision. * * @param n The number to round up. * @param precision The precision to round up to. * @return Returns the rounded up number. */ ceil( n: number, precision?: number ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.ceil */ ceil(precision?: number): number; } interface LoDashExplicitWrapper<T> { /** * @see _.ceil */ ceil(precision?: number): LoDashExplicitWrapper<number>; } //_.floor interface LoDashStatic { /** * Calculates n rounded down to precision. * * @param n The number to round down. * @param precision The precision to round down to. * @return Returns the rounded down number. */ floor( n: number, precision?: number ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.floor */ floor(precision?: number): number; } interface LoDashExplicitWrapper<T> { /** * @see _.floor */ floor(precision?: number): LoDashExplicitWrapper<number>; } //_.max interface LoDashStatic { /** * Computes the maximum value of `array`. If `array` is empty or falsey * `undefined` is returned. * * @static * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. */ max<T>( collection: List<T> ): T; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.max */ max(): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.max */ max<T>(): T; } //_.maxBy interface LoDashStatic { /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.a; }); * // => { 'n': 2 } * * // using the `_.property` iteratee shorthand * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ maxBy<T>( collection: List<T>, iteratee?: ListIterator<T, any> ): T; /** * @see _.maxBy */ maxBy<T>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): T; /** * @see _.maxBy */ maxBy<T>( collection: List<T>|Dictionary<T>, iteratee?: string ): T; /** * @see _.maxBy */ maxBy<TObject extends {}, T>( collection: List<T>|Dictionary<T>, whereValue?: TObject ): T; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.maxBy */ maxBy( iteratee?: ListIterator<T, any> ): T; /** * @see _.maxBy */ maxBy( iteratee?: string ): T; /** * @see _.maxBy */ maxBy<TObject extends {}>( whereValue?: TObject ): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.maxBy */ maxBy<T>( iteratee?: ListIterator<T, any>|DictionaryIterator<T, any> ): T; /** * @see _.maxBy */ maxBy<T>( iteratee?: string ): T; /** * @see _.maxBy */ maxBy<TObject extends {}, T>( whereValue?: TObject ): T; } //_.mean interface LoDashStatic { /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ mean<T>( collection: List<T> ): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.mean */ mean<T>(): number; /** * @see _.mean */ mean(): number; } //_.min interface LoDashStatic { /** * Computes the minimum value of `array`. If `array` is empty or falsey * `undefined` is returned. * * @static * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. */ min<T>( collection: List<T> ): T; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.min */ min(): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.min */ min<T>(): T; } //_.minBy interface LoDashStatic { /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.a; }); * // => { 'n': 1 } * * // using the `_.property` iteratee shorthand * _.minBy(objects, 'n'); * // => { 'n': 1 } */ minBy<T>( collection: List<T>, iteratee?: ListIterator<T, any> ): T; /** * @see _.minBy */ minBy<T>( collection: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): T; /** * @see _.minBy */ minBy<T>( collection: List<T>|Dictionary<T>, iteratee?: string ): T; /** * @see _.minBy */ minBy<TObject extends {}, T>( collection: List<T>|Dictionary<T>, whereValue?: TObject ): T; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.minBy */ minBy( iteratee?: ListIterator<T, any> ): T; /** * @see _.minBy */ minBy( iteratee?: string ): T; /** * @see _.minBy */ minBy<TObject extends {}>( whereValue?: TObject ): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.minBy */ minBy<T>( iteratee?: ListIterator<T, any>|DictionaryIterator<T, any> ): T; /** * @see _.minBy */ minBy<T>( iteratee?: string ): T; /** * @see _.minBy */ minBy<TObject extends {}, T>( whereValue?: TObject ): T; } //_.round interface LoDashStatic { /** * Calculates n rounded to precision. * * @param n The number to round. * @param precision The precision to round to. * @return Returns the rounded number. */ round( n: number, precision?: number ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.round */ round(precision?: number): number; } interface LoDashExplicitWrapper<T> { /** * @see _.round */ round(precision?: number): LoDashExplicitWrapper<number>; } //_.sum interface LoDashStatic { /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ sum<T>(collection: List<T>): number; /** * @see _.sum */ sum(collection: List<number>|Dictionary<number>): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sum */ sum(): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sum **/ sum<TValue>(): number; /** * @see _.sum */ sum(): number; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sum */ sum(): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sum */ sum<TValue>(): LoDashExplicitWrapper<number>; /** * @see _.sum */ sum(): LoDashExplicitWrapper<number>; } //_.sumBy interface LoDashStatic { /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // using the `_.property` iteratee shorthand * _.sumBy(objects, 'n'); * // => 20 */ sumBy<T>( collection: List<T>, iteratee: ListIterator<T, number> ): number; /** * @see _.sumBy **/ sumBy<T>( collection: Dictionary<T>, iteratee: DictionaryIterator<T, number> ): number; /** * @see _.sumBy */ sumBy<T>( collection: List<number>|Dictionary<number>, iteratee: string ): number; /** * @see _.sumBy */ sumBy<T>(collection: List<T>|Dictionary<T>): number; /** * @see _.sumBy */ sumBy(collection: List<number>|Dictionary<number>): number; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.sumBy */ sumBy( iteratee: ListIterator<T, number> ): number; /** * @see _.sumBy */ sumBy(iteratee: string): number; /** * @see _.sumBy */ sumBy(): number; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.sumBy **/ sumBy<TValue>( iteratee: ListIterator<TValue, number>|DictionaryIterator<TValue, number> ): number; /** * @see _.sumBy */ sumBy(iteratee: string): number; /** * @see _.sumBy */ sumBy(): number; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.sumBy */ sumBy( iteratee: ListIterator<T, number> ): LoDashExplicitWrapper<number>; /** * @see _.sumBy */ sumBy(iteratee: string): LoDashExplicitWrapper<number>; /** * @see _.sumBy */ sumBy(): LoDashExplicitWrapper<number>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.sumBy */ sumBy<TValue>( iteratee: ListIterator<TValue, number>|DictionaryIterator<TValue, number> ): LoDashExplicitWrapper<number>; /** * @see _.sumBy */ sumBy(iteratee: string): LoDashExplicitWrapper<number>; /** * @see _.sumBy */ sumBy(): LoDashExplicitWrapper<number>; } /********** * Number * **********/ //_.subtract interface LoDashStatic { /** * Subtract two numbers. * * @static * @memberOf _ * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ subtract( minuend: number, subtrahend: number ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.subtract */ subtract( subtrahend: number ): number; } interface LoDashExplicitWrapper<T> { /** * @see _.subtract */ subtract( subtrahend: number ): LoDashExplicitWrapper<number>; } //_.clamp interface LoDashStatic { /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ clamp( number: number, lower: number, upper: number ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.clamp */ clamp( lower: number, upper: number ): number; } interface LoDashExplicitWrapper<T> { /** * @see _.clamp */ clamp( lower: number, upper: number ): LoDashExplicitWrapper<number>; } //_.inRange interface LoDashStatic { /** * Checks if n is between start and up to but not including, end. If end is not specified it’s set to start * with start then set to 0. * * @param n The number to check. * @param start The start of the range. * @param end The end of the range. * @return Returns true if n is in the range, else false. */ inRange( n: number, start: number, end: number ): boolean; /** * @see _.inRange */ inRange( n: number, end: number ): boolean; } interface LoDashImplicitWrapper<T> { /** * @see _.inRange */ inRange( start: number, end: number ): boolean; /** * @see _.inRange */ inRange(end: number): boolean; } interface LoDashExplicitWrapper<T> { /** * @see _.inRange */ inRange( start: number, end: number ): LoDashExplicitWrapper<boolean>; /** * @see _.inRange */ inRange(end: number): LoDashExplicitWrapper<boolean>; } //_.random interface LoDashStatic { /** * Produces a random number between min and max (inclusive). If only one argument is provided a number between * 0 and the given number is returned. If floating is true, or either min or max are floats, a floating-point * number is returned instead of an integer. * * @param min The minimum possible value. * @param max The maximum possible value. * @param floating Specify returning a floating-point number. * @return Returns the random number. */ random( min?: number, max?: number, floating?: boolean ): number; /** * @see _.random */ random( min?: number, floating?: boolean ): number; /** * @see _.random */ random(floating?: boolean): number; } interface LoDashImplicitWrapper<T> { /** * @see _.random */ random( max?: number, floating?: boolean ): number; /** * @see _.random */ random(floating?: boolean): number; } interface LoDashExplicitWrapper<T> { /** * @see _.random */ random( max?: number, floating?: boolean ): LoDashExplicitWrapper<number>; /** * @see _.random */ random(floating?: boolean): LoDashExplicitWrapper<number>; } /********** * Object * **********/ //_.assign interface LoDashStatic { /** * Assigns own enumerable properties of source objects to the destination * object. Source objects are applied from left to right. Subsequent sources * overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.c = 3; * } * * function Bar() { * this.e = 5; * } * * Foo.prototype.d = 4; * Bar.prototype.f = 6; * * _.assign({ 'a': 1 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3, 'e': 5 } */ assign<TObject extends {}, TSource extends {}, TResult extends {}>( object: TObject, source: TSource ): TResult; /** * @see assign */ assign<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2 ): TResult; /** * @see assign */ assign<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3 ): TResult; /** * @see assign */ assign<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}> ( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 ): TResult; /** * @see _.assign */ assign<TObject extends {}>(object: TObject): TObject; /** * @see _.assign */ assign<TObject extends {}, TResult extends {}>( object: TObject, ...otherArgs: any[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.assign */ assign<TSource extends {}, TResult extends {}>( source: TSource ): LoDashImplicitObjectWrapper<TResult>; /** * @see assign */ assign<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2 ): LoDashImplicitObjectWrapper<TResult>; /** * @see assign */ assign<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3 ): LoDashImplicitObjectWrapper<TResult>; /** * @see assign */ assign<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.assign */ assign(): LoDashImplicitObjectWrapper<T>; /** * @see _.assign */ assign<TResult extends {}>(...otherArgs: any[]): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.assign */ assign<TSource extends {}, TResult extends {}>( source: TSource ): LoDashExplicitObjectWrapper<TResult>; /** * @see assign */ assign<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2 ): LoDashExplicitObjectWrapper<TResult>; /** * @see assign */ assign<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3 ): LoDashExplicitObjectWrapper<TResult>; /** * @see assign */ assign<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.assign */ assign(): LoDashExplicitObjectWrapper<T>; /** * @see _.assign */ assign<TResult extends {}>(...otherArgs: any[]): LoDashExplicitObjectWrapper<TResult>; } //_.assignWith interface AssignCustomizer { (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}): any; } interface LoDashStatic { /** * This method is like `_.assign` except that it accepts `customizer` which * is invoked to produce the assigned values. If `customizer` returns `undefined` * assignment is handled by the method instead. The `customizer` is invoked * with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ assignWith<TObject extends {}, TSource extends {}, TResult extends {}>( object: TObject, source: TSource, customizer: AssignCustomizer ): TResult; /** * @see assignWith */ assignWith<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2, customizer: AssignCustomizer ): TResult; /** * @see assignWith */ assignWith<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer ): TResult; /** * @see assignWith */ assignWith<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}> ( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer ): TResult; /** * @see _.assignWith */ assignWith<TObject extends {}>(object: TObject): TObject; /** * @see _.assignWith */ assignWith<TObject extends {}, TResult extends {}>( object: TObject, ...otherArgs: any[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.assignWith */ assignWith<TSource extends {}, TResult extends {}>( source: TSource, customizer: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see assignWith */ assignWith<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, customizer: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see assignWith */ assignWith<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see assignWith */ assignWith<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.assignWith */ assignWith(): LoDashImplicitObjectWrapper<T>; /** * @see _.assignWith */ assignWith<TResult extends {}>(...otherArgs: any[]): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.assignWith */ assignWith<TSource extends {}, TResult extends {}>( source: TSource, customizer: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see assignWith */ assignWith<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, customizer: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see assignWith */ assignWith<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see assignWith */ assignWith<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.assignWith */ assignWith(): LoDashExplicitObjectWrapper<T>; /** * @see _.assignWith */ assignWith<TResult extends {}>(...otherArgs: any[]): LoDashExplicitObjectWrapper<TResult>; } //_.assignIn interface LoDashStatic { /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.b = 2; * } * * function Bar() { * this.d = 4; * } * * Foo.prototype.c = 3; * Bar.prototype.e = 5; * * _.assignIn({ 'a': 1 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 } */ assignIn<TObject extends {}, TSource extends {}, TResult extends {}>( object: TObject, source: TSource ): TResult; /** * @see assignIn */ assignIn<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2 ): TResult; /** * @see assignIn */ assignIn<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3 ): TResult; /** * @see assignIn */ assignIn<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}> ( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 ): TResult; /** * @see _.assignIn */ assignIn<TObject extends {}>(object: TObject): TObject; /** * @see _.assignIn */ assignIn<TObject extends {}, TResult extends {}>( object: TObject, ...otherArgs: any[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.assignIn */ assignIn<TSource extends {}, TResult extends {}>( source: TSource ): LoDashImplicitObjectWrapper<TResult>; /** * @see assignIn */ assignIn<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2 ): LoDashImplicitObjectWrapper<TResult>; /** * @see assignIn */ assignIn<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3 ): LoDashImplicitObjectWrapper<TResult>; /** * @see assignIn */ assignIn<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.assignIn */ assignIn(): LoDashImplicitObjectWrapper<T>; /** * @see _.assignIn */ assignIn<TResult extends {}>(...otherArgs: any[]): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.assignIn */ assignIn<TSource extends {}, TResult extends {}>( source: TSource ): LoDashExplicitObjectWrapper<TResult>; /** * @see assignIn */ assignIn<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2 ): LoDashExplicitObjectWrapper<TResult>; /** * @see assignIn */ assignIn<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3 ): LoDashExplicitObjectWrapper<TResult>; /** * @see assignIn */ assignIn<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.assignIn */ assignIn(): LoDashExplicitObjectWrapper<T>; /** * @see _.assignIn */ assignIn<TResult extends {}>(...otherArgs: any[]): LoDashExplicitObjectWrapper<TResult>; } //_.assignInWith interface AssignCustomizer { (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}): any; } interface LoDashStatic { /** * This method is like `_.assignIn` except that it accepts `customizer` which * is invoked to produce the assigned values. If `customizer` returns `undefined` * assignment is handled by the method instead. The `customizer` is invoked * with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ assignInWith<TObject extends {}, TSource extends {}, TResult extends {}>( object: TObject, source: TSource, customizer: AssignCustomizer ): TResult; /** * @see assignInWith */ assignInWith<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2, customizer: AssignCustomizer ): TResult; /** * @see assignInWith */ assignInWith<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer ): TResult; /** * @see assignInWith */ assignInWith<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}> ( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer ): TResult; /** * @see _.assignInWith */ assignInWith<TObject extends {}>(object: TObject): TObject; /** * @see _.assignInWith */ assignInWith<TObject extends {}, TResult extends {}>( object: TObject, ...otherArgs: any[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.assignInWith */ assignInWith<TSource extends {}, TResult extends {}>( source: TSource, customizer: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see assignInWith */ assignInWith<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, customizer: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see assignInWith */ assignInWith<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see assignInWith */ assignInWith<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.assignInWith */ assignInWith(): LoDashImplicitObjectWrapper<T>; /** * @see _.assignInWith */ assignInWith<TResult extends {}>(...otherArgs: any[]): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.assignInWith */ assignInWith<TSource extends {}, TResult extends {}>( source: TSource, customizer: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see assignInWith */ assignInWith<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, customizer: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see assignInWith */ assignInWith<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see assignInWith */ assignInWith<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.assignInWith */ assignInWith(): LoDashExplicitObjectWrapper<T>; /** * @see _.assignInWith */ assignInWith<TResult extends {}>(...otherArgs: any[]): LoDashExplicitObjectWrapper<TResult>; } //_.create interface LoDashStatic { /** * Creates an object that inherits from the given prototype object. If a properties object is provided its own * enumerable properties are assigned to the created object. * * @param prototype The object to inherit from. * @param properties The properties to assign to the object. * @return Returns the new object. */ create<T extends Object, U extends Object>( prototype: T, properties?: U ): T & U; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.create */ create<U extends Object>(properties?: U): LoDashImplicitObjectWrapper<T & U>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.create */ create<U extends Object>(properties?: U): LoDashExplicitObjectWrapper<T & U>; } //_.defaults interface LoDashStatic { /** * Assigns own enumerable properties of source object(s) to the destination object for all destination * properties that resolve to undefined. Once a property is set, additional values of the same property are * ignored. * * Note: This method mutates object. * * @param object The destination object. * @param sources The source objects. * @return The destination object. */ defaults<Obj extends {}, TResult extends {}>( object: Obj, ...sources: {}[] ): TResult; /** * @see _.defaults */ defaults<Obj extends {}, S1 extends {}, TResult extends {}>( object: Obj, source1: S1, ...sources: {}[] ): TResult; /** * @see _.defaults */ defaults<Obj extends {}, S1 extends {}, S2 extends {}, TResult extends {}>( object: Obj, source1: S1, source2: S2, ...sources: {}[] ): TResult; /** * @see _.defaults */ defaults<Obj extends {}, S1 extends {}, S2 extends {}, S3 extends {}, TResult extends {}>( object: Obj, source1: S1, source2: S2, source3: S3, ...sources: {}[] ): TResult; /** * @see _.defaults */ defaults<Obj extends {}, S1 extends {}, S2 extends {}, S3 extends {}, S4 extends {}, TResult extends {}>( object: Obj, source1: S1, source2: S2, source3: S3, source4: S4, ...sources: {}[] ): TResult; /** * @see _.defaults */ defaults<TResult extends {}>( object: {}, ...sources: {}[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.defaults */ defaults<S1 extends {}, TResult extends {}>( source1: S1, ...sources: {}[] ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.defaults */ defaults<S1 extends {}, S2 extends {}, TResult extends {}>( source1: S1, source2: S2, ...sources: {}[] ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.defaults */ defaults<S1 extends {}, S2 extends {}, S3 extends {}, TResult extends {}>( source1: S1, source2: S2, source3: S3, ...sources: {}[] ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.defaults */ defaults<S1 extends {}, S2 extends {}, S3 extends {}, S4 extends {}, TResult extends {}>( source1: S1, source2: S2, source3: S3, source4: S4, ...sources: {}[] ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.defaults */ defaults(): LoDashImplicitObjectWrapper<T>; /** * @see _.defaults */ defaults<TResult>(...sources: {}[]): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.defaults */ defaults<S1 extends {}, TResult extends {}>( source1: S1, ...sources: {}[] ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.defaults */ defaults<S1 extends {}, S2 extends {}, TResult extends {}>( source1: S1, source2: S2, ...sources: {}[] ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.defaults */ defaults<S1 extends {}, S2 extends {}, S3 extends {}, TResult extends {}>( source1: S1, source2: S2, source3: S3, ...sources: {}[] ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.defaults */ defaults<S1 extends {}, S2 extends {}, S3 extends {}, S4 extends {}, TResult extends {}>( source1: S1, source2: S2, source3: S3, source4: S4, ...sources: {}[] ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.defaults */ defaults(): LoDashExplicitObjectWrapper<T>; /** * @see _.defaults */ defaults<TResult>(...sources: {}[]): LoDashExplicitObjectWrapper<TResult>; } //_.defaultsDeep interface LoDashStatic { /** * This method is like _.defaults except that it recursively assigns default properties. * @param object The destination object. * @param sources The source objects. * @return Returns object. **/ defaultsDeep<T, TResult>( object: T, ...sources: any[]): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.defaultsDeep **/ defaultsDeep<TResult>(...sources: any[]): LoDashImplicitObjectWrapper<TResult> } //_.extend interface LoDashStatic { /** * @see assign */ extend<TObject extends {}, TSource extends {}, TResult extends {}>( object: TObject, source: TSource, customizer?: AssignCustomizer ): TResult; /** * @see assign */ extend<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2, customizer?: AssignCustomizer ): TResult; /** * @see assign */ extend<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, customizer?: AssignCustomizer ): TResult; /** * @see assign */ extend<TObject extends {}, TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}> ( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer?: AssignCustomizer ): TResult; /** * @see _.assign */ extend<TObject extends {}>(object: TObject): TObject; /** * @see _.assign */ extend<TObject extends {}, TResult extends {}>( object: TObject, ...otherArgs: any[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.assign */ extend<TSource extends {}, TResult extends {}>( source: TSource, customizer?: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see assign */ extend<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, customizer?: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see assign */ extend<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, customizer?: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see assign */ extend<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer?: AssignCustomizer ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.assign */ extend(): LoDashImplicitObjectWrapper<T>; /** * @see _.assign */ extend<TResult extends {}>(...otherArgs: any[]): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.assign */ extend<TSource extends {}, TResult extends {}>( source: TSource, customizer?: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see assign */ extend<TSource1 extends {}, TSource2 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, customizer?: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see assign */ extend<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, customizer?: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see assign */ extend<TSource1 extends {}, TSource2 extends {}, TSource3 extends {}, TSource4 extends {}, TResult extends {}>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer?: AssignCustomizer ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.assign */ extend(): LoDashExplicitObjectWrapper<T>; /** * @see _.assign */ extend<TResult extends {}>(...otherArgs: any[]): LoDashExplicitObjectWrapper<TResult>; } //_.findKey interface LoDashStatic { /** * This method is like _.find except that it returns the key of the first element predicate returns truthy for * instead of the element itself. * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param object The object to search. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the key of the matched element, else undefined. */ findKey<TValues, TObject>( object: TObject, predicate?: DictionaryIterator<TValues, boolean> ): string; /** * @see _.findKey */ findKey<TObject>( object: TObject, predicate?: ObjectIterator<any, boolean> ): string; /** * @see _.findKey */ findKey<TObject>( object: TObject, predicate?: string ): string; /** * @see _.findKey */ findKey<TWhere extends Dictionary<any>, TObject>( object: TObject, predicate?: TWhere ): string; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.findKey */ findKey<TValues>( predicate?: DictionaryIterator<TValues, boolean> ): string; /** * @see _.findKey */ findKey( predicate?: ObjectIterator<any, boolean> ): string; /** * @see _.findKey */ findKey( predicate?: string ): string; /** * @see _.findKey */ findKey<TWhere extends Dictionary<any>>( predicate?: TWhere ): string; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.findKey */ findKey<TValues>( predicate?: DictionaryIterator<TValues, boolean> ): LoDashExplicitWrapper<string>; /** * @see _.findKey */ findKey( predicate?: ObjectIterator<any, boolean> ): LoDashExplicitWrapper<string>; /** * @see _.findKey */ findKey( predicate?: string ): LoDashExplicitWrapper<string>; /** * @see _.findKey */ findKey<TWhere extends Dictionary<any>>( predicate?: TWhere ): LoDashExplicitWrapper<string>; } //_.findLastKey interface LoDashStatic { /** * This method is like _.findKey except that it iterates over elements of a collection in the opposite order. * * If a property name is provided for predicate the created _.property style callback returns the property * value of the given element. * * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for * elements that have a matching property value, else false. * * If an object is provided for predicate the created _.matches style callback returns true for elements that * have the properties of the given object, else false. * * @param object The object to search. * @param predicate The function invoked per iteration. * @param thisArg The this binding of predicate. * @return Returns the key of the matched element, else undefined. */ findLastKey<TValues, TObject>( object: TObject, predicate?: DictionaryIterator<TValues, boolean> ): string; /** * @see _.findLastKey */ findLastKey<TObject>( object: TObject, predicate?: ObjectIterator<any, boolean> ): string; /** * @see _.findLastKey */ findLastKey<TObject>( object: TObject, predicate?: string ): string; /** * @see _.findLastKey */ findLastKey<TWhere extends Dictionary<any>, TObject>( object: TObject, predicate?: TWhere ): string; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.findLastKey */ findLastKey<TValues>( predicate?: DictionaryIterator<TValues, boolean> ): string; /** * @see _.findLastKey */ findLastKey( predicate?: ObjectIterator<any, boolean> ): string; /** * @see _.findLastKey */ findLastKey( predicate?: string ): string; /** * @see _.findLastKey */ findLastKey<TWhere extends Dictionary<any>>( predicate?: TWhere ): string; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.findLastKey */ findLastKey<TValues>( predicate?: DictionaryIterator<TValues, boolean> ): LoDashExplicitWrapper<string>; /** * @see _.findLastKey */ findLastKey( predicate?: ObjectIterator<any, boolean> ): LoDashExplicitWrapper<string>; /** * @see _.findLastKey */ findLastKey( predicate?: string ): LoDashExplicitWrapper<string>; /** * @see _.findLastKey */ findLastKey<TWhere extends Dictionary<any>>( predicate?: TWhere ): LoDashExplicitWrapper<string>; } //_.forIn interface LoDashStatic { /** * Iterates over own and inherited enumerable properties of an object invoking iteratee for each property. The * iteratee is bound to thisArg and invoked with three arguments: (value, key, object). Iteratee functions may * exit iteration early by explicitly returning false. * * @param object The object to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. * @return Returns object. */ forIn<T>( object: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.forIn */ forIn<T extends {}>( object: T, iteratee?: ObjectIterator<any, any> ): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.forIn */ forIn<TValue>( iteratee?: DictionaryIterator<TValue, any> ): _.LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.forIn */ forIn<TValue>( iteratee?: DictionaryIterator<TValue, any> ): _.LoDashExplicitObjectWrapper<T>; } //_.forInRight interface LoDashStatic { /** * This method is like _.forIn except that it iterates over properties of object in the opposite order. * * @param object The object to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. * @return Returns object. */ forInRight<T>( object: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.forInRight */ forInRight<T extends {}>( object: T, iteratee?: ObjectIterator<any, any> ): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.forInRight */ forInRight<TValue>( iteratee?: DictionaryIterator<TValue, any> ): _.LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.forInRight */ forInRight<TValue>( iteratee?: DictionaryIterator<TValue, any> ): _.LoDashExplicitObjectWrapper<T>; } //_.forOwn interface LoDashStatic { /** * Iterates over own enumerable properties of an object invoking iteratee for each property. The iteratee is * bound to thisArg and invoked with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning false. * * @param object The object to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. * @return Returns object. */ forOwn<T>( object: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.forOwn */ forOwn<T extends {}>( object: T, iteratee?: ObjectIterator<any, any> ): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.forOwn */ forOwn<TValue>( iteratee?: DictionaryIterator<TValue, any> ): _.LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.forOwn */ forOwn<TValue>( iteratee?: DictionaryIterator<TValue, any> ): _.LoDashExplicitObjectWrapper<T>; } //_.forOwnRight interface LoDashStatic { /** * This method is like _.forOwn except that it iterates over properties of object in the opposite order. * * @param object The object to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. * @return Returns object. */ forOwnRight<T>( object: Dictionary<T>, iteratee?: DictionaryIterator<T, any> ): Dictionary<T>; /** * @see _.forOwnRight */ forOwnRight<T extends {}>( object: T, iteratee?: ObjectIterator<any, any> ): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.forOwnRight */ forOwnRight<TValue>( iteratee?: DictionaryIterator<TValue, any> ): _.LoDashImplicitObjectWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.forOwnRight */ forOwnRight<TValue>( iteratee?: DictionaryIterator<TValue, any> ): _.LoDashExplicitObjectWrapper<T>; } //_.functions interface LoDashStatic { /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the new array of property names. * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ functions<T extends {}>(object: any): string[]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.functions */ functions(): _.LoDashImplicitArrayWrapper<string>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.functions */ functions(): _.LoDashExplicitArrayWrapper<string>; } //_.functionsIn interface LoDashStatic { /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the new array of property names. * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ functionsIn<T extends {}>(object: any): string[]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.functionsIn */ functionsIn(): _.LoDashImplicitArrayWrapper<string>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.functionsIn */ functionsIn(): _.LoDashExplicitArrayWrapper<string>; } //_.get interface LoDashStatic { /** * Gets the property value at path of object. If the resolved value is undefined the defaultValue is used * in its place. * * @param object The object to query. * @param path The path of the property to get. * @param defaultValue The value returned if the resolved value is undefined. * @return Returns the resolved value. */ get<TObject, TResult>( object: TObject, path: StringRepresentable|StringRepresentable[], defaultValue?: TResult ): TResult; /** * @see _.get */ get<TResult>( object: any, path: StringRepresentable|StringRepresentable[], defaultValue?: TResult ): TResult; } interface LoDashImplicitWrapper<T> { /** * @see _.get */ get<TResult>( path: StringRepresentable|StringRepresentable[], defaultValue?: TResult ): TResult; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.get */ get<TResult>( path: StringRepresentable|StringRepresentable[], defaultValue?: TResult ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.get */ get<TResult>( path: StringRepresentable|StringRepresentable[], defaultValue?: TResult ): TResult; } interface LoDashExplicitWrapper<T> { /** * @see _.get */ get<TResultWrapper>( path: StringRepresentable|StringRepresentable[], defaultValue?: any ): TResultWrapper; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.get */ get<TResultWrapper>( path: StringRepresentable|StringRepresentable[], defaultValue?: any ): TResultWrapper; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.get */ get<TResultWrapper>( path: StringRepresentable|StringRepresentable[], defaultValue?: any ): TResultWrapper; } //_.has interface LoDashStatic { /** * Checks if `path` is a direct property of `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': { 'c': 3 } } }; * var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b.c'); * // => true * * _.has(object, ['a', 'b', 'c']); * // => true * * _.has(other, 'a'); * // => false */ has<T extends {}>( object: T, path: StringRepresentable|StringRepresentable[] ): boolean; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.has */ has(path: StringRepresentable|StringRepresentable[]): boolean; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.has */ has(path: StringRepresentable|StringRepresentable[]): LoDashExplicitWrapper<boolean>; } //_.hasIn interface LoDashStatic { /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b.c'); * // => true * * _.hasIn(object, ['a', 'b', 'c']); * // => true * * _.hasIn(object, 'b'); * // => false */ hasIn<T extends {}>( object: T, path: StringRepresentable|StringRepresentable[] ): boolean; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.hasIn */ hasIn(path: StringRepresentable|StringRepresentable[]): boolean; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.hasIn */ hasIn(path: StringRepresentable|StringRepresentable[]): LoDashExplicitWrapper<boolean>; } //_.invert interface LoDashStatic { /** * Creates an object composed of the inverted keys and values of object. If object contains duplicate values, * subsequent values overwrite property assignments of previous values unless multiValue is true. * * @param object The object to invert. * @param multiValue Allow multiple values per key. * @return Returns the new inverted object. */ invert<T extends {}, TResult extends {}>( object: T, multiValue?: boolean ): TResult; /** * @see _.invert */ invert<TResult extends {}>( object: Object, multiValue?: boolean ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.invert */ invert<TResult extends {}>(multiValue?: boolean): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.invert */ invert<TResult extends {}>(multiValue?: boolean): LoDashExplicitObjectWrapper<TResult>; } //_.inverBy interface InvertByIterator<T> { (value: T): any; } interface LoDashStatic { /** * This method is like _.invert except that the inverted object is generated from the results of running each * element of object through iteratee. The corresponding inverted value of each inverted key is an array of * keys responsible for generating the inverted value. The iteratee is invoked with one argument: (value). * * @param object The object to invert. * @param interatee The iteratee invoked per element. * @return Returns the new inverted object. */ invertBy( object: Object, interatee?: InvertByIterator<any>|string ): Dictionary<string[]>; /** * @see _.invertBy */ invertBy<T>( object: _.Dictionary<T>|_.NumericDictionary<T>, interatee?: InvertByIterator<T>|string ): Dictionary<string[]>; /** * @see _.invertBy */ invertBy<W>( object: Object, interatee?: W ): Dictionary<string[]>; /** * @see _.invertBy */ invertBy<T, W>( object: _.Dictionary<T>, interatee?: W ): Dictionary<string[]>; } interface LoDashImplicitWrapper<T> { /** * @see _.invertBy */ invertBy( interatee?: InvertByIterator<any> ): LoDashImplicitObjectWrapper<Dictionary<string[]>>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.invertBy */ invertBy( interatee?: InvertByIterator<T>|string ): LoDashImplicitObjectWrapper<Dictionary<string[]>>; /** * @see _.invertBy */ invertBy<W>( interatee?: W ): LoDashImplicitObjectWrapper<Dictionary<string[]>>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.invertBy */ invertBy( interatee?: InvertByIterator<any>|string ): LoDashImplicitObjectWrapper<Dictionary<string[]>>; /** * @see _.invertBy */ invertBy<W>( interatee?: W ): LoDashImplicitObjectWrapper<Dictionary<string[]>>; } interface LoDashExplicitWrapper<T> { /** * @see _.invertBy */ invertBy( interatee?: InvertByIterator<any> ): LoDashExplicitObjectWrapper<Dictionary<string[]>>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.invertBy */ invertBy( interatee?: InvertByIterator<T>|string ): LoDashExplicitObjectWrapper<Dictionary<string[]>>; /** * @see _.invertBy */ invertBy<W>( interatee?: W ): LoDashExplicitObjectWrapper<Dictionary<string[]>>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.invertBy */ invertBy( interatee?: InvertByIterator<any>|string ): LoDashExplicitObjectWrapper<Dictionary<string[]>>; /** * @see _.invertBy */ invertBy<W>( interatee?: W ): LoDashExplicitObjectWrapper<Dictionary<string[]>>; } //_.keys interface LoDashStatic { /** * Creates an array of the own enumerable property names of object. * * Note: Non-object values are coerced to objects. See the ES spec for more details. * * @param object The object to query. * @return Returns the array of property names. */ keys(object?: any): string[]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.keys */ keys(): LoDashImplicitArrayWrapper<string>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.keys */ keys(): LoDashExplicitArrayWrapper<string>; } //_.keysIn interface LoDashStatic { /** * Creates an array of the own and inherited enumerable property names of object. * * Note: Non-object values are coerced to objects. * * @param object The object to query. * @return An array of property names. */ keysIn(object?: any): string[]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.keysIn */ keysIn(): LoDashImplicitArrayWrapper<string>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.keysIn */ keysIn(): LoDashExplicitArrayWrapper<string>; } //_.mapKeys interface LoDashStatic { /** * The opposite of _.mapValues; this method creates an object with the same values as object and keys generated * by running each own enumerable property of object through iteratee. * * @param object The object to iterate over. * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. * @return Returns the new mapped object. */ mapKeys<T, TKey>( object: List<T>, iteratee?: ListIterator<T, TKey> ): Dictionary<T>; /** * @see _.mapKeys */ mapKeys<T, TKey>( object: Dictionary<T>, iteratee?: DictionaryIterator<T, TKey> ): Dictionary<T>; /** * @see _.mapKeys */ mapKeys<T, TObject extends {}>( object: List<T>|Dictionary<T>, iteratee?: TObject ): Dictionary<T>; /** * @see _.mapKeys */ mapKeys<T>( object: List<T>|Dictionary<T>, iteratee?: string ): Dictionary<T>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.mapKeys */ mapKeys<TKey>( iteratee?: ListIterator<T, TKey> ): LoDashImplicitObjectWrapper<Dictionary<T>>; /** * @see _.mapKeys */ mapKeys<TObject extends {}>( iteratee?: TObject ): LoDashImplicitObjectWrapper<Dictionary<T>>; /** * @see _.mapKeys */ mapKeys( iteratee?: string ): LoDashImplicitObjectWrapper<Dictionary<T>>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.mapKeys */ mapKeys<TResult, TKey>( iteratee?: ListIterator<TResult, TKey>|DictionaryIterator<TResult, TKey> ): LoDashImplicitObjectWrapper<Dictionary<TResult>>; /** * @see _.mapKeys */ mapKeys<TResult, TObject extends {}>( iteratee?: TObject ): LoDashImplicitObjectWrapper<Dictionary<TResult>>; /** * @see _.mapKeys */ mapKeys<TResult>( iteratee?: string ): LoDashImplicitObjectWrapper<Dictionary<TResult>>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.mapKeys */ mapKeys<TKey>( iteratee?: ListIterator<T, TKey> ): LoDashExplicitObjectWrapper<Dictionary<T>>; /** * @see _.mapKeys */ mapKeys<TObject extends {}>( iteratee?: TObject ): LoDashExplicitObjectWrapper<Dictionary<T>>; /** * @see _.mapKeys */ mapKeys( iteratee?: string ): LoDashExplicitObjectWrapper<Dictionary<T>>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.mapKeys */ mapKeys<TResult, TKey>( iteratee?: ListIterator<TResult, TKey>|DictionaryIterator<TResult, TKey> ): LoDashExplicitObjectWrapper<Dictionary<TResult>>; /** * @see _.mapKeys */ mapKeys<TResult, TObject extends {}>( iteratee?: TObject ): LoDashExplicitObjectWrapper<Dictionary<TResult>>; /** * @see _.mapKeys */ mapKeys<TResult>( iteratee?: string ): LoDashExplicitObjectWrapper<Dictionary<TResult>>; } //_.mapValues interface LoDashStatic { /** * Creates an object with the same keys as object and values generated by running each own * enumerable property of object through iteratee. The iteratee function is bound to thisArg * and invoked with three arguments: (value, key, object). * * If a property name is provided iteratee the created "_.property" style callback returns * the property value of the given element. * * If a value is also provided for thisArg the creted "_.matchesProperty" style callback returns * true for elements that have a matching property value, else false;. * * If an object is provided for iteratee the created "_.matches" style callback returns true * for elements that have the properties of the given object, else false. * * @param {Object} object The object to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration. * @param {Object} [thisArg] The `this` binding of `iteratee`. * @return {Object} Returns the new mapped object. */ mapValues<T, TResult>(obj: Dictionary<T>, callback: ObjectIterator<T, TResult>): Dictionary<TResult>; mapValues<T>(obj: Dictionary<T>, where: Dictionary<T>): Dictionary<boolean>; mapValues<T, TMapped>(obj: T, pluck: string): TMapped; mapValues<T>(obj: T, callback: ObjectIterator<any, any>): T; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.mapValues * TValue is the type of the property values of T. * TResult is the type output by the ObjectIterator function */ mapValues<TValue, TResult>(callback: ObjectIterator<TValue, TResult>): LoDashImplicitObjectWrapper<Dictionary<TResult>>; /** * @see _.mapValues * TResult is the type of the property specified by pluck. * T should be a Dictionary<Dictionary<TResult>> */ mapValues<TResult>(pluck: string): LoDashImplicitObjectWrapper<Dictionary<TResult>>; /** * @see _.mapValues * TResult is the type of the properties of each object in the values of T * T should be a Dictionary<Dictionary<TResult>> */ mapValues<TResult>(where: Dictionary<TResult>): LoDashImplicitArrayWrapper<boolean>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.mapValues * TValue is the type of the property values of T. * TResult is the type output by the ObjectIterator function */ mapValues<TValue, TResult>(callback: ObjectIterator<TValue, TResult>): LoDashExplicitObjectWrapper<Dictionary<TResult>>; /** * @see _.mapValues * TResult is the type of the property specified by pluck. * T should be a Dictionary<Dictionary<TResult>> */ mapValues<TResult>(pluck: string): LoDashExplicitObjectWrapper<Dictionary<TResult>>; /** * @see _.mapValues * TResult is the type of the properties of each object in the values of T * T should be a Dictionary<Dictionary<TResult>> */ mapValues<TResult>(where: Dictionary<TResult>): LoDashExplicitObjectWrapper<boolean>; } //_.merge interface LoDashStatic { /** * Recursively merges own and inherited enumerable properties of source * objects into the destination object, skipping source properties that resolve * to `undefined`. Array and plain object properties are merged recursively. * Other objects and value types are overridden by assignment. Source objects * are applied from left to right. Subsequent sources overwrite property * assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } */ merge<TObject, TSource>( object: TObject, source: TSource ): TObject & TSource; /** * @see _.merge */ merge<TObject, TSource1, TSource2>( object: TObject, source1: TSource1, source2: TSource2 ): TObject & TSource1 & TSource2; /** * @see _.merge */ merge<TObject, TSource1, TSource2, TSource3>( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3 ): TObject & TSource1 & TSource2 & TSource3; /** * @see _.merge */ merge<TObject, TSource1, TSource2, TSource3, TSource4>( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.merge */ merge<TResult>( object: any, ...otherArgs: any[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.merge */ merge<TSource>( source: TSource ): LoDashImplicitObjectWrapper<T & TSource>; /** * @see _.merge */ merge<TSource1, TSource2>( source1: TSource1, source2: TSource2 ): LoDashImplicitObjectWrapper<T & TSource1 & TSource2>; /** * @see _.merge */ merge<TSource1, TSource2, TSource3>( source1: TSource1, source2: TSource2, source3: TSource3 ): LoDashImplicitObjectWrapper<T & TSource1 & TSource2 & TSource3>; /** * @see _.merge */ merge<TSource1, TSource2, TSource3, TSource4>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 ): LoDashImplicitObjectWrapper<T & TSource1 & TSource2 & TSource3 & TSource4>; /** * @see _.merge */ merge<TResult>( ...otherArgs: any[] ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.merge */ merge<TSource>( source: TSource ): LoDashExplicitObjectWrapper<T & TSource>; /** * @see _.merge */ merge<TSource1, TSource2>( source1: TSource1, source2: TSource2 ): LoDashExplicitObjectWrapper<T & TSource1 & TSource2>; /** * @see _.merge */ merge<TSource1, TSource2, TSource3>( source1: TSource1, source2: TSource2, source3: TSource3 ): LoDashExplicitObjectWrapper<T & TSource1 & TSource2 & TSource3>; /** * @see _.merge */ merge<TSource1, TSource2, TSource3, TSource4>( ): LoDashExplicitObjectWrapper<T & TSource1 & TSource2 & TSource3 & TSource4>; /** * @see _.merge */ merge<TResult>( ...otherArgs: any[] ): LoDashExplicitObjectWrapper<TResult>; } //_.mergeWith interface MergeWithCustomizer { (value: any, srcValue: any, key?: string, object?: Object, source?: Object): any; } interface LoDashStatic { /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined` merging is handled by the * method instead. The `customizer` is invoked with seven arguments: * (objValue, srcValue, key, object, source, stack). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, customizer); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ mergeWith<TObject, TSource>( object: TObject, source: TSource, customizer: MergeWithCustomizer ): TObject & TSource; /** * @see _.mergeWith */ mergeWith<TObject, TSource1, TSource2>( object: TObject, source1: TSource1, source2: TSource2, customizer: MergeWithCustomizer ): TObject & TSource1 & TSource2; /** * @see _.mergeWith */ mergeWith<TObject, TSource1, TSource2, TSource3>( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, customizer: MergeWithCustomizer ): TObject & TSource1 & TSource2 & TSource3; /** * @see _.mergeWith */ mergeWith<TObject, TSource1, TSource2, TSource3, TSource4>( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: MergeWithCustomizer ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.mergeWith */ mergeWith<TResult>( object: any, ...otherArgs: any[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.mergeWith */ mergeWith<TSource>( source: TSource, customizer: MergeWithCustomizer ): LoDashImplicitObjectWrapper<T & TSource>; /** * @see _.mergeWith */ mergeWith<TSource1, TSource2>( source1: TSource1, source2: TSource2, customizer: MergeWithCustomizer ): LoDashImplicitObjectWrapper<T & TSource1 & TSource2>; /** * @see _.mergeWith */ mergeWith<TSource1, TSource2, TSource3>( source1: TSource1, source2: TSource2, source3: TSource3, customizer: MergeWithCustomizer ): LoDashImplicitObjectWrapper<T & TSource1 & TSource2 & TSource3>; /** * @see _.mergeWith */ mergeWith<TSource1, TSource2, TSource3, TSource4>( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: MergeWithCustomizer ): LoDashImplicitObjectWrapper<T & TSource1 & TSource2 & TSource3 & TSource4>; /** * @see _.mergeWith */ mergeWith<TResult>( ...otherArgs: any[] ): LoDashImplicitObjectWrapper<TResult>; } //_.omit interface LoDashStatic { /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable properties of `object` that are not omitted. * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [props] The property names to omit, specified * individually or in arrays.. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ omit<TResult extends {}, T extends {}>( object: T, ...predicate: (StringRepresentable|StringRepresentable[])[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.omit */ omit<TResult extends {}>( ...predicate: (StringRepresentable|StringRepresentable[])[] ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.omit */ omit<TResult extends {}>( ...predicate: (StringRepresentable|StringRepresentable[])[] ): LoDashExplicitObjectWrapper<TResult>; } //_.omitBy interface LoDashStatic { /** * The opposite of `_.pickBy`; this method creates an object composed of the * own and inherited enumerable properties of `object` that `predicate` * doesn't return truthy for. * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {Function|Object|string} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ omitBy<TResult extends {}, T extends {}>( object: T, predicate: ObjectIterator<any, boolean> ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.omitBy */ omitBy<TResult extends {}>( predicate: ObjectIterator<any, boolean> ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.omitBy */ omitBy<TResult extends {}>( predicate: ObjectIterator<any, boolean> ): LoDashExplicitObjectWrapper<TResult>; } //_.pick interface LoDashStatic { /** * Creates an object composed of the picked `object` properties. * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [props] The property names to pick, specified * individually or in arrays. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ pick<TResult extends {}, T extends {}>( object: T, ...predicate: (StringRepresentable|StringRepresentable[])[] ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.pick */ pick<TResult extends {}>( ...predicate: (StringRepresentable|StringRepresentable[])[] ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.pick */ pick<TResult extends {}>( ...predicate: (StringRepresentable|StringRepresentable[])[] ): LoDashExplicitObjectWrapper<TResult>; } //_.pickBy interface LoDashStatic { /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with one argument: (value). * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {Function|Object|string} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ pickBy<TResult extends {}, T extends {}>( object: T, predicate?: ObjectIterator<any, boolean> ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.pickBy */ pickBy<TResult extends {}>( predicate?: ObjectIterator<any, boolean> ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.pickBy */ pickBy<TResult extends {}>( predicate?: ObjectIterator<any, boolean> ): LoDashExplicitObjectWrapper<TResult>; } //_.result interface LoDashStatic { /** * This method is like _.get except that if the resolved value is a function it’s invoked with the this binding * of its parent object and its result is returned. * * @param object The object to query. * @param path The path of the property to resolve. * @param defaultValue The value returned if the resolved value is undefined. * @return Returns the resolved value. */ result<TObject, TResult>( object: TObject, path: StringRepresentable|StringRepresentable[], defaultValue?: TResult|((...args: any[]) => TResult) ): TResult; /** * @see _.result */ result<TResult>( object: any, path: StringRepresentable|StringRepresentable[], defaultValue?: TResult|((...args: any[]) => TResult) ): TResult; } interface LoDashImplicitWrapper<T> { /** * @see _.result */ result<TResult>( path: StringRepresentable|StringRepresentable[], defaultValue?: TResult|((...args: any[]) => TResult) ): TResult; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.result */ result<TResult>( path: StringRepresentable|StringRepresentable[], defaultValue?: TResult|((...args: any[]) => TResult) ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.result */ result<TResult>( path: StringRepresentable|StringRepresentable[], defaultValue?: TResult|((...args: any[]) => TResult) ): TResult; } interface LoDashExplicitWrapper<T> { /** * @see _.result */ result<TResultWrapper>( path: StringRepresentable|StringRepresentable[], defaultValue?: any ): TResultWrapper; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.result */ result<TResultWrapper>( path: StringRepresentable|StringRepresentable[], defaultValue?: any ): TResultWrapper; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.result */ result<TResultWrapper>( path: StringRepresentable|StringRepresentable[], defaultValue?: any ): TResultWrapper; } //_.set interface LoDashStatic { /** * Sets the value at path of object. If a portion of path doesn’t exist it’s created. Arrays are created for * missing index properties while objects are created for all other missing properties. Use _.setWith to * customize path creation. * * @param object The object to modify. * @param path The path of the property to set. * @param value The value to set. * @return Returns object. */ set<TResult>( object: Object, path: StringRepresentable|StringRepresentable[], value: any ): TResult; /** * @see _.set */ set<V, TResult>( object: Object, path: StringRepresentable|StringRepresentable[], value: V ): TResult; /** * @see _.set */ set<O, V, TResult>( object: O, path: StringRepresentable|StringRepresentable[], value: V ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.set */ set<TResult>( path: StringRepresentable|StringRepresentable[], value: any ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.set */ set<V, TResult>( path: StringRepresentable|StringRepresentable[], value: V ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.set */ set<TResult>( path: StringRepresentable|StringRepresentable[], value: any ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.set */ set<V, TResult>( path: StringRepresentable|StringRepresentable[], value: V ): LoDashExplicitObjectWrapper<TResult>; } //_.setWith interface SetWithCustomizer<T> { (nsValue: any, key: string, nsObject: T): any; } interface LoDashStatic { /** * This method is like _.set except that it accepts customizer which is invoked to produce the objects of * path. If customizer returns undefined path creation is handled by the method instead. The customizer is * invoked with three arguments: (nsValue, key, nsObject). * * @param object The object to modify. * @param path The path of the property to set. * @param value The value to set. * @parem customizer The function to customize assigned values. * @return Returns object. */ setWith<TResult>( object: Object, path: StringRepresentable|StringRepresentable[], value: any, customizer?: SetWithCustomizer<Object> ): TResult; /** * @see _.setWith */ setWith<V, TResult>( object: Object, path: StringRepresentable|StringRepresentable[], value: V, customizer?: SetWithCustomizer<Object> ): TResult; /** * @see _.setWith */ setWith<O, V, TResult>( object: O, path: StringRepresentable|StringRepresentable[], value: V, customizer?: SetWithCustomizer<O> ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.setWith */ setWith<TResult>( path: StringRepresentable|StringRepresentable[], value: any, customizer?: SetWithCustomizer<T> ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.setWith */ setWith<V, TResult>( path: StringRepresentable|StringRepresentable[], value: V, customizer?: SetWithCustomizer<T> ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.setWith */ setWith<TResult>( path: StringRepresentable|StringRepresentable[], value: any, customizer?: SetWithCustomizer<T> ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.setWith */ setWith<V, TResult>( path: StringRepresentable|StringRepresentable[], value: V, customizer?: SetWithCustomizer<T> ): LoDashExplicitObjectWrapper<TResult>; } //_.toPairs interface LoDashStatic { /** * Creates an array of own enumerable key-value pairs for object. * * @param object The object to query. * @return Returns the new array of key-value pairs. */ toPairs<T extends {}>(object?: T): any[][]; toPairs<T extends {}, TResult>(object?: T): TResult[][]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.toPairs */ toPairs<TResult>(): LoDashImplicitArrayWrapper<TResult[]>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.toPairs */ toPairs<TResult>(): LoDashExplicitArrayWrapper<TResult[]>; } //_.toPairsIn interface LoDashStatic { /** * Creates an array of own and inherited enumerable key-value pairs for object. * * @param object The object to query. * @return Returns the new array of key-value pairs. */ toPairsIn<T extends {}>(object?: T): any[][]; toPairsIn<T extends {}, TResult>(object?: T): TResult[][]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.toPairsIn */ toPairsIn<TResult>(): LoDashImplicitArrayWrapper<TResult[]>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.toPairsIn */ toPairsIn<TResult>(): LoDashExplicitArrayWrapper<TResult[]>; } //_.transform interface LoDashStatic { /** * An alternative to _.reduce; this method transforms object to a new accumulator object which is the result of * running each of its own enumerable properties through iteratee, with each invocation potentially mutating * the accumulator object. The iteratee is bound to thisArg and invoked with four arguments: (accumulator, * value, key, object). Iteratee functions may exit iteration early by explicitly returning false. * * @param object The object to iterate over. * @param iteratee The function invoked per iteration. * @param accumulator The custom accumulator value. * @param thisArg The this binding of iteratee. * @return Returns the accumulated value. */ transform<T, TResult>( object: T[], iteratee?: MemoVoidArrayIterator<T, TResult[]>, accumulator?: TResult[] ): TResult[]; /** * @see _.transform */ transform<T, TResult>( object: T[], iteratee?: MemoVoidArrayIterator<T, Dictionary<TResult>>, accumulator?: Dictionary<TResult> ): Dictionary<TResult>; /** * @see _.transform */ transform<T, TResult>( object: Dictionary<T>, iteratee?: MemoVoidDictionaryIterator<T, Dictionary<TResult>>, accumulator?: Dictionary<TResult> ): Dictionary<TResult>; /** * @see _.transform */ transform<T, TResult>( object: Dictionary<T>, iteratee?: MemoVoidDictionaryIterator<T, TResult[]>, accumulator?: TResult[] ): TResult[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.transform */ transform<TResult>( iteratee?: MemoVoidArrayIterator<T, TResult[]>, accumulator?: TResult[] ): LoDashImplicitArrayWrapper<TResult>; /** * @see _.transform */ transform<TResult>( iteratee?: MemoVoidArrayIterator<T, Dictionary<TResult>>, accumulator?: Dictionary<TResult> ): LoDashImplicitObjectWrapper<Dictionary<TResult>>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.transform */ transform<T, TResult>( iteratee?: MemoVoidDictionaryIterator<T, Dictionary<TResult>>, accumulator?: Dictionary<TResult> ): LoDashImplicitObjectWrapper<Dictionary<TResult>>; /** * @see _.transform */ transform<T, TResult>( iteratee?: MemoVoidDictionaryIterator<T, TResult[]>, accumulator?: TResult[] ): LoDashImplicitArrayWrapper<TResult>; } //_.unset interface LoDashStatic { /** * Removes the property at path of object. * * Note: This method mutates object. * * @param object The object to modify. * @param path The path of the property to unset. * @return Returns true if the property is deleted, else false. */ unset<T>( object: T, path: StringRepresentable|StringRepresentable[] ): boolean; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.unset */ unset(path: StringRepresentable|StringRepresentable[]): LoDashImplicitWrapper<boolean>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.unset */ unset(path: StringRepresentable|StringRepresentable[]): LoDashExplicitWrapper<boolean>; } //_.update interface LoDashStatic { /** * This method is like _.set except that accepts updater to produce the value to set. Use _.updateWith to * customize path creation. The updater is invoked with one argument: (value). * * @param object The object to modify. * @param path The path of the property to set. * @param updater The function to produce the updated value. * @return Returns object. */ update<TResult>( object: Object, path: StringRepresentable|StringRepresentable[], updater: Function ): TResult; /** * @see _.update */ update<U extends Function, TResult>( object: Object, path: StringRepresentable|StringRepresentable[], updater: U ): TResult; /** * @see _.update */ update<O extends {}, TResult>( object: O, path: StringRepresentable|StringRepresentable[], updater: Function ): TResult; /** * @see _.update */ update<O, U extends Function, TResult>( object: O, path: StringRepresentable|StringRepresentable[], updater: U ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.update */ update<TResult>( path: StringRepresentable|StringRepresentable[], updater: any ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.update */ update<U extends Function, TResult>( path: StringRepresentable|StringRepresentable[], updater: U ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.update */ update<TResult>( path: StringRepresentable|StringRepresentable[], updater: any ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.update */ update<U extends Function, TResult>( path: StringRepresentable|StringRepresentable[], updater: U ): LoDashExplicitObjectWrapper<TResult>; } //_.values interface LoDashStatic { /** * Creates an array of the own enumerable property values of object. * * @param object The object to query. * @return Returns an array of property values. */ values<T>(object?: any): T[]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.values */ values<T>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.values */ values<T>(): LoDashExplicitArrayWrapper<T>; } //_.valuesIn interface LoDashStatic { /** * Creates an array of the own and inherited enumerable property values of object. * * @param object The object to query. * @return Returns the array of property values. */ valuesIn<T>(object?: any): T[]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.valuesIn */ valuesIn<T>(): LoDashImplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.valuesIn */ valuesIn<T>(): LoDashExplicitArrayWrapper<T>; } /********** * String * **********/ //_.camelCase interface LoDashStatic { /** * Converts string to camel case. * * @param string The string to convert. * @return Returns the camel cased string. */ camelCase(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.camelCase */ camelCase(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.camelCase */ camelCase(): LoDashExplicitWrapper<string>; } //_.capitalize interface LoDashStatic { /** * Converts the first character of string to upper case and the remaining to lower case. * * @param string The string to capitalize. * @return Returns the capitalized string. */ capitalize(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.capitalize */ capitalize(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.capitalize */ capitalize(): LoDashExplicitWrapper<string>; } //_.deburr interface LoDashStatic { /** * Deburrs string by converting latin-1 supplementary letters to basic latin letters and removing combining * diacritical marks. * * @param string The string to deburr. * @return Returns the deburred string. */ deburr(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.deburr */ deburr(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.deburr */ deburr(): LoDashExplicitWrapper<string>; } //_.endsWith interface LoDashStatic { /** * Checks if string ends with the given target string. * * @param string The string to search. * @param target The string to search for. * @param position The position to search from. * @return Returns true if string ends with target, else false. */ endsWith( string?: string, target?: string, position?: number ): boolean; } interface LoDashImplicitWrapper<T> { /** * @see _.endsWith */ endsWith( target?: string, position?: number ): boolean; } interface LoDashExplicitWrapper<T> { /** * @see _.endsWith */ endsWith( target?: string, position?: number ): LoDashExplicitWrapper<boolean>; } // _.escape interface LoDashStatic { /** * Converts the characters "&", "<", ">", '"', "'", and "`" in string to their corresponding HTML entities. * * Note: No other characters are escaped. To escape additional characters use a third-party library like he. * * hough the ">" character is escaped for symmetry, characters like ">" and "/" don’t need escaping in HTML * and have no special meaning unless they're part of a tag or unquoted attribute value. See Mathias Bynens’s * article (under "semi-related fun fact") for more details. * * Backticks are escaped because in IE < 9, they can break out of attribute values or HTML comments. See #59, * #102, #108, and #133 of the HTML5 Security Cheatsheet for more details. * * When working with HTML you should always quote attribute values to reduce XSS vectors. * * @param string The string to escape. * @return Returns the escaped string. */ escape(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.escape */ escape(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.escape */ escape(): LoDashExplicitWrapper<string>; } // _.escapeRegExp interface LoDashStatic { /** * Escapes the RegExp special characters "^", "$", "\", ".", "*", "+", "?", "(", ")", "[", "]", * "{", "}", and "|" in string. * * @param string The string to escape. * @return Returns the escaped string. */ escapeRegExp(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.escapeRegExp */ escapeRegExp(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.escapeRegExp */ escapeRegExp(): LoDashExplicitWrapper<string>; } //_.kebabCase interface LoDashStatic { /** * Converts string to kebab case. * * @param string The string to convert. * @return Returns the kebab cased string. */ kebabCase(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.kebabCase */ kebabCase(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.kebabCase */ kebabCase(): LoDashExplicitWrapper<string>; } //_.lowerCase interface LoDashStatic { /** * Converts `string`, as space separated words, to lower case. * * @param string The string to convert. * @return Returns the lower cased string. */ lowerCase(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.lowerCase */ lowerCase(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.lowerCase */ lowerCase(): LoDashExplicitWrapper<string>; } //_.lowerFirst interface LoDashStatic { /** * Converts the first character of `string` to lower case. * * @param string The string to convert. * @return Returns the converted string. */ lowerFirst(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.lowerFirst */ lowerFirst(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.lowerFirst */ lowerFirst(): LoDashExplicitWrapper<string>; } //_.pad interface LoDashStatic { /** * Pads string on the left and right sides if it’s shorter than length. Padding characters are truncated if * they can’t be evenly divided by length. * * @param string The string to pad. * @param length The padding length. * @param chars The string used as padding. * @return Returns the padded string. */ pad( string?: string, length?: number, chars?: string ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.pad */ pad( length?: number, chars?: string ): string; } interface LoDashExplicitWrapper<T> { /** * @see _.pad */ pad( length?: number, chars?: string ): LoDashExplicitWrapper<string>; } //_.padEnd interface LoDashStatic { /** * Pads string on the right side if it’s shorter than length. Padding characters are truncated if they exceed * length. * * @param string The string to pad. * @param length The padding length. * @param chars The string used as padding. * @return Returns the padded string. */ padEnd( string?: string, length?: number, chars?: string ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.padEnd */ padEnd( length?: number, chars?: string ): string; } interface LoDashExplicitWrapper<T> { /** * @see _.padEnd */ padEnd( length?: number, chars?: string ): LoDashExplicitWrapper<string>; } //_.padStart interface LoDashStatic { /** * Pads string on the left side if it’s shorter than length. Padding characters are truncated if they exceed * length. * * @param string The string to pad. * @param length The padding length. * @param chars The string used as padding. * @return Returns the padded string. */ padStart( string?: string, length?: number, chars?: string ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.padStart */ padStart( length?: number, chars?: string ): string; } interface LoDashExplicitWrapper<T> { /** * @see _.padStart */ padStart( length?: number, chars?: string ): LoDashExplicitWrapper<string>; } //_.parseInt interface LoDashStatic { /** * Converts string to an integer of the specified radix. If radix is undefined or 0, a radix of 10 is used * unless value is a hexadecimal, in which case a radix of 16 is used. * * Note: This method aligns with the ES5 implementation of parseInt. * * @param string The string to convert. * @param radix The radix to interpret value by. * @return Returns the converted integer. */ parseInt( string: string, radix?: number ): number; } interface LoDashImplicitWrapper<T> { /** * @see _.parseInt */ parseInt(radix?: number): number; } interface LoDashExplicitWrapper<T> { /** * @see _.parseInt */ parseInt(radix?: number): LoDashExplicitWrapper<number>; } //_.repeat interface LoDashStatic { /** * Repeats the given string n times. * * @param string The string to repeat. * @param n The number of times to repeat the string. * @return Returns the repeated string. */ repeat( string?: string, n?: number ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.repeat */ repeat(n?: number): string; } interface LoDashExplicitWrapper<T> { /** * @see _.repeat */ repeat(n?: number): LoDashExplicitWrapper<string>; } //_.replace interface LoDashStatic { /** * Replaces matches for pattern in string with replacement. * * Note: This method is based on String#replace. * * @param string * @param pattern * @param replacement * @return Returns the modified string. */ replace( string: string, pattern: RegExp|string, replacement: Function|string ): string; /** * @see _.replace */ replace( pattern?: RegExp|string, replacement?: Function|string ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.replace */ replace( pattern?: RegExp|string, replacement?: Function|string ): string; /** * @see _.replace */ replace( replacement?: Function|string ): string; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.replace */ replace( pattern?: RegExp|string, replacement?: Function|string ): string; /** * @see _.replace */ replace( replacement?: Function|string ): string; } interface LoDashExplicitWrapper<T> { /** * @see _.replace */ replace( pattern?: RegExp|string, replacement?: Function|string ): LoDashExplicitWrapper<string>; /** * @see _.replace */ replace( replacement?: Function|string ): LoDashExplicitWrapper<string>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.replace */ replace( pattern?: RegExp|string, replacement?: Function|string ): LoDashExplicitWrapper<string>; /** * @see _.replace */ replace( replacement?: Function|string ): LoDashExplicitWrapper<string>; } //_.snakeCase interface LoDashStatic { /** * Converts string to snake case. * * @param string The string to convert. * @return Returns the snake cased string. */ snakeCase(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.snakeCase */ snakeCase(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.snakeCase */ snakeCase(): LoDashExplicitWrapper<string>; } //_.split interface LoDashStatic { /** * Splits string by separator. * * Note: This method is based on String#split. * * @param string * @param separator * @param limit * @return Returns the new array of string segments. */ split( string: string, separator?: RegExp|string, limit?: number ): string[]; } interface LoDashImplicitWrapper<T> { /** * @see _.split */ split( separator?: RegExp|string, limit?: number ): LoDashImplicitArrayWrapper<string>; } interface LoDashExplicitWrapper<T> { /** * @see _.split */ split( separator?: RegExp|string, limit?: number ): LoDashExplicitArrayWrapper<string>; } //_.startCase interface LoDashStatic { /** * Converts string to start case. * * @param string The string to convert. * @return Returns the start cased string. */ startCase(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.startCase */ startCase(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.startCase */ startCase(): LoDashExplicitWrapper<string>; } //_.startsWith interface LoDashStatic { /** * Checks if string starts with the given target string. * * @param string The string to search. * @param target The string to search for. * @param position The position to search from. * @return Returns true if string starts with target, else false. */ startsWith( string?: string, target?: string, position?: number ): boolean; } interface LoDashImplicitWrapper<T> { /** * @see _.startsWith */ startsWith( target?: string, position?: number ): boolean; } interface LoDashExplicitWrapper<T> { /** * @see _.startsWith */ startsWith( target?: string, position?: number ): LoDashExplicitWrapper<boolean>; } //_.template interface TemplateOptions extends TemplateSettings { /** * The sourceURL of the template's compiled source. */ sourceURL?: string; } interface TemplateExecutor { (data?: Object): string; source: string; } interface LoDashStatic { /** * Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, * HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" * delimiters. Data properties may be accessed as free variables in the template. If a setting object is * provided it takes precedence over _.templateSettings values. * * Note: In the development build _.template utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier * debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @param string The template string. * @param options The options object. * @param options.escape The HTML "escape" delimiter. * @param options.evaluate The "evaluate" delimiter. * @param options.imports An object to import into the template as free variables. * @param options.interpolate The "interpolate" delimiter. * @param options.sourceURL The sourceURL of the template's compiled source. * @param options.variable The data object variable name. * @return Returns the compiled template function. */ template( string: string, options?: TemplateOptions ): TemplateExecutor; } interface LoDashImplicitWrapper<T> { /** * @see _.template */ template(options?: TemplateOptions): TemplateExecutor; } interface LoDashExplicitWrapper<T> { /** * @see _.template */ template(options?: TemplateOptions): LoDashExplicitObjectWrapper<TemplateExecutor>; } //_.toLower interface LoDashStatic { /** * Converts `string`, as a whole, to lower case. * * @param string The string to convert. * @return Returns the lower cased string. */ toLower(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.toLower */ toLower(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.toLower */ toLower(): LoDashExplicitWrapper<string>; } //_.toUpper interface LoDashStatic { /** * Converts `string`, as a whole, to upper case. * * @param string The string to convert. * @return Returns the upper cased string. */ toUpper(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.toUpper */ toUpper(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.toUpper */ toUpper(): LoDashExplicitWrapper<string>; } //_.trim interface LoDashStatic { /** * Removes leading and trailing whitespace or specified characters from string. * * @param string The string to trim. * @param chars The characters to trim. * @return Returns the trimmed string. */ trim( string?: string, chars?: string ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.trim */ trim(chars?: string): string; } interface LoDashExplicitWrapper<T> { /** * @see _.trim */ trim(chars?: string): LoDashExplicitWrapper<string>; } //_.trimEnd interface LoDashStatic { /** * Removes trailing whitespace or specified characters from string. * * @param string The string to trim. * @param chars The characters to trim. * @return Returns the trimmed string. */ trimEnd( string?: string, chars?: string ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.trimEnd */ trimEnd(chars?: string): string; } interface LoDashExplicitWrapper<T> { /** * @see _.trimEnd */ trimEnd(chars?: string): LoDashExplicitWrapper<string>; } //_.trimStart interface LoDashStatic { /** * Removes leading whitespace or specified characters from string. * * @param string The string to trim. * @param chars The characters to trim. * @return Returns the trimmed string. */ trimStart( string?: string, chars?: string ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.trimStart */ trimStart(chars?: string): string; } interface LoDashExplicitWrapper<T> { /** * @see _.trimStart */ trimStart(chars?: string): LoDashExplicitWrapper<string>; } //_.truncate interface TruncateOptions { /** The maximum string length. */ length?: number; /** The string to indicate text is omitted. */ omission?: string; /** The separator pattern to truncate to. */ separator?: string|RegExp; } interface LoDashStatic { /** * Truncates string if it’s longer than the given maximum string length. The last characters of the truncated * string are replaced with the omission string which defaults to "…". * * @param string The string to truncate. * @param options The options object or maximum string length. * @return Returns the truncated string. */ truncate( string?: string, options?: TruncateOptions ): string; } interface LoDashImplicitWrapper<T> { /** * @see _.truncate */ truncate(options?: TruncateOptions): string; } interface LoDashExplicitWrapper<T> { /** * @see _.truncate */ truncate(options?: TruncateOptions): LoDashExplicitWrapper<string>; } //_.unescape interface LoDashStatic { /** * The inverse of _.escape; this method converts the HTML entities &amp;, &lt;, &gt;, &quot;, &#39;, and &#96; * in string to their corresponding characters. * * Note: No other HTML entities are unescaped. To unescape additional HTML entities use a third-party library * like he. * * @param string The string to unescape. * @return Returns the unescaped string. */ unescape(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.unescape */ unescape(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.unescape */ unescape(): LoDashExplicitWrapper<string>; } //_.upperCase interface LoDashStatic { /** * Converts `string`, as space separated words, to upper case. * * @param string The string to convert. * @return Returns the upper cased string. */ upperCase(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.upperCase */ upperCase(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.upperCase */ upperCase(): LoDashExplicitWrapper<string>; } //_.upperFirst interface LoDashStatic { /** * Converts the first character of `string` to upper case. * * @param string The string to convert. * @return Returns the converted string. */ upperFirst(string?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.upperFirst */ upperFirst(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.upperFirst */ upperFirst(): LoDashExplicitWrapper<string>; } //_.words interface LoDashStatic { /** * Splits `string` into an array of its words. * * @param string The string to inspect. * @param pattern The pattern to match words. * @return Returns the words of `string`. */ words( string?: string, pattern?: string|RegExp ): string[]; } interface LoDashImplicitWrapper<T> { /** * @see _.words */ words(pattern?: string|RegExp): string[]; } interface LoDashExplicitWrapper<T> { /** * @see _.words */ words(pattern?: string|RegExp): LoDashExplicitArrayWrapper<string>; } /*********** * Utility * ***********/ //_.attempt interface LoDashStatic { /** * Attempts to invoke func, returning either the result or the caught error object. Any additional arguments * are provided to func when it’s invoked. * * @param func The function to attempt. * @return Returns the func result or error object. */ attempt<TResult>(func: (...args: any[]) => TResult, ...args: any[]): TResult|Error; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.attempt */ attempt<TResult>(...args: any[]): TResult|Error; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.attempt */ attempt<TResult>(...args: any[]): LoDashExplicitObjectWrapper<TResult|Error>; } //_.constant interface LoDashStatic { /** * Creates a function that returns value. * * @param value The value to return from the new function. * @return Returns the new function. */ constant<T>(value: T): () => T; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.constant */ constant<TResult>(): LoDashImplicitObjectWrapper<() => TResult>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.constant */ constant<TResult>(): LoDashExplicitObjectWrapper<() => TResult>; } //_.identity interface LoDashStatic { /** * This method returns the first argument provided to it. * * @param value Any value. * @return Returns value. */ identity<T>(value?: T): T; } interface LoDashImplicitWrapper<T> { /** * @see _.identity */ identity(): T; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.identity */ identity(): T[]; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.identity */ identity(): T; } interface LoDashExplicitWrapper<T> { /** * @see _.identity */ identity(): LoDashExplicitWrapper<T>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.identity */ identity(): LoDashExplicitArrayWrapper<T>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.identity */ identity(): LoDashExplicitObjectWrapper<T>; } //_.iteratee interface LoDashStatic { /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name the created callback returns the * property value for a given element. If `func` is an object the created * callback returns `true` for elements that contain the equivalent object properties, otherwise it returns `false`. * * @static * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // create custom iteratee shorthands * _.iteratee = _.wrap(_.iteratee, function(callback, func) { * var p = /^(\S+)\s*([<>])\s*(\S+)$/.exec(func); * return !p ? callback(func) : function(object) { * return (p[2] == '>' ? object[p[1]] > p[3] : object[p[1]] < p[3]); * }; * }); * * _.filter(users, 'age > 36'); * // => [{ 'user': 'fred', 'age': 40 }] */ iteratee<TResult>( func: Function ): (...args: any[]) => TResult; /** * @see _.iteratee */ iteratee<TResult>( func: string ): (object: any) => TResult; /** * @see _.iteratee */ iteratee( func: Object ): (object: any) => boolean; /** * @see _.iteratee */ iteratee<TResult>(): (value: TResult) => TResult; } interface LoDashImplicitWrapper<T> { /** * @see _.iteratee */ iteratee<TResult>(): LoDashImplicitObjectWrapper<(object: any) => TResult>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.iteratee */ iteratee(): LoDashImplicitObjectWrapper<(object: any) => boolean>; /** * @see _.iteratee */ iteratee<TResult>(): LoDashImplicitObjectWrapper<(...args: any[]) => TResult>; } interface LoDashExplicitWrapper<T> { /** * @see _.iteratee */ iteratee<TResult>(): LoDashExplicitObjectWrapper<(object: any) => TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.iteratee */ iteratee(): LoDashExplicitObjectWrapper<(object: any) => boolean>; /** * @see _.iteratee */ iteratee<TResult>(): LoDashExplicitObjectWrapper<(...args: any[]) => TResult>; } //_.matches interface LoDashStatic { /** * Creates a function that performs a deep comparison between a given object and source, returning true if the * given object has equivalent property values, else false. * * Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and * strings. Objects are compared by their own, not inherited, enumerable properties. For comparing a single own * or inherited property value see _.matchesProperty. * * @param source The object of property values to match. * @return Returns the new function. */ matches<T>(source: T): (value: any) => boolean; /** * @see _.matches */ matches<T, V>(source: T): (value: V) => boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.matches */ matches<V>(): LoDashImplicitObjectWrapper<(value: V) => boolean>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.matches */ matches<V>(): LoDashExplicitObjectWrapper<(value: V) => boolean>; } //_.matchesProperty interface LoDashStatic { /** * Creates a function that compares the property value of path on a given object to value. * * Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and * strings. Objects are compared by their own, not inherited, enumerable properties. * * @param path The path of the property to get. * @param srcValue The value to match. * @return Returns the new function. */ matchesProperty<T>( path: StringRepresentable|StringRepresentable[], srcValue: T ): (value: any) => boolean; /** * @see _.matchesProperty */ matchesProperty<T, V>( path: StringRepresentable|StringRepresentable[], srcValue: T ): (value: V) => boolean; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.matchesProperty */ matchesProperty<SrcValue>( srcValue: SrcValue ): LoDashImplicitObjectWrapper<(value: any) => boolean>; /** * @see _.matchesProperty */ matchesProperty<SrcValue, Value>( srcValue: SrcValue ): LoDashImplicitObjectWrapper<(value: Value) => boolean>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.matchesProperty */ matchesProperty<SrcValue>( srcValue: SrcValue ): LoDashExplicitObjectWrapper<(value: any) => boolean>; /** * @see _.matchesProperty */ matchesProperty<SrcValue, Value>( srcValue: SrcValue ): LoDashExplicitObjectWrapper<(value: Value) => boolean>; } //_.method interface LoDashStatic { /** * Creates a function that invokes the method at path on a given object. Any additional arguments are provided * to the invoked method. * * @param path The path of the method to invoke. * @param args The arguments to invoke the method with. * @return Returns the new function. */ method<TObject, TResult>( path: string|StringRepresentable[], ...args: any[] ): (object: TObject) => TResult; /** * @see _.method */ method<TResult>( path: string|StringRepresentable[], ...args: any[] ): (object: any) => TResult; } interface LoDashImplicitWrapper<T> { /** * @see _.method */ method<TObject, TResult>(...args: any[]): LoDashImplicitObjectWrapper<(object: TObject) => TResult>; /** * @see _.method */ method<TResult>(...args: any[]): LoDashImplicitObjectWrapper<(object: any) => TResult>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.method */ method<TObject, TResult>(...args: any[]): LoDashImplicitObjectWrapper<(object: TObject) => TResult>; /** * @see _.method */ method<TResult>(...args: any[]): LoDashImplicitObjectWrapper<(object: any) => TResult>; } interface LoDashExplicitWrapper<T> { /** * @see _.method */ method<TObject, TResult>(...args: any[]): LoDashExplicitObjectWrapper<(object: TObject) => TResult>; /** * @see _.method */ method<TResult>(...args: any[]): LoDashExplicitObjectWrapper<(object: any) => TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.method */ method<TObject, TResult>(...args: any[]): LoDashExplicitObjectWrapper<(object: TObject) => TResult>; /** * @see _.method */ method<TResult>(...args: any[]): LoDashExplicitObjectWrapper<(object: any) => TResult>; } //_.methodOf interface LoDashStatic { /** * The opposite of _.method; this method creates a function that invokes the method at a given path on object. * Any additional arguments are provided to the invoked method. * * @param object The object to query. * @param args The arguments to invoke the method with. * @return Returns the new function. */ methodOf<TObject extends {}, TResult>( object: TObject, ...args: any[] ): (path: StringRepresentable|StringRepresentable[]) => TResult; /** * @see _.methodOf */ methodOf<TResult>( object: {}, ...args: any[] ): (path: StringRepresentable|StringRepresentable[]) => TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.methodOf */ methodOf<TResult>( ...args: any[] ): LoDashImplicitObjectWrapper<(path: StringRepresentable|StringRepresentable[]) => TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.methodOf */ methodOf<TResult>( ...args: any[] ): LoDashExplicitObjectWrapper<(path: StringRepresentable|StringRepresentable[]) => TResult>; } //_.mixin interface MixinOptions { chain?: boolean; } interface LoDashStatic { /** * Adds all own enumerable function properties of a source object to the destination object. If object is a * function then methods are added to its prototype as well. * * Note: Use _.runInContext to create a pristine lodash function to avoid conflicts caused by modifying * the original. * * @param object The destination object. * @param source The object of functions to add. * @param options The options object. * @param options.chain Specify whether the functions added are chainable. * @return Returns object. */ mixin<TResult, TObject>( object: TObject, source: Dictionary<Function>, options?: MixinOptions ): TResult; /** * @see _.mixin */ mixin<TResult>( source: Dictionary<Function>, options?: MixinOptions ): TResult; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.mixin */ mixin<TResult>( source: Dictionary<Function>, options?: MixinOptions ): LoDashImplicitObjectWrapper<TResult>; /** * @see _.mixin */ mixin<TResult>( options?: MixinOptions ): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.mixin */ mixin<TResult>( source: Dictionary<Function>, options?: MixinOptions ): LoDashExplicitObjectWrapper<TResult>; /** * @see _.mixin */ mixin<TResult>( options?: MixinOptions ): LoDashExplicitObjectWrapper<TResult>; } //_.noConflict interface LoDashStatic { /** * Reverts the _ variable to its previous value and returns a reference to the lodash function. * * @return Returns the lodash function. */ noConflict(): typeof _; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.noConflict */ noConflict(): typeof _; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.noConflict */ noConflict(): LoDashExplicitObjectWrapper<typeof _>; } //_.noop interface LoDashStatic { /** * A no-operation function that returns undefined regardless of the arguments it receives. * * @return undefined */ noop(...args: any[]): void; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.noop */ noop(...args: any[]): void; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.noop */ noop(...args: any[]): _.LoDashExplicitWrapper<void>; } //_.nthArg interface LoDashStatic { /** * Creates a function that returns its nth argument. * * @param n The index of the argument to return. * @return Returns the new function. */ nthArg<TResult extends Function>(n?: number): TResult; } interface LoDashImplicitWrapper<T> { /** * @see _.nthArg */ nthArg<TResult extends Function>(): LoDashImplicitObjectWrapper<TResult>; } interface LoDashExplicitWrapper<T> { /** * @see _.nthArg */ nthArg<TResult extends Function>(): LoDashExplicitObjectWrapper<TResult>; } //_.over interface LoDashStatic { /** * Creates a function that invokes iteratees with the arguments provided to the created function and returns * their results. * * @param iteratees The iteratees to invoke. * @return Returns the new function. */ over<TResult>(...iteratees: (Function|Function[])[]): (...args: any[]) => TResult[]; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.over */ over<TResult>(...iteratees: (Function|Function[])[]): LoDashImplicitObjectWrapper<(...args: any[]) => TResult[]>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.over */ over<TResult>(...iteratees: (Function|Function[])[]): LoDashImplicitObjectWrapper<(...args: any[]) => TResult[]>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.over */ over<TResult>(...iteratees: (Function|Function[])[]): LoDashExplicitObjectWrapper<(...args: any[]) => TResult[]>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.over */ over<TResult>(...iteratees: (Function|Function[])[]): LoDashExplicitObjectWrapper<(...args: any[]) => TResult[]>; } //_.overEvery interface LoDashStatic { /** * Creates a function that checks if all of the predicates return truthy when invoked with the arguments * provided to the created function. * * @param predicates The predicates to check. * @return Returns the new function. */ overEvery(...predicates: (Function|Function[])[]): (...args: any[]) => boolean; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.overEvery */ overEvery(...predicates: (Function|Function[])[]): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.overEvery */ overEvery(...predicates: (Function|Function[])[]): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.overEvery */ overEvery(...predicates: (Function|Function[])[]): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.overEvery */ overEvery(...predicates: (Function|Function[])[]): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; } //_.overSome interface LoDashStatic { /** * Creates a function that checks if any of the predicates return truthy when invoked with the arguments * provided to the created function. * * @param predicates The predicates to check. * @return Returns the new function. */ overSome(...predicates: (Function|Function[])[]): (...args: any[]) => boolean; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.overSome */ overSome(...predicates: (Function|Function[])[]): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.overSome */ overSome(...predicates: (Function|Function[])[]): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.overSome */ overSome(...predicates: (Function|Function[])[]): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.overSome */ overSome(...predicates: (Function|Function[])[]): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; } //_.property interface LoDashStatic { /** * Creates a function that returns the property value at path on a given object. * * @param path The path of the property to get. * @return Returns the new function. */ property<TObj, TResult>(path: StringRepresentable|StringRepresentable[]): (obj: TObj) => TResult; } interface LoDashImplicitWrapper<T> { /** * @see _.property */ property<TObj, TResult>(): LoDashImplicitObjectWrapper<(obj: TObj) => TResult>; } interface LoDashImplicitArrayWrapper<T> { /** * @see _.property */ property<TObj, TResult>(): LoDashImplicitObjectWrapper<(obj: TObj) => TResult>; } interface LoDashExplicitWrapper<T> { /** * @see _.property */ property<TObj, TResult>(): LoDashExplicitObjectWrapper<(obj: TObj) => TResult>; } interface LoDashExplicitArrayWrapper<T> { /** * @see _.property */ property<TObj, TResult>(): LoDashExplicitObjectWrapper<(obj: TObj) => TResult>; } //_.propertyOf interface LoDashStatic { /** * The opposite of _.property; this method creates a function that returns the property value at a given path * on object. * * @param object The object to query. * @return Returns the new function. */ propertyOf<T extends {}>(object: T): (path: string|string[]) => any; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.propertyOf */ propertyOf(): LoDashImplicitObjectWrapper<(path: string|string[]) => any>; } interface LoDashExplicitObjectWrapper<T> { /** * @see _.propertyOf */ propertyOf(): LoDashExplicitObjectWrapper<(path: string|string[]) => any>; } //_.range interface LoDashStatic { /** * Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. * If end is not specified it’s set to start with start then set to 0. If end is less than start a zero-length * range is created unless a negative step is specified. * * @param start The start of the range. * @param end The end of the range. * @param step The value to increment or decrement by. * @return Returns a new range array. */ range( start: number, end: number, step?: number ): number[]; /** * @see _.range */ range( end: number, step?: number ): number[]; } interface LoDashImplicitWrapper<T> { /** * @see _.range */ range( end?: number, step?: number ): LoDashImplicitArrayWrapper<number>; } interface LoDashExplicitWrapper<T> { /** * @see _.range */ range( end?: number, step?: number ): LoDashExplicitArrayWrapper<number>; } //_.rangeRight interface LoDashStatic { /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the new array of numbers. * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ rangeRight( start: number, end: number, step?: number ): number[]; /** * @see _.rangeRight */ rangeRight( end: number, step?: number ): number[]; } interface LoDashImplicitWrapper<T> { /** * @see _.rangeRight */ rangeRight( end?: number, step?: number ): LoDashImplicitArrayWrapper<number>; } interface LoDashExplicitWrapper<T> { /** * @see _.rangeRight */ rangeRight( end?: number, step?: number ): LoDashExplicitArrayWrapper<number>; } //_.runInContext interface LoDashStatic { /** * Create a new pristine lodash function using the given context object. * * @param context The context object. * @return Returns a new lodash function. */ runInContext(context?: Object): typeof _; } interface LoDashImplicitObjectWrapper<T> { /** * @see _.runInContext */ runInContext(): typeof _; } //_.times interface LoDashStatic { /** * Invokes the iteratee function n times, returning an array of the results of each invocation. The iteratee * is invoked with one argument; (index). * * @param n The number of times to invoke iteratee. * @param iteratee The function invoked per iteration. * @return Returns the array of results. */ times<TResult>( n: number, iteratee: (num: number) => TResult ): TResult[]; /** * @see _.times */ times(n: number): number[]; } interface LoDashImplicitWrapper<T> { /** * @see _.times */ times<TResult>( iteratee: (num: number) => TResult ): TResult[]; /** * @see _.times */ times(): number[]; } interface LoDashExplicitWrapper<T> { /** * @see _.times */ times<TResult>( iteratee: (num: number) => TResult ): LoDashExplicitArrayWrapper<TResult>; /** * @see _.times */ times(): LoDashExplicitArrayWrapper<number>; } //_.toPath interface LoDashStatic { /** * Converts `value` to a property path array. * * @static * @memberOf _ * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] * * var path = ['a', 'b', 'c'], * newPath = _.toPath(path); * * console.log(newPath); * // => ['a', 'b', 'c'] * * console.log(path === newPath); * // => false */ toPath(value: any): string[]; } interface LoDashImplicitWrapperBase<T, TWrapper> { /** * @see _.toPath */ toPath(): LoDashImplicitWrapper<string[]>; } interface LoDashExplicitWrapperBase<T, TWrapper> { /** * @see _.toPath */ toPath(): LoDashExplicitWrapper<string[]>; } //_.uniqueId interface LoDashStatic { /** * Generates a unique ID. If prefix is provided the ID is appended to it. * * @param prefix The value to prefix the ID with. * @return Returns the unique ID. */ uniqueId(prefix?: string): string; } interface LoDashImplicitWrapper<T> { /** * @see _.uniqueId */ uniqueId(): string; } interface LoDashExplicitWrapper<T> { /** * @see _.uniqueId */ uniqueId(): LoDashExplicitWrapper<string>; } interface ListIterator<T, TResult> { (value: T, index: number, collection: List<T>): TResult; } interface DictionaryIterator<T, TResult> { (value: T, key?: string, collection?: Dictionary<T>): TResult; } interface NumericDictionaryIterator<T, TResult> { (value: T, key?: number, collection?: Dictionary<T>): TResult; } interface ObjectIterator<T, TResult> { (element: T, key?: string, collection?: any): TResult; } interface StringIterator<TResult> { (char: string, index?: number, string?: string): TResult; } interface MemoVoidIterator<T, TResult> { (prev: TResult, curr: T, indexOrKey?: any, list?: T[]): void; } interface MemoIterator<T, TResult> { (prev: TResult, curr: T, indexOrKey?: any, list?: T[]): TResult; } interface MemoVoidArrayIterator<T, TResult> { (acc: TResult, curr: T, index?: number, arr?: T[]): void; } interface MemoVoidDictionaryIterator<T, TResult> { (acc: TResult, curr: T, key?: string, dict?: Dictionary<T>): void; } //interface Collection<T> {} // Common interface between Arrays and jQuery objects interface List<T> { [index: number]: T; length: number; } interface Dictionary<T> { [index: string]: T; } interface NumericDictionary<T> { [index: number]: T; } interface StringRepresentable { toString(): string; } interface Cancelable { cancel(): void; } } // Named exports declare module "lodash/after" { const after: typeof _.after; export = after; } declare module "lodash/ary" { const ary: typeof _.ary; export = ary; } declare module "lodash/assign" { const assign: typeof _.assign; export = assign; } declare module "lodash/assignIn" { const assignIn: typeof _.assignIn; export = assignIn; } declare module "lodash/assignInWith" { const assignInWith: typeof _.assignInWith; export = assignInWith; } declare module "lodash/assignWith" { const assignWith: typeof _.assignWith; export = assignWith; } declare module "lodash/at" { const at: typeof _.at; export = at; } declare module "lodash/before" { const before: typeof _.before; export = before; } declare module "lodash/bind" { const bind: typeof _.bind; export = bind; } declare module "lodash/bindAll" { const bindAll: typeof _.bindAll; export = bindAll; } declare module "lodash/bindKey" { const bindKey: typeof _.bindKey; export = bindKey; } declare module "lodash/castArray" { const castArray: typeof _.castArray; export = castArray; } declare module "lodash/chain" { const chain: typeof _.chain; export = chain; } declare module "lodash/chunk" { const chunk: typeof _.chunk; export = chunk; } declare module "lodash/compact" { const compact: typeof _.compact; export = compact; } declare module "lodash/concat" { const concat: typeof _.concat; export = concat; } /** * uncoment it if definition exists */ /* declare module "lodash/cond" { const cond: typeof _.cond; export = cond; } */ /** * uncoment it if definition exists */ /* declare module "lodash/conforms" { const conforms: typeof _.conforms; export = conforms; } */ declare module "lodash/constant" { const constant: typeof _.constant; export = constant; } declare module "lodash/countBy" { const countBy: typeof _.countBy; export = countBy; } declare module "lodash/create" { const create: typeof _.create; export = create; } declare module "lodash/curry" { const curry: typeof _.curry; export = curry; } declare module "lodash/curryRight" { const curryRight: typeof _.curryRight; export = curryRight; } declare module "lodash/debounce" { const debounce: typeof _.debounce; export = debounce; } declare module "lodash/defaults" { const defaults: typeof _.defaults; export = defaults; } declare module "lodash/defaultsDeep" { const defaultsDeep: typeof _.defaultsDeep; export = defaultsDeep; } declare module "lodash/defer" { const defer: typeof _.defer; export = defer; } declare module "lodash/delay" { const delay: typeof _.delay; export = delay; } declare module "lodash/difference" { const difference: typeof _.difference; export = difference; } declare module "lodash/differenceBy" { const differenceBy: typeof _.differenceBy; export = differenceBy; } declare module "lodash/differenceWith" { const differenceWith: typeof _.differenceWith; export = differenceWith; } declare module "lodash/drop" { const drop: typeof _.drop; export = drop; } declare module "lodash/dropRight" { const dropRight: typeof _.dropRight; export = dropRight; } declare module "lodash/dropRightWhile" { const dropRightWhile: typeof _.dropRightWhile; export = dropRightWhile; } declare module "lodash/dropWhile" { const dropWhile: typeof _.dropWhile; export = dropWhile; } declare module "lodash/fill" { const fill: typeof _.fill; export = fill; } declare module "lodash/filter" { const filter: typeof _.filter; export = filter; } declare module "lodash/flatMap" { const flatMap: typeof _.flatMap; export = flatMap; } /** * uncoment it if definition exists */ /* declare module "lodash/flatMapDeep" { const flatMapDeep: typeof _.flatMapDeep; export = flatMapDeep; } */ /** * uncoment it if definition exists */ /* declare module "lodash/flatMapDepth" { const flatMapDepth: typeof _.flatMapDepth; export = flatMapDepth; } */ declare module "lodash/flatten" { const flatten: typeof _.flatten; export = flatten; } declare module "lodash/flattenDeep" { const flattenDeep: typeof _.flattenDeep; export = flattenDeep; } /** * uncoment it if definition exists */ /* declare module "lodash/flattenDepth" { const flattenDepth: typeof _.flattenDepth; export = flattenDepth; } */ declare module "lodash/flip" { const flip: typeof _.flip; export = flip; } declare module "lodash/flow" { const flow: typeof _.flow; export = flow; } declare module "lodash/flowRight" { const flowRight: typeof _.flowRight; export = flowRight; } declare module "lodash/fromPairs" { const fromPairs: typeof _.fromPairs; export = fromPairs; } declare module "lodash/functions" { const functions: typeof _.functions; export = functions; } declare module "lodash/functionsIn" { const functionsIn: typeof _.functionsIn; export = functionsIn; } declare module "lodash/groupBy" { const groupBy: typeof _.groupBy; export = groupBy; } declare module "lodash/initial" { const initial: typeof _.initial; export = initial; } declare module "lodash/intersection" { const intersection: typeof _.intersection; export = intersection; } declare module "lodash/intersectionBy" { const intersectionBy: typeof _.intersectionBy; export = intersectionBy; } declare module "lodash/intersectionWith" { const intersectionWith: typeof _.intersectionWith; export = intersectionWith; } declare module "lodash/invert" { const invert: typeof _.invert; export = invert; } declare module "lodash/invertBy" { const invertBy: typeof _.invertBy; export = invertBy; } declare module "lodash/invokeMap" { const invokeMap: typeof _.invokeMap; export = invokeMap; } declare module "lodash/iteratee" { const iteratee: typeof _.iteratee; export = iteratee; } declare module "lodash/keyBy" { const keyBy: typeof _.keyBy; export = keyBy; } declare module "lodash/keys" { const keys: typeof _.keys; export = keys; } declare module "lodash/keysIn" { const keysIn: typeof _.keysIn; export = keysIn; } declare module "lodash/map" { const map: typeof _.map; export = map; } declare module "lodash/mapKeys" { const mapKeys: typeof _.mapKeys; export = mapKeys; } declare module "lodash/mapValues" { const mapValues: typeof _.mapValues; export = mapValues; } declare module "lodash/matches" { const matches: typeof _.matches; export = matches; } declare module "lodash/matchesProperty" { const matchesProperty: typeof _.matchesProperty; export = matchesProperty; } declare module "lodash/memoize" { const memoize: typeof _.memoize; export = memoize; } declare module "lodash/merge" { const merge: typeof _.merge; export = merge; } declare module "lodash/mergeWith" { const mergeWith: typeof _.mergeWith; export = mergeWith; } declare module "lodash/method" { const method: typeof _.method; export = method; } declare module "lodash/methodOf" { const methodOf: typeof _.methodOf; export = methodOf; } declare module "lodash/mixin" { const mixin: typeof _.mixin; export = mixin; } declare module "lodash/negate" { const negate: typeof _.negate; export = negate; } declare module "lodash/nthArg" { const nthArg: typeof _.nthArg; export = nthArg; } declare module "lodash/omit" { const omit: typeof _.omit; export = omit; } declare module "lodash/omitBy" { const omitBy: typeof _.omitBy; export = omitBy; } declare module "lodash/once" { const once: typeof _.once; export = once; } declare module "lodash/orderBy" { const orderBy: typeof _.orderBy; export = orderBy; } declare module "lodash/over" { const over: typeof _.over; export = over; } declare module "lodash/overArgs" { const overArgs: typeof _.overArgs; export = overArgs; } declare module "lodash/overEvery" { const overEvery: typeof _.overEvery; export = overEvery; } declare module "lodash/overSome" { const overSome: typeof _.overSome; export = overSome; } declare module "lodash/partial" { const partial: typeof _.partial; export = partial; } declare module "lodash/partialRight" { const partialRight: typeof _.partialRight; export = partialRight; } declare module "lodash/partition" { const partition: typeof _.partition; export = partition; } declare module "lodash/pick" { const pick: typeof _.pick; export = pick; } declare module "lodash/pickBy" { const pickBy: typeof _.pickBy; export = pickBy; } declare module "lodash/property" { const property: typeof _.property; export = property; } declare module "lodash/propertyOf" { const propertyOf: typeof _.propertyOf; export = propertyOf; } declare module "lodash/pull" { const pull: typeof _.pull; export = pull; } declare module "lodash/pullAll" { const pullAll: typeof _.pullAll; export = pullAll; } declare module "lodash/pullAllBy" { const pullAllBy: typeof _.pullAllBy; export = pullAllBy; } /** * uncoment it if definition exists */ /* declare module "lodash/pullAllWith" { const pullAllWith: typeof _.pullAllWith; export = pullAllWith; } */ declare module "lodash/pullAt" { const pullAt: typeof _.pullAt; export = pullAt; } declare module "lodash/range" { const range: typeof _.range; export = range; } declare module "lodash/rangeRight" { const rangeRight: typeof _.rangeRight; export = rangeRight; } declare module "lodash/rearg" { const rearg: typeof _.rearg; export = rearg; } declare module "lodash/reject" { const reject: typeof _.reject; export = reject; } declare module "lodash/remove" { const remove: typeof _.remove; export = remove; } declare module "lodash/rest" { const rest: typeof _.rest; export = rest; } declare module "lodash/reverse" { const reverse: typeof _.reverse; export = reverse; } declare module "lodash/sampleSize" { const sampleSize: typeof _.sampleSize; export = sampleSize; } declare module "lodash/set" { const set: typeof _.set; export = set; } declare module "lodash/setWith" { const setWith: typeof _.setWith; export = setWith; } declare module "lodash/shuffle" { const shuffle: typeof _.shuffle; export = shuffle; } declare module "lodash/slice" { const slice: typeof _.slice; export = slice; } declare module "lodash/sortBy" { const sortBy: typeof _.sortBy; export = sortBy; } declare module "lodash/sortedUniq" { const sortedUniq: typeof _.sortedUniq; export = sortedUniq; } declare module "lodash/sortedUniqBy" { const sortedUniqBy: typeof _.sortedUniqBy; export = sortedUniqBy; } declare module "lodash/split" { const split: typeof _.split; export = split; } declare module "lodash/spread" { const spread: typeof _.spread; export = spread; } declare module "lodash/tail" { const tail: typeof _.tail; export = tail; } declare module "lodash/take" { const take: typeof _.take; export = take; } declare module "lodash/takeRight" { const takeRight: typeof _.takeRight; export = takeRight; } declare module "lodash/takeRightWhile" { const takeRightWhile: typeof _.takeRightWhile; export = takeRightWhile; } declare module "lodash/takeWhile" { const takeWhile: typeof _.takeWhile; export = takeWhile; } declare module "lodash/tap" { const tap: typeof _.tap; export = tap; } declare module "lodash/throttle" { const throttle: typeof _.throttle; export = throttle; } declare module "lodash/thru" { const thru: typeof _.thru; export = thru; } declare module "lodash/toArray" { const toArray: typeof _.toArray; export = toArray; } declare module "lodash/toPairs" { const toPairs: typeof _.toPairs; export = toPairs; } declare module "lodash/toPairsIn" { const toPairsIn: typeof _.toPairsIn; export = toPairsIn; } declare module "lodash/toPath" { const toPath: typeof _.toPath; export = toPath; } declare module "lodash/toPlainObject" { const toPlainObject: typeof _.toPlainObject; export = toPlainObject; } declare module "lodash/transform" { const transform: typeof _.transform; export = transform; } declare module "lodash/unary" { const unary: typeof _.unary; export = unary; } declare module "lodash/union" { const union: typeof _.union; export = union; } declare module "lodash/unionBy" { const unionBy: typeof _.unionBy; export = unionBy; } declare module "lodash/unionWith" { const unionWith: typeof _.unionWith; export = unionWith; } declare module "lodash/uniq" { const uniq: typeof _.uniq; export = uniq; } declare module "lodash/uniqBy" { const uniqBy: typeof _.uniqBy; export = uniqBy; } declare module "lodash/uniqWith" { const uniqWith: typeof _.uniqWith; export = uniqWith; } declare module "lodash/unset" { const unset: typeof _.unset; export = unset; } declare module "lodash/unzip" { const unzip: typeof _.unzip; export = unzip; } declare module "lodash/unzipWith" { const unzipWith: typeof _.unzipWith; export = unzipWith; } declare module "lodash/update" { const update: typeof _.update; export = update; } /** * uncoment it if definition exists */ /* declare module "lodash/updateWith" { const updateWith: typeof _.updateWith; export = updateWith; } */ declare module "lodash/values" { const values: typeof _.values; export = values; } declare module "lodash/valuesIn" { const valuesIn: typeof _.valuesIn; export = valuesIn; } declare module "lodash/without" { const without: typeof _.without; export = without; } declare module "lodash/words" { const words: typeof _.words; export = words; } declare module "lodash/wrap" { const wrap: typeof _.wrap; export = wrap; } declare module "lodash/xor" { const xor: typeof _.xor; export = xor; } declare module "lodash/xorBy" { const xorBy: typeof _.xorBy; export = xorBy; } declare module "lodash/xorWith" { const xorWith: typeof _.xorWith; export = xorWith; } declare module "lodash/zip" { const zip: typeof _.zip; export = zip; } declare module "lodash/zipObject" { const zipObject: typeof _.zipObject; export = zipObject; } /** * uncoment it if definition exists */ /* declare module "lodash/zipObjectDeep" { const zipObjectDeep: typeof _.zipObjectDeep; export = zipObjectDeep; } */ declare module "lodash/zipWith" { const zipWith: typeof _.zipWith; export = zipWith; } /** * uncoment it if definition exists */ /* declare module "lodash/entries" { const entries: typeof _.entries; export = entries; } */ /** * uncoment it if definition exists */ /* declare module "lodash/entriesIn" { const entriesIn: typeof _.entriesIn; export = entriesIn; } */ declare module "lodash/extend" { const extend: typeof _.extend; export = extend; } /** * uncoment it if definition exists */ /* declare module "lodash/extendWith" { const extendWith: typeof _.extendWith; export = extendWith; } */ declare module "lodash/add" { const add: typeof _.add; export = add; } declare module "lodash/attempt" { const attempt: typeof _.attempt; export = attempt; } declare module "lodash/camelCase" { const camelCase: typeof _.camelCase; export = camelCase; } declare module "lodash/capitalize" { const capitalize: typeof _.capitalize; export = capitalize; } declare module "lodash/ceil" { const ceil: typeof _.ceil; export = ceil; } declare module "lodash/clamp" { const clamp: typeof _.clamp; export = clamp; } declare module "lodash/clone" { const clone: typeof _.clone; export = clone; } declare module "lodash/cloneDeep" { const cloneDeep: typeof _.cloneDeep; export = cloneDeep; } declare module "lodash/cloneDeepWith" { const cloneDeepWith: typeof _.cloneDeepWith; export = cloneDeepWith; } declare module "lodash/cloneWith" { const cloneWith: typeof _.cloneWith; export = cloneWith; } declare module "lodash/deburr" { const deburr: typeof _.deburr; export = deburr; } /** * uncoment it if definition exists */ /* declare module "lodash/divide" { const divide: typeof _.divide; export = divide; } */ declare module "lodash/endsWith" { const endsWith: typeof _.endsWith; export = endsWith; } declare module "lodash/eq" { const eq: typeof _.eq; export = eq; } declare module "lodash/escape" { const escape: typeof _.escape; export = escape; } declare module "lodash/escapeRegExp" { const escapeRegExp: typeof _.escapeRegExp; export = escapeRegExp; } declare module "lodash/every" { const every: typeof _.every; export = every; } declare module "lodash/find" { const find: typeof _.find; export = find; } declare module "lodash/findIndex" { const findIndex: typeof _.findIndex; export = findIndex; } declare module "lodash/findKey" { const findKey: typeof _.findKey; export = findKey; } declare module "lodash/findLast" { const findLast: typeof _.findLast; export = findLast; } declare module "lodash/findLastIndex" { const findLastIndex: typeof _.findLastIndex; export = findLastIndex; } declare module "lodash/findLastKey" { const findLastKey: typeof _.findLastKey; export = findLastKey; } declare module "lodash/floor" { const floor: typeof _.floor; export = floor; } declare module "lodash/forEach" { const forEach: typeof _.forEach; export = forEach; } declare module "lodash/forEachRight" { const forEachRight: typeof _.forEachRight; export = forEachRight; } declare module "lodash/forIn" { const forIn: typeof _.forIn; export = forIn; } declare module "lodash/forInRight" { const forInRight: typeof _.forInRight; export = forInRight; } declare module "lodash/forOwn" { const forOwn: typeof _.forOwn; export = forOwn; } declare module "lodash/forOwnRight" { const forOwnRight: typeof _.forOwnRight; export = forOwnRight; } declare module "lodash/get" { const get: typeof _.get; export = get; } declare module "lodash/gt" { const gt: typeof _.gt; export = gt; } declare module "lodash/gte" { const gte: typeof _.gte; export = gte; } declare module "lodash/has" { const has: typeof _.has; export = has; } declare module "lodash/hasIn" { const hasIn: typeof _.hasIn; export = hasIn; } declare module "lodash/head" { const head: typeof _.head; export = head; } declare module "lodash/identity" { const identity: typeof _.identity; export = identity; } declare module "lodash/includes" { const includes: typeof _.includes; export = includes; } declare module "lodash/indexOf" { const indexOf: typeof _.indexOf; export = indexOf; } declare module "lodash/inRange" { const inRange: typeof _.inRange; export = inRange; } declare module "lodash/invoke" { const invoke: typeof _.invoke; export = invoke; } declare module "lodash/isArguments" { const isArguments: typeof _.isArguments; export = isArguments; } declare module "lodash/isArray" { const isArray: typeof _.isArray; export = isArray; } declare module "lodash/isArrayBuffer" { const isArrayBuffer: typeof _.isArrayBuffer; export = isArrayBuffer; } declare module "lodash/isArrayLike" { const isArrayLike: typeof _.isArrayLike; export = isArrayLike; } declare module "lodash/isArrayLikeObject" { const isArrayLikeObject: typeof _.isArrayLikeObject; export = isArrayLikeObject; } declare module "lodash/isBoolean" { const isBoolean: typeof _.isBoolean; export = isBoolean; } declare module "lodash/isBuffer" { const isBuffer: typeof _.isBuffer; export = isBuffer; } declare module "lodash/isDate" { const isDate: typeof _.isDate; export = isDate; } declare module "lodash/isElement" { const isElement: typeof _.isElement; export = isElement; } declare module "lodash/isEmpty" { const isEmpty: typeof _.isEmpty; export = isEmpty; } declare module "lodash/isEqual" { const isEqual: typeof _.isEqual; export = isEqual; } declare module "lodash/isEqualWith" { const isEqualWith: typeof _.isEqualWith; export = isEqualWith; } declare module "lodash/isError" { const isError: typeof _.isError; export = isError; } declare module "lodash/isFinite" { const isFinite: typeof _.isFinite; export = isFinite; } declare module "lodash/isFunction" { const isFunction: typeof _.isFunction; export = isFunction; } declare module "lodash/isInteger" { const isInteger: typeof _.isInteger; export = isInteger; } declare module "lodash/isLength" { const isLength: typeof _.isLength; export = isLength; } declare module "lodash/isMap" { const isMap: typeof _.isMap; export = isMap; } declare module "lodash/isMatch" { const isMatch: typeof _.isMatch; export = isMatch; } declare module "lodash/isMatchWith" { const isMatchWith: typeof _.isMatchWith; export = isMatchWith; } declare module "lodash/isNaN" { const isNaN: typeof _.isNaN; export = isNaN; } declare module "lodash/isNative" { const isNative: typeof _.isNative; export = isNative; } declare module "lodash/isNil" { const isNil: typeof _.isNil; export = isNil; } declare module "lodash/isNull" { const isNull: typeof _.isNull; export = isNull; } declare module "lodash/isNumber" { const isNumber: typeof _.isNumber; export = isNumber; } declare module "lodash/isObject" { const isObject: typeof _.isObject; export = isObject; } declare module "lodash/isObjectLike" { const isObjectLike: typeof _.isObjectLike; export = isObjectLike; } declare module "lodash/isPlainObject" { const isPlainObject: typeof _.isPlainObject; export = isPlainObject; } declare module "lodash/isRegExp" { const isRegExp: typeof _.isRegExp; export = isRegExp; } declare module "lodash/isSafeInteger" { const isSafeInteger: typeof _.isSafeInteger; export = isSafeInteger; } declare module "lodash/isSet" { const isSet: typeof _.isSet; export = isSet; } declare module "lodash/isString" { const isString: typeof _.isString; export = isString; } declare module "lodash/isSymbol" { const isSymbol: typeof _.isSymbol; export = isSymbol; } declare module "lodash/isTypedArray" { const isTypedArray: typeof _.isTypedArray; export = isTypedArray; } declare module "lodash/isUndefined" { const isUndefined: typeof _.isUndefined; export = isUndefined; } declare module "lodash/isWeakMap" { const isWeakMap: typeof _.isWeakMap; export = isWeakMap; } declare module "lodash/isWeakSet" { const isWeakSet: typeof _.isWeakSet; export = isWeakSet; } declare module "lodash/join" { const join: typeof _.join; export = join; } declare module "lodash/kebabCase" { const kebabCase: typeof _.kebabCase; export = kebabCase; } declare module "lodash/last" { const last: typeof _.last; export = last; } declare module "lodash/lastIndexOf" { const lastIndexOf: typeof _.lastIndexOf; export = lastIndexOf; } declare module "lodash/lowerCase" { const lowerCase: typeof _.lowerCase; export = lowerCase; } declare module "lodash/lowerFirst" { const lowerFirst: typeof _.lowerFirst; export = lowerFirst; } declare module "lodash/lt" { const lt: typeof _.lt; export = lt; } declare module "lodash/lte" { const lte: typeof _.lte; export = lte; } declare module "lodash/max" { const max: typeof _.max; export = max; } declare module "lodash/maxBy" { const maxBy: typeof _.maxBy; export = maxBy; } declare module "lodash/mean" { const mean: typeof _.mean; export = mean; } /** * uncoment it if definition exists */ /* declare module "lodash/meanBy" { const meanBy: typeof _.meanBy; export = meanBy; } */ declare module "lodash/min" { const min: typeof _.min; export = min; } declare module "lodash/minBy" { const minBy: typeof _.minBy; export = minBy; } /** * uncoment it if definition exists */ /* declare module "lodash/multiply" { const multiply: typeof _.multiply; export = multiply; } */ /** * uncoment it if definition exists */ /* declare module "lodash/nth" { const nth: typeof _.nth; export = nth; } */ declare module "lodash/noConflict" { const noConflict: typeof _.noConflict; export = noConflict; } declare module "lodash/noop" { const noop: typeof _.noop; export = noop; } declare module "lodash/now" { const now: typeof _.now; export = now; } declare module "lodash/pad" { const pad: typeof _.pad; export = pad; } declare module "lodash/padEnd" { const padEnd: typeof _.padEnd; export = padEnd; } declare module "lodash/padStart" { const padStart: typeof _.padStart; export = padStart; } declare module "lodash/parseInt" { const parseInt: typeof _.parseInt; export = parseInt; } declare module "lodash/random" { const random: typeof _.random; export = random; } declare module "lodash/reduce" { const reduce: typeof _.reduce; export = reduce; } declare module "lodash/reduceRight" { const reduceRight: typeof _.reduceRight; export = reduceRight; } declare module "lodash/repeat" { const repeat: typeof _.repeat; export = repeat; } declare module "lodash/replace" { const replace: typeof _.replace; export = replace; } declare module "lodash/result" { const result: typeof _.result; export = result; } declare module "lodash/round" { const round: typeof _.round; export = round; } declare module "lodash/runInContext" { const runInContext: typeof _.runInContext; export = runInContext; } declare module "lodash/sample" { const sample: typeof _.sample; export = sample; } declare module "lodash/size" { const size: typeof _.size; export = size; } declare module "lodash/snakeCase" { const snakeCase: typeof _.snakeCase; export = snakeCase; } declare module "lodash/some" { const some: typeof _.some; export = some; } declare module "lodash/sortedIndex" { const sortedIndex: typeof _.sortedIndex; export = sortedIndex; } declare module "lodash/sortedIndexBy" { const sortedIndexBy: typeof _.sortedIndexBy; export = sortedIndexBy; } declare module "lodash/sortedIndexOf" { const sortedIndexOf: typeof _.sortedIndexOf; export = sortedIndexOf; } declare module "lodash/sortedLastIndex" { const sortedLastIndex: typeof _.sortedLastIndex; export = sortedLastIndex; } declare module "lodash/sortedLastIndexBy" { const sortedLastIndexBy: typeof _.sortedLastIndexBy; export = sortedLastIndexBy; } declare module "lodash/sortedLastIndexOf" { const sortedLastIndexOf: typeof _.sortedLastIndexOf; export = sortedLastIndexOf; } declare module "lodash/startCase" { const startCase: typeof _.startCase; export = startCase; } declare module "lodash/startsWith" { const startsWith: typeof _.startsWith; export = startsWith; } declare module "lodash/subtract" { const subtract: typeof _.subtract; export = subtract; } declare module "lodash/sum" { const sum: typeof _.sum; export = sum; } declare module "lodash/sumBy" { const sumBy: typeof _.sumBy; export = sumBy; } declare module "lodash/template" { const template: typeof _.template; export = template; } declare module "lodash/times" { const times: typeof _.times; export = times; } declare module "lodash/toInteger" { const toInteger: typeof _.toInteger; export = toInteger; } declare module "lodash/toLength" { const toLength: typeof _.toLength; export = toLength; } declare module "lodash/toLower" { const toLower: typeof _.toLower; export = toLower; } declare module "lodash/toNumber" { const toNumber: typeof _.toNumber; export = toNumber; } declare module "lodash/toSafeInteger" { const toSafeInteger: typeof _.toSafeInteger; export = toSafeInteger; } declare module "lodash/toString" { const toString: typeof _.toString; export = toString; } declare module "lodash/toUpper" { const toUpper: typeof _.toUpper; export = toUpper; } declare module "lodash/trim" { const trim: typeof _.trim; export = trim; } declare module "lodash/trimEnd" { const trimEnd: typeof _.trimEnd; export = trimEnd; } declare module "lodash/trimStart" { const trimStart: typeof _.trimStart; export = trimStart; } declare module "lodash/truncate" { const truncate: typeof _.truncate; export = truncate; } declare module "lodash/unescape" { const unescape: typeof _.unescape; export = unescape; } declare module "lodash/uniqueId" { const uniqueId: typeof _.uniqueId; export = uniqueId; } declare module "lodash/upperCase" { const upperCase: typeof _.upperCase; export = upperCase; } declare module "lodash/upperFirst" { const upperFirst: typeof _.upperFirst; export = upperFirst; } declare module "lodash/each" { const each: typeof _.each; export = each; } declare module "lodash/eachRight" { const eachRight: typeof _.eachRight; export = eachRight; } declare module "lodash/first" { const first: typeof _.first; export = first; } declare module "lodash/fp" { export = _; } declare module "lodash" { export = _; } // Backward compatibility with --target es5 interface Set<T> {} interface Map<K, V> {} interface WeakSet<T> {} interface WeakMap<K, V> {}
sumbad/calendarium
typings/globals/lodash/index.d.ts
TypeScript
isc
547,077
var sendError = require('../../util/send-error'); // Create a new todo module.exports = function (options) { // Shorter reference to data store var store = options.store; return function (req, res) { var todo = store.todos.filter(function (t) { return t.id === req.params.id; })[0]; // No todo with that id if (!todo) { return sendError(res, 404, 'Todo not found'); } // Verify that user exists var user = store.users.filter(function (u) { return u.id === req.params.userId; })[0]; if (!user) { return sendError(res, 400, 'User not found: ' + req.params.userId); } // Set values todo.assignedTo = user.id; // Save data to store store.users.splice(store.users.indexOf(user), 1, user); // Respond res.status(200).json(todo); }; };
wesleytodd/express-todo-api
handlers/todos/assign.js
JavaScript
isc
784
var pi = require('./src/pi'); function run() { pi.send(parseInt(process.argv[2], 10)); setTimeout(run(), 2000); } run();
LucioFranco/bota2015
single.js
JavaScript
isc
128
'use strict' const net = require('net') const assert = require('assert') const eventList = require('../src/event-list') const tcpEmitterServer = require('../src/index') const { net: netUtils, payload: payloadUtils } = require('./utils') describe('TCP Emitter Server Tests:', function () { describe('Scenario: Creating a new TCP Emitter server:', function () { describe('When creating a new TCP Emitter server:', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { serverInst = tcpEmitterServer() }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) it('should return new instance of `net.Server`', function () { assert.ok(serverInst instanceof net.Server) }) }) }) describe('Scenario: Subscribing to an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be subscribing to an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('when the TCP Emitter client subscribes to an event:', function () { /** * Event which the TCP Emitter client will be subscribing to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' }) it('should emit TCP Emitter Subscribe Event with the TCP Emitter client & Event name', function (done) { serverInst.on(eventList.subscribe, (socket, eventName) => { // Assert that the emitted event name is the same as the event // name which the TCP Emitter client subscribed to. assert.strictEqual(event, eventName) // Assert that socket is of type 'net.Socket'. assert.ok(socket instanceof net.Socket) done() }) // Subscribe to an event. clientInst.write(payloadUtils.createSubscribe({ event })) }) }) }) }) }) describe('Scenario: Subscribing to an already subscribed event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be subscribing to an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('that is subscribed to an event,', function () { /** * Event which the TCP Emitter client will be subscribing to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' return clientInst.write(payloadUtils.createSubscribe({ event })) }) describe('when re-subscribing to the same event:', function () { it('should not emit TCP Emitter Subscribe Event', function (done) { global.setTimeout(done, 500) serverInst.on(eventList.subscribe, data => { assert.fail('TCP Emitter server should not emit TCP Emitter ' + 'Subscribe Event if the TCP Emitter client requests to ' + 'subscribe to an event that it is already subscribed to') done() }) // Subscribe to an event which the TCP Emitter client is already // subscribed to. clientInst.write(payloadUtils.createSubscribe({ event })) }) }) }) }) }) }) describe('Scenario: Unsubscribing from an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be unsubscribing from an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('that is subscribed to an event,', function () { /** * Event which the TCP Emitter client will be unsubscribing from. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' return clientInst.write(payloadUtils.createSubscribe({ event })) }) describe('when the TCP Emitter client unsubscribes from an event:', function () { it('should emit TCP Emitter Unsubscribe Event with the TCP Emitter client & Event name', function (done) { serverInst.on(eventList.unsubscribe, (socket, eventName) => { // Assert that the emitted event name is the same as the event // name which the TCP Emitter client subscribed to. assert.strictEqual(event, eventName) // Assert that socket is of type 'net.Socket'. assert.ok(socket instanceof net.Socket) done() }) // Subscribe to an event. return clientInst.write(payloadUtils.createUnsubscribe({ event })) }) }) }) }) }) }) describe('Scenario: Unsubscribing from an unsubscribed event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be subscribing to an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('when the TCP Emitter client request to unsubscribes from an event that it is not subscribed to:', function () { /** * Event which the TCP Emitter client will be unsubscribing from. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' }) it('should not emit TCP Emitter Unsubscribe Event', function (done) { global.setTimeout(done, 500) serverInst.on(eventList.unsubscribe, data => { assert.fail('TCP Emitter server should not emit TCP Emitter ' + 'Unsubscribe Event if the TCP Emitter client requests to ' + 'unsubscribe from an event that it is not subscribed to') done() }) // Unsubscribe from an event that the TCP Emitter client is not // subscribed to. clientInst.write(payloadUtils.createUnsubscribe({ event })) }) }) }) }) }) describe('Scenario: Broadcasting to an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be broadcasting to an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('when the TCP Emitter client broadcasts to an event:', function () { /** * Event which the TCP Emitter client will be broadcasting to. * @type {string} */ let event = null /** * Arguments that will be broadcasted. * @type {Array.<*>} */ let args = null beforeEach(function () { event = 'event-name' args = [ 1, '2', true, { name: 'luca' } ] }) it('should emit TCP Emitter Broadcast Event with the TCP Emitter client, Event name & Arguments', function (done) { // When an assertion fails in a EventEmitter, it will by default // emit the 'error' event with the error object. If there are no // listeners to the 'error' event it will throw the Error to the // process. // // Such implementation is expected when dealing with syncrhonous // processes, however since the Broadcast process uses Promises so // that it emits the TCP Emitter Broadcast Event once all the event // listeners (TCP Emitter clients) have been notified, when the // 'error' event is emitted, apart from the assertion error it will // also show the UnhandledPromiseRejectionWarning warning. // // This is why we are listening for the error event in this test // case. serverInst.on('error', done) serverInst.on(eventList.broadcast, (socket, eventName, broadcastedArgs) => { // Assert that the emitted event name is the same as the event // name which the TCP Emitter client broadcasted to. assert.strictEqual(event, eventName) // Assert that socket is of type 'net.Socket'. assert.ok(socket instanceof net.Socket) // Assert that the emitted arguments are the same as the // broadcasted arguments. assert.deepStrictEqual(args, broadcastedArgs) done() }) // Broadcast to an event. clientInst.write(payloadUtils.createBroadcast({ event, args })) }) }) }) }) }) describe('Scenario: Subscribing & broadcasting to an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter Server which the TCP Emitter clients will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with multiple connected TCP Emitter clients,', function () { /** * TCP Emitter client that will be receiving the payload. * @type {net.Socket} */ let receiverOne = null /** * TCP Emitter client that will be receiving the payload. * @type {net.Socket} */ let receiverTwo = null /** * TCP Emitter client that will be subscribed to another event. * @type {net.Socket} */ let otherClient = null /** * TCP Emitter client that will be broadcasting the payload. * @type {net.Socket} */ let broadcaster = null beforeEach(function () { // Create the TCP Emitter clients and connect them with the TCP // Emitter server for this test. return Promise.all([ netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()) ]).then(clients => { receiverOne = clients[0] receiverTwo = clients[1] otherClient = clients[2] broadcaster = clients[3] }) }) afterEach(function () { return Promise.all([ netUtils.closeTCPEmitterClient(receiverOne), netUtils.closeTCPEmitterClient(receiverTwo), netUtils.closeTCPEmitterClient(otherClient), netUtils.closeTCPEmitterClient(broadcaster) ]) }) describe('that are subscribed to an event,', function () { /** * Name of the event which the TCP Emitter clients will be subscribing * & broadcasting to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' // Subscribe the TCP Emitter clients. return Promise.all([ netUtils.write(receiverOne, payloadUtils.createSubscribe({ event })), netUtils.write(receiverTwo, payloadUtils.createSubscribe({ event })), netUtils.write(broadcaster, payloadUtils.createSubscribe({ event })), netUtils.write(otherClient, payloadUtils.createSubscribe({ event: 'other' })) ]) }) describe('when a TCP Emitter client broadcasts to an event:', function () { /** * Arguments that will be broadcasted. * @type {Array.<*>} */ let args = null beforeEach(function () { args = [ 1, '2', true, { name: 'luca' } ] }) it('should broadcast the payload to the listeners of the event', function (done) { // Wait for any data sent by the TCP Emitter server. Promise.all([ netUtils.waitForData(receiverOne), netUtils.waitForData(receiverTwo) ]).then(dataArray => { dataArray.forEach(data => { // Parse the data retrieved from TCP Emitter server. const payloads = payloadUtils.parsePayload({ data }) // Assert that only one payload was received. assert.strictEqual(payloads.length, 1) // Assert 'event' attribute. assert.strictEqual(event, payloads[0].event) // Assert 'args' attribute assert.deepStrictEqual(args, payloads[0].args) }) // Finalize test. done() }).catch(done) // Broadcast payload to the event which the receiver TCP Emitter // client is subscriibed to. broadcaster.write(payloadUtils.createBroadcast({ event, args })) }) it('should not broadcast the payload to the TCP Emitter client from where the broadcast originated from', function (done) { // Wait 500ms for any data sent by TCP Emitter Server before // assuming the test case is successful. global.setTimeout(done, 500) // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(broadcaster).then(() => { // TCP Emitter clients that broadcasted to the event should not // be notified by the TCP Emitter server. assert.fail('TCP Emitter clients that broadcasted to the ' + 'should not be notified') }).catch(done) // Broadcast payload to the event which the receiver TCP Emitter // client is subscriibed to. broadcaster.write(payloadUtils.createBroadcast({ event, args })) }) it('should not broadcast the payload to the TCP Emitter clients that are not subscribed to the event the broadcast was made for', function (done) { // Wait 500ms for any data sent by TCP Emitter Server before // assuming the test case is successful. global.setTimeout(done, 500) // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(otherClient).then(() => { // TCP Emitter clients which are not subscribed to the event // which the broadcast was made to, should not be notified. assert.fail('TCP Emitter client which is not subscribed to ' + 'the event the broadcast was made to, should not be notified') }).catch(done) // Broadcast payload to the event which the receiver TCP Emitter // client is subscriibed to. broadcaster.write(payloadUtils.createBroadcast({ event, args })) }) }) }) }) }) }) describe('Scenario: Unsubscribing from & broadcasting to an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter clients whill be // connecting return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with multiple connected TCP Emitter clients,', function () { /** * TCP Emitter client that will be receiving the payload. * @type {net.Socket} */ let receiver = null /** * TCP Emitter client that will be broadcasting the payload. * @type {net.Socket} */ let broadcaster = null /** * TCP Emitter client that will be unsubscribing from an event. * @type {net.Socket} */ let unsubscriber = null beforeEach(function () { // Create the TCP Emitter clients and connect them with the TCP // Emitter server for this test. return Promise.all([ netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()) ]).then(clients => { receiver = clients[0] broadcaster = clients[1] unsubscriber = clients[2] }) }) afterEach(function () { return Promise.all([ netUtils.closeTCPEmitterClient(receiver), netUtils.closeTCPEmitterClient(broadcaster), netUtils.closeTCPEmitterClient(unsubscriber) ]) }) describe('that are subscribed to an event,', function () { /** * Name of the event which the TCP Emitter clients will be subscribing * & broadcasting to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' // Subscribe the TCP Emitter clients return Promise.all([ netUtils.write(receiver, payloadUtils.createSubscribe({ event })), netUtils.write(unsubscriber, payloadUtils.createSubscribe({ event })) ]) }) describe('and a TCP Emitter client unsubscribes from an event,', function () { beforeEach(function () { return netUtils.write(unsubscriber, payloadUtils.createUnsubscribe({ event })) }) describe('when a TCP Emitter client broadcasts to an event:', function () { /** * Arguments that will be broadcasted. * @type {Array.<*>} */ let args = null beforeEach(function () { args = [ 1, '2', true, { name: 'luca' } ] }) it('should broadcast the payload to the listeners of the event', function (done) { // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(receiver).then((data) => { // Parse the data retrieved from TCP Emitter server. const payloads = payloadUtils.parsePayload({ data }) // Assert that only one payload was received. assert.strictEqual(payloads.length, 1) // Assert 'event' attribute. assert.strictEqual(event, payloads[0].event) // Assert 'args' attribute assert.deepStrictEqual(args, payloads[0].args) // Finalize test. done() }).catch(done) // Broadcast payload to the event which the TCP Emitter clients // have subscribed to. broadcaster.write(payloadUtils.createBroadcast({ event, args })) }) it('should not broadcast the payload to the TCP Emitter client that unsubscribed from the event', function (done) { // Wait 500ms for any data sent by TCP Emitter Server before // assuming the test case is successful. global.setTimeout(done, 500) // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(unsubscriber).then(() => { // The TCP Emitter client which broadcasted the event should not // be notified by the TCP Emitter server. assert.fail('TCP Emitter client that unsubscribed from an ' + 'event should not be notified') }).catch(done) // Broadcast payload to the event which the TCP Emitter clients // have subscribed to. broadcaster.write(payloadUtils.createBroadcast({ event })) }) }) }) }) }) }) }) describe('Scenario: Broadcasting multiple payloads with a single TCP request:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter Server which the TCP Emitter clients will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with multiple connected TCP Emitter clients', function () { /** * TCP Emitter client that will be receiving the payload. * @type {net.Socket} */ let receiver = null /** * TCP Emitter client that will be broadcasting the payload. * @type {net.Socket} */ let broadcaster = null beforeEach(function () { // Create the TCP Emitter clients and connect them with the TCP // Emitter server for this test. return Promise.all([ netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()) ]).then(clients => { receiver = clients[0] broadcaster = clients[1] }) }) afterEach(function () { return Promise.all([ netUtils.closeTCPEmitterClient(receiver), netUtils.closeTCPEmitterClient(broadcaster) ]) }) describe('and one of which is subscribed to an event,', function () { /** * Name of the event which the TCP Emitter clients will be subscribing * & broadcasting to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' // Subscribe the TCP Emitter client which will serve as the // receiver. return netUtils.write(receiver, payloadUtils.createSubscribe({ event })) }) describe('when broadcasting multiple payloads with a single TCP request:', function () { /** * Arguments that will be broadcasted in the first payload. * @type {Array.<*>} */ let argsOne = null /** * Arguments that will be broadcasted in the second payload. * @type {Array.<*>} */ let argsTwo = null beforeEach(function () { argsOne = [ 1, '2', true, { name: 'luca' } ] argsTwo = [ 2, '3', false, { surname: 'tabone' } ] }) it('should broadcast all the payloads to the listeners of the event accordingly', function (done) { // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(receiver).then(data => { // Parse the data retrieved from TCP Emitter server. const payloads = payloadUtils.parsePayload({ data }) // Assert that two payload was received. assert.strictEqual(payloads.length, 2) assert.deepStrictEqual(event, payloads[0].event) assert.deepStrictEqual(event, payloads[1].event) assert.deepStrictEqual(argsOne, payloads[0].args) assert.deepStrictEqual(argsTwo, payloads[1].args) done() }).catch(done) // Broadcast the first payload at the event which the receiver // TCP Emitter client is subscriibed to. broadcaster.write(payloadUtils .createBroadcast({ event, args: argsOne })) // Broadcast the second payload at the event which the receiver // TCP Emitter client is subscriibed to. broadcaster.write(payloadUtils .createBroadcast({ event, args: argsTwo })) }) }) }) }) }) }) })
tcp-emitter/server
test/tcp-emitter-server-test.js
JavaScript
isc
29,571
#!/usr/bin/env python3 def __safe_call(f, a): """Call a function and capture all exceptions.""" try: return f(a) except Exception as e: return "{}@{}({})".format(a.__class__.__name__, id(a), e) def __safe_error(msg, a, b): """Generate the error message for assert_XX without causing an error.""" return "{} ({}) {} {} ({})".format( __safe_call(str, a), __safe_call(repr, a), msg, __safe_call(str, b), __safe_call(repr, b), ) def assert_eq(a, b, msg=None): """Assert equal with better error message.""" assert a == b, msg or __safe_error("!=", a, b) def assert_not_in(needle, haystack, msg=None): """Assert equal with better error message.""" assert needle not in haystack, msg or __safe_error( "already in", needle, haystack ) def assert_is(a, b): """Assert is with better error message.""" assert a is b, __safe_error("is not", a, b) def assert_type( obj, cls, msg="{obj} ({obj!r}) should be a {cls}, not {objcls}" ): """Raise a type error if obj is not an instance of cls.""" if not isinstance(obj, cls): raise TypeError(msg.format(obj=obj, objcls=type(obj), cls=cls)) def assert_type_or_none(obj, classes): """Raise a type error if obj is not an instance of cls or None.""" if obj is not None: assert_type(obj, classes) def assert_len_eq(lists): """Check all lists in a list are equal length""" # Sanity check max_len = max(len(p) for p in lists) for i, p in enumerate(lists): assert len( p ) == max_len, "Length check failed!\nl[{}] has {} elements != {} ({!r})\n{!r}".format( i, len(p), max_len, p, lists )
SymbiFlow/symbiflow-arch-defs
utils/lib/asserts.py
Python
isc
1,746
export default { isMobile(window) { return window.innerWidth <= 420 }, generateTranslation(current, columnCount, elWidth, increment) { var position = current.position var value = current.value if (increment) { if (position < columnCount-1) { position = position + 1 } } else if (position > 0) { position = position - 1 } value = position ? `-${elWidth * position}px`: '0px' return { position: position, value: value } }, browserPrefix(attr, value) { var object = {} object[`-webkit-${attr}`] = value object[`-moz-${attr}`] = value object[`-o-${attr}`] = value return object }, stripeHeight() { const PRODUCT_HEADER_CLASS = 'product__header-menu' let bodyHeight = document.body.getBoundingClientRect().height let headerHeight = document.getElementsByClassName(PRODUCT_HEADER_CLASS)[0].getBoundingClientRect().height return bodyHeight - headerHeight } }
sprintly/sprintly-kanban
app/views/pages/helpers.js
JavaScript
isc
987
import React from 'react'; import { render } from 'react-dom'; import $ from 'jquery'; import IconAuthorAttrib from './subComponents/iconAuthorAttrib' import site_footer_switch from './helpers/site_footer_switch' export default class Foot extends React.Component { render(){ // console.log(this.props, 'was this.props in foot'); let resumeIconSrc = "./assets/icons/interface.svg" let portraitIconSrc = "./assets/icons/circle.svg" // let footStyle = let localListStyle = { listStyle: "none", // border: "1px solid black", paddingLeft: "0" } let localTextSize = { fontSize: "calc(5px + .3vh)", paddingLeft: "1px" } let iconAttrib; if(this.props.selectedLayout==="twitterMimic"){ iconAttrib = <div id="attribCollection" style={localTextSize} > <ul style={localListStyle}> <li><IconAuthorAttrib {...this.props} iconImg={resumeIconSrc} iconAuthorLink={"https://smashicons.com/"} /></li> <li><IconAuthorAttrib {...this.props} iconImg={portraitIconSrc} iconAuthorLink={"http://www.freepik.com/"} /></li> </ul> both authors found at <a href="https://www.flaticon.com">www.flaticon.com</a> </div> } else { iconAttrib = <div id="iconAttribNotNeeded"></div> } return( <div id="footContainer" style={site_footer_switch(this.props)} > {/*<div><a>webform to send me e-mails without giving out my email address?</a></div>*/} {iconAttrib} </div> ) } }
MelanistOnca/Pers
public/js/foot.js
JavaScript
isc
1,660
import React, { Component } from "react"; import { autobind } from "core-decorators"; import { DiscoverAddressesFormHeader as DiscoverAddressesHeader, DiscoverAddressesFormBody } from "./Form"; @autobind class DiscoverAddressesBody extends Component { constructor(props) { super(props); this.state = this.getInitialState(); } componentWillUnmount() { this.resetState(); } getInitialState() { return { passPhrase: "", hasAttemptedDiscover: false }; } render() { const { passPhrase, hasAttemptedDiscover } = this.state; const { onSetPassPhrase, onDiscoverAddresses, onKeyDown } = this; return ( <DiscoverAddressesFormBody {...{ ...this.props, passPhrase, hasAttemptedDiscover, onSetPassPhrase, onDiscoverAddresses, onKeyDown }} /> ); } resetState() { this.setState(this.getInitialState()); } onSetPassPhrase(passPhrase) { this.setState({ passPhrase }); } onDiscoverAddresses() { if (!this.state.passPhrase) { return this.setState({ hasAttemptedDiscover: true }); } this.props.onDiscoverAddresses(this.state.passPhrase); this.resetState(); } onKeyDown(e) { if(e.keyCode == 13) { // Enter key e.preventDefault(); this.onDiscoverAddresses(); } } } export { DiscoverAddressesHeader, DiscoverAddressesBody };
oktapodia/decrediton-appveyor-test
app/components/views/GetStartedPage/DiscoverAddresses/index.js
JavaScript
isc
1,439
'use strict'; module.exports = function(err, req, res, next) { let statusCode = err.statusCode || 500; let message = err.message || 'doh!'; let stack = err.stack || ''; res.status(statusCode).json({ message: message, stack: stack }); }
joerx/proto-ci
app/modules/api/error-handler.js
JavaScript
isc
256
// adopted from: https://github.com/fshost/node-dir // Copyright (c) 2012 Nathan Cartwright <fshost@yahoo.com> (MIT) var fs = require('fs') var path = require('path') var mm = require('../glob/minimatch') /** * merge two objects by extending target object with source object * @param target object to merge * @param source object to merge * @param {Boolean} [modify] whether to modify the target * @returns {Object} extended object */ function extend(target, source, modify) { var result = target ? modify ? target : extend({}, target, true) : {}; if (!source) return result; for (var key in source) { if (source.hasOwnProperty(key) && source[key] !== undefined) { result[key] = source[key]; } } return result; } /** * determine if a string is contained within an array or matches a regular expression * @param {String} str string to match * @param {Array|Regex} match array or regular expression to match against * @returns {Boolean} whether there is a match */ function matches(str, match) { if (Array.isArray(match)) { var l = match.length; for (var s = 0; s < l; s++) { if (mm(str, match[s])) { return true; } } return false; } return match.test(str); } /** * read files and call a function with the contents of each file * @param {String} dir path of dir containing the files to be read * @param {String} encoding file encoding (default is 'utf8') * @param {Object} options options hash for encoding, recursive, and match/exclude * @param {Function(error, string)} callback callback for each files content * @param {Function(error)} complete fn to call when finished */ function readFilesStream(dir, options, callback, complete) { if (typeof options === 'function') { complete = callback; callback = options; options = {}; } if (typeof options === 'string') options = { encoding: options }; options = extend({ recursive: true, encoding: 'utf8', doneOnErr: true }, options); var files = []; var done = function (err) { if (typeof complete === 'function') { if (err) return complete(err); complete(null, files); } }; fs.readdir(dir, function (err, list) { if (err) { if (options.doneOnErr === true) { if (err.code === 'EACCES') return done(); return done(err); } } var i = 0; if (options.reverse === true || (typeof options.sort == 'string' && (/reverse|desc/i).test(options.sort))) { list = list.reverse(); } else if (options.sort !== false) list = list.sort(); (function next() { var filename = list[i++]; if (!filename) return done(null, files); var file = path.join(dir, filename); fs.stat(file, function (err, stat) { if (err && options.doneOnErr === true) return done(err); if (stat && stat.isDirectory()) { if (options.recursive) { if (options.matchDir && !matches(filename, options.matchDir)) return next(); if (options.excludeDir && matches(filename, options.excludeDir)) return next(); readFilesStream(file, options, callback, function (err, sfiles) { if (err && options.doneOnErr === true) return done(err); files = files.concat(sfiles); next(); }); } else next(); } else if (stat && stat.isFile()) { if (options.match && !matches(filename, options.match)) return next(); if (options.exclude && matches(filename, options.exclude)) return next(); if (options.filter && !options.filter(filename)) return next(); if (options.shortName) files.push(filename); else files.push(file); var stream = fs.createReadStream(file); stream.setEncoding(options.encoding); stream.on('error', function (err) { if (options.doneOnErr === true) return done(err); next(); }); if (callback.length > 3) if (options.shortName) callback(null, stream, filename, next); else callback(null, stream, file, next); else callback(null, stream, next); } else { next(); } }); })(); }); } module.exports = readFilesStream;
akileez/toolz
src/stream/read-file-stream.js
JavaScript
isc
4,333
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Defined when linking against shared lib on Windows. #if defined(USING_V8_SHARED) && !defined(V8_SHARED) #define V8_SHARED #endif #ifdef COMPRESS_STARTUP_DATA_BZ2 #include <bzlib.h> #endif #include <errno.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #ifdef V8_SHARED #include <assert.h> #endif // V8_SHARED #ifndef V8_SHARED #include <algorithm> #endif // !V8_SHARED #ifdef V8_SHARED #include "include/v8-testing.h" #endif // V8_SHARED #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE) #include "src/gdb-jit.h" #endif #ifdef ENABLE_VTUNE_JIT_INTERFACE #include "src/third_party/vtune/v8-vtune.h" #endif #include "src/d8.h" #include "include/libplatform/libplatform.h" #ifndef V8_SHARED #include "src/api.h" #include "src/base/cpu.h" #include "src/base/logging.h" #include "src/base/platform/platform.h" #include "src/base/sys-info.h" #include "src/basic-block-profiler.h" #include "src/d8-debug.h" #include "src/debug.h" #include "src/natives.h" #include "src/v8.h" #endif // !V8_SHARED #if !defined(_WIN32) && !defined(_WIN64) #include <unistd.h> // NOLINT #else #include <windows.h> // NOLINT #if defined(_MSC_VER) #include <crtdbg.h> // NOLINT #endif // defined(_MSC_VER) #endif // !defined(_WIN32) && !defined(_WIN64) #ifndef DCHECK #define DCHECK(condition) assert(condition) #endif namespace v8 { static Handle<Value> Throw(Isolate* isolate, const char* message) { return isolate->ThrowException(String::NewFromUtf8(isolate, message)); } class PerIsolateData { public: explicit PerIsolateData(Isolate* isolate) : isolate_(isolate), realms_(NULL) { HandleScope scope(isolate); isolate->SetData(0, this); } ~PerIsolateData() { isolate_->SetData(0, NULL); // Not really needed, just to be sure... } inline static PerIsolateData* Get(Isolate* isolate) { return reinterpret_cast<PerIsolateData*>(isolate->GetData(0)); } class RealmScope { public: explicit RealmScope(PerIsolateData* data); ~RealmScope(); private: PerIsolateData* data_; }; private: friend class Shell; friend class RealmScope; Isolate* isolate_; int realm_count_; int realm_current_; int realm_switch_; Persistent<Context>* realms_; Persistent<Value> realm_shared_; int RealmIndexOrThrow(const v8::FunctionCallbackInfo<v8::Value>& args, int arg_offset); int RealmFind(Handle<Context> context); }; LineEditor *LineEditor::current_ = NULL; LineEditor::LineEditor(Type type, const char* name) : type_(type), name_(name) { if (current_ == NULL || current_->type_ < type) current_ = this; } class DumbLineEditor: public LineEditor { public: explicit DumbLineEditor(Isolate* isolate) : LineEditor(LineEditor::DUMB, "dumb"), isolate_(isolate) { } virtual Handle<String> Prompt(const char* prompt); private: Isolate* isolate_; }; Handle<String> DumbLineEditor::Prompt(const char* prompt) { printf("%s", prompt); #if defined(__native_client__) // Native Client libc is used to being embedded in Chrome and // has trouble recognizing when to flush. fflush(stdout); #endif return Shell::ReadFromStdin(isolate_); } #ifndef V8_SHARED CounterMap* Shell::counter_map_; base::OS::MemoryMappedFile* Shell::counters_file_ = NULL; CounterCollection Shell::local_counters_; CounterCollection* Shell::counters_ = &local_counters_; base::Mutex Shell::context_mutex_; const base::TimeTicks Shell::kInitialTicks = base::TimeTicks::HighResolutionNow(); Persistent<Context> Shell::utility_context_; #endif // !V8_SHARED Persistent<Context> Shell::evaluation_context_; ShellOptions Shell::options; const char* Shell::kPrompt = "d8> "; #ifndef V8_SHARED const int MB = 1024 * 1024; bool CounterMap::Match(void* key1, void* key2) { const char* name1 = reinterpret_cast<const char*>(key1); const char* name2 = reinterpret_cast<const char*>(key2); return strcmp(name1, name2) == 0; } #endif // !V8_SHARED // Converts a V8 value to a C string. const char* Shell::ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } // Compile a string within the current v8 context. Local<UnboundScript> Shell::CompileString( Isolate* isolate, Local<String> source, Local<Value> name, v8::ScriptCompiler::CompileOptions compile_options) { ScriptOrigin origin(name); ScriptCompiler::Source script_source(source, origin); Local<UnboundScript> script = ScriptCompiler::CompileUnbound(isolate, &script_source, compile_options); // Was caching requested & successful? Then compile again, now with cache. if (script_source.GetCachedData()) { if (compile_options == ScriptCompiler::kProduceCodeCache) { compile_options = ScriptCompiler::kConsumeCodeCache; } else if (compile_options == ScriptCompiler::kProduceParserCache) { compile_options = ScriptCompiler::kConsumeParserCache; } else { DCHECK(false); // A new compile option? } ScriptCompiler::Source cached_source( source, origin, new v8::ScriptCompiler::CachedData( script_source.GetCachedData()->data, script_source.GetCachedData()->length, v8::ScriptCompiler::CachedData::BufferNotOwned)); script = ScriptCompiler::CompileUnbound(isolate, &cached_source, compile_options); } return script; } // Executes a string within the current v8 context. bool Shell::ExecuteString(Isolate* isolate, Handle<String> source, Handle<Value> name, bool print_result, bool report_exceptions) { #ifndef V8_SHARED bool FLAG_debugger = i::FLAG_debugger; #else bool FLAG_debugger = false; #endif // !V8_SHARED HandleScope handle_scope(isolate); TryCatch try_catch; options.script_executed = true; if (FLAG_debugger) { // When debugging make exceptions appear to be uncaught. try_catch.SetVerbose(true); } Handle<UnboundScript> script = Shell::CompileString(isolate, source, name, options.compile_options); if (script.IsEmpty()) { // Print errors that happened during compilation. if (report_exceptions && !FLAG_debugger) ReportException(isolate, &try_catch); return false; } else { PerIsolateData* data = PerIsolateData::Get(isolate); Local<Context> realm = Local<Context>::New(isolate, data->realms_[data->realm_current_]); realm->Enter(); Handle<Value> result = script->BindToCurrentContext()->Run(); realm->Exit(); data->realm_current_ = data->realm_switch_; if (result.IsEmpty()) { DCHECK(try_catch.HasCaught()); // Print errors that happened during execution. if (report_exceptions && !FLAG_debugger) ReportException(isolate, &try_catch); return false; } else { DCHECK(!try_catch.HasCaught()); if (print_result) { #if !defined(V8_SHARED) if (options.test_shell) { #endif if (!result->IsUndefined()) { // If all went well and the result wasn't undefined then print // the returned value. v8::String::Utf8Value str(result); fwrite(*str, sizeof(**str), str.length(), stdout); printf("\n"); } #if !defined(V8_SHARED) } else { v8::TryCatch try_catch; v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, utility_context_); v8::Context::Scope context_scope(context); Handle<Object> global = context->Global(); Handle<Value> fun = global->Get(String::NewFromUtf8(isolate, "Stringify")); Handle<Value> argv[1] = { result }; Handle<Value> s = Handle<Function>::Cast(fun)->Call(global, 1, argv); if (try_catch.HasCaught()) return true; v8::String::Utf8Value str(s); fwrite(*str, sizeof(**str), str.length(), stdout); printf("\n"); } #endif } return true; } } } PerIsolateData::RealmScope::RealmScope(PerIsolateData* data) : data_(data) { data_->realm_count_ = 1; data_->realm_current_ = 0; data_->realm_switch_ = 0; data_->realms_ = new Persistent<Context>[1]; data_->realms_[0].Reset(data_->isolate_, data_->isolate_->GetEnteredContext()); } PerIsolateData::RealmScope::~RealmScope() { // Drop realms to avoid keeping them alive. for (int i = 0; i < data_->realm_count_; ++i) data_->realms_[i].Reset(); delete[] data_->realms_; if (!data_->realm_shared_.IsEmpty()) data_->realm_shared_.Reset(); } int PerIsolateData::RealmFind(Handle<Context> context) { for (int i = 0; i < realm_count_; ++i) { if (realms_[i] == context) return i; } return -1; } int PerIsolateData::RealmIndexOrThrow( const v8::FunctionCallbackInfo<v8::Value>& args, int arg_offset) { if (args.Length() < arg_offset || !args[arg_offset]->IsNumber()) { Throw(args.GetIsolate(), "Invalid argument"); return -1; } int index = args[arg_offset]->Int32Value(); if (index < 0 || index >= realm_count_ || realms_[index].IsEmpty()) { Throw(args.GetIsolate(), "Invalid realm index"); return -1; } return index; } #ifndef V8_SHARED // performance.now() returns a time stamp as double, measured in milliseconds. // When FLAG_verify_predictable mode is enabled it returns current value // of Heap::allocations_count(). void Shell::PerformanceNow(const v8::FunctionCallbackInfo<v8::Value>& args) { if (i::FLAG_verify_predictable) { Isolate* v8_isolate = args.GetIsolate(); i::Heap* heap = reinterpret_cast<i::Isolate*>(v8_isolate)->heap(); args.GetReturnValue().Set(heap->synthetic_time()); } else { base::TimeDelta delta = base::TimeTicks::HighResolutionNow() - kInitialTicks; args.GetReturnValue().Set(delta.InMillisecondsF()); } } #endif // !V8_SHARED // Realm.current() returns the index of the currently active realm. void Shell::RealmCurrent(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); PerIsolateData* data = PerIsolateData::Get(isolate); int index = data->RealmFind(isolate->GetEnteredContext()); if (index == -1) return; args.GetReturnValue().Set(index); } // Realm.owner(o) returns the index of the realm that created o. void Shell::RealmOwner(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); PerIsolateData* data = PerIsolateData::Get(isolate); if (args.Length() < 1 || !args[0]->IsObject()) { Throw(args.GetIsolate(), "Invalid argument"); return; } int index = data->RealmFind(args[0]->ToObject()->CreationContext()); if (index == -1) return; args.GetReturnValue().Set(index); } // Realm.global(i) returns the global object of realm i. // (Note that properties of global objects cannot be read/written cross-realm.) void Shell::RealmGlobal(const v8::FunctionCallbackInfo<v8::Value>& args) { PerIsolateData* data = PerIsolateData::Get(args.GetIsolate()); int index = data->RealmIndexOrThrow(args, 0); if (index == -1) return; args.GetReturnValue().Set( Local<Context>::New(args.GetIsolate(), data->realms_[index])->Global()); } // Realm.create() creates a new realm and returns its index. void Shell::RealmCreate(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); PerIsolateData* data = PerIsolateData::Get(isolate); Persistent<Context>* old_realms = data->realms_; int index = data->realm_count_; data->realms_ = new Persistent<Context>[++data->realm_count_]; for (int i = 0; i < index; ++i) { data->realms_[i].Reset(isolate, old_realms[i]); } delete[] old_realms; Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate); data->realms_[index].Reset( isolate, Context::New(isolate, NULL, global_template)); args.GetReturnValue().Set(index); } // Realm.dispose(i) disposes the reference to the realm i. void Shell::RealmDispose(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); PerIsolateData* data = PerIsolateData::Get(isolate); int index = data->RealmIndexOrThrow(args, 0); if (index == -1) return; if (index == 0 || index == data->realm_current_ || index == data->realm_switch_) { Throw(args.GetIsolate(), "Invalid realm index"); return; } data->realms_[index].Reset(); } // Realm.switch(i) switches to the realm i for consecutive interactive inputs. void Shell::RealmSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); PerIsolateData* data = PerIsolateData::Get(isolate); int index = data->RealmIndexOrThrow(args, 0); if (index == -1) return; data->realm_switch_ = index; } // Realm.eval(i, s) evaluates s in realm i and returns the result. void Shell::RealmEval(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); PerIsolateData* data = PerIsolateData::Get(isolate); int index = data->RealmIndexOrThrow(args, 0); if (index == -1) return; if (args.Length() < 2 || !args[1]->IsString()) { Throw(args.GetIsolate(), "Invalid argument"); return; } ScriptCompiler::Source script_source(args[1]->ToString()); Handle<UnboundScript> script = ScriptCompiler::CompileUnbound( isolate, &script_source); if (script.IsEmpty()) return; Local<Context> realm = Local<Context>::New(isolate, data->realms_[index]); realm->Enter(); Handle<Value> result = script->BindToCurrentContext()->Run(); realm->Exit(); args.GetReturnValue().Set(result); } // Realm.shared is an accessor for a single shared value across realms. void Shell::RealmSharedGet(Local<String> property, const PropertyCallbackInfo<Value>& info) { Isolate* isolate = info.GetIsolate(); PerIsolateData* data = PerIsolateData::Get(isolate); if (data->realm_shared_.IsEmpty()) return; info.GetReturnValue().Set(data->realm_shared_); } void Shell::RealmSharedSet(Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info) { Isolate* isolate = info.GetIsolate(); PerIsolateData* data = PerIsolateData::Get(isolate); data->realm_shared_.Reset(isolate, value); } void Shell::Print(const v8::FunctionCallbackInfo<v8::Value>& args) { Write(args); printf("\n"); fflush(stdout); } void Shell::Write(const v8::FunctionCallbackInfo<v8::Value>& args) { for (int i = 0; i < args.Length(); i++) { HandleScope handle_scope(args.GetIsolate()); if (i != 0) { printf(" "); } // Explicitly catch potential exceptions in toString(). v8::TryCatch try_catch; Handle<String> str_obj = args[i]->ToString(); if (try_catch.HasCaught()) { try_catch.ReThrow(); return; } v8::String::Utf8Value str(str_obj); int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), stdout)); if (n != str.length()) { printf("Error in fwrite\n"); Exit(1); } } } void Shell::Read(const v8::FunctionCallbackInfo<v8::Value>& args) { String::Utf8Value file(args[0]); if (*file == NULL) { Throw(args.GetIsolate(), "Error loading file"); return; } Handle<String> source = ReadFile(args.GetIsolate(), *file); if (source.IsEmpty()) { Throw(args.GetIsolate(), "Error loading file"); return; } args.GetReturnValue().Set(source); } Handle<String> Shell::ReadFromStdin(Isolate* isolate) { static const int kBufferSize = 256; char buffer[kBufferSize]; Handle<String> accumulator = String::NewFromUtf8(isolate, ""); int length; while (true) { // Continue reading if the line ends with an escape '\\' or the line has // not been fully read into the buffer yet (does not end with '\n'). // If fgets gets an error, just give up. char* input = NULL; input = fgets(buffer, kBufferSize, stdin); if (input == NULL) return Handle<String>(); length = static_cast<int>(strlen(buffer)); if (length == 0) { return accumulator; } else if (buffer[length-1] != '\n') { accumulator = String::Concat( accumulator, String::NewFromUtf8(isolate, buffer, String::kNormalString, length)); } else if (length > 1 && buffer[length-2] == '\\') { buffer[length-2] = '\n'; accumulator = String::Concat( accumulator, String::NewFromUtf8(isolate, buffer, String::kNormalString, length - 1)); } else { return String::Concat( accumulator, String::NewFromUtf8(isolate, buffer, String::kNormalString, length - 1)); } } } void Shell::Load(const v8::FunctionCallbackInfo<v8::Value>& args) { for (int i = 0; i < args.Length(); i++) { HandleScope handle_scope(args.GetIsolate()); String::Utf8Value file(args[i]); if (*file == NULL) { Throw(args.GetIsolate(), "Error loading file"); return; } Handle<String> source = ReadFile(args.GetIsolate(), *file); if (source.IsEmpty()) { Throw(args.GetIsolate(), "Error loading file"); return; } if (!ExecuteString(args.GetIsolate(), source, String::NewFromUtf8(args.GetIsolate(), *file), false, true)) { Throw(args.GetIsolate(), "Error executing file"); return; } } } void Shell::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) { int exit_code = args[0]->Int32Value(); OnExit(); exit(exit_code); } void Shell::Version(const v8::FunctionCallbackInfo<v8::Value>& args) { args.GetReturnValue().Set( String::NewFromUtf8(args.GetIsolate(), V8::GetVersion())); } void Shell::ReportException(Isolate* isolate, v8::TryCatch* try_catch) { HandleScope handle_scope(isolate); #ifndef V8_SHARED Handle<Context> utility_context; bool enter_context = !isolate->InContext(); if (enter_context) { utility_context = Local<Context>::New(isolate, utility_context_); utility_context->Enter(); } #endif // !V8_SHARED v8::String::Utf8Value exception(try_catch->Exception()); const char* exception_string = ToCString(exception); Handle<Message> message = try_catch->Message(); if (message.IsEmpty()) { // V8 didn't provide any extra information about this error; just // print the exception. printf("%s\n", exception_string); } else { // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); printf("%s:%i: %s\n", filename_string, linenum, exception_string); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); printf("%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { printf(" "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { printf("^"); } printf("\n"); v8::String::Utf8Value stack_trace(try_catch->StackTrace()); if (stack_trace.length() > 0) { const char* stack_trace_string = ToCString(stack_trace); printf("%s\n", stack_trace_string); } } printf("\n"); #ifndef V8_SHARED if (enter_context) utility_context->Exit(); #endif // !V8_SHARED } #ifndef V8_SHARED Handle<Array> Shell::GetCompletions(Isolate* isolate, Handle<String> text, Handle<String> full) { EscapableHandleScope handle_scope(isolate); v8::Local<v8::Context> utility_context = v8::Local<v8::Context>::New(isolate, utility_context_); v8::Context::Scope context_scope(utility_context); Handle<Object> global = utility_context->Global(); Local<Value> fun = global->Get(String::NewFromUtf8(isolate, "GetCompletions")); static const int kArgc = 3; v8::Local<v8::Context> evaluation_context = v8::Local<v8::Context>::New(isolate, evaluation_context_); Handle<Value> argv[kArgc] = { evaluation_context->Global(), text, full }; Local<Value> val = Local<Function>::Cast(fun)->Call(global, kArgc, argv); return handle_scope.Escape(Local<Array>::Cast(val)); } Local<Object> Shell::DebugMessageDetails(Isolate* isolate, Handle<String> message) { EscapableHandleScope handle_scope(isolate); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, utility_context_); v8::Context::Scope context_scope(context); Handle<Object> global = context->Global(); Handle<Value> fun = global->Get(String::NewFromUtf8(isolate, "DebugMessageDetails")); static const int kArgc = 1; Handle<Value> argv[kArgc] = { message }; Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv); return handle_scope.Escape(Local<Object>(Handle<Object>::Cast(val))); } Local<Value> Shell::DebugCommandToJSONRequest(Isolate* isolate, Handle<String> command) { EscapableHandleScope handle_scope(isolate); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, utility_context_); v8::Context::Scope context_scope(context); Handle<Object> global = context->Global(); Handle<Value> fun = global->Get(String::NewFromUtf8(isolate, "DebugCommandToJSONRequest")); static const int kArgc = 1; Handle<Value> argv[kArgc] = { command }; Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv); return handle_scope.Escape(Local<Value>(val)); } int32_t* Counter::Bind(const char* name, bool is_histogram) { int i; for (i = 0; i < kMaxNameSize - 1 && name[i]; i++) name_[i] = static_cast<char>(name[i]); name_[i] = '\0'; is_histogram_ = is_histogram; return ptr(); } void Counter::AddSample(int32_t sample) { count_++; sample_total_ += sample; } CounterCollection::CounterCollection() { magic_number_ = 0xDEADFACE; max_counters_ = kMaxCounters; max_name_size_ = Counter::kMaxNameSize; counters_in_use_ = 0; } Counter* CounterCollection::GetNextCounter() { if (counters_in_use_ == kMaxCounters) return NULL; return &counters_[counters_in_use_++]; } void Shell::MapCounters(v8::Isolate* isolate, const char* name) { counters_file_ = base::OS::MemoryMappedFile::create( name, sizeof(CounterCollection), &local_counters_); void* memory = (counters_file_ == NULL) ? NULL : counters_file_->memory(); if (memory == NULL) { printf("Could not map counters file %s\n", name); Exit(1); } counters_ = static_cast<CounterCollection*>(memory); isolate->SetCounterFunction(LookupCounter); isolate->SetCreateHistogramFunction(CreateHistogram); isolate->SetAddHistogramSampleFunction(AddHistogramSample); } int CounterMap::Hash(const char* name) { int h = 0; int c; while ((c = *name++) != 0) { h += h << 5; h += c; } return h; } Counter* Shell::GetCounter(const char* name, bool is_histogram) { Counter* counter = counter_map_->Lookup(name); if (counter == NULL) { counter = counters_->GetNextCounter(); if (counter != NULL) { counter_map_->Set(name, counter); counter->Bind(name, is_histogram); } } else { DCHECK(counter->is_histogram() == is_histogram); } return counter; } int* Shell::LookupCounter(const char* name) { Counter* counter = GetCounter(name, false); if (counter != NULL) { return counter->ptr(); } else { return NULL; } } void* Shell::CreateHistogram(const char* name, int min, int max, size_t buckets) { return GetCounter(name, true); } void Shell::AddHistogramSample(void* histogram, int sample) { Counter* counter = reinterpret_cast<Counter*>(histogram); counter->AddSample(sample); } void Shell::InstallUtilityScript(Isolate* isolate) { HandleScope scope(isolate); // If we use the utility context, we have to set the security tokens so that // utility, evaluation and debug context can all access each other. v8::Local<v8::Context> utility_context = v8::Local<v8::Context>::New(isolate, utility_context_); v8::Local<v8::Context> evaluation_context = v8::Local<v8::Context>::New(isolate, evaluation_context_); utility_context->SetSecurityToken(Undefined(isolate)); evaluation_context->SetSecurityToken(Undefined(isolate)); v8::Context::Scope context_scope(utility_context); if (i::FLAG_debugger) printf("JavaScript debugger enabled\n"); // Install the debugger object in the utility scope i::Debug* debug = reinterpret_cast<i::Isolate*>(isolate)->debug(); debug->Load(); i::Handle<i::Context> debug_context = debug->debug_context(); i::Handle<i::JSObject> js_debug = i::Handle<i::JSObject>(debug_context->global_object()); utility_context->Global()->Set(String::NewFromUtf8(isolate, "$debug"), Utils::ToLocal(js_debug)); debug_context->set_security_token( reinterpret_cast<i::Isolate*>(isolate)->heap()->undefined_value()); // Run the d8 shell utility script in the utility context int source_index = i::NativesCollection<i::D8>::GetIndex("d8"); i::Vector<const char> shell_source = i::NativesCollection<i::D8>::GetRawScriptSource(source_index); i::Vector<const char> shell_source_name = i::NativesCollection<i::D8>::GetScriptName(source_index); Handle<String> source = String::NewFromUtf8(isolate, shell_source.start(), String::kNormalString, shell_source.length()); Handle<String> name = String::NewFromUtf8(isolate, shell_source_name.start(), String::kNormalString, shell_source_name.length()); ScriptOrigin origin(name); Handle<Script> script = Script::Compile(source, &origin); script->Run(); // Mark the d8 shell script as native to avoid it showing up as normal source // in the debugger. i::Handle<i::Object> compiled_script = Utils::OpenHandle(*script); i::Handle<i::Script> script_object = compiled_script->IsJSFunction() ? i::Handle<i::Script>(i::Script::cast( i::JSFunction::cast(*compiled_script)->shared()->script())) : i::Handle<i::Script>(i::Script::cast( i::SharedFunctionInfo::cast(*compiled_script)->script())); script_object->set_type(i::Smi::FromInt(i::Script::TYPE_NATIVE)); // Start the in-process debugger if requested. if (i::FLAG_debugger) v8::Debug::SetDebugEventListener(HandleDebugEvent); } #endif // !V8_SHARED #ifdef COMPRESS_STARTUP_DATA_BZ2 class BZip2Decompressor : public v8::StartupDataDecompressor { public: virtual ~BZip2Decompressor() { } protected: virtual int DecompressData(char* raw_data, int* raw_data_size, const char* compressed_data, int compressed_data_size) { DCHECK_EQ(v8::StartupData::kBZip2, v8::V8::GetCompressedStartupDataAlgorithm()); unsigned int decompressed_size = *raw_data_size; int result = BZ2_bzBuffToBuffDecompress(raw_data, &decompressed_size, const_cast<char*>(compressed_data), compressed_data_size, 0, 1); if (result == BZ_OK) { *raw_data_size = decompressed_size; } return result; } }; #endif Handle<ObjectTemplate> Shell::CreateGlobalTemplate(Isolate* isolate) { Handle<ObjectTemplate> global_template = ObjectTemplate::New(isolate); global_template->Set(String::NewFromUtf8(isolate, "print"), FunctionTemplate::New(isolate, Print)); global_template->Set(String::NewFromUtf8(isolate, "write"), FunctionTemplate::New(isolate, Write)); global_template->Set(String::NewFromUtf8(isolate, "read"), FunctionTemplate::New(isolate, Read)); global_template->Set(String::NewFromUtf8(isolate, "readbuffer"), FunctionTemplate::New(isolate, ReadBuffer)); global_template->Set(String::NewFromUtf8(isolate, "readline"), FunctionTemplate::New(isolate, ReadLine)); global_template->Set(String::NewFromUtf8(isolate, "load"), FunctionTemplate::New(isolate, Load)); global_template->Set(String::NewFromUtf8(isolate, "quit"), FunctionTemplate::New(isolate, Quit)); global_template->Set(String::NewFromUtf8(isolate, "version"), FunctionTemplate::New(isolate, Version)); // Bind the Realm object. Handle<ObjectTemplate> realm_template = ObjectTemplate::New(isolate); realm_template->Set(String::NewFromUtf8(isolate, "current"), FunctionTemplate::New(isolate, RealmCurrent)); realm_template->Set(String::NewFromUtf8(isolate, "owner"), FunctionTemplate::New(isolate, RealmOwner)); realm_template->Set(String::NewFromUtf8(isolate, "global"), FunctionTemplate::New(isolate, RealmGlobal)); realm_template->Set(String::NewFromUtf8(isolate, "create"), FunctionTemplate::New(isolate, RealmCreate)); realm_template->Set(String::NewFromUtf8(isolate, "dispose"), FunctionTemplate::New(isolate, RealmDispose)); realm_template->Set(String::NewFromUtf8(isolate, "switch"), FunctionTemplate::New(isolate, RealmSwitch)); realm_template->Set(String::NewFromUtf8(isolate, "eval"), FunctionTemplate::New(isolate, RealmEval)); realm_template->SetAccessor(String::NewFromUtf8(isolate, "shared"), RealmSharedGet, RealmSharedSet); global_template->Set(String::NewFromUtf8(isolate, "Realm"), realm_template); #ifndef V8_SHARED Handle<ObjectTemplate> performance_template = ObjectTemplate::New(isolate); performance_template->Set(String::NewFromUtf8(isolate, "now"), FunctionTemplate::New(isolate, PerformanceNow)); global_template->Set(String::NewFromUtf8(isolate, "performance"), performance_template); #endif // !V8_SHARED Handle<ObjectTemplate> os_templ = ObjectTemplate::New(isolate); AddOSMethods(isolate, os_templ); global_template->Set(String::NewFromUtf8(isolate, "os"), os_templ); return global_template; } void Shell::Initialize(Isolate* isolate) { #ifdef COMPRESS_STARTUP_DATA_BZ2 BZip2Decompressor startup_data_decompressor; int bz2_result = startup_data_decompressor.Decompress(); if (bz2_result != BZ_OK) { fprintf(stderr, "bzip error code: %d\n", bz2_result); Exit(1); } #endif #ifndef V8_SHARED Shell::counter_map_ = new CounterMap(); // Set up counters if (i::StrLength(i::FLAG_map_counters) != 0) MapCounters(isolate, i::FLAG_map_counters); if (i::FLAG_dump_counters || i::FLAG_track_gc_object_stats) { isolate->SetCounterFunction(LookupCounter); isolate->SetCreateHistogramFunction(CreateHistogram); isolate->SetAddHistogramSampleFunction(AddHistogramSample); } #endif // !V8_SHARED } void Shell::InitializeDebugger(Isolate* isolate) { if (options.test_shell) return; #ifndef V8_SHARED HandleScope scope(isolate); Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate); utility_context_.Reset(isolate, Context::New(isolate, NULL, global_template)); #endif // !V8_SHARED } Local<Context> Shell::CreateEvaluationContext(Isolate* isolate) { #ifndef V8_SHARED // This needs to be a critical section since this is not thread-safe base::LockGuard<base::Mutex> lock_guard(&context_mutex_); #endif // !V8_SHARED // Initialize the global objects Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate); EscapableHandleScope handle_scope(isolate); Local<Context> context = Context::New(isolate, NULL, global_template); DCHECK(!context.IsEmpty()); Context::Scope scope(context); #ifndef V8_SHARED i::Factory* factory = reinterpret_cast<i::Isolate*>(isolate)->factory(); i::JSArguments js_args = i::FLAG_js_arguments; i::Handle<i::FixedArray> arguments_array = factory->NewFixedArray(js_args.argc); for (int j = 0; j < js_args.argc; j++) { i::Handle<i::String> arg = factory->NewStringFromUtf8(i::CStrVector(js_args[j])).ToHandleChecked(); arguments_array->set(j, *arg); } i::Handle<i::JSArray> arguments_jsarray = factory->NewJSArrayWithElements(arguments_array); context->Global()->Set(String::NewFromUtf8(isolate, "arguments"), Utils::ToLocal(arguments_jsarray)); #endif // !V8_SHARED return handle_scope.Escape(context); } void Shell::Exit(int exit_code) { // Use _exit instead of exit to avoid races between isolate // threads and static destructors. fflush(stdout); fflush(stderr); _exit(exit_code); } #ifndef V8_SHARED struct CounterAndKey { Counter* counter; const char* key; }; inline bool operator<(const CounterAndKey& lhs, const CounterAndKey& rhs) { return strcmp(lhs.key, rhs.key) < 0; } #endif // !V8_SHARED void Shell::OnExit() { LineEditor* line_editor = LineEditor::Get(); if (line_editor) line_editor->Close(); #ifndef V8_SHARED if (i::FLAG_dump_counters) { int number_of_counters = 0; for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) { number_of_counters++; } CounterAndKey* counters = new CounterAndKey[number_of_counters]; int j = 0; for (CounterMap::Iterator i(counter_map_); i.More(); i.Next(), j++) { counters[j].counter = i.CurrentValue(); counters[j].key = i.CurrentKey(); } std::sort(counters, counters + number_of_counters); printf("+----------------------------------------------------------------+" "-------------+\n"); printf("| Name |" " Value |\n"); printf("+----------------------------------------------------------------+" "-------------+\n"); for (j = 0; j < number_of_counters; j++) { Counter* counter = counters[j].counter; const char* key = counters[j].key; if (counter->is_histogram()) { printf("| c:%-60s | %11i |\n", key, counter->count()); printf("| t:%-60s | %11i |\n", key, counter->sample_total()); } else { printf("| %-62s | %11i |\n", key, counter->count()); } } printf("+----------------------------------------------------------------+" "-------------+\n"); delete [] counters; } delete counters_file_; delete counter_map_; #endif // !V8_SHARED } static FILE* FOpen(const char* path, const char* mode) { #if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64)) FILE* result; if (fopen_s(&result, path, mode) == 0) { return result; } else { return NULL; } #else FILE* file = fopen(path, mode); if (file == NULL) return NULL; struct stat file_stat; if (fstat(fileno(file), &file_stat) != 0) return NULL; bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0); if (is_regular_file) return file; fclose(file); return NULL; #endif } static char* ReadChars(Isolate* isolate, const char* name, int* size_out) { FILE* file = FOpen(name, "rb"); if (file == NULL) return NULL; fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { int read = static_cast<int>(fread(&chars[i], 1, size - i, file)); i += read; } fclose(file); *size_out = size; return chars; } struct DataAndPersistent { uint8_t* data; Persistent<ArrayBuffer> handle; }; static void ReadBufferWeakCallback( const v8::WeakCallbackData<ArrayBuffer, DataAndPersistent>& data) { size_t byte_length = data.GetValue()->ByteLength(); data.GetIsolate()->AdjustAmountOfExternalAllocatedMemory( -static_cast<intptr_t>(byte_length)); delete[] data.GetParameter()->data; data.GetParameter()->handle.Reset(); delete data.GetParameter(); } void Shell::ReadBuffer(const v8::FunctionCallbackInfo<v8::Value>& args) { DCHECK(sizeof(char) == sizeof(uint8_t)); // NOLINT String::Utf8Value filename(args[0]); int length; if (*filename == NULL) { Throw(args.GetIsolate(), "Error loading file"); return; } Isolate* isolate = args.GetIsolate(); DataAndPersistent* data = new DataAndPersistent; data->data = reinterpret_cast<uint8_t*>( ReadChars(args.GetIsolate(), *filename, &length)); if (data->data == NULL) { delete data; Throw(args.GetIsolate(), "Error reading file"); return; } Handle<v8::ArrayBuffer> buffer = ArrayBuffer::New(isolate, data->data, length); data->handle.Reset(isolate, buffer); data->handle.SetWeak(data, ReadBufferWeakCallback); data->handle.MarkIndependent(); isolate->AdjustAmountOfExternalAllocatedMemory(length); args.GetReturnValue().Set(buffer); } // Reads a file into a v8 string. Handle<String> Shell::ReadFile(Isolate* isolate, const char* name) { int size = 0; char* chars = ReadChars(isolate, name, &size); if (chars == NULL) return Handle<String>(); Handle<String> result = String::NewFromUtf8(isolate, chars, String::kNormalString, size); delete[] chars; return result; } void Shell::RunShell(Isolate* isolate) { HandleScope outer_scope(isolate); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, evaluation_context_); v8::Context::Scope context_scope(context); PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate)); Handle<String> name = String::NewFromUtf8(isolate, "(d8)"); LineEditor* console = LineEditor::Get(); printf("V8 version %s [console: %s]\n", V8::GetVersion(), console->name()); console->Open(isolate); while (true) { HandleScope inner_scope(isolate); Handle<String> input = console->Prompt(Shell::kPrompt); if (input.IsEmpty()) break; ExecuteString(isolate, input, name, true, true); } printf("\n"); } SourceGroup::~SourceGroup() { #ifndef V8_SHARED delete thread_; thread_ = NULL; #endif // !V8_SHARED } void SourceGroup::Execute(Isolate* isolate) { bool exception_was_thrown = false; for (int i = begin_offset_; i < end_offset_; ++i) { const char* arg = argv_[i]; if (strcmp(arg, "-e") == 0 && i + 1 < end_offset_) { // Execute argument given to -e option directly. HandleScope handle_scope(isolate); Handle<String> file_name = String::NewFromUtf8(isolate, "unnamed"); Handle<String> source = String::NewFromUtf8(isolate, argv_[i + 1]); if (!Shell::ExecuteString(isolate, source, file_name, false, true)) { exception_was_thrown = true; break; } ++i; } else if (arg[0] == '-') { // Ignore other options. They have been parsed already. } else { // Use all other arguments as names of files to load and run. HandleScope handle_scope(isolate); Handle<String> file_name = String::NewFromUtf8(isolate, arg); Handle<String> source = ReadFile(isolate, arg); if (source.IsEmpty()) { printf("Error reading '%s'\n", arg); Shell::Exit(1); } if (!Shell::ExecuteString(isolate, source, file_name, false, true)) { exception_was_thrown = true; break; } } } if (exception_was_thrown != Shell::options.expected_to_throw) { Shell::Exit(1); } } Handle<String> SourceGroup::ReadFile(Isolate* isolate, const char* name) { int size; char* chars = ReadChars(isolate, name, &size); if (chars == NULL) return Handle<String>(); Handle<String> result = String::NewFromUtf8(isolate, chars, String::kNormalString, size); delete[] chars; return result; } #ifndef V8_SHARED base::Thread::Options SourceGroup::GetThreadOptions() { // On some systems (OSX 10.6) the stack size default is 0.5Mb or less // which is not enough to parse the big literal expressions used in tests. // The stack size should be at least StackGuard::kLimitSize + some // OS-specific padding for thread startup code. 2Mbytes seems to be enough. return base::Thread::Options("IsolateThread", 2 * MB); } void SourceGroup::ExecuteInThread() { Isolate* isolate = Isolate::New(); do { next_semaphore_.Wait(); { Isolate::Scope iscope(isolate); { HandleScope scope(isolate); PerIsolateData data(isolate); Local<Context> context = Shell::CreateEvaluationContext(isolate); { Context::Scope cscope(context); PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate)); Execute(isolate); } } if (Shell::options.send_idle_notification) { const int kLongIdlePauseInMs = 1000; isolate->ContextDisposedNotification(); isolate->IdleNotification(kLongIdlePauseInMs); } if (Shell::options.invoke_weak_callbacks) { // By sending a low memory notifications, we will try hard to collect // all garbage and will therefore also invoke all weak callbacks of // actually unreachable persistent handles. isolate->LowMemoryNotification(); } } done_semaphore_.Signal(); } while (!Shell::options.last_run); isolate->Dispose(); } void SourceGroup::StartExecuteInThread() { if (thread_ == NULL) { thread_ = new IsolateThread(this); thread_->Start(); } next_semaphore_.Signal(); } void SourceGroup::WaitForThread() { if (thread_ == NULL) return; if (Shell::options.last_run) { thread_->Join(); } else { done_semaphore_.Wait(); } } #endif // !V8_SHARED void SetFlagsFromString(const char* flags) { v8::V8::SetFlagsFromString(flags, static_cast<int>(strlen(flags))); } bool Shell::SetOptions(int argc, char* argv[]) { bool logfile_per_isolate = false; for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "--stress-opt") == 0) { options.stress_opt = true; argv[i] = NULL; } else if (strcmp(argv[i], "--nostress-opt") == 0) { options.stress_opt = false; argv[i] = NULL; } else if (strcmp(argv[i], "--stress-deopt") == 0) { options.stress_deopt = true; argv[i] = NULL; } else if (strcmp(argv[i], "--mock-arraybuffer-allocator") == 0) { options.mock_arraybuffer_allocator = true; argv[i] = NULL; } else if (strcmp(argv[i], "--noalways-opt") == 0) { // No support for stressing if we can't use --always-opt. options.stress_opt = false; options.stress_deopt = false; } else if (strcmp(argv[i], "--logfile-per-isolate") == 0) { logfile_per_isolate = true; argv[i] = NULL; } else if (strcmp(argv[i], "--shell") == 0) { options.interactive_shell = true; argv[i] = NULL; } else if (strcmp(argv[i], "--test") == 0) { options.test_shell = true; argv[i] = NULL; } else if (strcmp(argv[i], "--send-idle-notification") == 0) { options.send_idle_notification = true; argv[i] = NULL; } else if (strcmp(argv[i], "--invoke-weak-callbacks") == 0) { options.invoke_weak_callbacks = true; // TODO(jochen) See issue 3351 options.send_idle_notification = true; argv[i] = NULL; } else if (strcmp(argv[i], "-f") == 0) { // Ignore any -f flags for compatibility with other stand-alone // JavaScript engines. continue; } else if (strcmp(argv[i], "--isolate") == 0) { #ifdef V8_SHARED printf("D8 with shared library does not support multi-threading\n"); return false; #endif // V8_SHARED options.num_isolates++; } else if (strcmp(argv[i], "--dump-heap-constants") == 0) { #ifdef V8_SHARED printf("D8 with shared library does not support constant dumping\n"); return false; #else options.dump_heap_constants = true; argv[i] = NULL; #endif // V8_SHARED } else if (strcmp(argv[i], "--throws") == 0) { options.expected_to_throw = true; argv[i] = NULL; } else if (strncmp(argv[i], "--icu-data-file=", 16) == 0) { options.icu_data_file = argv[i] + 16; argv[i] = NULL; #ifdef V8_SHARED } else if (strcmp(argv[i], "--dump-counters") == 0) { printf("D8 with shared library does not include counters\n"); return false; } else if (strcmp(argv[i], "--debugger") == 0) { printf("Javascript debugger not included\n"); return false; #endif // V8_SHARED #ifdef V8_USE_EXTERNAL_STARTUP_DATA } else if (strncmp(argv[i], "--natives_blob=", 15) == 0) { options.natives_blob = argv[i] + 15; argv[i] = NULL; } else if (strncmp(argv[i], "--snapshot_blob=", 16) == 0) { options.snapshot_blob = argv[i] + 16; argv[i] = NULL; #endif // V8_USE_EXTERNAL_STARTUP_DATA } else if (strcmp(argv[i], "--cache") == 0 || strncmp(argv[i], "--cache=", 8) == 0) { const char* value = argv[i] + 7; if (!*value || strncmp(value, "=code", 6) == 0) { options.compile_options = v8::ScriptCompiler::kProduceCodeCache; } else if (strncmp(value, "=parse", 7) == 0) { options.compile_options = v8::ScriptCompiler::kProduceParserCache; } else if (strncmp(value, "=none", 6) == 0) { options.compile_options = v8::ScriptCompiler::kNoCompileOptions; } else { printf("Unknown option to --cache.\n"); return false; } argv[i] = NULL; } } v8::V8::SetFlagsFromCommandLine(&argc, argv, true); // Set up isolated source groups. options.isolate_sources = new SourceGroup[options.num_isolates]; SourceGroup* current = options.isolate_sources; current->Begin(argv, 1); for (int i = 1; i < argc; i++) { const char* str = argv[i]; if (strcmp(str, "--isolate") == 0) { current->End(i); current++; current->Begin(argv, i + 1); } else if (strncmp(argv[i], "--", 2) == 0) { printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]); } } current->End(argc); if (!logfile_per_isolate && options.num_isolates) { SetFlagsFromString("--nologfile_per_isolate"); } return true; } int Shell::RunMain(Isolate* isolate, int argc, char* argv[]) { #ifndef V8_SHARED for (int i = 1; i < options.num_isolates; ++i) { options.isolate_sources[i].StartExecuteInThread(); } #endif // !V8_SHARED { HandleScope scope(isolate); Local<Context> context = CreateEvaluationContext(isolate); if (options.last_run && options.use_interactive_shell()) { // Keep using the same context in the interactive shell. evaluation_context_.Reset(isolate, context); #ifndef V8_SHARED // If the interactive debugger is enabled make sure to activate // it before running the files passed on the command line. if (i::FLAG_debugger) { InstallUtilityScript(isolate); } #endif // !V8_SHARED } { Context::Scope cscope(context); PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate)); options.isolate_sources[0].Execute(isolate); } } if (options.send_idle_notification) { const int kLongIdlePauseInMs = 1000; isolate->ContextDisposedNotification(); isolate->IdleNotification(kLongIdlePauseInMs); } if (options.invoke_weak_callbacks) { // By sending a low memory notifications, we will try hard to collect all // garbage and will therefore also invoke all weak callbacks of actually // unreachable persistent handles. isolate->LowMemoryNotification(); } #ifndef V8_SHARED for (int i = 1; i < options.num_isolates; ++i) { options.isolate_sources[i].WaitForThread(); } #endif // !V8_SHARED return 0; } #ifndef V8_SHARED static void DumpHeapConstants(i::Isolate* isolate) { i::Heap* heap = isolate->heap(); // Dump the INSTANCE_TYPES table to the console. printf("# List of known V8 instance types.\n"); #define DUMP_TYPE(T) printf(" %d: \"%s\",\n", i::T, #T); printf("INSTANCE_TYPES = {\n"); INSTANCE_TYPE_LIST(DUMP_TYPE) printf("}\n"); #undef DUMP_TYPE // Dump the KNOWN_MAP table to the console. printf("\n# List of known V8 maps.\n"); #define ROOT_LIST_CASE(type, name, camel_name) \ if (n == NULL && o == heap->name()) n = #camel_name; #define STRUCT_LIST_CASE(upper_name, camel_name, name) \ if (n == NULL && o == heap->name##_map()) n = #camel_name "Map"; i::HeapObjectIterator it(heap->map_space()); printf("KNOWN_MAPS = {\n"); for (i::Object* o = it.Next(); o != NULL; o = it.Next()) { i::Map* m = i::Map::cast(o); const char* n = NULL; intptr_t p = reinterpret_cast<intptr_t>(m) & 0xfffff; int t = m->instance_type(); ROOT_LIST(ROOT_LIST_CASE) STRUCT_LIST(STRUCT_LIST_CASE) if (n == NULL) continue; printf(" 0x%05" V8PRIxPTR ": (%d, \"%s\"),\n", p, t, n); } printf("}\n"); #undef STRUCT_LIST_CASE #undef ROOT_LIST_CASE // Dump the KNOWN_OBJECTS table to the console. printf("\n# List of known V8 objects.\n"); #define ROOT_LIST_CASE(type, name, camel_name) \ if (n == NULL && o == heap->name()) n = #camel_name; i::OldSpaces spit(heap); printf("KNOWN_OBJECTS = {\n"); for (i::PagedSpace* s = spit.next(); s != NULL; s = spit.next()) { i::HeapObjectIterator it(s); const char* sname = AllocationSpaceName(s->identity()); for (i::Object* o = it.Next(); o != NULL; o = it.Next()) { const char* n = NULL; intptr_t p = reinterpret_cast<intptr_t>(o) & 0xfffff; ROOT_LIST(ROOT_LIST_CASE) if (n == NULL) continue; printf(" (\"%s\", 0x%05" V8PRIxPTR "): \"%s\",\n", sname, p, n); } } printf("}\n"); #undef ROOT_LIST_CASE } #endif // !V8_SHARED class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator { public: virtual void* Allocate(size_t length) { void* data = AllocateUninitialized(length); return data == NULL ? data : memset(data, 0, length); } virtual void* AllocateUninitialized(size_t length) { return malloc(length); } virtual void Free(void* data, size_t) { free(data); } }; class MockArrayBufferAllocator : public v8::ArrayBuffer::Allocator { public: virtual void* Allocate(size_t) OVERRIDE { return malloc(0); } virtual void* AllocateUninitialized(size_t length) OVERRIDE { return malloc(0); } virtual void Free(void* p, size_t) OVERRIDE { free(p); } }; #ifdef V8_USE_EXTERNAL_STARTUP_DATA class StartupDataHandler { public: StartupDataHandler(const char* natives_blob, const char* snapshot_blob) { Load(natives_blob, &natives_, v8::V8::SetNativesDataBlob); Load(snapshot_blob, &snapshot_, v8::V8::SetSnapshotDataBlob); } ~StartupDataHandler() { delete[] natives_.data; delete[] snapshot_.data; } private: void Load(const char* blob_file, v8::StartupData* startup_data, void (*setter_fn)(v8::StartupData*)) { startup_data->data = NULL; startup_data->compressed_size = 0; startup_data->raw_size = 0; if (!blob_file) return; FILE* file = fopen(blob_file, "rb"); if (!file) return; fseek(file, 0, SEEK_END); startup_data->raw_size = ftell(file); rewind(file); startup_data->data = new char[startup_data->raw_size]; startup_data->compressed_size = fread( const_cast<char*>(startup_data->data), 1, startup_data->raw_size, file); fclose(file); if (startup_data->raw_size == startup_data->compressed_size) (*setter_fn)(startup_data); } v8::StartupData natives_; v8::StartupData snapshot_; // Disallow copy & assign. StartupDataHandler(const StartupDataHandler& other); void operator=(const StartupDataHandler& other); }; #endif // V8_USE_EXTERNAL_STARTUP_DATA int Shell::Main(int argc, char* argv[]) { #if (defined(_WIN32) || defined(_WIN64)) UINT new_flags = SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX; UINT existing_flags = SetErrorMode(new_flags); SetErrorMode(existing_flags | new_flags); #if defined(_MSC_VER) _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _set_error_mode(_OUT_TO_STDERR); #endif // defined(_MSC_VER) #endif // defined(_WIN32) || defined(_WIN64) if (!SetOptions(argc, argv)) return 1; v8::V8::InitializeICU(options.icu_data_file); v8::Platform* platform = v8::platform::CreateDefaultPlatform(); v8::V8::InitializePlatform(platform); v8::V8::Initialize(); #ifdef V8_USE_EXTERNAL_STARTUP_DATA StartupDataHandler startup_data(options.natives_blob, options.snapshot_blob); #endif SetFlagsFromString("--trace-hydrogen-file=hydrogen.cfg"); SetFlagsFromString("--redirect-code-traces-to=code.asm"); ShellArrayBufferAllocator array_buffer_allocator; MockArrayBufferAllocator mock_arraybuffer_allocator; if (options.mock_arraybuffer_allocator) { v8::V8::SetArrayBufferAllocator(&mock_arraybuffer_allocator); } else { v8::V8::SetArrayBufferAllocator(&array_buffer_allocator); } int result = 0; Isolate::CreateParams create_params; #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE) if (i::FLAG_gdbjit) { create_params.code_event_handler = i::GDBJITInterface::EventHandler; } #endif #ifdef ENABLE_VTUNE_JIT_INTERFACE vTune::InitializeVtuneForV8(create_params); #endif #ifndef V8_SHARED create_params.constraints.ConfigureDefaults( base::SysInfo::AmountOfPhysicalMemory(), base::SysInfo::AmountOfVirtualMemory(), base::SysInfo::NumberOfProcessors()); #endif Isolate* isolate = Isolate::New(create_params); DumbLineEditor dumb_line_editor(isolate); { Isolate::Scope scope(isolate); Initialize(isolate); PerIsolateData data(isolate); InitializeDebugger(isolate); #ifndef V8_SHARED if (options.dump_heap_constants) { DumpHeapConstants(reinterpret_cast<i::Isolate*>(isolate)); return 0; } #endif if (options.stress_opt || options.stress_deopt) { Testing::SetStressRunType(options.stress_opt ? Testing::kStressTypeOpt : Testing::kStressTypeDeopt); int stress_runs = Testing::GetStressRuns(); for (int i = 0; i < stress_runs && result == 0; i++) { printf("============ Stress %d/%d ============\n", i + 1, stress_runs); Testing::PrepareStressRun(i); options.last_run = (i == stress_runs - 1); result = RunMain(isolate, argc, argv); } printf("======== Full Deoptimization =======\n"); Testing::DeoptimizeAll(); #if !defined(V8_SHARED) } else if (i::FLAG_stress_runs > 0) { int stress_runs = i::FLAG_stress_runs; for (int i = 0; i < stress_runs && result == 0; i++) { printf("============ Run %d/%d ============\n", i + 1, stress_runs); options.last_run = (i == stress_runs - 1); result = RunMain(isolate, argc, argv); } #endif } else { result = RunMain(isolate, argc, argv); } // Run interactive shell if explicitly requested or if no script has been // executed, but never on --test if (options.use_interactive_shell()) { #ifndef V8_SHARED if (!i::FLAG_debugger) { InstallUtilityScript(isolate); } #endif // !V8_SHARED RunShell(isolate); } } #ifndef V8_SHARED // Dump basic block profiling data. if (i::BasicBlockProfiler* profiler = reinterpret_cast<i::Isolate*>(isolate)->basic_block_profiler()) { i::OFStream os(stdout); os << *profiler; } #endif // !V8_SHARED isolate->Dispose(); V8::Dispose(); V8::ShutdownPlatform(); delete platform; OnExit(); return result; } } // namespace v8 #ifndef GOOGLE3 int main(int argc, char* argv[]) { return v8::Shell::Main(argc, argv); } #endif
tempbottle/v8.rs
src/d8.cc
C++
isc
56,683
var http = require('http'); var util = require('util'); module.exports.createServer = createServer; module.exports.Server = Server; module.exports.install = install; function createServer(listener) { var server = http.createServer.apply(http, arguments); return install(server); } function Server() { http.Server.apply(this, arguments); install(this); } util.inherits(Server, http.Server); function install(server) { var conns = new Map([]); server.on('connection', function (conn) { conns.set(conn, null); conn.on('close', function () { conns.delete(conn); }); }); server.on('request', function (req, res) { var conn = req.connection; conns.set(conn, res); res.on('finish', function () { conns.set(conn, null); }); }); server.gracefulClose = function (done) { conns.forEach(function (res, conn) { if (res !== null && !res.headersSent) { debug('sending response with "Connection: close"'); res.setHeader('Connection', 'close'); } else if (res !== null) { res.on('finish', function () { setIdleTimeout(server, conn); }); } else { setIdleTimeout(server, conn); } }); return server.close.apply(server, arguments); }; debug('graceful-http-server installed'); return server; } function setIdleTimeout(server, conn) { var onTimeout = function () { debug('closing connection'); conn.destroy(); server.removeListener('request', onRequest); }; conn.setTimeout(400, onTimeout); var onRequest = function (req, res) { if (conn === req.connection) { debug('sending response with "Connection: close"'); res.setHeader('Connection', 'close'); conn.removeListener('timeout', onTimeout); server.removeListener('request', onRequest); } }; server.on('request', onRequest); } function debug(message) { // console.log.apply(console, arguments); }
AtsushiSuzuki/http-graceful-close
index.js
JavaScript
isc
2,024
const {createServer} = require('http') const {readFileSync} = require('fs') const template = readFileSync(__dirname + '/index.html') createServer((req, res) => { if (req.url === '/favicon.ico') { res.writeHead(404) res.end() } else if (req.headers.referer && req.url !== '/') { res.writeHead(302, { 'Location': 'ob:/' + req.url.replace('ob://', '') }) res.end() } else { res.end(template) } }).listen(8888)
overra/oblink
index.js
JavaScript
isc
447
require 'spec_helper' require 'time' describe Server do before(:each) do end it "should create a new instance given valid attributes" do s = Factory.build(:server) s.valid?.should be true end it "should not be valid when no hostname is given" do s = Factory.build(:server) s.hostname = nil s.valid?.should be false end it "should not be valid when no interval is given" do s = Factory.build(:server) s.interval_hours = nil s.valid?.should be false end it "should not be valid when no ssh_port is given" do s = Factory.build(:server) s.ssh_port = nil s.valid?.should be false end it "should not be valid when no keep_snapshots is given" do s = Factory.build(:server) s.keep_snapshots = nil s.valid?.should be false end it "should not accept impossible hours" do s = Factory.build(:server) s.window_start = 25 s.valid?.should be false s.window_start = 1 s.window_stop = 25 s.valid?.should be false s.window_stop = 2 s.valid?.should be true end it "should be valid when the other attributes are not given" do s = Factory.build(:server) s.connect_to = nil s.enabled = nil s.backup_server_id = nil s.valid?.should be true end it "should provide a instance method to determine valid backup servers" do s1 = Factory.build(:server, :connect_to => '127.0.0.1') s2 = Factory.build(:server) s2.connect_to = nil BackupServer.should_receive(:available_for).with(s1.connect_to) BackupServer.should_receive(:available_for).with(s2.hostname) s1.possible_backup_servers s2.possible_backup_servers end it "should provide a to_s method" do s = Factory.build(:server) s.to_s.should == s.hostname end it "should know if a backup is running" do server = Factory.build(:server) job = Factory(:backup_job, :server => server, :status => 'running', :finished => false) server.backup_running?.should be true end it "should know when a backup is already queued" do server = Factory.build(:server) job = Factory(:backup_job, :server => server, :status => 'queued') server.backup_running?.should be true end it "should not mark a backup as running when the status is not queued or running" do server = Factory.build(:server) job = Factory(:backup_job, :server => server, :status => 'OK', :finished => true) server.backup_running?.should be false end it "knows no backup is running when there are 0 backup jobs" do server = Factory.build(:server) server.backup_jobs.size.should == 0 server.backup_running?.should be false end it "should always be in the backup window when no start and end is given" do server = Factory.build(:server) server.window_start = nil server.window_stop = nil server.in_backup_window?.should be true end it "should know when it's not in the window" do server_one_hour_window = Factory.build(:server) server_one_hour_window.window_start = 1 server_one_hour_window.window_stop = 2 Time.should_receive(:new).and_return(Time.parse("03:00")) server_one_hour_window.in_backup_window?.should be false server_23_hour_window = Factory.build(:server) server_23_hour_window.window_start = 0 server_23_hour_window.window_stop = 23 Time.should_receive(:new).and_return(Time.parse("23:30")) server_23_hour_window.in_backup_window?.should be false end it "should know when it's in the window" do server = Factory.build(:server) server.window_start = 1 server.window_stop = 2 Time.should_receive(:new).and_return(Time.parse("01:30")) server.in_backup_window?.should be true server.window_start = 0 server.window_stop = 1 Time.should_receive(:new).and_return(Time.parse("00:30")) server.in_backup_window?.should be true server.window_start = 23 server.window_stop = 0 Time.should_receive(:new).and_return(Time.parse("23:30")) server.in_backup_window?.should be true end it "should handle windows that cross midnight" do server = Factory(:server) server.window_start = 22 server.window_stop = 2 next_day = Time.new.tomorrow parsed_when = Time.parse("#{next_day.strftime('%Y-%m-%d')} 01:00") Time.should_receive(:new).and_return(parsed_when) server.in_backup_window?.should be true end it "should know when its past the interval" do s = Factory.build(:server, :interval_hours => 1) j = Factory(:backup_job, :created_at => (Time.new - 3601), :server => s) s.interval_passed?.should be true s.interval_hours = 3 s.interval_passed?.should be false end it "should not backup when backups are not enabled" do s = Factory.build(:server, :enabled => false) s.should_backup?.should be false end it "should not backup when there is no backup server configured" do s = Factory.build(:server, :backup_server => nil) s.should_backup?.should be false end it "should not backup when a backup is already running" do s = Factory.build(:server) s.stub(:backup_running?).and_return true s.should_backup?.should be false end it "should not backup when its outside of the window" do s = Factory.build(:server) s.stub(:in_backup_window?).and_return false s.should_backup?.should be false end it "should not backup when the interval didnt pass" do s = Factory.build(:server) s.stub(:interval_passed?).and_return false s.should_backup?.should be false end it "should know when to backup" do s = Factory.build(:server) s.stub(:backup_running?).and_return false s.stub(:in_backup_window?).and_return true s.stub(:interval_passed?).and_return true s.should_backup?.should be true end it "should know the excludes inherited trough the profiles" do s = Factory.build(:server) # we need one server p1 = Factory.build(:profile, :name => 'linux') # profile one p2 = Factory.build(:profile, :name => 'standard') # and another one p1.excludes << Factory.build(:exclude, :path => '/') # exclude one p2.excludes << Factory.build(:exclude, :path => '/var/log') # second exclude s.profiles << p1 s.profiles << p2 s.excludes.size.should == 2 end it "should know the includes inherited trough the profiles" do s = Factory.build(:server) # we need one server p1 = Factory.build(:profile, :name => 'linux') # profile one p2 = Factory.build(:profile, :name => 'standard') # and another one p1.includes << Factory.build(:include, :path => '/') # include one p2.includes << Factory.build(:include, :path => '/var/log') # second include s.profiles << p1 s.profiles << p2 s.includes.size.should == 2 end it "should compile the list of excludes to valid rsync args" do s = Factory.build(:server) # we need one server p1 = Factory.build(:profile, :name => 'linux') # profile one p2 = Factory.build(:profile, :name => 'standard') # and another one p1.excludes << Factory.build(:exclude, :path => '/') # include one p2.excludes << Factory.build(:exclude, :path => '/var/log') # second include s.profiles << p1 s.profiles << p2 s.rsync_excludes.should == '--exclude=/ --exclude=/var/log' end it "should compile the list of includes to valid rsync args" do s = Factory.build(:server) # we need one server p1 = Factory.build(:profile, :name => 'linux') # profile one p2 = Factory.build(:profile, :name => 'standard') # and another one p1.includes << Factory.build(:include, :path => '/') # include one p2.includes << Factory.build(:include, :path => '/var/log') # second include s.profiles << p1 s.profiles << p2 s.rsync_includes.should == '--include=/ --include=/var/log' end it "should compile a list of splits in order to protect them" do s = Factory.build(:server) p1 = Factory.build(:profile, :name => 'linux') p2 = Factory.build(:profile, :name => 'standard') p1.splits << Factory.build(:split, :path => '/var/spool/mqueue') p2.splits << Factory.build(:split, :path => '/home') s.profiles << p1 s.profiles << p2 s.rsync_protects.should == "--filter='protect /var/spool/mqueue' --filter='protect /home'" end it "should compile a list of splits in order to exclude them" do s = Factory.build(:server) p1 = Factory.build(:profile, :name => 'linux') p2 = Factory.build(:profile, :name => 'standard') p1.splits << Factory.build(:split, :path => '/var/spool/mqueue') p2.splits << Factory.build(:split, :path => '/home') s.profiles << p1 s.profiles << p2 s.rsync_split_excludes.should == '--exclude=/var/spool/mqueue --exclude=/home' end it "should turn the snapshots property into a array" do s = Factory(:server, :snapshots => '1234,5678,90') s.current_snapshots.size.should == 3 s.current_snapshots[0].should == '1234' s.current_snapshots[2].should == '90' end it "should queue a backup when queue_backup is called" do s = Factory(:server) s.backup_jobs.size.should == 0 s.queue_backup s.backup_jobs.size.should == 1 s.backup_jobs.last.status.should == 'queued' end it "scheduling should not crash on servers in remove only mode" do s = Factory(:server, :remove_only => true, :keep_snapshots => 0) s.last_started.should be_nil end it "should cleanup old backupjobs" do pending "Not sure what behaviour is prefered now" server = Factory.create(:server, :keep_snapshots => 5) 6.times do Factory.create(:backup_job, :backup_server => server.backup_server, :server => server, :status => 'OK') end job = server.backup_jobs.last server.backup_jobs.size.should == 6 server.cleanup_old_jobs server.backup_jobs.size.should == 5 end it "should have a method that gets or creates an exclusive profile" do server = Factory(:server) p1 = Factory(:profile) server.profiles << p1 server.profiles.count.should == 1 p2 = server.exclusive_profile p2.exclusive.should == true server.profiles.length.should == 2 p2.save p3 = server.exclusive_profile p3.should === p2 end end
Wijnand/retcon-web
spec/models/server_spec.rb
Ruby
isc
10,201
require 'sidewalk/controller_mixins/view_templates' require 'sidewalk/app_uri' class IndexController < Sidewalk::Controller # If this was a real app, you'd probably do this include in your # ApplicationController or similar: # Look for views/foo.bar, render it with BarHandler. include Sidewalk::ControllerMixins::ViewTemplates # Actually return some content def response @links = { 'Hello, world' => Sidewalk::AppUri.new('/hello'), } render end end
fredemmott/sidewalk
examples/controllers/index_controller.rb
Ruby
isc
484
'use strict'; const XmlNode = require('./XmlNode'); /** A processing instruction within an XML document. @public */ class XmlProcessingInstruction extends XmlNode { /** @param {string} name @param {string} [content] */ constructor(name, content = '') { super(); /** Name of this processing instruction. Also sometimes referred to as the processing instruction "target". @type {string} @public */ this.name = name; /** Content of this processing instruction. @type {string} @public */ this.content = content; } get type() { return XmlNode.TYPE_PROCESSING_INSTRUCTION; } toJSON() { return Object.assign(XmlNode.prototype.toJSON.call(this), { name: this.name, content: this.content, }); } } module.exports = XmlProcessingInstruction;
rgrove/parse-xml
src/lib/XmlProcessingInstruction.js
JavaScript
isc
841
package minecraft_test import ( "fmt" "vimagination.zapto.org/minecraft" ) func Example() { path := minecraft.NewMemPath() level, _ := minecraft.NewLevel(path) level.LevelName("TestMine") name := level.GetLevelName() fmt.Println(name) // Output: // TestMine }
MJKWoolnough/minecraft
example_test.go
GO
isc
272
package com.computing.cloud.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.computing.cloud.dao.InstanceRepository; import com.computing.cloud.domain.Instance; import com.computing.cloud.service.InstanceService; @Service @Transactional public class InstanceServiceImpl implements InstanceService { @Autowired private InstanceRepository instanceRepository; @Override public Instance findById(Long id) { return instanceRepository.findOne(id); } @Override public List<Instance> findAll() { return (List<Instance>) instanceRepository.findAll(); } }
ralphavalon/cloud-computing-instance-management
src/main/java/com/computing/cloud/service/impl/InstanceServiceImpl.java
Java
mit
741
import auth from './authReducer' export { auth }
nattatorn-dev/expo-with-realworld
modules/Auth/reducers/index.js
JavaScript
mit
50
/*********************************************************** * Credits: * * Created By: Joe Mayo, 8/26/08 * *********************************************************/ using System; using System.Collections.Generic; using System.Globalization; using System.Text.Json; using System.Xml.Serialization; using LinqToTwitter.Common; namespace LinqToTwitter { /// <summary> /// information for a twitter user /// </summary> [XmlType(Namespace = "LinqToTwitter")] public class User { public User() {} public User(JsonElement user) { if (user.IsNull()) return; BannerSizes = new List<BannerSize>(); Categories = new List<Category>(); UserIDResponse = user.GetUlong("id").ToString(CultureInfo.InvariantCulture); ScreenNameResponse = user.GetString("screen_name"); Name = user.GetString("name"); Location = user.GetString("location"); Description = user.GetString("description"); ProfileImageUrl = user.GetString("profile_image_url"); ProfileImageUrlHttps = user.GetString("profile_image_url_https"); Url = user.GetString("url"); user.TryGetProperty("entities", out JsonElement entitiesValue); Entities = new UserEntities(entitiesValue); Protected = user.GetBool("protected"); ProfileUseBackgroundImage = user.GetBool("profile_use_background_image"); IsTranslator = user.GetBool("is_translator"); FollowersCount = user.GetInt("followers_count"); DefaultProfile = user.GetBool("default_profile"); ProfileBackgroundColor = user.GetString("profile_background_color"); LangResponse = user.GetString("lang"); ProfileTextColor = user.GetString("profile_text_color"); ProfileLinkColor = user.GetString("profile_link_color"); ProfileSidebarFillColor = user.GetString("profile_sidebar_fill_color"); ProfileSidebarBorderColor = user.GetString("profile_sidebar_border_color"); FriendsCount = user.GetInt("friends_count"); DefaultProfileImage = user.GetBool("default_profile_image"); CreatedAt = (user.GetString("created_at") ?? string.Empty).GetDate(DateTime.MinValue); FavoritesCount = user.GetInt("favourites_count"); UtcOffset = user.GetInt("utc_offset"); TimeZone = user.GetString("time_zone"); ProfileBackgroundImageUrl = user.GetString("profile_background_image_url"); ProfileBackgroundImageUrlHttps = user.GetString("profile_background_image_url_https"); ProfileBackgroundTile = user.GetBool("profile_background_tile"); ProfileBannerUrl = user.GetString("profile_banner_url"); StatusesCount = user.GetInt("statuses_count"); Notifications = user.GetBool("notifications"); GeoEnabled = user.GetBool("geo_enabled"); Verified = user.GetBool("verified"); ContributorsEnabled = user.GetBool("contributors_enabled"); Following = user.GetBool("following"); ShowAllInlineMedia = user.GetBool("show_all_inline_media"); ListedCount = user.GetInt("listed_count"); FollowRequestSent = user.GetBool("follow_request_sent"); user.TryGetProperty("status", out JsonElement statusElement); Status = new Status(statusElement); CursorMovement = new Cursors(user); Email = user.GetString("email"); } /// <summary> /// type of user request (i.e. Friends, Followers, or Show) /// </summary> public UserType? Type { get; set; } /// <summary> /// Query User ID /// </summary> public ulong UserID { get; set; } /// <summary> /// Comma-separated list of user IDs (e.g. for Lookup query) /// </summary> public string? UserIdList { get; set; } /// <summary> /// Query screen name /// </summary> public string? ScreenName { get; set; } /// <summary> /// Comma-separated list of screen names (e.g. for Lookup queries) /// </summary> public string? ScreenNameList { get; set; } /// <summary> /// Number of users to return for each page /// </summary> public int Count { get; set; } /// <summary> /// Indicator for which page to get next /// </summary> /// <remarks> /// This is not a page number, but is an indicator to /// Twitter on which page you need back. Your choices /// are Previous and Next, which you can find in the /// CursorResponse property when your response comes back. /// </remarks> public long Cursor { get; set; } /// <summary> /// Used to identify suggested users category /// </summary> public string? Slug { get; set; } /// <summary> /// Query for User Search /// </summary> public string? Query { get; set; } /// <summary> /// Add entities to results (default: true) /// </summary> public bool IncludeEntities { get; set; } /// <summary> /// Remove status from results /// </summary> public bool SkipStatus { get; set; } /// <summary> /// Query User ID /// </summary> public string? UserIDResponse { get; set; } /// <summary> /// Query screen name /// </summary> public string? ScreenNameResponse { get; set; } /// <summary> /// Size for UserProfileImage query /// </summary> public ProfileImageSize? ImageSize { get; set; } /// <summary> /// Set to TweetMode.Extended to receive 280 characters in Status.FullText property /// </summary> public TweetMode? TweetMode { get; set; } /// <summary> /// Contains Next and Previous cursors /// </summary> /// <remarks> /// This is read-only and returned with the response /// from Twitter. You use it by setting Cursor on the /// next request to indicate that you want to move to /// either the next or previous page. /// </remarks> [XmlIgnore] public Cursors? CursorMovement { get; internal set; } /// <summary> /// name of user /// </summary> public string? Name { get; set; } /// <summary> /// location of user /// </summary> public string? Location { get; set; } /// <summary> /// user's description /// </summary> public string? Description { get; set; } /// <summary> /// user's image /// </summary> public string? ProfileImageUrl { get; set; } /// <summary> /// user's image for use on HTTPS secured pages /// </summary> public string? ProfileImageUrlHttps { get; set; } /// <summary> /// user's image is a defaulted placeholder /// </summary> public bool DefaultProfileImage{ get; set; } /// <summary> /// user's URL /// </summary> public string? Url { get; set; } /// <summary> /// Entities connected to the <see cref="User"/> /// </summary> public UserEntities? Entities { get; set; } /// <summary> /// user's profile has not been configured (is just defaults) /// </summary> public bool DefaultProfile { get; set; } /// <summary> /// is user protected /// </summary> public bool Protected { get; set; } /// <summary> /// number of people following user /// </summary> public int FollowersCount { get; set; } /// <summary> /// color of profile background /// </summary> public string? ProfileBackgroundColor { get; set; } /// <summary> /// color of profile text /// </summary> public string? ProfileTextColor { get; set; } /// <summary> /// color of profile links /// </summary> public string? ProfileLinkColor { get; set; } /// <summary> /// color of profile sidebar /// </summary> public string? ProfileSidebarFillColor { get; set; } /// <summary> /// color of profile sidebar border /// </summary> public string? ProfileSidebarBorderColor { get; set; } /// <summary> /// number of friends /// </summary> public int FriendsCount { get; set; } /// <summary> /// date and time when profile was created /// </summary> public DateTime CreatedAt { get; set; } /// <summary> /// number of favorites /// </summary> public int FavoritesCount { get; set; } /// <summary> /// UTC Offset /// </summary> public int UtcOffset { get; set; } /// <summary> /// Time Zone /// </summary> public string? TimeZone { get; set; } /// <summary> /// URL of profile background image /// </summary> public string? ProfileBackgroundImageUrl { get; set; } /// <summary> /// URL of profile background image for use on HTTPS secured pages /// </summary> public string? ProfileBackgroundImageUrlHttps { get; set; } /// <summary> /// Title of profile background /// </summary> public bool ProfileBackgroundTile { get; set; } /// <summary> /// Should we use the profile background image? /// </summary> public bool ProfileUseBackgroundImage { get; set; } /// <summary> /// number of status updates user has made /// </summary> public int StatusesCount { get; set; } /// <summary> /// type of device notifications /// </summary> public bool Notifications { get; set; } /// <summary> /// Supports Geo Tracking /// </summary> public bool GeoEnabled { get; set; } /// <summary> /// Is a verified account /// </summary> public bool Verified { get; set; } /// <summary> /// Is contributors enabled on account? /// </summary> public bool ContributorsEnabled { get; set; } /// <summary> /// Is this a translator? /// </summary> public bool IsTranslator { get; set; } /// <summary> /// is authenticated user following this user /// </summary> public bool Following { get; set; } /// <summary> /// current user status (valid only in user queries) /// </summary> public Status? Status { get; set; } /// <summary> /// User categories for Twitter Suggested Users /// </summary> public List<Category>? Categories { get; set; } /// <summary> /// Input param for Category queries /// </summary> public string? Lang { get; set; } /// <summary> /// Return results for specified language /// Note: Twitter only supports a limited number of languages, /// which include en, fr, de, es, it when this feature was added. /// </summary> public string? LangResponse { get; set; } /// <summary> /// Indicates if user has inline media enabled /// </summary> public bool ShowAllInlineMedia { get; set; } /// <summary> /// Number of lists user is a member of /// </summary> public int ListedCount { get; set; } /// <summary> /// If authenticated user has requested to follow this use /// </summary> public bool FollowRequestSent { get; set; } /// <summary> /// Response from ProfileImage query /// </summary> public string? ProfileImage { get; set; } /// <summary> /// Url of Profile Banner image. /// </summary> public string? ProfileBannerUrl { get; set; } /// <summary> /// Available sizes to use in account banners. /// </summary> public List<BannerSize>? BannerSizes { get; set; } /// <summary> /// User's email-address (null if not filled in on app is /// lacking whitelisting) /// </summary> public string? Email { get; set; } } }
JoeMayo/LinqToTwitter
src/LinqToTwitter6/LinqToTwitter/User/User.cs
C#
mit
12,718