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
package de.justsoftware.toolbox.testng; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; /** * Utility for {@link org.testng.annotations.DataProvider}s. * * @author Jan Burkhardt (initial creation) */ public final class DataProviders { private DataProviders() { super(); } private abstract static class DataProviderIterator<T> implements Iterator<Object[]> { private final Iterator<? extends T> _iterator; private DataProviderIterator(@Nonnull final Iterator<? extends T> iterator) { _iterator = iterator; } @Override public final boolean hasNext() { return _iterator.hasNext(); } @Override public final Object[] next() { return next(_iterator.next()); } @Nonnull protected abstract Object[] next(@Nullable T next); @Override public final void remove() { throw new UnsupportedOperationException(); } } @Nonnull public static Iterator<Object[]> provideIterator(@Nonnull final Iterator<?> iterator) { return new DataProviderIterator<Object>(iterator) { @Override protected Object[] next(final Object next) { return new Object[] { next }; } }; } @Nonnull public static Iterator<Object[]> provideIterable(@Nonnull final Iterable<?> iterable) { return provideIterator(iterable.iterator()); } @Nonnull public static <T> Iterator<Object[]> provideArray(@Nonnull final T[] objects) { return provideIterator(Iterators.forArray(objects)); } @Nonnull public static Iterator<Object[]> provideVarargs(@Nonnull final Object... objects) { return provideArray(objects); } @Nonnull public static <T extends Entry<?, ?>> Iterator<Object[]> provideEntryIterator(@Nonnull final Iterator<T> iterator) { return new DataProviderIterator<T>(iterator) { @Override protected Object[] next(final T next) { if (next == null) { return new Object[] { null, null }; } return new Object[] { next.getKey(), next.getValue() }; } }; } @Nonnull public static Iterator<Object[]> provideEntrySet(@Nonnull final Iterable<? extends Entry<?, ?>> iterable) { return provideEntryIterator(iterable.iterator()); } @Nonnull public static Iterator<Object[]> provideMap(@Nonnull final Map<?, ?> map) { return provideEntrySet(map.entrySet()); } /** * produces a cartesian product of the provided sets, see {@link Sets#cartesianProduct#cartesianProduct} for * more info */ @Nonnull public static Iterator<Object[]> cartesianProduct(@Nonnull final Set<?>... sets) { return FluentIterable.from(Sets.cartesianProduct(sets)).transform(List::toArray).iterator(); } }
bjrke/just-java-toolbox
just-java-test-toolbox/src/main/java/de/justsoftware/toolbox/testng/DataProviders.java
Java
mit
3,248
export default function calculateScore (subject, chosenId, time) { const isCorrectAnswer = subject.id === chosenId let score if(isCorrectAnswer) { if(time < 7) { score = 3 } else { // Needs review score = .9 + (2 * (1/subject.seenCount)) } } else { // Degrees of failure score = 1/subject.seenCount } subject.score = score return [subject, score] }
johnloy/wat-namegame
lib/calculate-score.js
JavaScript
mit
401
#region Copyright // // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion #region Usings using Telerik.Web.UI; #endregion namespace DotNetNuke.Web.UI.WebControls { public class DnnContextMenuElementTarget : ContextMenuElementTarget { } }
RichardHowells/Dnn.Platform
DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenuElementTarget.cs
C#
mit
1,387
import { createRouter, createWebHistory } from "vue-router/dist/vue-router.esm.js"; import Home from "./views/Home.vue"; const routerHistory = createWebHistory("/"); let router = createRouter({ history: routerHistory, routes: [ { path: '/', component: Home, name: '' }, { path: '/who', component: Home, name: 'who' }, { path: '/what', component: Home, name: 'what' }, { path: '/where', component: Home, name: 'where' }, { path: '/when', component: Home, name: 'when' }, { path: '/why', component: Home, name: 'why' } ] }); router.afterEach((to, from) => { console.info((to, from, window.location.pathname)); }) export default router;
senei/senei.github.io
router/router.js
JavaScript
mit
680
# encoding: utf-8 require File.expand_path("../../spec_helper", __FILE__) describe Babosa::Transliterator::Bulgarian do let(:t) { described_class.instance } it_behaves_like "a cyrillic transliterator" it "should transliterate Cyrillic characters" do examples = { "Ютия" => "Iutiia", "Чушка" => "Chushka", "кьорав" => "kiorav", "Щъркел" => "Shturkel", "полицай" => "policai" } examples.each {|k, v| expect(t.transliterate(k)).to eql(v)} end end
humancopy/babosa
spec/transliterators/bulgarian_spec.rb
Ruby
mit
533
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Reactive; using Microsoft.Xna.Framework; using Microsoft.Devices.Sensors; namespace WP7AccelerometerSample { public class AccelerometerObservable { public static IObservable<Vector3> GetAccelerometer() { var accelerometer = new Accelerometer(); accelerometer.Start(); IObservable<IEvent<AccelerometerReadingEventArgs>> accelerometerReadingAsObservable = Observable.FromEvent<AccelerometerReadingEventArgs>( ev => accelerometer.ReadingChanged += ev, ev => accelerometer.ReadingChanged -= ev); var vector3FromAccelerometerEventArgs = from args in accelerometerReadingAsObservable select new Vector3( (float)args.EventArgs.X, (float)args.EventArgs.Y, (float)args.EventArgs.Z); return vector3FromAccelerometerEventArgs; } } }
jwooley/RxSamples
WP7AccelerometerSample/WP7AccelerometerSample/AccelerometerObservable.cs
C#
mit
1,391
// 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. #nullable enable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService { internal partial class WorkCoordinator { private sealed class AsyncProjectWorkItemQueue : AsyncWorkItemQueue<ProjectId> { private readonly Dictionary<ProjectId, WorkItem> _projectWorkQueue = new Dictionary<ProjectId, WorkItem>(); public AsyncProjectWorkItemQueue(SolutionCrawlerProgressReporter progressReporter, Workspace workspace) : base(progressReporter, workspace) { } protected override int WorkItemCount_NoLock => _projectWorkQueue.Count; public override Task WaitAsync(CancellationToken cancellationToken) { if (!HasAnyWork) { Logger.Log(FunctionId.WorkCoordinator_AsyncWorkItemQueue_LastItem); } return base.WaitAsync(cancellationToken); } protected override bool TryTake_NoLock(ProjectId key, out WorkItem workInfo) { if (!_projectWorkQueue.TryGetValue(key, out workInfo)) { workInfo = default; return false; } return _projectWorkQueue.Remove(key); } protected override bool TryTakeAnyWork_NoLock( ProjectId? preferableProjectId, ProjectDependencyGraph dependencyGraph, IDiagnosticAnalyzerService? analyzerService, out WorkItem workItem) { // there must be at least one item in the map when this is called unless host is shutting down. if (_projectWorkQueue.Count == 0) { workItem = default; return false; } var projectId = GetBestProjectId_NoLock(_projectWorkQueue, preferableProjectId, dependencyGraph, analyzerService); if (TryTake_NoLock(projectId, out workItem)) { return true; } throw ExceptionUtilities.Unreachable; } protected override bool AddOrReplace_NoLock(WorkItem item) { var key = item.ProjectId; Cancel_NoLock(key); // now document work // see whether we need to update if (_projectWorkQueue.TryGetValue(key, out var existingWorkItem)) { // replace it. _projectWorkQueue[key] = existingWorkItem.With(item.InvocationReasons, item.ActiveMember, item.SpecificAnalyzers, item.IsRetry, item.AsyncToken); return false; } // okay, it is new one // always hold onto the most recent one for the same project _projectWorkQueue.Add(key, item); return true; } protected override void Dispose_NoLock() { foreach (var workItem in _projectWorkQueue.Values) { workItem.AsyncToken.Dispose(); } _projectWorkQueue.Clear(); } } } } }
genlu/roslyn
src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.AsyncProjectWorkItemQueue.cs
C#
mit
4,021
/* A Bison parser, made by GNU Bison 2.4.1. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.4.1" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Using locations. */ #define YYLSP_NEEDED 0 /* Substitute the variable and function names. */ #define yyparse Genesisparse #define yylex Genesislex #define yyerror Genesiserror #define yylval Genesislval #define yychar Genesischar #define yydebug Genesisdebug #define yynerrs Genesisnerrs /* Copy the first part of user declarations. */ #include "stdneb.h" #include "rendersystem/base/RenderDeviceTypes.h" #include "GenesisShaderParser.h" #include "../GenesisMaterial.h" #include "addons/shadercompiler/Utility/ShaderCompilerUtil.h" void ResetParserParams(); int yyerror (const char *s); extern int Genesislineno; extern char* yytext; int yylex (); using namespace GenesisMaterialMaker; using namespace ShaderProgramCompiler; GenesisMaterial* g_GenesisMaterial; static GenesisMakePass* g_curMakePass = NULL; static GenesisMakeTechnique* g_curGenesisMakeTechnique = NULL; static GenesisMakeMaterial* g_curGenesisMakeMaterial = NULL; static GenesisMakeGPUProgram* g_curGenesisMakeGPUProgram = NULL; static Graphic::ShaderParam* g_curShaderParameter = NULL; static Graphic::MaterialParam* g_curMatParam = NULL; static GPtr<RenderBase::RenderStateDesc> g_rsDesc = 0; #define ASSIGN(s,d) {s = *d; delete d;} #define YYDEBUG 1 /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { TSHADER = 258, TTECHNIQUE = 259, TPASS = 260, TSETSHADERCODE = 261, TPARAMETERS = 262, TRENDERQUEUE = 263, TSHADERTYPE = 264, TRENDERDEVICETYPE = 265, TSETPARAM = 266, TRENDERSTATE = 267, TCULLMODE = 268, TFILLMODE = 269, TCOLORMASK = 270, TDEPTHTEST = 271, TDEPTHWRITE = 272, TBLENDCOLOR = 273, TALPHATEST = 274, TSAMPLER = 275, TMATTYPE = 276, TMATRIX = 277, TVECTOR = 278, TFLOAT = 279, TTEXTURE = 280, TREALSTRING = 281, TVAR = 282, TOPERATOR = 283, TNUMBER = 284, TBOOLEAN = 285 }; #endif /* Tokens. */ #define TSHADER 258 #define TTECHNIQUE 259 #define TPASS 260 #define TSETSHADERCODE 261 #define TPARAMETERS 262 #define TRENDERQUEUE 263 #define TSHADERTYPE 264 #define TRENDERDEVICETYPE 265 #define TSETPARAM 266 #define TRENDERSTATE 267 #define TCULLMODE 268 #define TFILLMODE 269 #define TCOLORMASK 270 #define TDEPTHTEST 271 #define TDEPTHWRITE 272 #define TBLENDCOLOR 273 #define TALPHATEST 274 #define TSAMPLER 275 #define TMATTYPE 276 #define TMATRIX 277 #define TVECTOR 278 #define TFLOAT 279 #define TTEXTURE 280 #define TREALSTRING 281 #define TVAR 282 #define TOPERATOR 283 #define TNUMBER 284 #define TBOOLEAN 285 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { char* str; float num; Graphic::ShaderParamType spt; bool boolean; } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif /* Copy the second part of user declarations. */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 4 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 100 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 34 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 36 /* YYNRULES -- Number of rules. */ #define YYNRULES 73 /* YYNRULES -- Number of states. */ #define YYNSTATES 130 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 285 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 33, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 31, 2, 32, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint8 yyprhs[] = { 0, 0, 3, 4, 5, 6, 15, 16, 17, 18, 26, 30, 31, 37, 38, 45, 46, 52, 59, 66, 72, 79, 85, 92, 98, 99, 100, 104, 105, 109, 110, 111, 112, 122, 123, 126, 127, 130, 133, 134, 135, 136, 144, 145, 149, 153, 157, 160, 164, 167, 170, 173, 177, 182, 185, 188, 193, 196, 200, 203, 204, 205, 206, 215, 216, 217, 218, 219, 229, 230, 234, 240, 246, 252 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 35, 0, -1, -1, -1, -1, 3, 26, 36, 31, 37, 39, 38, 32, -1, -1, -1, -1, 39, 7, 31, 40, 44, 41, 32, -1, 39, 8, 26, -1, -1, 39, 4, 31, 42, 45, -1, -1, 39, 4, 26, 31, 43, 45, -1, -1, 44, 25, 27, 33, 26, -1, 44, 25, 27, 28, 33, 26, -1, 44, 22, 27, 28, 33, 26, -1, 44, 22, 27, 33, 26, -1, 44, 23, 27, 28, 33, 26, -1, 44, 23, 27, 33, 26, -1, 44, 24, 27, 28, 33, 26, -1, 44, 24, 27, 33, 26, -1, -1, -1, 47, 46, 32, -1, -1, 47, 21, 26, -1, -1, -1, -1, 47, 5, 51, 48, 31, 49, 52, 50, 32, -1, -1, 51, 26, -1, -1, 52, 53, -1, 52, 61, -1, -1, -1, -1, 53, 12, 31, 54, 56, 55, 32, -1, -1, 56, 13, 26, -1, 56, 14, 26, -1, 56, 15, 26, -1, 56, 58, -1, 56, 17, 30, -1, 56, 59, -1, 56, 60, -1, 56, 57, -1, 20, 26, 27, -1, 20, 26, 27, 27, -1, 16, 27, -1, 16, 30, -1, 18, 27, 26, 26, -1, 18, 30, -1, 19, 27, 26, -1, 19, 30, -1, -1, -1, -1, 9, 26, 62, 31, 63, 65, 64, 32, -1, -1, -1, -1, -1, 65, 10, 26, 66, 31, 67, 69, 68, 32, -1, -1, 69, 6, 26, -1, 69, 11, 29, 27, 25, -1, 69, 11, 29, 27, 22, -1, 69, 11, 29, 27, 23, -1, 69, 11, 29, 27, 24, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 68, 68, 74, 76, 68, 83, 85, 87, 85, 91, 94, 94, 99, 99, 105, 107, 151, 195, 203, 211, 219, 227, 235, 244, 246, 246, 254, 256, 259, 261, 264, 259, 273, 278, 284, 286, 288, 291, 293, 298, 293, 305, 307, 312, 317, 322, 324, 329, 331, 333, 336, 339, 343, 350, 357, 366, 373, 390, 397, 403, 405, 397, 416, 417, 422, 424, 417, 430, 432, 437, 446, 455, 464 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "TSHADER", "TTECHNIQUE", "TPASS", "TSETSHADERCODE", "TPARAMETERS", "TRENDERQUEUE", "TSHADERTYPE", "TRENDERDEVICETYPE", "TSETPARAM", "TRENDERSTATE", "TCULLMODE", "TFILLMODE", "TCOLORMASK", "TDEPTHTEST", "TDEPTHWRITE", "TBLENDCOLOR", "TALPHATEST", "TSAMPLER", "TMATTYPE", "TMATRIX", "TVECTOR", "TFLOAT", "TTEXTURE", "TREALSTRING", "TVAR", "TOPERATOR", "TNUMBER", "TBOOLEAN", "'{'", "'}'", "'='", "$accept", "shader", "$@1", "$@2", "$@3", "PropertySection", "$@4", "$@5", "$@6", "$@7", "ParameterSection", "TechniqueSection", "$@8", "PassSection", "$@9", "$@10", "$@11", "PassType", "codeSection", "StateSection", "$@12", "$@13", "RenderStateSetup", "SamplerSetup", "DepthTestSetup", "BlendSetup", "AlphaTestSetup", "shadertype", "$@14", "$@15", "$@16", "DeviceTypeSetup", "$@17", "$@18", "$@19", "CodeBlock", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 123, 125, 61 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 34, 36, 37, 38, 35, 39, 40, 41, 39, 39, 42, 39, 43, 39, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 46, 45, 47, 47, 48, 49, 50, 47, 51, 51, 52, 52, 52, 53, 54, 55, 53, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 62, 63, 64, 61, 65, 66, 67, 68, 65, 69, 69, 69, 69, 69, 69 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 0, 0, 0, 8, 0, 0, 0, 7, 3, 0, 5, 0, 6, 0, 5, 6, 6, 5, 6, 5, 6, 5, 0, 0, 3, 0, 3, 0, 0, 0, 9, 0, 2, 0, 2, 2, 0, 0, 0, 7, 0, 3, 3, 3, 2, 3, 2, 2, 2, 3, 4, 2, 2, 4, 2, 3, 2, 0, 0, 0, 8, 0, 0, 0, 0, 9, 0, 3, 5, 5, 5, 5 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 0, 0, 0, 2, 1, 0, 3, 6, 4, 0, 0, 0, 0, 0, 11, 7, 10, 5, 13, 24, 15, 24, 12, 25, 8, 14, 33, 0, 0, 0, 0, 0, 0, 0, 29, 28, 26, 0, 0, 0, 0, 9, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0, 19, 0, 21, 0, 23, 0, 16, 35, 18, 20, 22, 17, 31, 0, 0, 36, 37, 59, 32, 0, 0, 39, 60, 42, 63, 40, 61, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 46, 48, 49, 0, 0, 43, 44, 45, 53, 54, 47, 0, 56, 0, 58, 0, 41, 64, 62, 0, 57, 51, 0, 55, 52, 65, 68, 66, 0, 0, 0, 69, 0, 67, 0, 71, 72, 73, 70 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 2, 5, 7, 12, 8, 20, 33, 19, 21, 24, 22, 28, 23, 43, 61, 68, 34, 66, 69, 77, 89, 79, 90, 91, 92, 93, 70, 74, 78, 95, 80, 113, 117, 121, 118 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -17 static const yytype_int8 yypact[] = { 8, -3, 12, -17, -17, -2, -17, -17, 24, -16, -1, 17, 10, 21, -17, -17, -17, -17, -17, -5, -17, -5, -17, -4, 11, -17, -17, 25, 22, 26, 28, 29, 30, 27, 34, -17, -17, -15, -14, -8, -7, -17, -17, 31, -9, 35, 33, 37, 36, 38, 39, 41, -17, 42, -17, 44, -17, 45, -17, 47, -17, -17, -17, -17, -17, -17, 32, 48, 43, 46, -17, -17, -17, 49, 50, -17, -17, -17, -17, -11, 55, 51, 52, 53, 18, 54, 19, 20, 56, 57, -17, -17, -17, -17, 59, 58, -17, -17, -17, -17, -17, -17, 60, -17, 61, -17, 64, -17, -17, -17, 62, -17, 65, 63, -17, -17, -17, -17, 16, 67, 66, 68, -17, 69, -17, 15, -17, -17, -17, -17 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, 76, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -39 static const yytype_int16 yytable[] = { -27, 26, 81, 82, 83, 84, 85, 86, 87, 88, 13, 1, 4, 44, 46, 14, -27, 27, 45, 47, 48, 50, 119, 3, 53, 49, 51, 120, 9, 6, 15, 10, 11, 29, 30, 31, 32, 126, 127, 128, 129, 67, 17, 16, -38, 99, 102, 104, 100, 103, 105, 35, 18, 37, 36, 38, 39, 40, 73, 41, 42, 54, 52, 56, 58, 94, 55, 60, 62, 57, 63, 64, 59, 65, 71, 72, 0, 96, 97, 98, 75, 76, 106, 0, 101, 108, 110, 111, 114, 107, 109, 112, 115, 122, 116, 123, 125, 25, 0, 0, 124 }; static const yytype_int8 yycheck[] = { 5, 5, 13, 14, 15, 16, 17, 18, 19, 20, 26, 3, 0, 28, 28, 31, 21, 21, 33, 33, 28, 28, 6, 26, 33, 33, 33, 11, 4, 31, 31, 7, 8, 22, 23, 24, 25, 22, 23, 24, 25, 9, 32, 26, 12, 27, 27, 27, 30, 30, 30, 26, 31, 27, 32, 27, 27, 27, 12, 32, 26, 26, 31, 26, 26, 10, 33, 26, 26, 33, 26, 26, 33, 26, 26, 32, -1, 26, 26, 26, 31, 31, 26, -1, 30, 26, 26, 26, 26, 32, 32, 27, 27, 26, 31, 29, 27, 21, -1, -1, 32 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 3, 35, 26, 0, 36, 31, 37, 39, 4, 7, 8, 38, 26, 31, 31, 26, 32, 31, 42, 40, 43, 45, 47, 44, 45, 5, 21, 46, 22, 23, 24, 25, 41, 51, 26, 32, 27, 27, 27, 27, 32, 26, 48, 28, 33, 28, 33, 28, 33, 28, 33, 31, 33, 26, 33, 26, 33, 26, 33, 26, 49, 26, 26, 26, 26, 52, 9, 50, 53, 61, 26, 32, 12, 62, 31, 31, 54, 63, 56, 65, 13, 14, 15, 16, 17, 18, 19, 20, 55, 57, 58, 59, 60, 10, 64, 26, 26, 26, 27, 30, 30, 27, 30, 27, 30, 26, 32, 26, 32, 26, 26, 27, 66, 26, 27, 31, 67, 69, 6, 11, 68, 26, 29, 32, 27, 22, 23, 24, 25 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (YYLEX_PARAM) #else # define YYLEX yylex () #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) #else static void yy_stack_print (yybottom, yytop) yytype_int16 *yybottom; yytype_int16 *yytop; #endif { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, int yyrule) #else static void yy_reduce_print (yyvsp, yyrule) YYSTYPE *yyvsp; int yyrule; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) ); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, Rule); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) #else static void yydestruct (yymsg, yytype, yyvaluep) const char *yymsg; int yytype; YYSTYPE *yyvaluep; #endif { YYUSE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (void); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*-------------------------. | yyparse or yypush_parse. | `-------------------------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: { //n_printf("init genesisshader\n"); g_GenesisMaterial->SetName((yyvsp[(2) - (2)].str)); delete[] (yyvsp[(2) - (2)].str); ResetParserParams(); g_curGenesisMakeMaterial = new GenesisMakeMaterial(); } break; case 3: { //n_printf("in genesisshader,left\n"); } break; case 4: { //n_printf("from PropertySection to genesisshader\n"); } break; case 5: { //n_printf("out genesisshader,right\n"); g_GenesisMaterial->AddMaterial(*g_curGenesisMakeMaterial); delete g_curGenesisMakeMaterial; g_curGenesisMakeMaterial = 0; } break; case 6: {//n_printf("init PropertySection\n"); } break; case 7: {//n_printf("in ParameterSection,left\n"); } break; case 8: {//n_printf("from ParameterSection to PropertySection\n"); } break; case 9: { //n_printf("out ParameterSection,right\n"); } break; case 10: { g_curGenesisMakeMaterial->SetRenderQueue(Graphic::RenderQueue::FromString((yyvsp[(3) - (3)].str))); //n_printf("in PropertySection,setrenderqueue:%s\n", Util::String($3).AsCharPtr()); } break; case 11: { //n_printf("in TechniqueSection,left\n"); g_curGenesisMakeTechnique = new GenesisMakeTechnique(); } break; case 12: {//n_printf("from TechniqueSection to PropertySection\n"); } break; case 13: { //n_printf("in TechniqueSection,left\n"); g_curGenesisMakeTechnique = new GenesisMakeTechnique(); g_curGenesisMakeTechnique->SetName((yyvsp[(3) - (4)].str)); } break; case 14: {//n_printf("from TechniqueSection to PropertySection\n"); } break; case 15: {//n_printf("init ParameterSection\n"); } break; case 16: { if((yyvsp[(2) - (5)].spt) == Graphic::eShaderParamTexture2D) { g_curMatParam = new Graphic::MaterialParamTex2D(); } else if((yyvsp[(2) - (5)].spt) == Graphic::eShaderParamTextureCUBE) { g_curMatParam = new Graphic::MaterialParamTexCube(); } else if((yyvsp[(2) - (5)].spt) == Graphic::eShaderParamTexture1D) { g_curMatParam = new Graphic::MaterialParamTex1D(); } else if((yyvsp[(2) - (5)].spt) == Graphic::eShaderParamTexture3D) { g_curMatParam = new Graphic::MaterialParamTex3D(); } else { n_error("GenesisShader Parser : Invalid Texture Type !"); } g_curMatParam->SetName((yyvsp[(3) - (5)].str)); g_curMatParam->SetDesc((yyvsp[(3) - (5)].str)); g_curMatParam->SetStringValue((yyvsp[(5) - (5)].str)); //n_printf("define texture\n"); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; if ((yyvsp[(2) - (5)].spt) == Graphic::eShaderParamTexture2D) { char texOffestScaleValue[] = "0.0,0.0,1.0,1.0"; Util::String texOffestScale; texOffestScale.Clear(); texOffestScale.Format("%s_UV_OffsetScale",(yyvsp[(3) - (5)].str)); g_curMatParam = new Graphic::MaterialParamVector(); g_curMatParam->SetName(texOffestScale); g_curMatParam->SetDesc(texOffestScale); g_curMatParam->SetStringValue(texOffestScaleValue); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; } } break; case 17: { if((yyvsp[(2) - (6)].spt) == Graphic::eShaderParamTexture2D) { g_curMatParam = new Graphic::MaterialParamTex2D(); } else if((yyvsp[(2) - (6)].spt) == Graphic::eShaderParamTextureCUBE) { g_curMatParam = new Graphic::MaterialParamTexCube(); } else if((yyvsp[(2) - (6)].spt) == Graphic::eShaderParamTexture1D) { g_curMatParam = new Graphic::MaterialParamTex1D(); } else if((yyvsp[(2) - (6)].spt) == Graphic::eShaderParamTexture3D) { g_curMatParam = new Graphic::MaterialParamTex3D(); } else { n_error("GenesisShader Parser : Invalid Texture Type !"); } g_curMatParam->SetName((yyvsp[(3) - (6)].str)); g_curMatParam->SetDesc((yyvsp[(4) - (6)].str)); g_curMatParam->SetStringValue((yyvsp[(6) - (6)].str)); //n_printf("define texture\n"); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; if ((yyvsp[(2) - (6)].spt) == Graphic::eShaderParamTexture2D) { char texOffestScaleValue[] = "0.0,0.0,1.0,1.0"; Util::String texOffestScale; texOffestScale.Clear(); texOffestScale.Format("%s_UV_OffsetScale",(yyvsp[(3) - (6)].str)); g_curMatParam = new Graphic::MaterialParamVector(); g_curMatParam->SetName(texOffestScale); g_curMatParam->SetDesc(texOffestScale); g_curMatParam->SetStringValue(texOffestScaleValue); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; } } break; case 18: { g_curMatParam = new Graphic::MaterialParamMatrix(); g_curMatParam->SetName((yyvsp[(3) - (6)].str)); g_curMatParam->SetDesc((yyvsp[(4) - (6)].str)); g_curMatParam->SetStringValue((yyvsp[(6) - (6)].str)); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; } break; case 19: { g_curMatParam = new Graphic::MaterialParamMatrix(); g_curMatParam->SetName((yyvsp[(3) - (5)].str)); g_curMatParam->SetDesc((yyvsp[(3) - (5)].str)); g_curMatParam->SetStringValue((yyvsp[(5) - (5)].str)); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; } break; case 20: { g_curMatParam = new Graphic::MaterialParamVector(); g_curMatParam->SetName((yyvsp[(3) - (6)].str)); g_curMatParam->SetDesc((yyvsp[(4) - (6)].str)); g_curMatParam->SetStringValue((yyvsp[(6) - (6)].str)); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; } break; case 21: { g_curMatParam = new Graphic::MaterialParamVector(); g_curMatParam->SetName((yyvsp[(3) - (5)].str)); g_curMatParam->SetDesc((yyvsp[(3) - (5)].str)); g_curMatParam->SetStringValue((yyvsp[(5) - (5)].str)); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; } break; case 22: { g_curMatParam = new Graphic::MaterialParamFloat(); g_curMatParam->SetName((yyvsp[(3) - (6)].str)); g_curMatParam->SetDesc((yyvsp[(4) - (6)].str)); g_curMatParam->SetStringValue((yyvsp[(6) - (6)].str)); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; } break; case 23: { g_curMatParam = new Graphic::MaterialParamFloat(); g_curMatParam->SetName((yyvsp[(3) - (5)].str)); g_curMatParam->SetDesc((yyvsp[(3) - (5)].str)); g_curMatParam->SetStringValue((yyvsp[(5) - (5)].str)); g_curGenesisMakeMaterial->AddMatParam(g_curMatParam); g_curMatParam = NULL; } break; case 24: { //n_printf("init TechniqueSection\n"); } break; case 25: { //n_printf("from PassSection to TechniqueSection\n"); } break; case 26: { //n_printf("out TechniqueSection,right\n"); g_curGenesisMakeMaterial->AddTechnique(*g_curGenesisMakeTechnique); delete g_curGenesisMakeTechnique; g_curGenesisMakeTechnique = 0; } break; case 27: { //n_printf("init PassSection\n"); } break; case 28: { printf("set MatType\n"); g_curGenesisMakeTechnique->SetIsMatTemplate((yyvsp[(3) - (3)].str)); } break; case 29: { //n_printf("init Pass\n"); } break; case 30: { //n_printf("in PassSection,left\n"); } break; case 31: { //n_printf("from codeSection to PassSection\n"); } break; case 32: { //n_printf("out PassSection,right\n"); g_curGenesisMakeTechnique->AddPass(*g_curMakePass); delete g_curMakePass; g_curMakePass = 0; } break; case 33: { n_printf("in PassSection,left\n"); g_curMakePass = new GenesisMakePass(); g_curMakePass->SetName("NoName"); } break; case 34: { n_printf("in PassSection,left\n"); g_curMakePass = new GenesisMakePass(); g_curMakePass->SetName((yyvsp[(2) - (2)].str)); } break; case 35: { //n_printf("in codeSection\n"); } break; case 36: { //n_printf("from shadertype,to StateSection\n"); } break; case 37: { //n_printf("from shadertype,to shadertype\n"); } break; case 38: { //n_printf("in StateSection\n"); } break; case 39: { g_rsDesc = RenderBase::RenderStateDesc::Create(); g_rsDesc->Setup(); //n_printf("Create StateSection\n");//n_printf("init StateSection\n"); } break; case 40: { } break; case 41: { g_curMakePass->SetRenderStateDesc(g_rsDesc); g_rsDesc = 0; //n_printf("from RenderStateSetup,to shadertype\n"); } break; case 42: { //n_printf("in RenderStateSetup\n"); } break; case 43: { RenderBase::DeviceRasterizerState rrs = g_rsDesc->GetRasterizerState(); rrs.m_cullMode = RenderBase::CullModeConverter::FromString((yyvsp[(3) - (3)].str)); g_rsDesc->SetRasterizerState(rrs); } break; case 44: { RenderBase::DeviceRasterizerState rrs = g_rsDesc->GetRasterizerState(); rrs.m_fillMode = RenderBase::FillModeConverter::FromString((yyvsp[(3) - (3)].str)); g_rsDesc->SetRasterizerState(rrs); } break; case 45: { RenderBase::DeviceBlendState rbs = g_rsDesc->GetBlendState(); rbs.m_colorWriteMask[0] = RenderBase::ColorMaskConverter::FromString((yyvsp[(3) - (3)].str)); g_rsDesc->SetBlendState(rbs); } break; case 46: { //n_printf("set depthtest complete \n"); } break; case 47: { RenderBase::DeviceDepthAndStencilState rdss = g_rsDesc->GetDepthAndStencilState(); rdss.m_depthWriteMask = (yyvsp[(3) - (3)].boolean); g_rsDesc->SetDepthAndStencilState(rdss); } break; case 48: { //n_printf("set blendmode complete \n"); } break; case 49: { //n_printf("set alphatest complete \n"); } break; case 50: { //n_printf("set samplerstate complete \n"); } break; case 51: { g_curGenesisMakeMaterial->AddTextureSampler((yyvsp[(2) - (3)].str),RenderBase::TextureAddressModeConverter::FromString((yyvsp[(3) - (3)].str))); } break; case 52: { g_curGenesisMakeMaterial->AddTextureSampler((yyvsp[(2) - (4)].str),RenderBase::TextureAddressModeConverter::FromString((yyvsp[(3) - (4)].str)),RenderBase::TextureFilterOperationConverter::FromString((yyvsp[(4) - (4)].str))); } break; case 53: { RenderBase::DeviceDepthAndStencilState rdss = g_rsDesc->GetDepthAndStencilState(); rdss.m_depthEnable = true; rdss.m_zFunc = RenderBase::CompareFunctionConverter::FromString((yyvsp[(2) - (2)].str)); g_rsDesc->SetDepthAndStencilState(rdss); } break; case 54: { RenderBase::DeviceDepthAndStencilState rdss = g_rsDesc->GetDepthAndStencilState(); rdss.m_depthEnable = (yyvsp[(2) - (2)].boolean); g_rsDesc->SetDepthAndStencilState(rdss); } break; case 55: { RenderBase::DeviceBlendState rbs = g_rsDesc->GetBlendState(); rbs.m_alphaBlendEnable[0] = true; rbs.m_blendOP[0] = RenderBase::BlendOperationConverter::FromString((yyvsp[(2) - (4)].str)); rbs.m_srcBlend[0] = RenderBase::AlphaBlendFactorConverter::FromString((yyvsp[(3) - (4)].str)); rbs.m_destBlend[0] = RenderBase::AlphaBlendFactorConverter::FromString((yyvsp[(4) - (4)].str)); g_rsDesc->SetBlendState(rbs); } break; case 56: { RenderBase::DeviceBlendState rbs = g_rsDesc->GetBlendState(); rbs.m_alphaBlendEnable[0] = (yyvsp[(2) - (2)].boolean); g_rsDesc->SetBlendState(rbs); } break; case 57: { RenderBase::DeviceBlendState rbs = g_rsDesc->GetBlendState(); rbs.m_alphaTestEnable = true; rbs.m_alphaFunc = RenderBase::CompareFunctionConverter::FromString((yyvsp[(2) - (3)].str)); const Util::String& valueStr = g_curGenesisMakeMaterial->GetMatParamValueByName((yyvsp[(3) - (3)].str)); if(!valueStr.IsValidFloat() || valueStr.IsEmpty()) { n_error("Invalid alpha_to_coverage_ref value!please check your parameter type(float) and name!"); } else { rbs.m_alphaRef = valueStr.AsFloat(); } g_rsDesc->SetBlendState(rbs); } break; case 58: { RenderBase::DeviceBlendState rbs = g_rsDesc->GetBlendState(); rbs.m_alphaTestEnable = (yyvsp[(2) - (2)].boolean); g_rsDesc->SetBlendState(rbs); } break; case 59: { g_curGenesisMakeGPUProgram = new GenesisMakeGPUProgram(); g_curGenesisMakeGPUProgram->SetShaderType((yyvsp[(2) - (2)].str)); //n_printf("in shaderType,SetShaderType\n"); delete[] (yyvsp[(2) - (2)].str); } break; case 60: { //n_printf("in shaderType,left\n"); } break; case 61: { //n_printf("from DeviceTypeSetup to shaderType\n"); } break; case 62: { if(g_curGenesisMakeGPUProgram != NULL) { delete g_curGenesisMakeGPUProgram; g_curGenesisMakeGPUProgram = NULL; } //n_printf("out shaderType,right\n"); } break; case 63: { n_printf("in DeviceTypeSetup\n");} break; case 64: { g_curGenesisMakeGPUProgram->SetDeviceType((yyvsp[(3) - (3)].str)); //n_printf("in DeviceTypeSetup\n"); delete[] (yyvsp[(3) - (3)].str); } break; case 65: { //n_printf("in DeviceTypeSetup,left\n"); } break; case 66: { //n_printf("from CodeBlock to DeviceTypeSetup\n"); } break; case 67: { //n_printf("out DeviceTypeSetup,right\n"); g_curMakePass->AddShaderProgram(*g_curGenesisMakeGPUProgram); } break; case 68: { //n_printf("in CodeBlock\n"); } break; case 69: { g_curGenesisMakeGPUProgram->SetShaderCode((yyvsp[(3) - (3)].str)); //n_printf("in CodeBlock,AddGPUProgram\n"); delete[] (yyvsp[(3) - (3)].str); } break; case 70: { g_curShaderParameter = new Graphic::ShaderParam(); g_curShaderParameter->SetParamType((yyvsp[(5) - (5)].spt)); g_curShaderParameter->SetRegister((yyvsp[(3) - (5)].num)); g_curShaderParameter->SetName((yyvsp[(4) - (5)].str)); g_curGenesisMakeGPUProgram->AddParam(*g_curShaderParameter); //n_printf("bind texture\n"); delete[] $4; delete g_curShaderParameter; g_curShaderParameter = 0; } break; case 71: { g_curShaderParameter = new Graphic::ShaderParam(); g_curShaderParameter->SetParamType((yyvsp[(5) - (5)].spt)); g_curShaderParameter->SetRegister((yyvsp[(3) - (5)].num)); g_curShaderParameter->SetName((yyvsp[(4) - (5)].str)); g_curGenesisMakeGPUProgram->AddParam(*g_curShaderParameter); //n_printf("setparam matrix register\n"); delete[] $4; delete g_curShaderParameter; g_curShaderParameter = 0; } break; case 72: { g_curShaderParameter = new Graphic::ShaderParam(); g_curShaderParameter->SetParamType((yyvsp[(5) - (5)].spt)); g_curShaderParameter->SetRegister((yyvsp[(3) - (5)].num)); g_curShaderParameter->SetName((yyvsp[(4) - (5)].str)); g_curGenesisMakeGPUProgram->AddParam(*g_curShaderParameter); //n_printf("setparam vector register\n"); delete[] $4; delete g_curShaderParameter; g_curShaderParameter = 0; } break; case 73: { g_curShaderParameter = new Graphic::ShaderParam(); g_curShaderParameter->SetParamType((yyvsp[(5) - (5)].spt)); g_curShaderParameter->SetRegister((yyvsp[(3) - (5)].num)); g_curShaderParameter->SetName((yyvsp[(4) - (5)].str)); g_curGenesisMakeGPUProgram->AddParam(*g_curShaderParameter); //n_printf("setparam float register\n"); delete[] $4; delete g_curShaderParameter; g_curShaderParameter = 0; } break; default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } int yyerror (const char *s) { n_printf("GenesisShader Error: %s At line:%d\n",s,Genesislineno); return 0; } void ResetParserParams() { if(g_curGenesisMakeGPUProgram != NULL) { delete g_curGenesisMakeGPUProgram; g_curGenesisMakeGPUProgram = NULL; } if(g_curShaderParameter != NULL) { delete g_curShaderParameter; g_curShaderParameter = NULL; } if(g_curMatParam != NULL) { delete g_curMatParam; g_curMatParam = NULL; } if(g_rsDesc.isvalid()) { g_rsDesc = 0; } if(g_curMakePass != NULL) { delete g_curMakePass; g_curMakePass = NULL; } if(g_curGenesisMakeTechnique != NULL) { delete g_curGenesisMakeTechnique; g_curGenesisMakeTechnique = NULL; } if(g_curGenesisMakeMaterial != NULL) { delete g_curGenesisMakeMaterial; g_curGenesisMakeMaterial = NULL; } }
EngineDreamer/DreamEngine
Engine/addons/materialmaker/parser/GenesisShaderBison.cpp
C++
mit
72,460
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; /** * Created by Linty on 2/12/2017. * 用 apache的 commons-csv 的公共类,编写一个适用于用例中读取Csv的方法 */ public class CsvUtility { public Iterable<CSVRecord> readCsvFile(String csvPath) { // 读取 csv 文件到FilerReader中 // 用捕获异常的方式 进行文件读取,防止出现“文件不存在”的异常 Reader reader = null; try { reader = new FileReader(csvPath); } catch (FileNotFoundException e) { e.printStackTrace(); } // 读取 csv 到 records中 Iterable<CSVRecord> records = null; try { if (reader != null) { records = CSVFormat.EXCEL.parse(reader); } } catch (IOException e) { e.printStackTrace(); } return records; } }
lintyleo/seleniumpro
SealSelenium/src/main/java/CsvUtility.java
Java
mit
1,057
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Scs")] [assembly: AssemblyDescription("Simple Client/Server Framework")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Halil ibrahim Kalkan")] [assembly: AssemblyProduct("Scs")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("20dfc06b-5632-4956-beaf-a5e0bb126bb5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.1")] [assembly: AssemblyFileVersion("1.1.0.1")]
furesoft/scs
src/Scs/Properties/AssemblyInfo.cs
C#
mit
1,414
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. --------------------------------------------------------------------------- */ /** @file Implementation of the post processing step "MakeVerboseFormat" */ #include "MakeVerboseFormat.h" #include <assimp/scene.h> #include <assimp/DefaultLogger.hpp> using namespace Assimp; // ------------------------------------------------------------------------------------------------ MakeVerboseFormatProcess::MakeVerboseFormatProcess() { // nothing to do here } // ------------------------------------------------------------------------------------------------ MakeVerboseFormatProcess::~MakeVerboseFormatProcess() { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Executes the post processing step on the given imported data. void MakeVerboseFormatProcess::Execute( aiScene* pScene) { ai_assert(NULL != pScene); ASSIMP_LOG_DEBUG("MakeVerboseFormatProcess begin"); bool bHas = false; for( unsigned int a = 0; a < pScene->mNumMeshes; a++) { if( MakeVerboseFormat( pScene->mMeshes[a])) bHas = true; } if (bHas) { ASSIMP_LOG_INFO("MakeVerboseFormatProcess finished. There was much work to do ..."); } else { ASSIMP_LOG_DEBUG("MakeVerboseFormatProcess. There was nothing to do."); } pScene->mFlags &= ~AI_SCENE_FLAGS_NON_VERBOSE_FORMAT; } // ------------------------------------------------------------------------------------------------ // Executes the post processing step on the given imported data. bool MakeVerboseFormatProcess::MakeVerboseFormat(aiMesh* pcMesh) { ai_assert(NULL != pcMesh); unsigned int iOldNumVertices = pcMesh->mNumVertices; const unsigned int iNumVerts = pcMesh->mNumFaces*3; aiVector3D* pvPositions = new aiVector3D[ iNumVerts ]; aiVector3D* pvNormals = NULL; if (pcMesh->HasNormals()) { pvNormals = new aiVector3D[iNumVerts]; } aiVector3D* pvTangents = NULL, *pvBitangents = NULL; if (pcMesh->HasTangentsAndBitangents()) { pvTangents = new aiVector3D[iNumVerts]; pvBitangents = new aiVector3D[iNumVerts]; } aiVector3D* apvTextureCoords[AI_MAX_NUMBER_OF_TEXTURECOORDS] = {0}; aiColor4D* apvColorSets[AI_MAX_NUMBER_OF_COLOR_SETS] = {0}; unsigned int p = 0; while (pcMesh->HasTextureCoords(p)) apvTextureCoords[p++] = new aiVector3D[iNumVerts]; p = 0; while (pcMesh->HasVertexColors(p)) apvColorSets[p++] = new aiColor4D[iNumVerts]; // allocate enough memory to hold output bones and vertex weights ... std::vector<aiVertexWeight>* newWeights = new std::vector<aiVertexWeight>[pcMesh->mNumBones]; for (unsigned int i = 0;i < pcMesh->mNumBones;++i) { newWeights[i].reserve(pcMesh->mBones[i]->mNumWeights*3); } // iterate through all faces and build a clean list unsigned int iIndex = 0; for (unsigned int a = 0; a< pcMesh->mNumFaces;++a) { aiFace* pcFace = &pcMesh->mFaces[a]; for (unsigned int q = 0; q < pcFace->mNumIndices;++q,++iIndex) { // need to build a clean list of bones, too for (unsigned int i = 0;i < pcMesh->mNumBones;++i) { for (unsigned int a = 0; a < pcMesh->mBones[i]->mNumWeights;a++) { const aiVertexWeight& w = pcMesh->mBones[i]->mWeights[a]; if(pcFace->mIndices[q] == w.mVertexId) { aiVertexWeight wNew; wNew.mVertexId = iIndex; wNew.mWeight = w.mWeight; newWeights[i].push_back(wNew); } } } pvPositions[iIndex] = pcMesh->mVertices[pcFace->mIndices[q]]; if (pcMesh->HasNormals()) { pvNormals[iIndex] = pcMesh->mNormals[pcFace->mIndices[q]]; } if (pcMesh->HasTangentsAndBitangents()) { pvTangents[iIndex] = pcMesh->mTangents[pcFace->mIndices[q]]; pvBitangents[iIndex] = pcMesh->mBitangents[pcFace->mIndices[q]]; } unsigned int p = 0; while (pcMesh->HasTextureCoords(p)) { apvTextureCoords[p][iIndex] = pcMesh->mTextureCoords[p][pcFace->mIndices[q]]; ++p; } p = 0; while (pcMesh->HasVertexColors(p)) { apvColorSets[p][iIndex] = pcMesh->mColors[p][pcFace->mIndices[q]]; ++p; } pcFace->mIndices[q] = iIndex; } } // build output vertex weights for (unsigned int i = 0;i < pcMesh->mNumBones;++i) { delete [] pcMesh->mBones[i]->mWeights; if (!newWeights[i].empty()) { pcMesh->mBones[i]->mWeights = new aiVertexWeight[newWeights[i].size()]; aiVertexWeight *weightToCopy = &( newWeights[i][0] ); memcpy(pcMesh->mBones[i]->mWeights, weightToCopy, sizeof(aiVertexWeight) * newWeights[i].size()); } else { pcMesh->mBones[i]->mWeights = NULL; } } delete[] newWeights; // delete the old members delete[] pcMesh->mVertices; pcMesh->mVertices = pvPositions; p = 0; while (pcMesh->HasTextureCoords(p)) { delete[] pcMesh->mTextureCoords[p]; pcMesh->mTextureCoords[p] = apvTextureCoords[p]; ++p; } p = 0; while (pcMesh->HasVertexColors(p)) { delete[] pcMesh->mColors[p]; pcMesh->mColors[p] = apvColorSets[p]; ++p; } pcMesh->mNumVertices = iNumVerts; if (pcMesh->HasNormals()) { delete[] pcMesh->mNormals; pcMesh->mNormals = pvNormals; } if (pcMesh->HasTangentsAndBitangents()) { delete[] pcMesh->mTangents; pcMesh->mTangents = pvTangents; delete[] pcMesh->mBitangents; pcMesh->mBitangents = pvBitangents; } return (pcMesh->mNumVertices != iOldNumVertices); } // ------------------------------------------------------------------------------------------------ bool IsMeshInVerboseFormat(const aiMesh* mesh) { // avoid slow vector<bool> specialization std::vector<unsigned int> seen(mesh->mNumVertices,0); for(unsigned int i = 0; i < mesh->mNumFaces; ++i) { const aiFace& f = mesh->mFaces[i]; for(unsigned int j = 0; j < f.mNumIndices; ++j) { if(++seen[f.mIndices[j]] == 2) { // found a duplicate index return false; } } } return true; } // ------------------------------------------------------------------------------------------------ bool MakeVerboseFormatProcess::IsVerboseFormat(const aiScene* pScene) { for(unsigned int i = 0; i < pScene->mNumMeshes; ++i) { if(!IsMeshInVerboseFormat(pScene->mMeshes[i])) { return false; } } return true; }
Bloodknight/Torque3D
Engine/lib/assimp/code/PostProcessing/MakeVerboseFormat.cpp
C++
mit
8,769
# frozen_string_literal: true require 'image_optim/pack'
Ladvien/ladvien.github.io
vendor/cache/ruby/3.0.0/gems/image_optim_pack-0.7.0.20210511-x86_64-darwin/lib/image_optim_pack.rb
Ruby
mit
58
/* * Copyright (C) 2017, Ulrich Wolffgang <ulrich.wolffgang@proleap.io> * All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package io.proleap.cobol.asg.metamodel.identification; import io.proleap.cobol.asg.metamodel.CobolDivisionElement; import io.proleap.cobol.asg.metamodel.NamedElement; /** * Specifies program name and assigns attributes to it. */ public interface ProgramIdParagraph extends CobolDivisionElement, NamedElement { enum Attribute { COMMON, DEFINITION, INITIAL, LIBRARY, RECURSIVE } Attribute getAttribute(); void setAttribute(Attribute attribute); }
uwol/cobol85parser
src/main/java/io/proleap/cobol/asg/metamodel/identification/ProgramIdParagraph.java
Java
mit
685
from collections.abc import Iterable from django import template from django.db.models import Model register = template.Library() @register.filter def get_type(value): # inspired by: https://stackoverflow.com/a/12028864 return type(value) @register.filter def is_model(value): return isinstance(value, Model) @register.filter def is_iterable(value): return isinstance(value, Iterable) @register.filter def is_str(value): return isinstance(value, str) @register.filter def is_bool(value): return isinstance(value, bool)
pbanaszkiewicz/amy
amy/autoemails/templatetags/type_extras.py
Python
mit
555
using System.Diagnostics.Contracts; using JetBrains.DocumentModel; using JetBrains.ReSharper.Daemon; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; using ReSharper.ContractExtensions.ProblemAnalyzers.PreconditionAnalyzers.MalformContractAnalyzers; [assembly: RegisterConfigurableSeverity(CodeContractErrorHighlighting.Id, null, HighlightingGroupIds.CompilerWarnings, CodeContractErrorHighlighting.Id, "Warn for malformed method contract", Severity.ERROR, false)] namespace ReSharper.ContractExtensions.ProblemAnalyzers.PreconditionAnalyzers.MalformContractAnalyzers { /// <summary> /// Shows errors, produced by Code Contract compiler. /// </summary> [ConfigurableSeverityHighlighting(Id, CSharpLanguage.Name)] public sealed class CodeContractErrorHighlighting : IHighlighting, ICodeContractFixableIssue { private readonly CodeContractErrorValidationResult _error; private readonly ValidatedContractBlock _contractBlock; public const string Id = "Malformed method contract error highlighting"; private readonly string _toolTip; private readonly DocumentRange _range; internal CodeContractErrorHighlighting(ICSharpStatement statement, CodeContractErrorValidationResult error, ValidatedContractBlock contractBlock) { Contract.Requires(error != null); Contract.Requires(contractBlock != null); Contract.Requires(statement != null); _range = statement.GetHighlightingRange(); _error = error; _contractBlock = contractBlock; _toolTip = error.GetErrorText(); } public bool IsValid() { return true; } /// <summary> /// Calculates range of a highlighting. /// </summary> public DocumentRange CalculateRange() { return _range; } public string ToolTip { get { return _toolTip; } } public string ErrorStripeToolTip { get { return ToolTip; } } public int NavigationOffsetPatch { get { return 0; } } ValidationResult ICodeContractFixableIssue.ValidationResult { get { return _error; } } ValidatedContractBlock ICodeContractFixableIssue.ValidatedContractBlock { get { return _contractBlock; } } } }
Diagonactic/ReSharperContractExtensions
ContractExtensions/ProblemAnalyzers/PreconditionAnalyzers/MalformContractAnalyzers/CodeContractErrorHighlighting.cs
C#
mit
2,491
<?php $eZTranslationCacheCodeDate = 1058863428; $CacheInfo = array ( 'charset' => 'utf-8', ); $TranslationInfo = array ( 'context' => 'design/admin/notification/runfilter', ); $TranslationRoot = array ( '15a89335cfe98f8888e91a21abcdbf64' => array ( 'context' => 'design/admin/notification/runfilter', 'source' => 'The notification time event was spawned.', 'comment' => NULL, 'translation' => 'L\'evento temporale di notifica è stato generato.', 'key' => '15a89335cfe98f8888e91a21abcdbf64', ), '8bd2193d5e22df5641e55d296f9e29e2' => array ( 'context' => 'design/admin/notification/runfilter', 'source' => 'Notification', 'comment' => NULL, 'translation' => 'Notifica', 'key' => '8bd2193d5e22df5641e55d296f9e29e2', ), '354a2de7aa8777fd278606cca31a501a' => array ( 'context' => 'design/admin/notification/runfilter', 'source' => 'Spawn time event', 'comment' => NULL, 'translation' => 'Genera evento temporale', 'key' => '354a2de7aa8777fd278606cca31a501a', ), 'ba9e3ada748cbda65ab5cdea60fbc894' => array ( 'context' => 'design/admin/notification/runfilter', 'source' => 'The notification filter processed all available notification events.', 'comment' => NULL, 'translation' => 'Il filtro notifica ha processato tutti gli eventi di notifica disponibili.', 'key' => 'ba9e3ada748cbda65ab5cdea60fbc894', ), '40cd9655ba559c327a9d1df2ab506192' => array ( 'context' => 'design/admin/notification/runfilter', 'source' => 'Run notification filter', 'comment' => NULL, 'translation' => 'Esegui filtro notifica', 'key' => '40cd9655ba559c327a9d1df2ab506192', ), ); ?>
SnceGroup/snce-website
web/var/ezdemo_site/cache/translation/7ea3246ce3f3b0d74450a358f0d52a8c/ita-IT/2deaf73fbdb30373798bff18c18ac53a.php
PHP
mit
1,696
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * This file is part of the PWAK (PHP Web Application Kit) framework. * * PWAK is a php framework initially developed for the * {@link http://onlogistics.googlecode.com Onlogistics} ERP/Supply Chain * management web application. * It provides components and tools for developers to build complex web * applications faster and in a more reliable way. * * PHP version 5.1.0+ * * LICENSE: This source file is subject to the MIT license that is available * through the world-wide-web at the following URI: * http://opensource.org/licenses/mit-license.php * * @package PWAK * @author ATEOR dev team <dev@ateor.com> * @copyright 2003-2008 ATEOR <contact@ateor.com> * @license http://opensource.org/licenses/mit-license.php MIT License * @version SVN: $Id$ * @link http://pwak.googlecode.com * @since File available since release 0.1.0 * @filesource */ require_once 'Calendar/Decorator/Textual.php'; /** * Decorateur pour avoir les mois en mode text et dans * un langage choisi (FR par defaut) * * @package Framework * @subpackage TimetableDecorators */ class TimetableDecoratorTextualLang extends Calendar_Decorator_Textual { /** * Les mois en lettre et en entier * @var array * @access private */ protected $longMonthArray; /** * Les mois en lettre et abrégés * @var array * @access private */ protected $shortMonthArray; /** * Les jours de la semaine en lettre et en entier * @var array * @access private */ protected $longWeekDayNames; /** * Les jours de la semaine en lettre et en abrégés * @var array * @access private */ protected $shortWeekDayNames; /** * Constructs Calendar_Decorator_Textual_Lang * @param object subclass of Calendar * @access public * @return void */ public function __construct($calendar) { parent::Calendar_Decorator_Textual($calendar); $this->longMonthArray = I18N::getMonthesArray(); $this->shortMonthArray = I18N::getMonthesArray(true); $this->longWeekDayNames = I18N::getDaysArray(); $this->shortWeekDayNames = I18N::getDaysArray(true); } /** * Retourne le jour du mois * @param string $format 'long' ou 'short' * @return string * @access public */ public function thisMonthName($format='long') { $month = Calendar_Decorator_Textual::thisMonth('int'); switch ($format) { case 'long': return $this->longMonthArray[$month]; break; case 'short': return $this->shortMonthArray[$month]; } } /** * Retourne le jour du mois * @param string $format 'long' ou 'short' * @return string * @access public */ public function thisDayName($format='long') { $day = Calendar_Decorator_Textual::thisDayName(); $dayArray = Calendar_Decorator_Textual::weekdayNames(); $d = array_keys($dayArray, $day); switch ($format) { case 'long': return $this->longWeekDayNames[$d[0]]; break; case 'short': return $this->shortWeekDayNames[$d[0]]; } } /** * retourne les mois d'année en francais * @param string $format 'long' ou 'short' * @return string * @access public */ public function monthNames($format='long') { switch ($format){ case 'long': return $this->longMonthArray; break; case 'short': return $this->shortMonthArray; break; } } /** * Retourne les jours de la semaines en francais * @param string $format 'long' ou 'short' * @return string * @access public */ public function weekdayNames($format='long') { return $this->longWeekDayNames; } } ?>
arhe/pwak
lib/Timetable/Decorators/TimetableDecoratorTextualLang.php
PHP
mit
4,112
'use strict'; var crypto = require('crypto'); exports.typeOf = function(obj) { var classToType; if (obj === void 0 || obj === null) { return String(obj); } classToType = { '[object Boolean]': 'boolean', '[object Number]': 'number', '[object String]': 'string', '[object Function]': 'function', '[object Array]': 'array', '[object Date]': 'date', '[object RegExp]': 'regexp', '[object Object]': 'object' }; return classToType[Object.prototype.toString.call(obj)]; }; exports.unauthResp = function(res) { res.statusCode = 401; res.setHeader('content-type', 'application/json; charset=UTF-8'); return res.end(JSON.stringify({ code: 401, error: 'Unauthorized.' })); }; exports.signHook = function(masterKey, hookName, ts) { return ts + ',' + crypto.createHmac('sha1', masterKey).update(hookName + ':' + ts).digest('hex'); }; exports.verifyHookSign = function(masterKey, hookName, sign) { if (sign) { return exports.signHook(masterKey, hookName, sign.split(',')[0]) === sign; } else { return false; } }; /* options: req, user, params, object*/ exports.prepareRequestObject = function(options) { var req = options.req; var user = options.user; var currentUser = user || (req && req.AV && req.AV.user); return { expressReq: req, params: options.params, object: options.object, meta: { remoteAddress: req && req.headers && getRemoteAddress(req) }, user: user, currentUser: currentUser, sessionToken: (currentUser && currentUser.getSessionToken()) || (req && req.sessionToken) }; }; exports.prepareResponseObject = function(res, callback) { return { success: function(result) { callback(null, result); }, error: function(error) { callback(error); } }; }; var getRemoteAddress = exports.getRemoteAddress = function(req) { return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress }; exports.endsWith = function(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; };
CxyYuan/luyoutec_lanyou5_2
node_modules/leanengine/lib/utils.js
JavaScript
mit
2,089
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M17 3H3v18h18V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z" }), 'SaveSharp');
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/SaveSharp.js
JavaScript
mit
278
import fulfillQuery from '../../../src/webserver/db/fulfillQuery' // eslint-disable-line describe('webserver/db/fulfillQuery', () => { it('should work') })
esex/esex
test/webserver/db/fulfillQueryTest.js
JavaScript
mit
159
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\EntityManager\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Event\Observer; use Magento\Framework\Model\AbstractModel; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; /** * Class AfterEntitySave */ class AfterEntitySave implements ObserverInterface { /** * Apply model save operation * * @param Observer $observer * @throws \Magento\Framework\Validator\Exception * @return void */ public function execute(Observer $observer) { $entity = $observer->getEvent()->getEntity(); if ($entity instanceof AbstractModel) { if (method_exists($entity->getResource(), 'loadAllAttributes')) { $entity->getResource()->loadAllAttributes(); } $entity->getResource()->afterSave($entity); $entity->afterSave(); $entity->getResource()->addCommitCallback([$entity, 'afterCommitCallback']); if ($entity->getResource() instanceof AbstractDb) { $entity->getResource()->unserializeFields($entity); } $entity->setHasDataChanges(false); } } }
j-froehlich/magento2_wk
vendor/magento/framework/EntityManager/Observer/AfterEntitySave.php
PHP
mit
1,305
# Doc placeholder module ZimbraRestApi class Cos < ZimbraBase end end
pbruna/zimbra-rest-api
lib/models/cos.rb
Ruby
mit
74
<?php /** * This file is part of Rakuten Web Service SDK * * (c) Rakuten, Inc * * For the full copyright and license information, please view the LICENSE * file that was distributed with source code. */ /** * Http Client that use curl extension * * @package RakutenRws * @subpackage HttpClient */ class RakutenRws_HttpClient_CurlHttpClient extends RakutenRws_HttpClient { protected $curlOptions = array(); public function __construct($options = array()) { $this->curlOptions = $options; } protected function getHandler() { $ch = curl_init(); curl_setopt_array($ch, $this->curlOptions); if ($this->proxy !== null) { curl_setopt($ch, CURLOPT_PROXY, $this->proxy); } curl_setopt($ch, CURLOPT_USERAGENT, 'RakutenWebService SDK for PHP-'.RakutenRws_Client::VERSION); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); return $ch; } protected function makeResponse($url, $params, $curl) { $rawResponse = curl_exec($curl); if ($rawResponse === false) { $msg = curl_error($curl); throw new RakutenRws_Exception('http reqeust error: '.$msg); } $parts = preg_split('/((?:\\r?\\n){2})/', $rawResponse, -1, PREG_SPLIT_DELIM_CAPTURE); for ($i = count($parts) - 3; $i >= 0; $i -= 2) { if (preg_match('/^http\//i', $parts[$i])) { $rawHeaders = $parts[$i]; $contents = implode('', array_slice($parts, $i+2)); break; } } $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); $headers = array(); foreach (preg_split('/\r?\n/', $rawHeaders) as $header) { if (!$header) { continue; } $token = explode(' ', $header); if (1 === strpos($token[0], 'HTTP/')) { $headers = array(); } $headers[] = $header; } return new RakutenRws_HttpResponse( $url, $params, $code, $headers, $contents ); } public function getCurlOptions($options) { return $this->curlOptions; } public function setCurlOptions($options) { $this->curlOptions = $options; } public function get($url, $params = array()) { $requestUrl = $url; if (count($params)) { $requestUrl .= false === strpos($requestUrl, '?') ? '?' : '&'; $requestUrl .= http_build_query($params); } $ch = $this->getHandler(); curl_setopt($ch, CURLOPT_URL, $requestUrl); return $this->makeResponse($url, $params, $ch); } public function post($url, $params = array()) { $ch = $this->getHandler(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); return $this->makeResponse($url, $params, $ch); } }
BookShuffle/bookshuffle.cloud.net
vendor/rakuten-ws/rws-php-sdk/lib/RakutenRws/HttpClient/CurlHttpClient.php
PHP
mit
3,227
 // .\Release\x64\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=FastSinCos // NOLINT(whitespace/line_length) #include "numerics/fast_sin_cos_2π.hpp" #include <pmmintrin.h> #include <random> #include <vector> #include "benchmark/benchmark.h" #include "quantities/numbers.hpp" namespace principia { namespace numerics { namespace { // Returns a value which has a data dependency on both cos_2πx and sin_2πx. // The result is (cos_2πx bitand cos_mask) bitxor sin_2πx. // The latency is between 1 and 2 cycles: at worst this is an and and an xor, at // best the xor can only be computed given both trigonometric lines. double MixTrigonometricLines(double cos_2πx, double sin_2πx, __m128d const cos_mask) { __m128d const cos_bits = _mm_and_pd(_mm_set_sd(cos_2πx), cos_mask); __m128d const sin_all_bits = _mm_set_sd(sin_2πx); __m128d const mixed_bits = _mm_xor_pd(cos_bits, sin_all_bits); return _mm_cvtsd_f64(mixed_bits); } static const __m128d mantissa_bits = _mm_castsi128_pd(_mm_cvtsi64_si128(0x000F'FFFF'FFFF'FFFF)); // When iterated, the quadrant of the result is unbiased. double ThoroughlyMixTrigonometricLines(double cos_2πx, double sin_2πx) { return MixTrigonometricLines(cos_2πx, sin_2πx, mantissa_bits); } static const __m128d mantissa_bits_and_5_bits_of_exponent = _mm_castsi128_pd(_mm_cvtsi64_si128(0x01FF'FFFF'FFFF'FFFF)); // Same as above, but when iterated, the result is quickly confined to [0, 1/8]. double PoorlyMixTrigonometricLines(double cos_2πx, double sin_2πx) { return MixTrigonometricLines( cos_2πx, sin_2πx, mantissa_bits_and_5_bits_of_exponent); } } // namespace void BM_FastSinCos2πPoorlyPredictedLatency(benchmark::State& state) { for (auto _ : state) { double sin = π; double cos = 0.0; for (int i = 0; i < 1e3; ++i) { FastSinCos2π(ThoroughlyMixTrigonometricLines(cos, sin), sin, cos); } } } void BM_FastSinCos2πWellPredictedLatency(benchmark::State& state) { for (auto _ : state) { double sin = π; double cos = 0.0; for (int i = 0; i < 1e3; ++i) { FastSinCos2π(PoorlyMixTrigonometricLines(cos, sin), sin, cos); } } } void BM_FastSinCos2πThroughput(benchmark::State& state) { std::mt19937_64 random(42); std::uniform_real_distribution<> distribution(-1.0, 1.0); std::vector<double> input; for (int i = 0; i < 1e3; ++i) { input.push_back(distribution(random)); } for (auto _ : state) { double sin; double cos; for (double const x : input) { FastSinCos2π(x, sin, cos); } benchmark::DoNotOptimize(sin); benchmark::DoNotOptimize(cos); } } BENCHMARK(BM_FastSinCos2πPoorlyPredictedLatency)->Unit(benchmark::kMicrosecond); BENCHMARK(BM_FastSinCos2πWellPredictedLatency)->Unit(benchmark::kMicrosecond); BENCHMARK(BM_FastSinCos2πThroughput)->Unit(benchmark::kMicrosecond); } // namespace numerics } // namespace principia
mockingbirdnest/Principia
benchmarks/fast_sin_cos_2π_benchmark.cpp
C++
mit
3,010
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// HttpFailure operations. /// </summary> public partial class HttpFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpFailure { /// <summary> /// Initializes a new instance of the HttpFailure class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public HttpFailure(AutoRestHttpInfrastructureTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestHttpInfrastructureTestService /// </summary> public AutoRestHttpInfrastructureTestService Client { get; private set; } /// <summary> /// Get empty error form server /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<bool?>> GetEmptyErrorWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmptyError", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/emptybody/error").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get empty error form server /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<bool?>> GetNoModelErrorWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNoModelError", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/error").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get empty response from server /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<bool?>> GetNoModelEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNoModelEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/empty").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
yugangw-msft/autorest
src/generator/AutoRest.CSharp.Tests/Expected/AcceptanceTests/Http/HttpFailure.cs
C#
mit
18,043
<?php namespace Platformsh\Cli\Command\Variable; use Platformsh\Cli\Command\PlatformCommand; use Platformsh\Client\Model\Variable; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class VariableGetCommand extends PlatformCommand { /** * {@inheritdoc} */ protected function configure() { $this ->setName('variable:get') ->setAliases(array('variables', 'vget')) ->addArgument('name', InputArgument::OPTIONAL, 'The name of the variable') ->addOption('pipe', null, InputOption::VALUE_NONE, 'Output the full variable value only') ->addOption('ssh', null, InputOption::VALUE_NONE, 'Use SSH to get the currently active variables') ->setDescription('Get a variable for an environment'); $this->addProjectOption() ->addEnvironmentOption(); $this->addExample('Get the variable "example"', 'example'); } protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); // @todo This --ssh option is only here as a temporary workaround. if ($input->getOption('ssh')) { $shellHelper = $this->getHelper('shell'); $platformVariables = $shellHelper->execute( array( 'ssh', $this->getSelectedEnvironment() ->getSshUrl(), 'echo $PLATFORM_VARIABLES', ), true ); $results = json_decode(base64_decode($platformVariables), true); foreach ($results as $id => $value) { if (!is_scalar($value)) { $value = json_encode($value); } $output->writeln("$id\t$value"); } return 0; } $name = $input->getArgument('name'); if ($name) { $variable = $this->getSelectedEnvironment() ->getVariable($name); if (!$variable) { $this->stdErr->writeln("Variable not found: <error>$name</error>"); return 1; } $results = array($variable); } else { $results = $this->getSelectedEnvironment() ->getVariables(); if (!$results) { $this->stdErr->writeln('No variables found'); return 1; } } if ($input->getOption('pipe')) { foreach ($results as $variable) { $output->writeln($variable['id'] . "\t" . $variable['value']); } } else { $table = $this->buildVariablesTable($results, $output); $table->render(); } return 0; } /** * @param Variable[] $variables * @param OutputInterface $output * * @return Table */ protected function buildVariablesTable(array $variables, OutputInterface $output) { $table = new Table($output); $table->setHeaders(array("ID", "Value", "Inherited", "JSON")); foreach ($variables as $variable) { $value = $variable['value']; // Truncate long values. if (strlen($value) > 60) { $value = substr($value, 0, 57) . '...'; } // Wrap long values. $value = wordwrap($value, 30, "\n", true); $table->addRow( array( $variable['id'], $value, $variable['inherited'] ? 'Yes' : 'No', $variable['is_json'] ? 'Yes' : 'No', ) ); } return $table; } }
Fredplais/platformsh-cli
src/Command/Variable/VariableGetCommand.php
PHP
mit
3,918
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoingui.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "notificator.h" #include "openuridialog.h" #include "optionsdialog.h" #include "optionsmodel.h" #include "rpcconsole.h" #include "utilitydialog.h" #ifdef ENABLE_WALLET #include "walletframe.h" #include "walletmodel.h" #endif #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #include "init.h" #include "ui_interface.h" #include <iostream> #include <QApplication> #include <QDateTime> #include <QDesktopWidget> #include <QDragEnterEvent> #include <QIcon> #include <QLabel> #include <QListWidget> #include <QMenu> #include <QMenuBar> #include <QMessageBox> #include <QMimeData> #include <QProgressBar> #include <QSettings> #include <QStackedWidget> #include <QStatusBar> #include <QStyle> #include <QTimer> #include <QToolBar> #include <QVBoxLayout> #if QT_VERSION < 0x050000 #include <QUrl> #include <QTextDocument> #else #include <QUrlQuery> #endif const QString BitcoinGUI::DEFAULT_WALLET = "~Default"; BitcoinGUI::BitcoinGUI(bool fIsTestnet, QWidget *parent) : QMainWindow(parent), clientModel(0), walletFrame(0), encryptWalletAction(0), changePassphraseAction(0), aboutQtAction(0), trayIcon(0), notificator(0), rpcConsole(0), prevBlocks(0), spinnerFrame(0) { GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this); QString windowTitle = tr("Riecoin Core") + " - "; #ifdef ENABLE_WALLET /* if compiled with wallet support, -disablewallet can still disable the wallet */ bool enableWallet = !GetBoolArg("-disablewallet", false); #else bool enableWallet = false; #endif if(enableWallet) { windowTitle += tr("Wallet"); } else { windowTitle += tr("Node"); } if (!fIsTestnet) { #ifndef Q_OS_MAC QApplication::setWindowIcon(QIcon(":icons/riecoin")); setWindowIcon(QIcon(":icons/riecoin")); #else MacDockIconHandler::instance()->setIcon(QIcon(":icons/riecoin")); #endif } else { windowTitle += " " + tr("[testnet]"); #ifndef Q_OS_MAC QApplication::setWindowIcon(QIcon(":icons/riecoin_testnet")); setWindowIcon(QIcon(":icons/riecoin_testnet")); #else MacDockIconHandler::instance()->setIcon(QIcon(":icons/riecoin_testnet")); #endif } setWindowTitle(windowTitle); #if defined(Q_OS_MAC) && QT_VERSION < 0x050000 // This property is not implemented in Qt 5. Setting it has no effect. // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras. setUnifiedTitleAndToolBarOnMac(true); #endif rpcConsole = new RPCConsole(enableWallet ? this : 0); #ifdef ENABLE_WALLET if(enableWallet) { /** Create wallet frame and make it the central widget */ walletFrame = new WalletFrame(this); setCentralWidget(walletFrame); } else #endif { /* When compiled without wallet or -disablewallet is provided, * the central widget is the rpc console. */ setCentralWidget(rpcConsole); } // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(fIsTestnet); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(fIsTestnet); // Create status bar statusBar(); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); labelEncryptionIcon = new QLabel(); labelConnectionsIcon = new QLabel(); labelBlocksIcon = new QLabel(); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(false); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show())); // prevents an oben debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); // Subscribe to notifications from core subscribeToCoreSignals(); } BitcoinGUI::~BitcoinGUI() { // Unsubscribe from notifications from core unsubscribeFromCoreSignals(); GUIUtil::saveWindowGeometry("nWindow", this); if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete appMenuBar; MacDockIconHandler::instance()->setMainWindow(NULL); #endif } void BitcoinGUI::createActions(bool fIsTestnet) { QActionGroup *tabGroup = new QActionGroup(this); overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setStatusTip(tr("Show general overview of wallet")); overviewAction->setToolTip(overviewAction->statusTip()); overviewAction->setCheckable(true); overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this); sendCoinsAction->setStatusTip(tr("Send coins to a Riecoin address")); sendCoinsAction->setToolTip(sendCoinsAction->statusTip()); sendCoinsAction->setCheckable(true); sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); tabGroup->addAction(sendCoinsAction); receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this); receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and riecoin: URIs)")); receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip()); receiveCoinsAction->setCheckable(true); receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); tabGroup->addAction(receiveCoinsAction); historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setStatusTip(tr("Browse transaction history")); historyAction->setToolTip(historyAction->statusTip()); historyAction->setCheckable(true); historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); tabGroup->addAction(historyAction); // These showNormalIfMinimized are needed because Send Coins and Receive Coins // can be triggered from the tray menu, and need to show the GUI to be useful. connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); if (!fIsTestnet) aboutAction = new QAction(QIcon(":/icons/riecoin"), tr("&About Riecoin Core"), this); else aboutAction = new QAction(QIcon(":/icons/riecoin_testnet"), tr("&About Riecoin Core"), this); aboutAction->setStatusTip(tr("Show information about Riecoin")); aboutAction->setMenuRole(QAction::AboutRole); #if QT_VERSION < 0x050000 aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); #else aboutQtAction = new QAction(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); #endif aboutQtAction->setStatusTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setStatusTip(tr("Modify configuration options for Riecoin")); optionsAction->setMenuRole(QAction::PreferencesRole); if (!fIsTestnet) toggleHideAction = new QAction(QIcon(":/icons/riecoin"), tr("&Show / Hide"), this); else toggleHideAction = new QAction(QIcon(":/icons/riecoin_testnet"), tr("&Show / Hide"), this); toggleHideAction->setStatusTip(tr("Show or hide the main Window")); encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setStatusTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption")); signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this); signMessageAction->setStatusTip(tr("Sign messages with your Riecoin addresses to prove you own them")); verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this); verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Riecoin addresses")); openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this); openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console")); usedSendingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Sending addresses..."), this); usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels")); usedReceivingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Receiving addresses..."), this); usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels")); openAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_FileIcon), tr("Open &URI..."), this); openAction->setStatusTip(tr("Open a Riecoin: URI or payment request")); showHelpMessageAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Command-line options"), this); showHelpMessageAction->setStatusTip(tr("Show the Riecoin Core help message to get a list with possible Riecoin command-line options")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden())); connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked())); #ifdef ENABLE_WALLET if(walletFrame) { connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses())); connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses())); connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked())); } #endif } void BitcoinGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu *file = appMenuBar->addMenu(tr("&File")); if(walletFrame) { file->addAction(openAction); file->addAction(backupWalletAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); file->addAction(usedSendingAddressesAction); file->addAction(usedReceivingAddressesAction); file->addSeparator(); } file->addAction(quitAction); QMenu *settings = appMenuBar->addMenu(tr("&Settings")); if(walletFrame) { settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addSeparator(); } settings->addAction(optionsAction); QMenu *help = appMenuBar->addMenu(tr("&Help")); if(walletFrame) { help->addAction(openRPCConsoleAction); } help->addAction(showHelpMessageAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); } void BitcoinGUI::createToolBars() { if(walletFrame) { QToolBar *toolbar = addToolBar(tr("Tabs toolbar")); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); overviewAction->setChecked(true); } } void BitcoinGUI::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; if(clientModel) { // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions, // while the client has not yet fully loaded createTrayIconMenu(); // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers()); connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Receive and report messages from client model connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int))); rpcConsole->setClientModel(clientModel); #ifdef ENABLE_WALLET if(walletFrame) { walletFrame->setClientModel(clientModel); } #endif } } #ifdef ENABLE_WALLET bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel) { if(!walletFrame) return false; setWalletActionsEnabled(true); return walletFrame->addWallet(name, walletModel); } bool BitcoinGUI::setCurrentWallet(const QString& name) { if(!walletFrame) return false; return walletFrame->setCurrentWallet(name); } void BitcoinGUI::removeAllWallets() { if(!walletFrame) return; setWalletActionsEnabled(false); walletFrame->removeAllWallets(); } #endif void BitcoinGUI::setWalletActionsEnabled(bool enabled) { overviewAction->setEnabled(enabled); sendCoinsAction->setEnabled(enabled); receiveCoinsAction->setEnabled(enabled); historyAction->setEnabled(enabled); encryptWalletAction->setEnabled(enabled); backupWalletAction->setEnabled(enabled); changePassphraseAction->setEnabled(enabled); signMessageAction->setEnabled(enabled); verifyMessageAction->setEnabled(enabled); usedSendingAddressesAction->setEnabled(enabled); usedReceivingAddressesAction->setEnabled(enabled); openAction->setEnabled(enabled); } void BitcoinGUI::createTrayIcon(bool fIsTestnet) { #ifndef Q_OS_MAC trayIcon = new QSystemTrayIcon(this); if (!fIsTestnet) { trayIcon->setToolTip(tr("Riecoin client")); trayIcon->setIcon(QIcon(":/icons/toolbar")); } else { trayIcon->setToolTip(tr("Riecoin client") + " " + tr("[testnet]")); trayIcon->setIcon(QIcon(":/icons/toolbar_testnet")); } trayIcon->show(); #endif notificator = new Notificator(QApplication::applicationName(), trayIcon, this); } void BitcoinGUI::createTrayIconMenu() { QMenu *trayIconMenu; #ifndef Q_OS_MAC // return if trayIcon is unset (only on non-Mac OSes) if (!trayIcon) return; trayIconMenu = new QMenu(this); trayIcon->setContextMenu(trayIconMenu); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); #else // Note: On Mac, the dock icon is used to provide the tray's functionality. MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance(); dockIconHandler->setMainWindow((QMainWindow *)this); trayIconMenu = dockIconHandler->dockMenu(); #endif // Configuration of the tray icon (or dock icon) icon menu trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(sendCoinsAction); trayIconMenu->addAction(receiveCoinsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(optionsAction); trayIconMenu->addAction(openRPCConsoleAction); #ifndef Q_OS_MAC // This is built-in on Mac trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif } #ifndef Q_OS_MAC void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHideAction->trigger(); } } #endif void BitcoinGUI::optionsClicked() { if(!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg(this); dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { if(!clientModel) return; AboutDialog dlg(this); dlg.setModel(clientModel); dlg.exec(); } void BitcoinGUI::showHelpMessageClicked() { HelpMessageDialog *help = new HelpMessageDialog(this); help->setAttribute(Qt::WA_DeleteOnClose); help->show(); } #ifdef ENABLE_WALLET void BitcoinGUI::openClicked() { OpenURIDialog dlg(this); if(dlg.exec()) { emit receivedURI(dlg.getURI()); } } void BitcoinGUI::gotoOverviewPage() { overviewAction->setChecked(true); if (walletFrame) walletFrame->gotoOverviewPage(); } void BitcoinGUI::gotoHistoryPage() { historyAction->setChecked(true); if (walletFrame) walletFrame->gotoHistoryPage(); } void BitcoinGUI::gotoReceiveCoinsPage() { receiveCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoReceiveCoinsPage(); } void BitcoinGUI::gotoSendCoinsPage(QString addr) { sendCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoSendCoinsPage(addr); } void BitcoinGUI::gotoSignMessageTab(QString addr) { if (walletFrame) walletFrame->gotoSignMessageTab(addr); } void BitcoinGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } #endif void BitcoinGUI::setNumConnections(int count) { QString icon; switch(count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Riecoin network", "", count)); } void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks) { // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text) statusBar()->clearMessage(); // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); switch (blockSource) { case BLOCK_SOURCE_NETWORK: progressBarLabel->setText(tr("Synchronizing with network...")); break; case BLOCK_SOURCE_DISK: progressBarLabel->setText(tr("Importing blocks from disk...")); break; case BLOCK_SOURCE_REINDEX: progressBarLabel->setText(tr("Reindexing blocks on disk...")); break; case BLOCK_SOURCE_NONE: // Case: not Importing, not Reindexing and no network connection progressBarLabel->setText(tr("No block source available...")); break; } QString tooltip; QDateTime lastBlockDate = clientModel->getLastBlockDate(); QDateTime currentDate = QDateTime::currentDateTime(); int secs = lastBlockDate.secsTo(currentDate); if(count < nTotalBlocks) { tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks); } else { tooltip = tr("Processed %1 blocks of transaction history.").arg(count); } // Set icon state: spinning if catching up, tick otherwise if(secs < 90*60 && count >= nTotalBlocks) { tooltip = tr("Up to date") + QString(".<br>") + tooltip; labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); #ifdef ENABLE_WALLET if(walletFrame) walletFrame->showOutOfSyncWarning(false); #endif progressBarLabel->setVisible(false); progressBar->setVisible(false); } else { // Represent time from last generated block in human readable text QString timeBehindText; const int HOUR_IN_SECONDS = 60*60; const int DAY_IN_SECONDS = 24*60*60; const int WEEK_IN_SECONDS = 7*24*60*60; const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar if(secs < 2*DAY_IN_SECONDS) { timeBehindText = tr("%n hour(s)","",secs/HOUR_IN_SECONDS); } else if(secs < 2*WEEK_IN_SECONDS) { timeBehindText = tr("%n day(s)","",secs/DAY_IN_SECONDS); } else if(secs < YEAR_IN_SECONDS) { timeBehindText = tr("%n week(s)","",secs/WEEK_IN_SECONDS); } else { int years = secs / YEAR_IN_SECONDS; int remainder = secs % YEAR_IN_SECONDS; timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)","", remainder/WEEK_IN_SECONDS)); } progressBarLabel->setVisible(true); progressBar->setFormat(tr("%1 behind").arg(timeBehindText)); progressBar->setMaximum(1000000000); progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5); progressBar->setVisible(true); tooltip = tr("Catching up...") + QString("<br>") + tooltip; if(count != prevBlocks) { labelBlocksIcon->setPixmap(QIcon(QString( ":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0'))) .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES; } prevBlocks = count; #ifdef ENABLE_WALLET if(walletFrame) walletFrame->showOutOfSyncWarning(true); #endif tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); tooltip += QString("<br>"); tooltip += tr("Transactions after this will not yet be visible."); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret) { QString strTitle = tr("Riecoin"); // default title // Default to information icon int nMBoxIcon = QMessageBox::Information; int nNotifyIcon = Notificator::Information; QString msgType; // Prefer supplied title over style based title if (!title.isEmpty()) { msgType = title; } else { switch (style) { case CClientUIInterface::MSG_ERROR: msgType = tr("Error"); break; case CClientUIInterface::MSG_WARNING: msgType = tr("Warning"); break; case CClientUIInterface::MSG_INFORMATION: msgType = tr("Information"); break; default: break; } } // Append title to "Riecoin - " if (!msgType.isEmpty()) strTitle += " - " + msgType; // Check for error/warning icon if (style & CClientUIInterface::ICON_ERROR) { nMBoxIcon = QMessageBox::Critical; nNotifyIcon = Notificator::Critical; } else if (style & CClientUIInterface::ICON_WARNING) { nMBoxIcon = QMessageBox::Warning; nNotifyIcon = Notificator::Warning; } // Display message if (style & CClientUIInterface::MODAL) { // Check for buttons, use OK as default, if none was supplied QMessageBox::StandardButton buttons; if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK))) buttons = QMessageBox::Ok; // Ensure we get users attention, but only if main window is visible // as we don't want to pop up the main window for messages that happen before // initialization is finished. if(!(style & CClientUIInterface::NOSHOWGUI)) showNormalIfMinimized(); QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this); int r = mBox.exec(); if (ret != NULL) *ret = r == QMessageBox::Ok; } else notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message); } void BitcoinGUI::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if(e->type() == QEvent::WindowStateChange) { if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e); if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, SLOT(hide())); e->ignore(); } } } #endif } void BitcoinGUI::closeEvent(QCloseEvent *event) { if(clientModel) { #ifndef Q_OS_MAC // Ignored on Mac if(!clientModel->getOptionsModel()->getMinimizeToTray() && !clientModel->getOptionsModel()->getMinimizeOnClose()) { QApplication::quit(); } #endif } QMainWindow::closeEvent(event); } #ifdef ENABLE_WALLET void BitcoinGUI::incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address) { // On new transaction, make an info balloon message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"), tr("Date: %1\n" "Amount: %2\n" "Type: %3\n" "Address: %4\n") .arg(date) .arg(BitcoinUnits::formatWithUnit(unit, amount, true)) .arg(type) .arg(address), CClientUIInterface::MSG_INFORMATION); } #endif void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event) { // Accept only URIs if(event->mimeData()->hasUrls()) event->acceptProposedAction(); } void BitcoinGUI::dropEvent(QDropEvent *event) { if(event->mimeData()->hasUrls()) { foreach(const QUrl &uri, event->mimeData()->urls()) { emit receivedURI(uri.toString()); } } event->acceptProposedAction(); } bool BitcoinGUI::eventFilter(QObject *object, QEvent *event) { // Catch status tip events if (event->type() == QEvent::StatusTip) { // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff if (progressBarLabel->isVisible() || progressBar->isVisible()) return true; } return QMainWindow::eventFilter(object, event); } #ifdef ENABLE_WALLET bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient) { // URI has to be valid if (walletFrame && walletFrame->handlePaymentRequest(recipient)) { showNormalIfMinimized(); gotoSendCoinsPage(); return true; } else return false; } void BitcoinGUI::setEncryptionStatus(int status) { switch(status) { case WalletModel::Unencrypted: labelEncryptionIcon->hide(); encryptWalletAction->setChecked(false); changePassphraseAction->setEnabled(false); encryptWalletAction->setEnabled(true); break; case WalletModel::Unlocked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::Locked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } } #endif void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { // activateWindow() (sometimes) helps with keyboard focus on Windows if (isHidden()) { show(); activateWindow(); } else if (isMinimized()) { showNormal(); activateWindow(); } else if (GUIUtil::isObscured(this)) { raise(); activateWindow(); } else if(fToggleHidden) hide(); } void BitcoinGUI::toggleHidden() { showNormalIfMinimized(true); } void BitcoinGUI::detectShutdown() { if (ShutdownRequested()) { if(rpcConsole) rpcConsole->hide(); qApp->quit(); } } static bool ThreadSafeMessageBox(BitcoinGUI *gui, const std::string& message, const std::string& caption, unsigned int style) { bool modal = (style & CClientUIInterface::MODAL); bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(gui, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } void BitcoinGUI::subscribeToCoreSignals() { // Connect signals to client uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); } void BitcoinGUI::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); }
NeosStore/riecoin-master
src/qt/bitcoingui.cpp
C++
mit
34,089
'use strict'; var Foundationify = (function () { // Initalize product image gallery function on product pages function initProductImages() { // Define the scope var $productImages = $('#product-images', 'body.product'); // Select the thumbnails var $thumbs = $('ul img', $productImages); if ($thumbs.length) { // Select the large image var $largeImage = $('img', $productImages).first(); // Change the large image src and alt attributes on click $thumbs.on('click', function (e) { e.preventDefault(); // Skip if thumb matches large if ($largeImage.attr('src') === $(this).parent('a').attr('href')) { return; } // Change the cursor to the loading cursor $('body').css('cursor', 'progress'); // Change the src and alt attributes of the large image $largeImage.attr('src', $(this).parent('a').attr('href')) .attr('alt', $(this).attr('alt')); }); // Return the loading cursor to default after the large image has loaded $largeImage.on('load', function () { $('body').css('cursor', 'auto'); }); } } return { init: function () { initProductImages(); } }; }()); $(document).ready(function () { Foundationify.init(); });
Leland/foundationify
src/scripts/main.js
JavaScript
mit
1,229
using System; using System.Diagnostics.CodeAnalysis; namespace GenFx.Validation { /// <summary> /// Represents an <see cref="Attribute"/> that describes how a target <see cref="GeneticComponent"/> should be validated. /// </summary> /// <remarks> /// Attributes that implement this interface can be attached to components that need to describe /// how validation should be done for some other component when the attributed component is being used. /// Note to developers: if creating your own <see cref="ComponentValidatorAttribute"/>, it is a best /// practice to also create a version of the attribute that implements the <see cref="IExternalComponentValidatorAttribute"/> /// interface. This allows third-party developers to use your attribute like they would a built-in GenFx attribute. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public interface IExternalComponentValidatorAttribute { /// <summary> /// Gets the <see cref="Type"/> of the component to be validated. /// </summary> Type TargetComponentType { get; } /// <summary> /// Gets the validator used to verify the <see cref="GeneticComponent"/>. /// </summary> ComponentValidator Validator { get; } } }
mthalman/GenFx
src/GenFx/Validation/IExternalComponentValidatorAttribute.cs
C#
mit
1,406
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wagtaildocs', '0003_add_verbose_names'), ('articles', '0075_auto_20151015_2022'), ] operations = [ migrations.AddField( model_name='articlepage', name='video_document', field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtaildocs.Document', null=True), ), ]
CIGIHub/greyjay
greyjay/articles/migrations/0076_articlepage_video_document.py
Python
mit
598
<?php namespace CodeIgniter\HTTP; /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2017, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author CodeIgniter Dev Team * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/) * @license https://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 3.0.0 * @filesource */ /** * Representation of an iHTTP request. * */ class Request extends Message implements RequestInterface { /** * IP address of the current user. * * @var string */ protected $ipAddress = ''; /** * Proxy IPs * * @var type */ protected $proxyIPs; //-------------------------------------------------------------------- /** * Constructor. * * @param type $config */ public function __construct($config) { $this->proxyIPs = $config->proxyIPs; } //-------------------------------------------------------------------- /** * Gets the user's IP address. * * @return string IP address */ public function getIPAddress(): string { if (! empty($this->ipAddress)) { return $this->ipAddress; } $proxy_ips = $this->proxyIPs; if ( ! empty($this->proxyIPs) && ! is_array($this->proxyIPs)) { $proxy_ips = explode(',', str_replace(' ', '', $this->proxyIPs)); } $this->ipAddress = $this->getServer('REMOTE_ADDR'); if ($proxy_ips) { foreach (array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP') as $header) { if (($spoof = $this->getServer($header)) !== NULL) { // Some proxies typically list the whole chain of IP // addresses through which the client has reached us. // e.g. client_ip, proxy_ip1, proxy_ip2, etc. sscanf($spoof, '%[^,]', $spoof); if ( ! $this->isValidIP($spoof)) { $spoof = NULL; } else { break; } } } if ($spoof) { for ($i = 0, $c = count($this->proxyIPs); $i < $c; $i++) { // Check if we have an IP address or a subnet if (strpos($proxy_ips[$i], '/') === FALSE) { // An IP address (and not a subnet) is specified. // We can compare right away. if ($proxy_ips[$i] === $this->ipAddress) { $this->ipAddress = $spoof; break; } continue; } // We have a subnet ... now the heavy lifting begins isset($separator) OR $separator = $this->isValidIP($this->ipAddress, 'ipv6') ? ':' : '.'; // If the proxy entry doesn't match the IP protocol - skip it if (strpos($proxy_ips[$i], $separator) === FALSE) { continue; } // Convert the REMOTE_ADDR IP address to binary, if needed if ( ! isset($ip, $sprintf)) { if ($separator === ':') { // Make sure we're have the "full" IPv6 format $ip = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($this->ipAddress, ':')), $this->ipAddress ) ); for ($j = 0; $j < 8; $j++) { $ip[$j] = intval($ip[$j], 16); } $sprintf = '%016b%016b%016b%016b%016b%016b%016b%016b'; } else { $ip = explode('.', $this->ipAddress); $sprintf = '%08b%08b%08b%08b'; } $ip = vsprintf($sprintf, $ip); } // Split the netmask length off the network address sscanf($proxy_ips[$i], '%[^/]/%d', $netaddr, $masklen); // Again, an IPv6 address is most likely in a compressed form if ($separator === ':') { $netaddr = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($netaddr, ':')), $netaddr)); for ($i = 0; $i < 8; $i++) { $netaddr[$i] = intval($netaddr[$i], 16); } } else { $netaddr = explode('.', $netaddr); } // Convert to binary and finally compare if (strncmp($ip, vsprintf($sprintf, $netaddr), $masklen) === 0) { $this->ipAddress = $spoof; break; } } } } if ( ! $this->isValidIP($this->ipAddress)) { return $this->ipAddress = '0.0.0.0'; } return empty($this->ipAddress) ? '' : $this->ipAddress; } //-------------------------------------------------------------------- /** * Validate an IP address * * @param $ip IP Address * @param string $which IP protocol: 'ipv4' or 'ipv6' * * @return bool */ public function isValidIP(string $ip, string $which = null): bool { switch (strtolower($which)) { case 'ipv4': $which = FILTER_FLAG_IPV4; break; case 'ipv6': $which = FILTER_FLAG_IPV6; break; default: $which = NULL; break; } return (bool) filter_var($ip, FILTER_VALIDATE_IP, $which); } //-------------------------------------------------------------------- /** * Get the request method. * * @param bool|false $upper Whether to return in upper or lower case. * * @return string */ public function getMethod($upper = false): string { return ($upper) ? strtoupper($this->getServer('REQUEST_METHOD')) : strtolower($this->getServer('REQUEST_METHOD')); } //-------------------------------------------------------------------- /** * Fetch an item from the $_SERVER array. * * @param null $index Index for item to be fetched from $_SERVER * @param null $filter A filter name to be applied * @return mixed */ public function getServer($index = null, $filter = null) { return $this->fetchGlobal(INPUT_SERVER, $index, $filter); } //-------------------------------------------------------------------- /** * Fetch an item from the $_ENV array. * * @param null $index Index for item to be fetched from $_ENV * @param null $filter A filter name to be applied * @return mixed */ public function getEnv($index = null, $filter = null) { return $this->fetchGlobal(INPUT_ENV, $index, $filter); } //-------------------------------------------------------------------- /** * Fetches one or more items from a global, like cookies, get, post, etc. * Can optionally filter the input when you retrieve it by passing in * a filter. * * If $type is an array, it must conform to the input allowed by the * filter_input_array method. * * http://php.net/manual/en/filter.filters.sanitize.php * * @param $type * @param null $index * @param null $filter * * @return mixed */ protected function fetchGlobal($type, $index = null, $filter = null) { // Null filters cause null values to return. if (is_null($filter)) { $filter = FILTER_DEFAULT; } // If $index is null, it means that the whole input type array is requested if (is_null($index)) { $loopThrough = []; switch ($type) { case INPUT_GET : $loopThrough = $_GET; break; case INPUT_POST : $loopThrough = $_POST; break; case INPUT_COOKIE : $loopThrough = $_COOKIE; break; case INPUT_SERVER : $loopThrough = $_SERVER; break; case INPUT_ENV : $loopThrough = $_ENV; break; } $values = []; foreach ($loopThrough as $key => $value) { $values[$key] = is_array($value) ? $this->fetchGlobal($type, $key, $filter) : filter_var($value, $filter); } return $values; } // allow fetching multiple keys at once if (is_array($index)) { $output = []; foreach ($index as $key) { $output[$key] = $this->fetchGlobal($type, $key, $filter); } return $output; } // // // Does the index contain array notation? // if (($count = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $index, $matches)) > 1) // Does the index contain array notation // { // $value = $array; // for ($i = 0; $i < $count; $i++) // { // $key = trim($matches[0][$i], '[]'); // if ($key === '') // Empty notation will return the value as array // { // break; // } // // if (isset($value[$key])) // { // $value = $value[$key]; // } // else // { // return NULL; // } // } // } // Due to issues with FastCGI and testing, // we need to do these all manually instead // of the simpler filter_input(); switch ($type) { case INPUT_GET: $value = $_GET[$index] ?? null; break; case INPUT_POST: $value = $_POST[$index] ?? null; break; case INPUT_SERVER: $value = $_SERVER[$index] ?? null; break; case INPUT_ENV: $value = $_ENV[$index] ?? null; break; case INPUT_COOKIE: $value = $_COOKIE[$index] ?? null; break; case INPUT_REQUEST: $value = $_REQUEST[$index] ?? null; break; case INPUT_SESSION: $value = $_SESSION[$index] ?? null; break; default: $value = ''; } if (is_array($value) || is_object($value) || is_null($value)) { return $value; } return filter_var($value, $filter); } //-------------------------------------------------------------------- }
wuzheng40/CodeIgniter4
system/HTTP/Request.php
PHP
mit
10,113
"use strict"; var SourceLine_1 = require("../source/SourceLine"); var Prop_1 = require("../entities/Prop"); var Method_1 = require("../entities/Method"); var MethodKind_1 = require("../kind/MethodKind"); var ProgramError_1 = require("../errors/ProgramError"); var ClassDefn_1 = require("../define/ClassDefn"); var StructDefn_1 = require("../define/StructDefn"); var CONST_1 = require("../CONST"); var PropQual_1 = require("../entities/PropQual"); var ParamParser_1 = require("../parser/ParamParser"); /** * Created by Nidin Vinayakan on 4/7/2016. */ var DefinitionService = (function () { function DefinitionService() { } /** * Collect all definitions from the source code * */ DefinitionService.prototype.collectDefinitions = function (filename, lines) { var _this = this; var defs = []; var turboLines = []; var i = 0; var numLines = lines.length; var line; while (i < numLines) { line = lines[i++]; if (!CONST_1.Matcher.START.test(line)) { turboLines.push(new SourceLine_1.SourceLine(filename, i, line)); continue; } var kind = ""; var name_1 = ""; var inherit = ""; var lineNumber = i; var m = null; if (m = CONST_1.Matcher.STRUCT.exec(line)) { kind = "struct"; name_1 = m[1]; } else if (m = CONST_1.Matcher.CLASS.exec(line)) { kind = "class"; name_1 = m[1]; inherit = m[2] ? m[2] : ""; } else { throw new ProgramError_1.ProgramError(filename, i, "Syntax error: Malformed definition line"); } var properties = []; var methods = []; var in_method = false; var mbody = null; var method_type = MethodKind_1.MethodKind.Virtual; var method_name = ""; var method_line = 0; var method_signature = null; // Do not check for duplicate names here since that needs to // take into account inheritance. while (i < numLines) { line = lines[i++]; if (CONST_1.Matcher.END.test(line)) { break; } if (m = CONST_1.Matcher.METHOD.exec(line.trim())) { if (kind != "class") { throw new ProgramError_1.ProgramError(filename, i, "@method is only allowed in classes"); } if (in_method) { methods.push(new Method_1.Method(method_line, method_type, method_name, method_signature, mbody)); } in_method = true; method_line = i; method_type = (m[1] == "method" ? MethodKind_1.MethodKind.NonVirtual : MethodKind_1.MethodKind.Virtual); method_name = m[2]; // Parse the signature. Just use the param parser for now, // but note that what we get back will need postprocessing. var pp = new ParamParser_1.ParamParser(filename, i, m[3], /* skip left paren */ 1); var args = pp.allArgs(); args.shift(); // Discard SELF // Issue #15: In principle there are two signatures here: there is the // parameter signature, which we should keep intact in the // virtual, and there is the set of arguments extracted from that, // including any splat. method_signature = args.map(function (x) { return _this.parameterToArgument(filename, i, x); }); mbody = [m[3]]; } else if (m = CONST_1.Matcher.SPECIAL.exec(line.trim())) { if (kind != "struct") throw new ProgramError_1.ProgramError(filename, i, "@" + m[1] + " is only allowed in structs"); if (in_method) methods.push(new Method_1.Method(method_line, method_type, method_name, method_signature, mbody)); method_line = i; in_method = true; switch (m[1]) { case "get": method_type = MethodKind_1.MethodKind.Get; break; case "set": method_type = MethodKind_1.MethodKind.Set; break; } method_name = ""; method_signature = null; mbody = [m[2]]; } else if (in_method) { // TODO: if we're going to be collecting random cruft // then blank and comment lines at the end of a method // really should be placed at the beginning of the // next method. Also see hack in pasteupTypes() that // removes blank lines from the end of a method body. mbody.push(line); } else if (m = CONST_1.Matcher.PROP.exec(line)) { var qual = PropQual_1.PropQual.None; switch (m[3]) { case "synchronic": qual = PropQual_1.PropQual.Synchronic; break; case "atomic": qual = PropQual_1.PropQual.Atomic; break; } properties.push(new Prop_1.Prop(i, m[1], qual, m[4] == "Array", m[2])); } else if (CONST_1.blank_re.test(line)) { } else throw new ProgramError_1.ProgramError(filename, i, "Syntax error: Not a property or method: " + line); } if (in_method) methods.push(new Method_1.Method(method_line, method_type, method_name, method_signature, mbody)); if (kind == "class") defs.push(new ClassDefn_1.ClassDefn(filename, lineNumber, name_1, inherit, properties, methods, turboLines.length)); else defs.push(new StructDefn_1.StructDefn(filename, lineNumber, name_1, properties, methods, turboLines.length)); } return [defs, turboLines]; }; // The input is Id, Id:Blah, or ...Id. Strip any :Blah annotations. DefinitionService.prototype.parameterToArgument = function (file, line, s) { if (/^\s*(?:\.\.\.)[A-Za-z_$][A-Za-z0-9_$]*\s*$/.test(s)) return s; var m = /^\s*([A-Za-z_\$][A-Za-z0-9_\$]*)\s*:?/.exec(s); if (!m) throw new ProgramError_1.ProgramError(file, line, "Unable to understand argument to virtual function: " + s); return m[1]; }; return DefinitionService; }()); exports.DefinitionService = DefinitionService; //# sourceMappingURL=DefinitionService.js.map
01alchemist/parallel-js
src/modules/turbo.js/compiler/services/DefinitionService.js
JavaScript
mit
7,225
require_relative '../spec_helper' describe "Hello World for Node v15.x" do context "a single-process Node v15.x app" do let(:app) { Hatchet::Runner.new("spec/fixtures/repos/node-15") } it "should deploy successfully" do app.deploy do |app| expect(successful_body(app).strip).to eq("Hello, world!") end end end end
heroku/heroku-buildpack-nodejs
spec/ci/node_15_spec.rb
Ruby
mit
363
# # Copyright (c) 2018 ITO SOFT DESIGN Inc. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <<-DOC Here is a sample configuration. Puts your configuration to config/plugins/ifttt.yml web_hook_key: your_web_hook_key events: - name: event1 trigger: device: M0 type: raise_and_fall value_type: bool params: value1: error value2: unit1 - name: event2 trigger: device: D0 value: word type: changed params: value1: temperature value2: 値2 value3: 値3 - name: event3 trigger: device: D2 value: dword type: interval time: 10.0 params: value1: @value value2: 値2 value3: 値3 DOC require 'net/https' module LadderDrive module Emulator class IftttPlugin < Plugin def initialize plc super #plc return if disabled? @values = {} @times = {} @worker_queue = Queue.new setup end def run_cycle plc return if disabled? config[:events].each do |event| begin next unless self.triggered?(event) v = trigger_state_for(event).value @worker_queue.push event:event[:name], payload:event[:params].dup || {}, value:v rescue => e puts $! puts $@ p e end end if config[:events] end def disabled? return false unless super unless config[:web_hook_key] puts "ERROR: IftttPlugin requires web_hook_key." false else super end end private def setup Thread.start { thread_proc } end def thread_proc while arg = @worker_queue.pop begin uri = URI.parse("https://maker.ifttt.com/trigger/#{arg[:event]}/with/key/#{config[:web_hook_key]}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE req = Net::HTTP::Post.new(uri.path) payload = arg[:payload] payload.keys.each do |key| payload[key] = arg[:value] if payload[key] == "__value__" end req.set_form_data(payload) http.request(req) rescue => e # TODO: Resend if it fails. p e end end end end end end def plugin_ifttt_init plc @ifttt_plugin = LadderDrive::Emulator::IftttPlugin.new plc end def plugin_ifttt_exec plc @ifttt_plugin.run_cycle plc end
ito-soft-design/escalator
plugins/ifttt_plugin.rb
Ruby
mit
3,429
from keras.models import Sequential from keras.layers import convolutional from keras.layers.core import Dense, Flatten from SGD_exponential_decay import SGD_exponential_decay as SGD ### Parameters obtained from paper ### K = 152 # depth of convolutional layers LEARNING_RATE = .003 # initial learning rate DECAY = 8.664339379294006e-08 # rate of exponential learning_rate decay class value_trainer: def __init__(self): self.model = Sequential() self.model.add(convolutional.Convolution2D(input_shape=(49, 19, 19), nb_filter=K, nb_row=5, nb_col=5, init='uniform', activation='relu', border_mode='same')) for i in range(2,13): self.model.add(convolutional.Convolution2D(nb_filter=K, nb_row=3, nb_col=3, init='uniform', activation='relu', border_mode='same')) self.model.add(convolutional.Convolution2D(nb_filter=1, nb_row=1, nb_col=1, init='uniform', activation='linear', border_mode='same')) self.model.add(Flatten()) self.model.add(Dense(256,init='uniform')) self.model.add(Dense(1,init='uniform',activation="tanh")) sgd = SGD(lr=LEARNING_RATE, decay=DECAY) self.model.compile(loss='mean_squared_error', optimizer=sgd) def get_samples(self): # TODO non-terminating loop that draws training samples uniformly at random pass def train(self): # TODO use self.model.fit_generator to train from data source pass if __name__ == '__main__': trainer = value_trainer() # TODO command line instantiation
wrongu/AlphaGo
AlphaGo/models/value.py
Python
mit
1,711
require 'pathname' require 'generator/git_command' module Generator module Files def self.read(filename) File.read(filename) if File.exist?(filename) end class Readable attr_reader :filename, :repository_root def initialize(filename:, repository_root: nil) @filename = filename @repository_root = repository_root end def to_s Files.read(filename) end def abbreviated_commit_hash GitCommand.abbreviated_commit_hash(git_path, relative_filename) end private def relative_filename Pathname.new(filename).relative_path_from(Pathname.new(repository_root)).to_s end def git_path File.join(repository_root, '.git') end end class Writable < Readable def save(content) write(content) unless content == to_s content end private def write(content) File.open(filename, 'w') do |file| file.write content end end end end end
Insti/xruby
lib/generator/files.rb
Ruby
mit
1,046
module.exports = function(EmailAddress) { };
soltrinox/vator-api-dev
common/models/email-address.js
JavaScript
mit
46
version https://git-lfs.github.com/spec/v1 oid sha256:07e25b6c05d06d085c2840d85f2966476dc38544be904c978d7c66dbe688decb size 4672
yogeshsaroya/new-cdnjs
ajax/libs/dojo/1.8.1/cldr/nls/pt/gregorian.js.uncompressed.js
JavaScript
mit
129
package it.gemmed.database; import it.gemmed.resource.Iscrizione; import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Crea una nuova iscrizione all'interno del database. Sono richiesti solo i campi * not NULL, per settare gli altri campi utilizzare la classe UpdateIscrizioneDatabase * * @author GEMMED * @version 0.1 */ public class CreateIscrizioneDatabase { /** * Statement SQL per l'inserimento */ private static final String STATEMENT = "INSERT INTO iscrizione (giocatore,torneo, disponibilita) VALUES (?, ?, ?)"; /** * Connessione al database */ private final Connection con; /** * Elemento di tipo iscrizione che dese essere aggiunto al database */ private final Iscrizione iscrizione; /** * Creazione di un nuovo oggetto per poter inserire elementi di tipo iscrizione nel database * * @param con * connessione al database * @param i * iscrizione da salvare nel database */ public CreateIscrizioneDatabase(final Connection con, final Iscrizione i) { this.con = con; this.iscrizione = i; } /** * Savataggio di elementi di tipo iscrizione nel database * * @throws SQLException * se si verificano errori nello storing dell'elemento */ public void createIscrizione() throws SQLException { PreparedStatement pstmt = null; try { pstmt = con.prepareStatement(STATEMENT); pstmt.setString(1, iscrizione.getGiocatore()); pstmt.setInt(2, iscrizione.getTorneo()); // iscrizione.getDisponibilita().toByteArray(); Array sql = con.createArrayOf("boolean", iscrizione.getDisponibilita()); pstmt.setArray(3, sql); pstmt.execute(); } finally { if (pstmt != null) { pstmt.close(); } con.close(); } } }
manuel-zulian/Match-Point
trunk/src/java/it/gemmed/database/CreateIscrizioneDatabase.java
Java
mit
1,902
/** * Copyright 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule relayUnstableBatchedUpdates * * @format */ 'use strict'; module.exports = require('react-dom').unstable_batchedUpdates;
amiechen/amiechen.github.io
node_modules/relay-runtime/lib/relayUnstableBatchedUpdates.js
JavaScript
mit
322
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace Citysim { class Setting { public class Tiles { public static int tileSize; } public class World { public static int width; public static int height; } public class Camera { public static int lowSpeed; public static int highSpeed; } public static void load(String xml) { XmlDocument doc = new XmlDocument(); doc.Load(xml); //load tile's size XmlNode element = doc.SelectSingleNode("//settings/tiles"); Tiles.tileSize = getInt(element, "size"); //load world's width and height element = doc.SelectSingleNode("//settings/world"); World.width = getInt(element, "width"); World.height = getInt(element, "height"); //load camera's speed element = doc.SelectSingleNode("//settings/camera"); Camera.lowSpeed = getInt(element, "lowSpeed"); Camera.highSpeed = getInt(element,"highSpeed"); } public static void load() { load("Settings/settings.xml"); } private static Int32 getInt(XmlNode element, String name) { XmlNode nextNode = element.SelectSingleNode(name); return Convert.ToInt32(nextNode.LastChild.Value); } } }
mitchfizz05/Citysim
Citysim/Settings/Setting.cs
C#
mit
1,542
// support CommonJS, AMD & browser /* istanbul ignore next */ if (typeof exports === T_OBJECT) module.exports = riot else if (typeof define === 'function' && define.amd) define(function() { return (window.riot = riot) }) else window.riot = riot })(typeof window != 'undefined' ? window : void 0);
xtity/riot
lib/browser/wrap/suffix.js
JavaScript
mit
320
// Copyright (C) 2013,2014 Vicente J. Botet Escriba // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // 2013/09 Vicente J. Botet Escriba // Adapt to boost from CCIA C++11 implementation #ifndef BOOST_THREAD_EXECUTORS_EXECUTOR_HPP #define BOOST_THREAD_EXECUTORS_EXECUTOR_HPP #include <boost/thread/detail/config.hpp> #include <boost/thread/detail/delete.hpp> #include <boost/thread/detail/move.hpp> #include <boost/thread/executors/work.hpp> #include <boost/config/abi_prefix.hpp> namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost { namespace executors { class executor { public: /// type-erasure to store the works to do typedef executors::work work; /// executor is not copyable. BOOST_THREAD_NO_COPYABLE(executor) executor() {} /** * \par Effects * Destroys the executor. * * \par Synchronization * The completion of all the closures happen before the completion of the executor destructor. */ virtual ~executor() {}; /** * \par Effects * Close the \c executor for submissions. * The worker threads will work until there is no more closures to run. */ virtual void close() = 0; /** * \par Returns * Whether the pool is closed for submissions. */ virtual bool closed() = 0; /** * \par Effects * The specified closure will be scheduled for execution at some point in the future. * If invoked closure throws an exception the executor will call std::terminate, as is the case with threads. * * \par Synchronization * Ccompletion of closure on a particular thread happens before destruction of thread's thread local variables. * * \par Throws * \c sync_queue_is_closed if the thread pool is closed. * Whatever exception that can be throw while storing the closure. */ virtual void submit(BOOST_THREAD_RV_REF(work) closure) = 0; // virtual void submit(work& closure) = 0; /** * \par Requires * \c Closure is a model of Callable(void()) and a model of CopyConstructible/MoveConstructible. * * \par Effects * The specified closure will be scheduled for execution at some point in the future. * If invoked closure throws an exception the thread pool will call std::terminate, as is the case with threads. * * \par Synchronization * Completion of closure on a particular thread happens before destruction of thread's thread local variables. * * \par Throws * \c sync_queue_is_closed if the thread pool is closed. * Whatever exception that can be throw while storing the closure. */ #if defined(BOOST_NO_CXX11_RVALUE_REFERENCES) template <typename Closure> void submit(Closure & closure) { work w ((closure)); submit(mars_boost::move(w)); } #endif void submit(void (*closure)()) { work w ((closure)); submit(mars_boost::move(w)); } template <typename Closure> void submit(BOOST_THREAD_FWD_REF(Closure) closure) { //submit(work(mars_boost::forward<Closure>(closure))); work w((mars_boost::forward<Closure>(closure))); submit(mars_boost::move(w)); } /** * \par Effects * Try to execute one task. * * \par Returns * Whether a task has been executed. * * \par Throws * Whatever the current task constructor throws or the task() throws. */ virtual bool try_executing_one() = 0; /** * \par Requires * This must be called from an scheduled task. * * \par Effects * Reschedule functions until pred() */ template <typename Pred> bool reschedule_until(Pred const& pred) { do { //schedule_one_or_yield(); if ( ! try_executing_one()) { return false; } } while (! pred()); return true; } }; } using executors::executor; } #include <boost/config/abi_suffix.hpp> #endif
zhenyiyi/LearnDiary
mars/boost/thread/executors/executor.hpp
C++
mit
4,119
// LzmaDecoder.cs using System; namespace SevenZip.Compression.LZMA { using RangeCoder; internal class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream { class LenDecoder { BitDecoder m_Choice = new BitDecoder(); BitDecoder m_Choice2 = new BitDecoder(); BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); uint m_NumPosStates = 0; public void Create(uint numPosStates) { for (uint posState = m_NumPosStates; posState < numPosStates; posState++) { m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits); m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits); } m_NumPosStates = numPosStates; } public void Init() { m_Choice.Init(); for (uint posState = 0; posState < m_NumPosStates; posState++) { m_LowCoder[posState].Init(); m_MidCoder[posState].Init(); } m_Choice2.Init(); m_HighCoder.Init(); } public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) { if (m_Choice.Decode(rangeDecoder) == 0) return m_LowCoder[posState].Decode(rangeDecoder); else { uint symbol = Base.kNumLowLenSymbols; if (m_Choice2.Decode(rangeDecoder) == 0) symbol += m_MidCoder[posState].Decode(rangeDecoder); else { symbol += Base.kNumMidLenSymbols; symbol += m_HighCoder.Decode(rangeDecoder); } return symbol; } } } class LiteralDecoder { struct Decoder2 { BitDecoder[] m_Decoders; public void Create() { m_Decoders = new BitDecoder[0x300]; } public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) { uint symbol = 1; do symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); while (symbol < 0x100); return (byte)symbol; } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) { uint symbol = 1; do { uint matchBit = (uint)(matchByte >> 7) & 1; matchByte <<= 1; uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); symbol = (symbol << 1) | bit; if (matchBit != bit) { while (symbol < 0x100) symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); break; } } while (symbol < 0x100); return (byte)symbol; } } Decoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; uint m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = ((uint)1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Decoder2[numStates]; for (uint i = 0; i < numStates; i++) m_Coders[i].Create(); } public void Init() { uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); for (uint i = 0; i < numStates; i++) m_Coders[i].Init(); } uint GetState(uint pos, byte prevByte) { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) { return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } }; LZ.OutWindow m_OutWindow = new LZ.OutWindow(); RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); LenDecoder m_LenDecoder = new LenDecoder(); LenDecoder m_RepLenDecoder = new LenDecoder(); LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); uint m_DictionarySize; uint m_DictionarySizeCheck; uint m_PosStateMask; public Decoder() { m_DictionarySize = 0xFFFFFFFF; for (int i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); } void SetDictionarySize(uint dictionarySize) { if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); m_OutWindow.Create(blockSize); } } void SetLiteralProperties(int lp, int lc) { if (lp > 8) throw new InvalidParamException(); if (lc > 8) throw new InvalidParamException(); m_LiteralDecoder.Create(lp, lc); } void SetPosBitsProperties(int pb) { if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); uint numPosStates = (uint)1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; } bool _solid = false; void Init(System.IO.Stream inStream, System.IO.Stream outStream) { m_RangeDecoder.Init(inStream); m_OutWindow.Init(outStream, _solid); uint i; for (i = 0; i < Base.kNumStates; i++) { for (uint j = 0; j <= m_PosStateMask; j++) { uint index = (i << Base.kNumPosStatesBitsMax) + j; m_IsMatchDecoders[index].Init(); m_IsRep0LongDecoders[index].Init(); } m_IsRepDecoders[i].Init(); m_IsRepG0Decoders[i].Init(); m_IsRepG1Decoders[i].Init(); m_IsRepG2Decoders[i].Init(); } m_LiteralDecoder.Init(); for (i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i].Init(); // m_PosSpecDecoder.Init(); for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) m_PosDecoders[i].Init(); m_LenDecoder.Init(); m_RepLenDecoder.Init(); m_PosAlignDecoder.Init(); } public void Code(System.IO.Stream inStream, System.IO.Stream outStream, Int64 inSize, Int64 outSize, ICodeProgress progress) { Init(inStream, outStream); Base.State state = new Base.State(); state.Init(); uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; UInt64 nowPos64 = 0; UInt64 outSize64 = (UInt64)outSize; if (nowPos64 < outSize64) { if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) throw new DataErrorException(); state.UpdateChar(); byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); m_OutWindow.PutByte(b); nowPos64++; } while (nowPos64 < outSize64) { // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64); // while(nowPos64 < next) { uint posState = (uint)nowPos64 & m_PosStateMask; if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { byte b; byte prevByte = m_OutWindow.GetByte(0); if (!state.IsCharState()) b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0)); else b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte); m_OutWindow.PutByte(b); state.UpdateChar(); nowPos64++; } else { uint len; if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) { if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) { if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { state.UpdateShortRep(); m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); nowPos64++; continue; } } else { UInt32 distance; if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) { distance = rep1; } else { if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) distance = rep2; else { distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; state.UpdateRep(); } else { rep3 = rep2; rep2 = rep1; rep1 = rep0; len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); state.UpdateMatch(); uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); if (posSlot >= Base.kStartPosModelIndex) { int numDirectBits = (int)((posSlot >> 1) - 1); rep0 = ((2 | (posSlot & 1)) << numDirectBits); if (posSlot < Base.kEndPosModelIndex) rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); else { rep0 += (m_RangeDecoder.DecodeDirectBits( numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); } } else rep0 = posSlot; } if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) { if (rep0 == 0xFFFFFFFF) break; throw new DataErrorException(); } m_OutWindow.CopyBlock(rep0, len); nowPos64 += len; } } } m_OutWindow.Flush(); m_OutWindow.ReleaseStream(); m_RangeDecoder.ReleaseStream(); } public void SetDecoderProperties(byte[] properties) { if (properties.Length < 5) throw new InvalidParamException(); int lc = properties[0] % 9; int remainder = properties[0] / 9; int lp = remainder % 5; int pb = remainder / 5; if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); UInt32 dictionarySize = 0; for (int i = 0; i < 4; i++) dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8); SetDictionarySize(dictionarySize); SetLiteralProperties(lp, lc); SetPosBitsProperties(pb); } public bool Train(System.IO.Stream stream) { _solid = true; return m_OutWindow.Train(stream); } /* public override bool CanRead { get { return true; }} public override bool CanWrite { get { return true; }} public override bool CanSeek { get { return true; }} public override long Length { get { return 0; }} public override long Position { get { return 0; } set { } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override void Write(byte[] buffer, int offset, int count) { } public override long Seek(long offset, System.IO.SeekOrigin origin) { return 0; } public override void SetLength(long value) {} */ } }
FICTURE7/CoCSharp
src/CoCSharp/Csv/Compression/Compress/LZMA/LzmaDecoder.cs
C#
mit
16,283
<h3 class="page-header"><a onclick="page<?=$this->e($page['key'])?>();"><?=$this->e($page['name'])?></a></h3> <?php if (isset($flash)): ?> <?php if ($flash['success']): ?> <div class="alert alert-success" role="alert"> Incident successfully updated! </div> <?php else: ?> <div class="alert alert-danger" role="alert"> Something went wrong! </div> <?php endif?> <?php endif?> <div class="row"> <div class="col-sm-12"> <form action="/dashboard/incidents/p/<?=$this->e($page['key'])?>" method="POST"> <input type="hidden" name="form" value="update-create-incident"> <input type="hidden" name="page[key]" value="<?=$this->e($page['key'])?>"> <div class="form-group"> <div class="control-group"> <label>Status</label> <div> <span class="radio-button"> <input id="investigating" checked="checked" name="incident[status]" type="radio" value="investigating"> <label for="investigating"> Investigating </label> </span> <span class="radio-button"> <input id="identified" name="incident[status]" type="radio" value="identified"> <label for="identified"> Identified </label> </span> <span class="radio-button"> <input id="monitoring" name="incident[status]" type="radio" value="monitoring"> <label for="monitoring"> Monitoring </label> </span> <span class="radio-button"> <input id="resolved" name="incident[status]" type="radio" value="resolved"> <label for="resolved"> Resolved </label> </span> <span class="radio-button"> <input id="custom" name="incident[status]" type="radio" value="custom"> <label for="custom"> <input class="form-control input-lg" name="incident[custom]" type="text"> </label> </span> </div> </div> </div> <div class="form-group"> <label>Description</label> <textarea class="form-control input-lg" name="incident[description]" placeholder="Incident Description (& Message)"></textarea> </div> <button type="submit" class="btn btn-lg btn-primary">Update Incident</button> </form> </div> </div> <div class="row"> <div class="col-sm-12"> <hr> </div> </div> <?php foreach ($incidents as $incident): ?> <div class="row"> <div class="col-sm-2"> <h5> <a onclick="incident<?=$this->e($incident['key'])?>();"> <?=ucfirst($this->e($incident['status']))?> </a> </h5> </div> <div class="col-sm-10"> <p><?=$this->e($incident['description'])?></p> <p><small class="text-muted"><?=$this->e($incident['time'])?></small></p> </div> </div> <div class="row"> <div class="col-sm-12"> <br> </div> </div> <?php endforeach?> <script type="text/javascript"> var page<?=$this->e($page['key'])?> = function() { bootbox.dialog({ title: "Edit - <?=$this->e($page['name'])?>", message: '<form id="edit<?=$this->e($page['key'])?>" \ action="/dashboard/incidents/p/<?=$this->e($page['key'])?>" method="POST"> \ <input type="hidden" name="form" value="update-page"> \ <input type="hidden" name="page[key]" value="<?=$this->e($page['key'])?>"> \ <div class="form-group"> \ <label>Name</label> \ <input type="text" class="form-control input-lg" name="page[name]" placeholder="Page Name" value="<?=$this->e($page['name'])?>"> \ </div> \ </form>', buttons: { delete: { label: "Delete", className: "pull-left btn-danger", callback: function () { $('<input type="hidden" name="action" value="delete">').appendTo("#edit<?=$this->e($page['key'])?>"); $("#edit<?=$this->e($page['key'])?>").submit(); } }, success: { label: "Save", className: "btn-primary", callback: function () { $('<input type="hidden" name="action" value="save">').appendTo("#edit<?=$this->e($page['key'])?>"); $("#edit<?=$this->e($page['key'])?>").submit(); } } } }); }; <?php foreach ($incidents as $incident): ?> var incident<?=$this->e($incident['key'])?> = function() { bootbox.dialog({ backdrop: true, title: "Edit - <?=$this->e($page['name'])?>", message: '<form id="edit<?=$this->e($incident['key'])?>" \ action="/dashboard/incidents/p/<?=$this->e($page['key'])?>" method="POST"> \ <input type="hidden" name="form" value="update-incident"> \ <input type="hidden" name="page[key]" value="<?=$this->e($page['key'])?>"> \ <input type="hidden" name="incident[key]" value="<?=$this->e($incident['key'])?>"> \ <div class="form-group"> \ <div class="control-group"> \ <label>Status</label> \ <div> \ <span class="radio-button" style="margin-bottom: 10px;"> \ <input id="investigating" <?php if (strtolower($this->e($incident['status'])) === 'investigating'): ?>checked="checked"<?php endif?> name="incident[status]" type="radio" value="investigating"> \ <label for="investigating"> \ Investigating \ </label> \ </span> \ <span class="radio-button" style="margin-bottom: 10px;"> \ <input id="identified" <?php if (strtolower($this->e($incident['status'])) === 'identified'): ?>checked="checked"<?php endif?> name="incident[status]" type="radio" value="identified"> \ <label for="identified"> \ Identified \ </label> \ </span> \ <span class="radio-button" style="margin-bottom: 10px;"> \ <input id="monitoring" <?php if (strtolower($this->e($incident['status'])) === 'monitoring'): ?>checked="checked"<?php endif?> name="incident[status]" type="radio" value="monitoring"> \ <label for="monitoring"> \ Monitoring \ </label> \ </span> \ <span class="radio-button" style="margin-bottom: 10px;"> \ <input id="resolved" <?php if (strtolower($this->e($incident['status'])) === 'resolved'): ?>checked="checked"<?php endif?> name="incident[status]" type="radio" value="resolved"> \ <label for="resolved"> \ Resolved \ </label> \ </span> \ <span class="radio-button" style="margin-bottom: 10px;"> \ <input id="custom" \ <?php if (strtolower($this->e($incident['status']) !== 'investigating') && strtolower($this->e($incident['status']) !== 'identified') && strtolower($this->e($incident['status']) !== 'monitoring') && strtolower($this->e($incident['status']) !== 'resolved')): ?>checked="checked"<?php endif?> name="incident[status]" type="radio" value="custom"> \ <label for="custom"> \ <input class="form-control input-lg" name="incident[custom]" type="text" <?php if (strtolower($this->e($incident['status']) !== 'investigating') && strtolower($this->e($incident['status']) !== 'identified') && strtolower($this->e($incident['status']) !== 'monitoring') && strtolower($this->e($incident['status']) !== 'resolved')): ?> value="<?=ucfirst($this->e($incident['status']))?> <?php endif?>"> \ </label> \ </span> \ </div> \ </div> \ </div> \ <div class="form-group"> \ <label>Description</label> \ <textarea class="form-control input-lg <?=$this->e($incident['key'])?>" name="incident[description]" placeholder="Incident Description" style="max-width:100%;max-height:200px;"><?=$this->e(preg_replace('/\r|\n/', ' ', $incident['description']))?></textarea> \ </div> \ </form>', buttons: { delete: { label: "Delete", className: "pull-left btn-danger", callback: function () { $('<input type="hidden" name="action" value="delete">').appendTo("#edit<?=$this->e($incident['key'])?>"); $("#edit<?=$this->e($incident['key'])?>").submit(); } }, success: { label: "Save", className: "btn-primary", callback: function () { $('<input type="hidden" name="action" value="save">').appendTo("#edit<?=$this->e($incident['key'])?>"); $("#edit<?=$this->e($incident['key'])?>").submit(); } } } }); $('textarea.<?=$this->e($incident['key'])?>').autosize(); }; <?php endforeach?> $(function(){ $('textarea').autosize(); }); </script>
Xfers/status-cat
app/views/partials/dashboard/_single.php
PHP
mit
8,897
/* $(document.body).ready(function() { FormKit.install(); FormKit.initialize(document.body); }); Inside Ajax Region: $(document.body).ready(function() { FormKit.initialize( div element ); }); */ var FormKit = { register: function(initHandler,installHandler) { $(FormKit).bind('formkit.initialize',initHandler); if( installHandler ) { $(this).bind('formkit.install',installHandler); } }, initialize: function(scopeEl) { if(!scopeEl) scopeEl = document.body; $(FormKit).trigger('formkit.initialize',[scopeEl]); }, install: function() { $(FormKit).trigger('formkit.install'); } };
c9s/FormKit
assets/formkit/formkit.js
JavaScript
mit
703
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GlobalcachingApplication.Plugins.FormulaSolver.FormulaInterpreter.Functions { interface ICharacterMapper { int GetCharacterCode(char character); } }
RH-Code/GAPP
DefaultPlugins/GlobalcachingApplication.Plugins.FormulaSolver/FormulaInterpreter/Functions/Utils/ICharacterMapper.cs
C#
mit
269
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace LinqToDB.ServiceModel { using Common; using Extensions; using Mapping; using SqlQuery; static class LinqServiceSerializer { #region Public Members public static string Serialize(SelectQuery query, SqlParameter[] parameters, List<string> queryHints) { return new QuerySerializer().Serialize(query, parameters, queryHints); } public static LinqServiceQuery Deserialize(string str) { return new QueryDeserializer().Deserialize(str); } public static string Serialize(LinqServiceResult result) { return new ResultSerializer().Serialize(result); } public static LinqServiceResult DeserializeResult(string str) { return new ResultDeserializer().DeserializeResult(str); } public static string Serialize(string[] data) { return new StringArraySerializer().Serialize(data); } public static string[] DeserializeStringArray(string str) { return new StringArrayDeserializer().Deserialize(str); } #endregion #region SerializerBase const int ParamIndex = -1; const int TypeIndex = -2; const int TypeArrayIndex = -3; class SerializerBase { protected readonly StringBuilder Builder = new StringBuilder(); protected readonly Dictionary<object,int> Dic = new Dictionary<object,int>(); protected int Index; static string ConvertToString(Type type, object value) { switch (type.GetTypeCodeEx()) { case TypeCode.Decimal : return ((decimal) value).ToString(CultureInfo.InvariantCulture); case TypeCode.Double : return ((double) value).ToString(CultureInfo.InvariantCulture); case TypeCode.Single : return ((float) value).ToString(CultureInfo.InvariantCulture); case TypeCode.DateTime : return ((DateTime)value).ToString("o"); } if (type == typeof(DateTimeOffset)) return ((DateTimeOffset)value).ToString("o"); return Converter.ChangeTypeTo<string>(value); } protected void Append(Type type, object value) { Append(type); if (value == null) Append((string)null); else if (!type.IsArray) { Append(ConvertToString(type, value)); } else { var elementType = type.GetElementType(); Builder.Append(' '); var len = Builder.Length; var cnt = 0; if (elementType.IsArray) foreach (var val in (IEnumerable)value) { Append(elementType, val); cnt++; } else foreach (var val in (IEnumerable)value) { if (val == null) Append(elementType, null); else Append(val.GetType(), val); //Append(ConvertToString(val.GetType(), val)); cnt++; } Builder.Insert(len, cnt.ToString(CultureInfo.CurrentCulture)); } } protected void Append(int value) { Builder.Append(' ').Append(value); } protected void Append(int? value) { Builder.Append(' ').Append(value.HasValue ? '1' : '0'); if (value.HasValue) Builder.Append(value.Value); } protected void Append(Type value) { Builder.Append(' ').Append(value == null ? 0 : GetType(value)); } protected void Append(bool value) { Builder.Append(' ').Append(value ? '1' : '0'); } protected void Append(IQueryElement element) { Builder.Append(' ').Append(element == null ? 0 : Dic[element]); } protected void Append(string str) { Builder.Append(' '); if (str == null) { Builder.Append('-'); } else if (str.Length == 0) { Builder.Append('0'); } else { Builder .Append(str.Length) .Append(':') .Append(str); } } protected int GetType(Type type) { if (type == null) return 0; int idx; if (!Dic.TryGetValue(type, out idx)) { if (type.IsArray) { var elementType = GetType(type.GetElementType()); Dic.Add(type, idx = ++Index); Builder .Append(idx) .Append(' ') .Append(TypeArrayIndex) .Append(' ') .Append(elementType); } else { Dic.Add(type, idx = ++Index); Builder .Append(idx) .Append(' ') .Append(TypeIndex); Append(Configuration.LinqService.SerializeAssemblyQualifiedName ? type.AssemblyQualifiedName : type.FullName); } Builder.AppendLine(); } return idx; } } #endregion #region DeserializerBase public class DeserializerBase { protected readonly Dictionary<int,object> Dic = new Dictionary<int,object>(); protected string Str; protected int Pos; protected char Peek() { return Str[Pos]; } char Next() { return Str[++Pos]; } protected bool Get(char c) { if (Peek() == c) { Pos++; return true; } return false; } protected int ReadInt() { Get(' '); var minus = Get('-'); var value = 0; for (var c = Peek(); char.IsDigit(c); c = Next()) value = value * 10 + ((int)c - '0'); return minus ? -value : value; } protected int? ReadNullableInt() { Get(' '); if (Get('0')) return null; Get('1'); var minus = Get('-'); var value = 0; for (var c = Peek(); char.IsDigit(c); c = Next()) value = value * 10 + ((int)c - '0'); return minus ? -value : value; } protected int? ReadCount() { Get(' '); if (Get('-')) return null; var value = 0; for (var c = Peek(); char.IsDigit(c); c = Next()) value = value * 10 + ((int)c - '0'); return value; } protected string ReadString() { Get(' '); var c = Peek(); if (c == '-') { Pos++; return null; } if (c == '0') { Pos++; return string.Empty; } var len = ReadInt(); var value = Str.Substring(++Pos, len); Pos += len; return value; } protected bool ReadBool() { Get(' '); var value = Peek() == '1'; Pos++; return value; } protected T Read<T>() where T : class { var idx = ReadInt(); return idx == 0 ? null : (T)Dic[idx]; } protected Type ReadType() { var idx = ReadInt(); object type; if (!Dic.TryGetValue(idx, out type)) { Pos++; var typecode = ReadInt(); Pos++; switch (typecode) { case TypeIndex : type = ResolveType(ReadString()); break; case TypeArrayIndex: type = GetArrayType(Read<Type>()); break; default: throw new SerializationException("TypeIndex or TypeArrayIndex ({0} or {1}) expected, but was {2}".Args(TypeIndex, TypeArrayIndex, typecode)); } Dic.Add(idx, type); NextLine(); var idx2 = ReadInt(); if (idx2 != idx) throw new SerializationException("Wrong type reading, expected index is {0} but was {1}".Args(idx, idx2)); } return (Type) type; } protected T[] ReadArray<T>() where T : class { var count = ReadCount(); if (count == null) return null; var items = new T[count.Value]; for (var i = 0; i < count; i++) items[i] = Read<T>(); return items; } protected List<T> ReadList<T>() where T : class { var count = ReadCount(); if (count == null) return null; var items = new List<T>(count.Value); for (var i = 0; i < count; i++) items.Add(Read<T>()); return items; } protected void NextLine() { while (Pos < Str.Length && (Peek() == '\n' || Peek() == '\r')) Pos++; } interface IDeserializerHelper { object GetArray(DeserializerBase deserializer); } class DeserializerHelper<T> : IDeserializerHelper { public object GetArray(DeserializerBase deserializer) { var count = deserializer.ReadCount(); if (count == null) return null; var arr = new T[count.Value]; for (var i = 0; i < count.Value; i++) { var elementType = deserializer.ReadType(); arr[i] = (T) deserializer.ReadValue(elementType); } return arr; } } static readonly Dictionary<Type,Func<DeserializerBase,object>> _arrayDeserializers = new Dictionary<Type,Func<DeserializerBase,object>>(); protected object ReadValue(Type type) { if (type == null) return ReadString(); if (type.IsArray) { var elem = type.GetElementType(); Func<DeserializerBase,object> deserializer; lock (_arrayDeserializers) { if (!_arrayDeserializers.TryGetValue(elem, out deserializer)) { var helper = (IDeserializerHelper)Activator.CreateInstance(typeof(DeserializerHelper<>).MakeGenericType(elem)); _arrayDeserializers.Add(elem, deserializer = helper.GetArray); } } return deserializer(this); } var str = ReadString(); if (str == null) return null; switch (type.GetTypeCodeEx()) { case TypeCode.Decimal : return decimal. Parse(str, CultureInfo.InvariantCulture); case TypeCode.Double : return double. Parse(str, CultureInfo.InvariantCulture); case TypeCode.Single : return float. Parse(str, CultureInfo.InvariantCulture); case TypeCode.DateTime : return DateTime.ParseExact(str, "o", CultureInfo.InvariantCulture); } if (type == typeof(DateTimeOffset)) return DateTimeOffset.ParseExact(str, "o", CultureInfo.InvariantCulture); return Converter.ChangeType(str, type); } protected readonly List<string> UnresolvedTypes = new List<string>(); protected Type ResolveType(string str) { if (str == null) return null; var type = Type.GetType(str, false); if (type == null) { if (str == "System.Data.Linq.Binary") return typeof(System.Data.Linq.Binary); #if !SILVERLIGHT && !NETFX_CORE type = LinqService.TypeResolver(str); #endif if (type == null) { if (Configuration.LinqService.ThrowUnresolvedTypeException) throw new LinqToDBException("Type '{0}' cannot be resolved. Use LinqService.TypeResolver to resolve unknown types.".Args(str)); UnresolvedTypes.Add(str); Debug.WriteLine( "Type '{0}' cannot be resolved. Use LinqService.TypeResolver to resolve unknown types.".Args(str), "LinqServiceSerializer"); } } return type; } } #endregion #region QuerySerializer class QuerySerializer : SerializerBase { public string Serialize(SelectQuery query, SqlParameter[] parameters, List<string> queryHints) { var queryHintCount = queryHints == null ? 0 : queryHints.Count; Builder.AppendLine(queryHintCount.ToString()); if (queryHintCount > 0) foreach (var hint in queryHints) Builder.AppendLine(hint); var visitor = new QueryVisitor(); visitor.Visit(query, Visit); foreach (var parameter in parameters) if (!Dic.ContainsKey(parameter)) Visit(parameter); Builder .Append(++Index) .Append(' ') .Append(ParamIndex); Append(parameters.Length); foreach (var parameter in parameters) Append(parameter); Builder.AppendLine(); return Builder.ToString(); } void Visit(IQueryElement e) { switch (e.ElementType) { case QueryElementType.SqlField : { var fld = (SqlField)e; if (fld != fld.Table.All) GetType(fld.SystemType); break; } case QueryElementType.SqlParameter : { var p = (SqlParameter)e; var v = p.Value; var t = v == null ? p.SystemType : v.GetType(); if (v == null || t.IsArray || t == typeof(string) || !(v is IEnumerable)) { GetType(t); } else { var elemType = t.GetItemType(); GetType(GetArrayType(elemType)); } break; } case QueryElementType.SqlFunction : GetType(((SqlFunction) e).SystemType); break; case QueryElementType.SqlExpression : GetType(((SqlExpression) e).SystemType); break; case QueryElementType.SqlBinaryExpression : GetType(((SqlBinaryExpression)e).SystemType); break; case QueryElementType.SqlDataType : GetType(((SqlDataType) e).Type); break; case QueryElementType.SqlValue : GetType(((SqlValue) e).SystemType); break; case QueryElementType.SqlTable : GetType(((SqlTable) e).ObjectType); break; } Dic.Add(e, ++Index); Builder .Append(Index) .Append(' ') .Append((int)e.ElementType); switch (e.ElementType) { case QueryElementType.SqlField : { var elem = (SqlField)e; Append(elem.SystemType); Append(elem.Name); Append(elem.PhysicalName); Append(elem.CanBeNull); Append(elem.IsPrimaryKey); Append(elem.PrimaryKeyOrder); Append(elem.IsIdentity); Append(elem.IsUpdatable); Append(elem.IsInsertable); Append((int)elem.DataType); Append(elem.DbType); Append(elem.Length); Append(elem.Precision); Append(elem.Scale); Append(elem.CreateFormat); break; } case QueryElementType.SqlFunction : { var elem = (SqlFunction)e; Append(elem.SystemType); Append(elem.Name); Append(elem.IsAggregate); Append(elem.Precedence); Append(elem.Parameters); break; } case QueryElementType.SqlParameter : { var elem = (SqlParameter)e; Append(elem.Name); Append(elem.IsQueryParameter); Append((int)elem.DataType); Append(elem.DbSize); Append(elem.LikeStart); Append(elem.LikeEnd); Append(elem.ReplaceLike); var value = elem.LikeStart != null ? elem.RawValue : elem.Value; var type = value == null ? elem.SystemType : value.GetType(); if (value == null || type.IsArray || type == typeof(string) || !(value is IEnumerable)) { Append(type, value); } else { var elemType = type.GetItemType(); value = ConvertIEnumerableToArray(value, elemType); Append(GetArrayType(elemType), value); } break; } case QueryElementType.SqlExpression : { var elem = (SqlExpression)e; Append(elem.SystemType); Append(elem.Expr); Append(elem.Precedence); Append(elem.Parameters); break; } case QueryElementType.SqlBinaryExpression : { var elem = (SqlBinaryExpression)e; Append(elem.SystemType); Append(elem.Expr1); Append(elem.Operation); Append(elem.Expr2); Append(elem.Precedence); break; } case QueryElementType.SqlValue : { var elem = (SqlValue)e; Append(elem.SystemType, elem.Value); break; } case QueryElementType.SqlDataType : { var elem = (SqlDataType)e; Append((int)elem.DataType); Append(elem.Type); Append(elem.Length); Append(elem.Precision); Append(elem.Scale); break; } case QueryElementType.SqlTable : { var elem = (SqlTable)e; Append(elem.SourceID); Append(elem.Name); Append(elem.Alias); Append(elem.Database); Append(elem.Owner); Append(elem.PhysicalName); Append(elem.ObjectType); if (elem.SequenceAttributes.IsNullOrEmpty()) Builder.Append(" -"); else { Append(elem.SequenceAttributes.Length); foreach (var a in elem.SequenceAttributes) { Append(a.Configuration); Append(a.SequenceName); } } Append(Dic[elem.All]); Append(elem.Fields.Count); foreach (var field in elem.Fields) Append(Dic[field.Value]); Append((int)elem.SqlTableType); if (elem.SqlTableType != SqlTableType.Table) { if (elem.TableArguments == null) Append(0); else { Append(elem.TableArguments.Length); foreach (var expr in elem.TableArguments) Append(Dic[expr]); } } break; } case QueryElementType.ExprPredicate : { var elem = (SelectQuery.Predicate.Expr)e; Append(elem.Expr1); Append(elem.Precedence); break; } case QueryElementType.NotExprPredicate : { var elem = (SelectQuery.Predicate.NotExpr)e; Append(elem.Expr1); Append(elem.IsNot); Append(elem.Precedence); break; } case QueryElementType.ExprExprPredicate : { var elem = (SelectQuery.Predicate.ExprExpr)e; Append(elem.Expr1); Append((int)elem.Operator); Append(elem.Expr2); break; } case QueryElementType.LikePredicate : { var elem = (SelectQuery.Predicate.Like)e; Append(elem.Expr1); Append(elem.IsNot); Append(elem.Expr2); Append(elem.Escape); break; } case QueryElementType.BetweenPredicate : { var elem = (SelectQuery.Predicate.Between)e; Append(elem.Expr1); Append(elem.IsNot); Append(elem.Expr2); Append(elem.Expr3); break; } case QueryElementType.IsNullPredicate : { var elem = (SelectQuery.Predicate.IsNull)e; Append(elem.Expr1); Append(elem.IsNot); break; } case QueryElementType.InSubQueryPredicate : { var elem = (SelectQuery.Predicate.InSubQuery)e; Append(elem.Expr1); Append(elem.IsNot); Append(elem.SubQuery); break; } case QueryElementType.InListPredicate : { var elem = (SelectQuery.Predicate.InList)e; Append(elem.Expr1); Append(elem.IsNot); Append(elem.Values); break; } case QueryElementType.FuncLikePredicate : { var elem = (SelectQuery.Predicate.FuncLike)e; Append(elem.Function); break; } case QueryElementType.SqlQuery : { var elem = (SelectQuery)e; Append(elem.SourceID); Append((int)elem.QueryType); Append(elem.From); var appendInsert = false; var appendUpdate = false; var appendDelete = false; var appendSelect = false; var appendCreateTable = false; switch (elem.QueryType) { case QueryType.InsertOrUpdate : appendUpdate = true; appendInsert = true; break; case QueryType.Update : appendUpdate = true; appendSelect = elem.Select.SkipValue != null || elem.Select.TakeValue != null; break; case QueryType.Delete : appendDelete = true; appendSelect = true; break; case QueryType.Insert : appendInsert = true; if (elem.From.Tables.Count != 0) appendSelect = true; break; case QueryType.CreateTable : appendCreateTable = true; break; default : appendSelect = true; break; } Append(appendInsert); if (appendInsert) Append(elem.Insert); Append(appendUpdate); if (appendUpdate) Append(elem.Update); Append(appendDelete); if (appendDelete) Append(elem.Delete); Append(appendSelect); if (appendSelect) Append(elem.Select); Append(appendCreateTable); if (appendCreateTable) Append(elem.CreateTable); Append(elem.Where); Append(elem.GroupBy); Append(elem.Having); Append(elem.OrderBy); Append(elem.ParentSelect == null ? 0 : elem.ParentSelect.SourceID); Append(elem.IsParameterDependent); if (!elem.HasUnion) Builder.Append(" -"); else Append(elem.Unions); Append(elem.Parameters); if (Dic.ContainsKey(elem.All)) Append(Dic[elem.All]); else Builder.Append(" -"); break; } case QueryElementType.Column : { var elem = (SelectQuery.Column) e; Append(elem.Parent.SourceID); Append(elem.Expression); Append(elem._alias); break; } case QueryElementType.SearchCondition : { Append(((SelectQuery.SearchCondition)e).Conditions); break; } case QueryElementType.Condition : { var elem = (SelectQuery.Condition)e; Append(elem.IsNot); Append(elem.Predicate); Append(elem.IsOr); break; } case QueryElementType.TableSource : { var elem = (SelectQuery.TableSource)e; Append(elem.Source); Append(elem._alias); Append(elem.Joins); break; } case QueryElementType.JoinedTable : { var elem = (SelectQuery.JoinedTable)e; Append((int)elem.JoinType); Append(elem.Table); Append(elem.IsWeak); Append(elem.Condition); break; } case QueryElementType.SelectClause : { var elem = (SelectQuery.SelectClause)e; Append(elem.IsDistinct); Append(elem.SkipValue); Append(elem.TakeValue); Append(elem.Columns); break; } case QueryElementType.InsertClause : { var elem = (SelectQuery.InsertClause)e; Append(elem.Items); Append(elem.Into); Append(elem.WithIdentity); break; } case QueryElementType.UpdateClause : { var elem = (SelectQuery.UpdateClause)e; Append(elem.Items); Append(elem.Keys); Append(elem.Table); break; } case QueryElementType.DeleteClause : { Append(((SelectQuery.DeleteClause)e).Table); break; } case QueryElementType.SetExpression : { var elem = (SelectQuery.SetExpression)e; Append(elem.Column); Append(elem.Expression); break; } case QueryElementType.CreateTableStatement : { var elem = (SelectQuery.CreateTableStatement)e; Append(elem.Table); Append(elem.IsDrop); Append(elem.StatementHeader); Append(elem.StatementFooter); Append((int)elem.DefaulNullable); break; } case QueryElementType.FromClause : Append(((SelectQuery.FromClause) e).Tables); break; case QueryElementType.WhereClause : Append(((SelectQuery.WhereClause) e).SearchCondition); break; case QueryElementType.GroupByClause : Append(((SelectQuery.GroupByClause)e).Items); break; case QueryElementType.OrderByClause : Append(((SelectQuery.OrderByClause)e).Items); break; case QueryElementType.OrderByItem : { var elem = (SelectQuery.OrderByItem)e; Append(elem.Expression); Append(elem.IsDescending); break; } case QueryElementType.Union : { var elem = (SelectQuery.Union)e; Append(elem.SelectQuery); Append(elem.IsAll); break; } } Builder.AppendLine(); } void Append<T>(ICollection<T> exprs) where T : IQueryElement { if (exprs == null) Builder.Append(" -"); else { Append(exprs.Count); foreach (var e in exprs) Append(Dic[e]); } } } #endregion #region QueryDeserializer public class QueryDeserializer : DeserializerBase { SelectQuery _query; SqlParameter[] _parameters; readonly Dictionary<int,SelectQuery> _queries = new Dictionary<int,SelectQuery>(); readonly List<Action> _actions = new List<Action>(); public LinqServiceQuery Deserialize(string str) { Str = str; List<string> queryHints = null; var queryHintCount = ReadInt(); NextLine(); if (queryHintCount > 0) { queryHints = new List<string>(); for (var i = 0; i < queryHintCount; i++) { var pos = Pos; while (Pos < Str.Length && Peek() != '\n' && Peek() != '\r') Pos++; queryHints.Add(Str.Substring(pos, Pos - pos)); NextLine(); } } while (Parse()) {} foreach (var action in _actions) action(); return new LinqServiceQuery { Query = _query, Parameters = _parameters, QueryHints = queryHints }; } bool Parse() { NextLine(); if (Pos >= Str.Length) return false; var obj = null as object; var idx = ReadInt(); Pos++; var type = ReadInt(); Pos++; switch ((QueryElementType)type) { case (QueryElementType)ParamIndex : obj = _parameters = ReadArray<SqlParameter>(); break; case (QueryElementType)TypeIndex : obj = ResolveType(ReadString()); break; case (QueryElementType)TypeArrayIndex : obj = GetArrayType(Read<Type>()); break; case QueryElementType.SqlField : { var systemType = Read<Type>(); var name = ReadString(); var physicalName = ReadString(); var nullable = ReadBool(); var isPrimaryKey = ReadBool(); var primaryKeyOrder = ReadInt(); var isIdentity = ReadBool(); var isUpdatable = ReadBool(); var isInsertable = ReadBool(); var dataType = ReadInt(); var dbType = ReadString(); var length = ReadNullableInt(); var precision = ReadNullableInt(); var scale = ReadNullableInt(); var createFormat = ReadString(); obj = new SqlField { SystemType = systemType, Name = name, PhysicalName = physicalName, CanBeNull = nullable, IsPrimaryKey = isPrimaryKey, PrimaryKeyOrder = primaryKeyOrder, IsIdentity = isIdentity, IsInsertable = isInsertable, IsUpdatable = isUpdatable, DataType = (DataType)dataType, DbType = dbType, Length = length, Precision = precision, Scale = scale, CreateFormat = createFormat, }; break; } case QueryElementType.SqlFunction : { var systemType = Read<Type>(); var name = ReadString(); var isAggregate = ReadBool(); var precedence = ReadInt(); var parameters = ReadArray<ISqlExpression>(); obj = new SqlFunction(systemType, name, isAggregate, precedence, parameters); break; } case QueryElementType.SqlParameter : { var name = ReadString(); var isQueryParameter = ReadBool(); var dbType = (DataType)ReadInt(); var dbSize = ReadInt(); var likeStart = ReadString(); var likeEnd = ReadString(); var replaceLike = ReadBool(); var systemType = Read<Type>(); var value = ReadValue(systemType); obj = new SqlParameter(systemType, name, value) { IsQueryParameter = isQueryParameter, DataType = dbType, DbSize = dbSize, LikeStart = likeStart, LikeEnd = likeEnd, ReplaceLike = replaceLike, }; break; } case QueryElementType.SqlExpression : { var systemType = Read<Type>(); var expr = ReadString(); var precedence = ReadInt(); var parameters = ReadArray<ISqlExpression>(); obj = new SqlExpression(systemType, expr, precedence, parameters); break; } case QueryElementType.SqlBinaryExpression : { var systemType = Read<Type>(); var expr1 = Read<ISqlExpression>(); var operation = ReadString(); var expr2 = Read<ISqlExpression>(); var precedence = ReadInt(); obj = new SqlBinaryExpression(systemType, expr1, operation, expr2, precedence); break; } case QueryElementType.SqlValue : { var systemType = Read<Type>(); var value = ReadValue(systemType); obj = new SqlValue(systemType, value); break; } case QueryElementType.SqlDataType : { var dbType = (DataType)ReadInt(); var systemType = Read<Type>(); var length = ReadNullableInt(); var precision = ReadNullableInt(); var scale = ReadNullableInt(); obj = new SqlDataType(dbType, systemType, length, precision, scale); break; } case QueryElementType.SqlTable : { var sourceID = ReadInt(); var name = ReadString(); var alias = ReadString(); var database = ReadString(); var owner = ReadString(); var physicalName = ReadString(); var objectType = Read<Type>(); var sequenceAttributes = null as SequenceNameAttribute[]; var count = ReadCount(); if (count != null) { sequenceAttributes = new SequenceNameAttribute[count.Value]; for (var i = 0; i < count.Value; i++) sequenceAttributes[i] = new SequenceNameAttribute(ReadString(), ReadString()); } var all = Read<SqlField>(); var fields = ReadArray<SqlField>(); var flds = new SqlField[fields.Length + 1]; flds[0] = all; Array.Copy(fields, 0, flds, 1, fields.Length); var sqlTableType = (SqlTableType)ReadInt(); var tableArgs = sqlTableType == SqlTableType.Table ? null : ReadArray<ISqlExpression>(); obj = new SqlTable( sourceID, name, alias, database, owner, physicalName, objectType, sequenceAttributes, flds, sqlTableType, tableArgs); break; } case QueryElementType.ExprPredicate : { var expr1 = Read<ISqlExpression>(); var precedence = ReadInt(); obj = new SelectQuery.Predicate.Expr(expr1, precedence); break; } case QueryElementType.NotExprPredicate : { var expr1 = Read<ISqlExpression>(); var isNot = ReadBool(); var precedence = ReadInt(); obj = new SelectQuery.Predicate.NotExpr(expr1, isNot, precedence); break; } case QueryElementType.ExprExprPredicate : { var expr1 = Read<ISqlExpression>(); var @operator = (SelectQuery.Predicate.Operator)ReadInt(); var expr2 = Read<ISqlExpression>(); obj = new SelectQuery.Predicate.ExprExpr(expr1, @operator, expr2); break; } case QueryElementType.LikePredicate : { var expr1 = Read<ISqlExpression>(); var isNot = ReadBool(); var expr2 = Read<ISqlExpression>(); var escape = Read<ISqlExpression>(); obj = new SelectQuery.Predicate.Like(expr1, isNot, expr2, escape); break; } case QueryElementType.BetweenPredicate : { var expr1 = Read<ISqlExpression>(); var isNot = ReadBool(); var expr2 = Read<ISqlExpression>(); var expr3 = Read<ISqlExpression>(); obj = new SelectQuery.Predicate.Between(expr1, isNot, expr2, expr3); break; } case QueryElementType.IsNullPredicate : { var expr1 = Read<ISqlExpression>(); var isNot = ReadBool(); obj = new SelectQuery.Predicate.IsNull(expr1, isNot); break; } case QueryElementType.InSubQueryPredicate : { var expr1 = Read<ISqlExpression>(); var isNot = ReadBool(); var subQuery = Read<SelectQuery>(); obj = new SelectQuery.Predicate.InSubQuery(expr1, isNot, subQuery); break; } case QueryElementType.InListPredicate : { var expr1 = Read<ISqlExpression>(); var isNot = ReadBool(); var values = ReadList<ISqlExpression>(); obj = new SelectQuery.Predicate.InList(expr1, isNot, values); break; } case QueryElementType.FuncLikePredicate : { var func = Read<SqlFunction>(); obj = new SelectQuery.Predicate.FuncLike(func); break; } case QueryElementType.SqlQuery : { var sid = ReadInt(); var queryType = (QueryType)ReadInt(); var from = Read<SelectQuery.FromClause>(); var readInsert = ReadBool(); var insert = readInsert ? Read<SelectQuery.InsertClause>() : null; var readUpdate = ReadBool(); var update = readUpdate ? Read<SelectQuery.UpdateClause>() : null; var readDelete = ReadBool(); var delete = readDelete ? Read<SelectQuery.DeleteClause>() : null; var readSelect = ReadBool(); var select = readSelect ? Read<SelectQuery.SelectClause>() : new SelectQuery.SelectClause(null); var readCreateTable = ReadBool(); var createTable = readCreateTable ? Read<SelectQuery.CreateTableStatement>() : new SelectQuery.CreateTableStatement(); var where = Read<SelectQuery.WhereClause>(); var groupBy = Read<SelectQuery.GroupByClause>(); var having = Read<SelectQuery.WhereClause>(); var orderBy = Read<SelectQuery.OrderByClause>(); var parentSql = ReadInt(); var parameterDependent = ReadBool(); var unions = ReadArray<SelectQuery.Union>(); var parameters = ReadArray<SqlParameter>(); var query = _query = new SelectQuery(sid) { QueryType = queryType }; query.Init( insert, update, delete, select, from, where, groupBy, having, orderBy, unions == null ? null : unions.ToList(), null, createTable, parameterDependent, parameters.ToList()); _queries.Add(sid, _query); if (parentSql != 0) _actions.Add(() => { SelectQuery selectQuery; if (_queries.TryGetValue(parentSql, out selectQuery)) query.ParentSelect = selectQuery; }); query.All = Read<SqlField>(); obj = query; break; } case QueryElementType.Column : { var sid = ReadInt(); var expression = Read<ISqlExpression>(); var alias = ReadString(); var col = new SelectQuery.Column(null, expression, alias); _actions.Add(() => { col.Parent = _queries[sid]; return; }); obj = col; break; } case QueryElementType.SearchCondition : obj = new SelectQuery.SearchCondition(ReadArray<SelectQuery.Condition>()); break; case QueryElementType.Condition : obj = new SelectQuery.Condition(ReadBool(), Read<ISqlPredicate>(), ReadBool()); break; case QueryElementType.TableSource : { var source = Read<ISqlTableSource>(); var alias = ReadString(); var joins = ReadArray<SelectQuery.JoinedTable>(); obj = new SelectQuery.TableSource(source, alias, joins); break; } case QueryElementType.JoinedTable : { var joinType = (SelectQuery.JoinType)ReadInt(); var table = Read<SelectQuery.TableSource>(); var isWeak = ReadBool(); var condition = Read<SelectQuery.SearchCondition>(); obj = new SelectQuery.JoinedTable(joinType, table, isWeak, condition); break; } case QueryElementType.SelectClause : { var isDistinct = ReadBool(); var skipValue = Read<ISqlExpression>(); var takeValue = Read<ISqlExpression>(); var columns = ReadArray<SelectQuery.Column>(); obj = new SelectQuery.SelectClause(isDistinct, takeValue, skipValue, columns); break; } case QueryElementType.InsertClause : { var items = ReadArray<SelectQuery.SetExpression>(); var into = Read<SqlTable>(); var wid = ReadBool(); var c = new SelectQuery.InsertClause { Into = into, WithIdentity = wid }; c.Items.AddRange(items); obj = c; break; } case QueryElementType.UpdateClause : { var items = ReadArray<SelectQuery.SetExpression>(); var keys = ReadArray<SelectQuery.SetExpression>(); var table = Read<SqlTable>(); var c = new SelectQuery.UpdateClause { Table = table }; c.Items.AddRange(items); c.Keys. AddRange(keys); obj = c; break; } case QueryElementType.DeleteClause : { var table = Read<SqlTable>(); obj = new SelectQuery.DeleteClause { Table = table }; break; } case QueryElementType.CreateTableStatement : { var table = Read<SqlTable>(); var isDrop = ReadBool(); var statementHeader = ReadString(); var statementFooter = ReadString(); var defaultNullable = (DefaulNullable)ReadInt(); obj = new SelectQuery.CreateTableStatement { Table = table, IsDrop = isDrop, StatementHeader = statementHeader, StatementFooter = statementFooter, DefaulNullable = defaultNullable, }; break; } case QueryElementType.SetExpression : obj = new SelectQuery.SetExpression(Read <ISqlExpression>(), Read<ISqlExpression>()); break; case QueryElementType.FromClause : obj = new SelectQuery.FromClause (ReadArray<SelectQuery.TableSource>()); break; case QueryElementType.WhereClause : obj = new SelectQuery.WhereClause (Read <SelectQuery.SearchCondition>()); break; case QueryElementType.GroupByClause : obj = new SelectQuery.GroupByClause(ReadArray<ISqlExpression>()); break; case QueryElementType.OrderByClause : obj = new SelectQuery.OrderByClause(ReadArray<SelectQuery.OrderByItem>()); break; case QueryElementType.OrderByItem : { var expression = Read<ISqlExpression>(); var isDescending = ReadBool(); obj = new SelectQuery.OrderByItem(expression, isDescending); break; } case QueryElementType.Union : { var sqlQuery = Read<SelectQuery>(); var isAll = ReadBool(); obj = new SelectQuery.Union(sqlQuery, isAll); break; } } Dic.Add(idx, obj); return true; } } #endregion #region ResultSerializer class ResultSerializer : SerializerBase { public string Serialize(LinqServiceResult result) { Append(result.FieldCount); Append(result.VaryingTypes.Length); Append(result.RowCount); Append(result.QueryID.ToString()); Builder.AppendLine(); foreach (var name in result.FieldNames) { Append(name); Builder.AppendLine(); } foreach (var type in result.FieldTypes) { Append(Configuration.LinqService.SerializeAssemblyQualifiedName ? type.AssemblyQualifiedName : type.FullName); Builder.AppendLine(); } foreach (var type in result.VaryingTypes) { Append(type.FullName); Builder.AppendLine(); } foreach (var data in result.Data) { foreach (var str in data) { if (result.VaryingTypes.Length > 0 && !string.IsNullOrEmpty(str) && str[0] == '\0') { Builder.Append('*'); Append((int)str[1]); Append(str.Substring(2)); } else Append(str); } Builder.AppendLine(); } return Builder.ToString(); } } #endregion #region ResultDeserializer class ResultDeserializer : DeserializerBase { public LinqServiceResult DeserializeResult(string str) { Str = str; var fieldCount = ReadInt(); var varTypesLen = ReadInt(); var result = new LinqServiceResult { FieldCount = fieldCount, RowCount = ReadInt(), VaryingTypes = new Type[varTypesLen], QueryID = new Guid(ReadString()), FieldNames = new string[fieldCount], FieldTypes = new Type [fieldCount], Data = new List<string[]>(), }; NextLine(); for (var i = 0; i < fieldCount; i++) { result.FieldNames [i] = ReadString(); NextLine(); } for (var i = 0; i < fieldCount; i++) { result.FieldTypes [i] = ResolveType(ReadString()); NextLine(); } for (var i = 0; i < varTypesLen; i++) { result.VaryingTypes[i] = ResolveType(ReadString()); NextLine(); } for (var n = 0; n < result.RowCount; n++) { var data = new string[fieldCount]; for (var i = 0; i < fieldCount; i++) { if (varTypesLen > 0) { Get(' '); if (Get('*')) { var idx = ReadInt(); data[i] = "\0" + (char)idx + ReadString(); } else data[i] = ReadString(); } else data[i] = ReadString(); } result.Data.Add(data); NextLine(); } return result; } } #endregion #region StringArraySerializer class StringArraySerializer : SerializerBase { public string Serialize(string[] data) { Append(data.Length); foreach (var str in data) Append(str); Builder.AppendLine(); return Builder.ToString(); } } #endregion #region StringArrayDeserializer class StringArrayDeserializer : DeserializerBase { public string[] Deserialize(string str) { Str = str; var data = new string[ReadInt()]; for (var i = 0; i < data.Length; i++) data[i] = ReadString(); return data; } } #endregion #region Helpers interface IArrayHelper { Type GetArrayType(); object ConvertToArray(object list); } class ArrayHelper<T> : IArrayHelper { public Type GetArrayType() { return typeof(T[]); } public object ConvertToArray(object list) { return ((IEnumerable<T>)list).ToArray(); } } static readonly Dictionary<Type,Type> _arrayTypes = new Dictionary<Type,Type>(); static readonly Dictionary<Type,Func<object,object>> _arrayConverters = new Dictionary<Type,Func<object,object>>(); static Type GetArrayType(Type elementType) { Type arrayType; lock (_arrayTypes) { if (!_arrayTypes.TryGetValue(elementType, out arrayType)) { var helper = (IArrayHelper)Activator.CreateInstance(typeof(ArrayHelper<>).MakeGenericType(elementType)); _arrayTypes.Add(elementType, arrayType = helper.GetArrayType()); } } return arrayType; } static object ConvertIEnumerableToArray(object list, Type elementType) { Func<object,object> converter; lock (_arrayConverters) { if (!_arrayConverters.TryGetValue(elementType, out converter)) { var helper = (IArrayHelper)Activator.CreateInstance(typeof(ArrayHelper<>).MakeGenericType(elementType)); _arrayConverters.Add(elementType, converter = helper.ConvertToArray); } } return converter(list); } #endregion } }
lvaleriu/linq2db
Source/ServiceModel/LinqServiceSerializer.cs
C#
mit
45,280
/** * Validates the inputted Firebase reference. * * @param {Firebase} firebaseRef The Firebase reference to validate. */ var _validateFirebaseRef = function(firebaseRef) { var error; if (typeof firebaseRef === "undefined") { error = "no \"firebaseRef\" specified"; } else if (firebaseRef instanceof Firebase === false) { // TODO: can they pass in a limit query? error = "\"firebaseRef\" must be an instance of Firebase"; } if (typeof error !== "undefined") { throw new Error("FireGrapher: " + error); } }; /** * Validates the inputted CSS selector. * * @param {string} cssSelector The CSS selector to validate. */ var _validateCssSelector = function(cssSelector) { var error; if (typeof cssSelector === "undefined") { error = "no \"cssSelector\" specified"; } else if (typeof cssSelector !== "string") { error = "\"cssSelector\" must be a string"; } else { var matchedElements = document.querySelectorAll(cssSelector); if (matchedElements.length === 0) { error = "no element matches the CSS selector '" + cssSelector + "'"; } else if (matchedElements.length > 1) { error = "multiple elements (" + matchedElements.length + " total) match the CSS selector '" + cssSelector + "'"; } } if (typeof error !== "undefined") { throw new Error("FireGrapher: " + error); } }; /** * Validates the inputted config object and makes sure no options have invalid values. * * @param {object} config The graph configuration object to validate. */ var _validateConfig = function(config) { // TODO: upgrade var error; if (typeof config === "undefined") { error = "no \"config\" specified"; } else if (typeof config !== "object") { error = "\"config\" must be an object"; } // Every config needs to specify the graph type var validGraphTypes = ["table", "line", "scatter", "bar", "map"]; if (typeof config.type === "undefined") { error = "no graph \"type\" specified. Must be \"table\", \"line\", or \"scatter\""; } if (validGraphTypes.indexOf(config.type) === -1) { error = "Invalid graph \"type\" specified. Must be \"table\", \"line\", or \"scatter\""; } // Every config needs to specify the path to an individual record if (typeof config.path === "undefined") { error = "no \"path\" to individual record specified"; } // TODO: other validation for things like $, *, etc. switch (config.type) { case "map": if (typeof config.marker === "undefined" || typeof config.marker.latitude === "undefined" || typeof config.marker.longitude === "undefined" || typeof config.marker.magnitude === "undefined") { error = "incomplete \"marker\" definition specified. \nExpected: " + JSON.stringify(_getDefaultConfig().marker) + "\nActual: " + JSON.stringify(config.marker); } break; case "table": // Every table config needs to specify its column labels and values if (typeof config.columns === "undefined") { error = "no table \"columns\" specified"; } config.columns.forEach(function(column) { if (typeof column.label === "undefined") { error = "missing \"columns\" label"; } if (typeof column.value === "undefined") { error = "missing \"columns\" value"; } }); break; case "line": if (typeof config.xCoord === "undefined") { error = "no \"xCoord\" specified"; } if (typeof config.yCoord === "undefined") { error = "no \"yCoord\" specified."; } break; case "bar": if (typeof config.value === "undefined") { error = "no \"value\" specified."; } break; case "scatter": break; } if (typeof error !== "undefined") { throw new Error("FireGrapher: " + error); } }; /** * Validates the inputted grapher object. * * @param {object} grapher The grapher object to validate. */ var _validateGrapher = function(grapher) { var error; if (grapher === null || typeof grapher !== "object") { error = "\"grapher\" must be an object"; } // TODO: figure out what this should be to support both production and testing /*if (grapher instanceof D3Graph === false && grapher instanceof D3Table === false && grapher instanceof D3Map === false) { throw new Error("FireGrapher: \"grapher\" must be an instance of FireGrapherD3"); }*/ else if (typeof grapher.init !== "function") { error = "\"grapher\" must have an init() method"; } else if (typeof grapher.draw !== "function") { error = "\"grapher\" must have a draw() method"; } else if (typeof grapher.addDataPoint !== "function") { error = "\"grapher\" must have a addDataPoint() method"; } if (typeof error !== "undefined") { throw new Error("FireGrapher: " + error); } }; /** * Adds default values to the graph config object */ var _getDefaultConfig = function() { // Default colors (turquoise, alizaren (red), amethyst (purple), peter river (blue), sunflower, pumpkin, emerald, carrot, midnight blue, pomegranate) var defaultStrokeColors = ["#1ABC9C", "#E74C3C", "#9B59B6", "#3498DB", "#F1C40F", "#D35400", "#2ECC71", "#E67E22", "#2C3E50", "#C0392B"]; var defaultFillColors = ["#28E1BC", "#ED7469", "#B07CC6", "#5FAEE3", "#F4D03F", "#FF6607", "#54D98B", "#EB9850", "#3E5771", "#D65448"]; // Define a default config object return { "styles": { "fillColor": "#DDDDDD", "fillOpacity": 0.3, "outerStrokeColor": "#000000", "outerStrokeWidth": 2, "innerStrokeColor": "#000000", "innerStrokeWidth": 1, /*"size": { "width": 500, "height": 300 },*/ "axes": { "x": { "ticks": { "fillColor": "#000000", "fontSize": "14px" }, "label": { "fillColor": "#000000", "fontSize": "14px" } }, "y": { "ticks": { "fillColor": "#000000", "fontSize": "14px" }, "label": { "fillColor": "#000000", "fontSize": "14px" } } }, "series": { "strokeWidth": 2, "strokeColors": defaultStrokeColors }, "markers": { "size": 3.5, "strokeWidth": 2, "style": "default", "strokeColors": defaultStrokeColors, "fillColors": defaultFillColors // What about if style is set to "flat"? }, "legend": { "fontSize": "16px", "stroke": "#000000", "strokeWidth": "2px", "fill": "#AAAAAA", "fillOpacity": 0.7 } }, "xCoord": { "label": "" }, "yCoord": { "label": "" }, "marker": { "label" : "label", "latitude" : "latitude", "longitude" : "longitude", "magnitude" : "radius" } }; };
lauradhamilton/firegrapher
src/firegrapherUtils.js
JavaScript
mit
6,936
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.storage.blob.changefeed.models; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** * This class represents the different BlobChangefeedEventTypes. */ public final class BlobChangefeedEventType extends ExpandableStringEnum<BlobChangefeedEventType> { /** * Static value BlobCreated for BlobChangefeedEventType. */ public static final BlobChangefeedEventType BLOB_CREATED = fromString("BlobCreated"); /** * Static value BlobDeleted for BlobChangefeedEventType. */ public static final BlobChangefeedEventType BLOB_DELETED = fromString("BlobDeleted"); /** * Creates or finds a BlobChangefeedEventType from its string representation. * * @param name a name to look for. * @return the corresponding BlobChangefeedEventType. */ public static BlobChangefeedEventType fromString(String name) { return fromString(name, BlobChangefeedEventType.class); } /** * @return known BlobChangefeedEventType values. */ public static Collection<BlobChangefeedEventType> values() { return values(BlobChangefeedEventType.class); } }
selvasingh/azure-sdk-for-java
sdk/storage/azure-storage-blob-changefeed/src/main/java/com/azure/storage/blob/changefeed/models/BlobChangefeedEventType.java
Java
mit
1,274
/** * Method to set dom events * * @example * wysihtml.dom.observe(iframe.contentWindow.document.body, ["focus", "blur"], function() { ... }); */ wysihtml.dom.observe = function(element, eventNames, handler) { eventNames = typeof(eventNames) === "string" ? [eventNames] : eventNames; var handlerWrapper, eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.addEventListener) { element.addEventListener(eventName, handler, false); } else { handlerWrapper = function(event) { if (!("target" in event)) { event.target = event.srcElement; } event.preventDefault = event.preventDefault || function() { this.returnValue = false; }; event.stopPropagation = event.stopPropagation || function() { this.cancelBubble = true; }; handler.call(element, event); }; element.attachEvent("on" + eventName, handlerWrapper); } } return { stop: function() { var eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.removeEventListener) { element.removeEventListener(eventName, handler, false); } else { element.detachEvent("on" + eventName, handlerWrapper); } } } }; };
Voog/wysihtml
src/dom/observe.js
JavaScript
mit
1,440
namespace SportSystem.Data { using System; using System.Collections.Generic; using SportSystem.Data.Repositories; using SportSystem.Models; public class SportSystemData : ISportSystemData { private ISportSystemDbContext context; private IDictionary<Type, object> repositories; public SportSystemData(ISportSystemDbContext context) { this.context = context; this.repositories = new Dictionary<Type, object>(); } public IRepository<User> Users { get { return this.GetRepository<User>(); } } public IRepository<Bet> Bets { get { return this.GetRepository<Bet>(); } } public IRepository<Match> Matches { get { return this.GetRepository<Match>(); } } public IRepository<Comment> Comments { get { return this.GetRepository<Comment>(); } } public IRepository<Player> Players { get { return this.GetRepository<Player>(); } } public IRepository<Team> Teams { get { return this.GetRepository<Team>(); } } public IRepository<Vote> Votes { get { return this.GetRepository<Vote>(); } } public int SaveChanges() { return this.context.SaveChanges(); } private IRepository<T> GetRepository<T>() where T : class { var type = typeof(T); if (!this.repositories.ContainsKey(type)) { var typeOfRepository = typeof(GenericRepository<T>); var repository = Activator.CreateInstance(typeOfRepository, this.context); this.repositories.Add(type, repository); } return (IRepository<T>)this.repositories[type]; } } }
kaizer04/SoftUni
ASP.NET MVC/toSend/SportSystem/SportSystem.Data/SportSystemData.cs
C#
mit
1,917
import { includes } from './array_proxy' /** * Given a record and an update object, apply the update on the record. Note * that the `operate` object is unapplied. * * @param {Object} record * @param {Object} update */ export default function applyUpdate (record, update) { for (let field in update.replace) record[field] = update.replace[field] for (let field in update.push) { const value = update.push[field] record[field] = record[field] ? record[field].slice() : [] if (Array.isArray(value)) record[field].push(...value) else record[field].push(value) } for (let field in update.pull) { const value = update.pull[field] record[field] = record[field] ? record[field].slice().filter(exclude.bind(null, Array.isArray(value) ? value : [ value ])) : [] } } function exclude (values, value) { return !includes(values, value) }
geoapi/crowdclarify
node_modules/fortune/lib/common/apply_update.js
JavaScript
mit
891
from django import template from django.utils.safestring import mark_safe from django.utils.html import escape from django.utils.translation import ugettext as _ from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR from django.conf import settings from django.contrib.sites.models import Site from BeautifulSoup import BeautifulSoup register = template.Library() @register.simple_tag def atb_site_link(): if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK: return ''' <li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i class="icon-home icon-white"></i></a></li> <li class="divider-vertical"></li> ''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site')) else: return '' @register.simple_tag def atb_site_name(): if 'django.contrib.sites' in settings.INSTALLED_APPS: return Site.objects.get_current().name else: return _('Django site') @register.simple_tag def bootstrap_page_url(cl, page_num): """ generates page URL for given page_num, uses for prev and next links django numerates pages from 0 """ return escape(cl.get_query_string({PAGE_VAR: page_num-1})) DOT = '.' def bootstrap_paginator_number(cl,i, li_class=None): """ Generates an individual page index link in a paginated list. """ if i == DOT: return u'<li><a href="#">...</a></li>' elif i == cl.page_num: return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1)) else: return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1)) paginator_number = register.simple_tag(bootstrap_paginator_number) def bootstrap_pagination(cl): """ Generates the series of links to the pages in a paginated list. """ paginator, page_num = cl.paginator, cl.page_num pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page if not pagination_required: page_range = [] else: ON_EACH_SIDE = 3 ON_ENDS = 2 # If there are 10 or fewer pages, display links to every page. # Otherwise, do some fancy if paginator.num_pages <= 10: page_range = range(paginator.num_pages) else: # Insert "smart" pagination links, so that there are always ON_ENDS # links at either end of the list of pages, and there are always # ON_EACH_SIDE links at either end of the "current page" link. page_range = [] if page_num > (ON_EACH_SIDE + ON_ENDS): page_range.extend(range(0, ON_EACH_SIDE - 1)) page_range.append(DOT) page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1)) else: page_range.extend(range(0, page_num + 1)) if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1): page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1)) page_range.append(DOT) page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages)) else: page_range.extend(range(page_num + 1, paginator.num_pages)) need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page return { 'cl': cl, 'pagination_required': pagination_required, 'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}), 'page_range': page_range, 'ALL_VAR': ALL_VAR, '1': 1, 'curr_page': cl.paginator.page(cl.page_num+1), } bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination) # breadcrumbs tag class BreadcrumbsNode(template.Node): """ renders bootstrap breadcrumbs list. usage:: {% breadcrumbs %} url1|text1 url2|text2 text3 {% endbreadcrumbs %} | is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it. lines without delimiters are interpreted as active breadcrumbs """ def __init__(self, nodelist, delimiter): self.nodelist = nodelist self.delimiter = delimiter def render(self, context): data = self.nodelist.render(context).strip() if not data: return '' try: data.index('<div class="breadcrumbs">') except ValueError: lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ] else: # data is django-style breadcrumbs, parsing try: soup = BeautifulSoup(data) lines = [ (a.get('href'), a.text) for a in soup.findAll('a')] lines.append([soup.find('div').text.split('&rsaquo;')[-1].strip()]) except Exception, e: lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]] out = '<ul class="breadcrumb">' curr = 0 for d in lines: if d[0][0] == '*': active = ' class="active"' d[0] = d[0][1:] else: active = '' curr += 1 if (len(lines) == curr): # last divider = '' else: divider = '<span class="divider">/</span>' if len(d) == 2: out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider) elif len(d) == 1: out += '<li%s>%s%s</li>' % (active, d[0], divider) else: raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d)) out += '</ul>' return out @register.tag(name='breadcrumbs') def do_breadcrumbs(parser, token): try: tag_name, delimiter = token.contents.split(None, 1) except ValueError: delimiter = '|' nodelist = parser.parse(('endbreadcrumbs',)) parser.delete_first_token() return BreadcrumbsNode(nodelist, delimiter)
quinode/django-admintools-bootstrap
admintools_bootstrap/templatetags/admintools_bootstrap.py
Python
mit
6,117
/* 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.klinker.android.link_builder; import android.graphics.Color; import android.os.Handler; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.view.View; public class TouchableSpan extends ClickableSpan { private final Link link; public boolean touched = false; /** * Construct new TouchableSpan using the link * @param link */ public TouchableSpan(Link link) { this.link = link; } /** * This TouchableSpan has been clicked. * @param widget TextView containing the touchable span */ public void onClick(View widget) { // handle the click if (link.getClickListener() != null) { link.getClickListener().onClick(link.getText()); } new Handler().postDelayed(new Runnable() { @Override public void run() { TouchableMovementMethod.touched = false; } }, 500); } /** * This TouchableSpan has been long clicked. * @param widget TextView containing the touchable span */ public void onLongClick(View widget) { // handle the long click if (link.getLongClickListener() != null) { link.getLongClickListener().onLongClick(link.getText()); } new Handler().postDelayed(new Runnable() { @Override public void run() { TouchableMovementMethod.touched = false; } }, 500); } /** * Set the alpha for the color based on the alpha factor * @param color original color * @param factor how much we want to scale the alpha to * @return new color with scaled alpha */ public int adjustAlpha(int color, float factor) { int alpha = Math.round(Color.alpha(color) * factor); int red = Color.red(color); int green = Color.green(color); int blue = Color.blue(color); return Color.argb(alpha, red, green, blue); } /** * Draw the links background and set whether or not we want it to be underlined * @param ds the link */ @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(link.isUnderlined()); ds.setColor(link.getTextColor()); ds.bgColor = touched ? adjustAlpha(link.getTextColor(), link.getHighlightAlpha()) : Color.TRANSPARENT; } /** * Specifiy whether or not the link is currently touched * @param touched */ public void setTouched(boolean touched) { this.touched = touched; } }
klinker41/Android-TextView-LinkBuilder
library/src/main/java/com/klinker/android/link_builder/TouchableSpan.java
Java
mit
3,202
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.policy.v2018_05_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for PolicyType. */ public final class PolicyType extends ExpandableStringEnum<PolicyType> { /** Static value NotSpecified for PolicyType. */ public static final PolicyType NOT_SPECIFIED = fromString("NotSpecified"); /** Static value BuiltIn for PolicyType. */ public static final PolicyType BUILT_IN = fromString("BuiltIn"); /** Static value Custom for PolicyType. */ public static final PolicyType CUSTOM = fromString("Custom"); /** * Creates or finds a PolicyType from its string representation. * @param name a name to look for * @return the corresponding PolicyType */ @JsonCreator public static PolicyType fromString(String name) { return fromString(name, PolicyType.class); } /** * @return known PolicyType values */ public static Collection<PolicyType> values() { return values(PolicyType.class); } }
navalev/azure-sdk-for-java
sdk/policy/mgmt-v2018_05_01/src/main/java/com/microsoft/azure/management/policy/v2018_05_01/PolicyType.java
Java
mit
1,356
# -*- coding: utf-8 -*- """ Written by Daniel M. Aukes and CONTRIBUTORS Email: danaukes<at>asu.edu. Please see LICENSE for full license. """ import sys import popupcad import qt.QtCore as qc import qt.QtGui as qg if __name__=='__main__': app = qg.QApplication(sys.argv[0]) filename_from = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R08.cad' filename_to = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R09.cad' d = popupcad.filetypes.design.Design.load_yaml(filename_from) widget = qg.QDialog() layout = qg.QVBoxLayout() layout1 = qg.QHBoxLayout() layout2 = qg.QHBoxLayout() list1 = qg.QListWidget() list2 = qg.QListWidget() button_ok = qg.QPushButton('Ok') button_cancel = qg.QPushButton('Cancel') subdesign_list = list(d.subdesigns.values()) for item in subdesign_list: list1.addItem(str(item)) list2.addItem(str(item)) layout1.addWidget(list1) layout1.addWidget(list2) layout2.addWidget(button_ok) layout2.addWidget(button_cancel) layout.addLayout(layout1) layout.addLayout(layout2) widget.setLayout(layout) button_ok.pressed.connect(widget.accept) button_cancel.pressed.connect(widget.reject) if widget.exec_(): if len(list1.selectedIndexes())==1 and len(list2.selectedIndexes())==1: ii_from = list1.selectedIndexes()[0].row() ii_to = list2.selectedIndexes()[0].row() print(ii_from,ii_to) d.replace_subdesign_refs(subdesign_list[ii_from].id,subdesign_list[ii_to].id) d.subdesigns.pop(subdesign_list[ii_from].id) d.save_yaml(filename_to) sys.exit(app.exec_())
danaukes/popupcad
api_examples/switch_subdesign.py
Python
mit
1,814
/** * Parse an array of chromsizes, for example that result * from reading rows of a chromsizes CSV file. * @param {array} data Array of [chrName, chrLen] "tuples". * @returns {object} Object containing properties * { cumPositions, chrPositions, totalLength, chromLengths }. */ function parseChromsizesRows(data) { const cumValues = []; const chromLengths = {}; const chrPositions = {}; let totalLength = 0; for (let i = 0; i < data.length; i++) { const length = Number(data[i][1]); totalLength += length; const newValue = { id: i, chr: data[i][0], pos: totalLength - length, }; cumValues.push(newValue); chrPositions[newValue.chr] = newValue; chromLengths[data[i][0]] = length; } return { cumPositions: cumValues, chrPositions, totalLength, chromLengths, }; } export default parseChromsizesRows;
hms-dbmi/4DN_matrix-viewer
app/scripts/utils/parse-chromsizes-rows.js
JavaScript
mit
887
'use strict'; /** * Module dependencies */ var hbs = require('express-hbs'); function content(options) { return new hbs.handlebars.SafeString(this.html || ''); } module.exports = content; // downsize = Tag-safe truncation for HTML and XML. Works by word!
Robinyo/Vardyger
core/server/helpers/content.js
JavaScript
mit
263
require 'spec_helper' describe Listen::TCP::Broadcaster do let(:host) { '10.0.0.2' } let(:port) { 4000 } subject { described_class.new(host, port) } let(:server) { double(described_class::TCPServer, close: true, accept: nil) } let(:socket) { double(described_class::TCPSocket, write: true) } let(:payload) { Listen::TCP::Message.new.payload } before do expect(described_class::TCPServer).to receive(:new).with(host, port).and_return server end after do subject.terminate end describe '#initialize' do it 'initializes and exposes a server' do expect(subject.server).to be server end it 'initializes and exposes a list of sockets' do expect(subject.sockets).to eq [] end end describe '#start' do let(:async) { double('TCP-listener async') } it 'invokes run loop asynchronously' do subject.stub(:async).and_return async expect(async).to receive(:run) subject.start end end describe '#finalize' do it 'clears sockets' do expect(subject.sockets).to receive(:clear) subject.finalize end it 'closes server' do expect(subject.server).to receive(:close) subject.finalize expect(subject.server).to be_nil end end describe '#broadcast' do it 'unicasts to connected sockets' do subject.handle_connection socket expect(subject.wrapped_object).to receive(:unicast).with socket, payload subject.broadcast payload end end describe '#unicast' do before do subject.handle_connection socket end context 'when succesful' do it 'returns true and leaves socket untouched' do expect(subject.unicast(socket, payload)).to be_true expect(subject.sockets).to include socket end end context 'on IO errors' do it 'returns false and removes socket from list' do socket.stub(:write).and_raise IOError expect(subject.unicast(socket, payload)).to be_false expect(subject.sockets).not_to include socket end end context 'on connection reset by peer' do it 'returns false and removes socket from list' do socket.stub(:write).and_raise Errno::ECONNRESET expect(subject.unicast(socket, payload)).to be_false expect(subject.sockets).not_to include socket end end context 'on broken pipe' do it 'returns false and removes socket from list' do socket.stub(:write).and_raise Errno::EPIPE expect(subject.unicast(socket, payload)).to be_false expect(subject.sockets).not_to include socket end end end describe '#run' do it 'handles incoming connections' do server.stub(:accept).and_return socket, nil expect(subject.wrapped_object).to receive(:handle_connection).with socket subject.run end end describe '#handle_connection' do it 'adds socket to list' do subject.handle_connection socket expect(subject.sockets).to include socket end end end
bradholbrook/rJackal
vendor/bundle/ruby/1.9.1/gems/listen-2.7.1/spec/lib/listen/tcp/broadcaster_spec.rb
Ruby
mit
3,035
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Calculator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Calculator")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f1f48b44-c998-4862-bf13-3a26a6ab009e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
tokera/TelerikAcademyHomeworks
HTML/HTMLTables/Calculator/Properties/AssemblyInfo.cs
C#
mit
1,356
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M15 6H4v12.01h16V11h-5z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M4 4c-1.1 0-2 .9-2 2v12.01c0 1.1.9 1.99 2 1.99h16c1.1 0 2-.9 2-2v-8l-6-6H4zm16 14.01H4V6h11v5h5v7.01z" }, "1")], 'NoteTwoTone'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/NoteTwoTone.js
JavaScript
mit
675
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const _ = require("underscore") const path = require("path") const jade = require("jade") const fs = require("fs") const moment = require("moment") const Curation = require("../../../../../models/curation.coffee") const Article = require("../../../../../models/article.coffee") const render = function (templateName) { const filename = path.resolve( __dirname, `../../../components/venice_2017/templates/${templateName}.jade` ) return jade.compile(fs.readFileSync(filename), { filename }) } describe("Venice index", () => it("uses social metadata", function () { const curation = new Curation({ sections: [ { social_description: "Social Description", social_title: "Social Title", social_image: "files.artsy.net/img/social_image.jpg", seo_description: "Seo Description", }, ], sub_articles: [], }) const html = render("index")({ videoIndex: 0, curation, isSubscribed: false, sub_articles: [], videoGuide: new Article(), crop(url) { return url }, resize(url) { return url }, moment, sd: {}, markdown() {}, asset() {}, }) html.should.containEql( '<meta property="og:image" content="files.artsy.net/img/social_image.jpg">' ) html.should.containEql('<meta property="og:title" content="Social Title">') html.should.containEql( '<meta property="og:description" content="Social Description">' ) return html.should.containEql( '<meta name="description" content="Seo Description">' ) })) describe("Venice video_completed", () => it("passes section url to social mixin", function () { const html = render("video_completed")({ section: { social_title: "Social Title", slug: "ep-1", }, sd: { APP_URL: "http://localhost:5000" }, }) html.should.containEql( "https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Flocalhost%3A5000%2Fvenice-biennale%2Fep-1" ) return html.should.containEql("Social Title") })) describe("Venice video_description", () => it("passes section url to social mixin", function () { const html = render("video_description")({ section: { social_title: "Social Title", slug: "ep-1", published: true, }, sd: { APP_URL: "http://localhost:5000" }, markdown() {}, }) html.should.containEql( "https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Flocalhost%3A5000%2Fvenice-biennale%2Fep-1" ) return html.should.containEql("Social Title") }))
joeyAghion/force
src/desktop/apps/editorial_features/test/components/venice_2017/templates.test.js
JavaScript
mit
2,842
require "spec_helper" RSpec.describe PlainRuby::Vehicle do let(:vehicle) { described_class.new } before do expect(vehicle.state).to eq :parked end it "can properly run throught all the states" do vehicle.ignite expect(vehicle.state).to eq :idling vehicle.shift_up expect(vehicle.state).to eq :first_gear vehicle.shift_up expect(vehicle.state).to eq :second_gear vehicle.shift_up expect(vehicle.state).to eq :third_gear vehicle.shift_down expect(vehicle.state).to eq :second_gear vehicle.shift_down expect(vehicle.state).to eq :first_gear vehicle.crash expect(vehicle.state).to eq :stalled vehicle.repair expect(vehicle.state).to eq :parked vehicle.ignite expect(vehicle.state).to eq :idling vehicle.shift_up expect(vehicle.state).to eq :first_gear vehicle.idle expect(vehicle.state).to eq :idling end it 'returns error when transition rule is not respected' do expect { vehicle.crash }.to raise_error RuntimeError expect(vehicle.state).to eq :parked end context 'when event has multiple transition and is called in wrong state' do it 'returns error' do expect { vehicle.shift_down }.to raise_error RuntimeError end end end
SamuelMartini/interstate_machine
spec/integration/plain_ruby/vehicle_spec.rb
Ruby
mit
1,269
ActiveRecord::Schema.define do create_table :users, comment: "comment" do |t| t.string :nickname t.string :thumbnail_url t.binary :blob t.datetime :joined_at t.datetime :deleted_at t.timestamps end create_sequence_for :users, comment: "comment" create_table :user_profiles do |t| t.belongs_to :user, null: false t.date :birthday t.text :data t.boolean :published, null: false, default: false t.integer :lock_version, null: false, default: 0 t.datetime :deleted_at, default: nil t.timestamps end create_sequence_for :user_profiles create_table :items do |t| t.string :name, null: false t.timestamps end create_table :user_items do |t| t.belongs_to :user, null: false t.belongs_to :item, null: false t.integer :num, null: false, default: 1 t.datetime :deleted_at, default: nil t.timestamps end create_sequence_for :user_items create_table :user_item_histories do |t| t.belongs_to :user, null: false t.belongs_to :user_item, null: false t.timestamps end create_sequence_for :user_item_histories create_table :user_event_histories do |t| t.belongs_to :user, null: false t.belongs_to :event_user, null: false t.belongs_to :user_item, null: false t.string :type, default: nil t.timestamps end create_sequence_for :user_event_histories end
drecom/activerecord-turntable
spec/migrations/schema.rb
Ruby
mit
1,456
#region Copyright // // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion #region Usings using System; using System.Collections.Generic; using System.Linq; using System.Net; using Dnn.PersonaBar.Roles.Services.DTO; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Framework; using DotNetNuke.Security.Roles; using DotNetNuke.Services.Localization; #endregion namespace Dnn.PersonaBar.Roles.Components { public class RolesController : ServiceLocator<IRolesController, RolesController>, IRolesController { protected override Func<IRolesController> GetFactory() { return () => new RolesController(); } #region Public Methods /// <summary> /// Gets a paginated list of Roles matching given search criteria /// </summary> /// <param name="portalSettings"></param> /// <param name="groupId"></param> /// <param name="keyword"></param> /// <param name="total"></param> /// <param name="startIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public IEnumerable<RoleInfo> GetRoles(PortalSettings portalSettings, int groupId, string keyword, out int total, int startIndex, int pageSize) { var isAdmin = IsAdmin(portalSettings); var roles = (groupId < Null.NullInteger ? RoleController.Instance.GetRoles(portalSettings.PortalId) : RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.RoleGroupID == groupId)) .Where(r => isAdmin || r.RoleID != portalSettings.AdministratorRoleId); if (!string.IsNullOrEmpty(keyword)) { roles = roles.Where(r => r.RoleName.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) > Null.NullInteger); } var roleInfos = roles as IList<RoleInfo> ?? roles.ToList(); total = roleInfos.Count; return roleInfos.Skip(startIndex).Take(pageSize); } /// <summary> /// Gets a list (not paginated) of Roles given a comma separated list of Roles' names. /// </summary> /// <param name="portalSettings"></param> /// <param name="groupId"></param> /// <param name="rolesFilter"></param> /// <returns>List of found Roles</returns> public IList<RoleInfo> GetRolesByNames(PortalSettings portalSettings, int groupId, IList<string> rolesFilter) { var isAdmin = IsAdmin(portalSettings); List<RoleInfo> foundRoles = null; if (rolesFilter.Count() > 0) { var allRoles = (groupId < Null.NullInteger ? RoleController.Instance.GetRoles(portalSettings.PortalId) : RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.RoleGroupID == groupId)); foundRoles = allRoles.Where(r => { bool adminCheck = isAdmin || r.RoleID != portalSettings.AdministratorRoleId; return adminCheck && rolesFilter.Contains(r.RoleName); }).ToList(); } return foundRoles; } public RoleInfo GetRole(PortalSettings portalSettings, int roleId) { var isAdmin = IsAdmin(portalSettings); var role = RoleController.Instance.GetRoleById(portalSettings.PortalId, roleId); if (!isAdmin && role.RoleID == portalSettings.AdministratorRoleId) return null; return role; } public bool SaveRole(PortalSettings portalSettings, RoleDto roleDto, bool assignExistUsers, out KeyValuePair<HttpStatusCode, string> message) { message = new KeyValuePair<HttpStatusCode, string>(); if (!IsAdmin(portalSettings) && roleDto.Id == portalSettings.AdministratorRoleId) { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.BadRequest, Localization.GetString("InvalidRequest", Constants.LocalResourcesFile)); return false; } var role = roleDto.ToRoleInfo(); role.PortalID = portalSettings.PortalId; var rolename = role.RoleName.ToUpperInvariant(); if (roleDto.Id == Null.NullInteger) { if (RoleController.Instance.GetRole(portalSettings.PortalId, r => rolename.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase)) == null) { RoleController.Instance.AddRole(role, assignExistUsers); roleDto.Id = role.RoleID; } else { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.BadRequest, Localization.GetString("DuplicateRole", Constants.LocalResourcesFile)); return false; } } else { var existingRole = RoleController.Instance.GetRoleById(portalSettings.PortalId, roleDto.Id); if (existingRole == null) { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.NotFound, Localization.GetString("RoleNotFound", Constants.LocalResourcesFile)); return false; } if (existingRole.IsSystemRole) { if (role.Description != existingRole.Description)//In System roles only description can be updated. { existingRole.Description = role.Description; RoleController.Instance.UpdateRole(existingRole, assignExistUsers); } } else if (RoleController.Instance.GetRole(portalSettings.PortalId, r => rolename.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase) && r.RoleID != roleDto.Id) == null) { existingRole.RoleName = role.RoleName; existingRole.Description = role.Description; existingRole.RoleGroupID = role.RoleGroupID; existingRole.SecurityMode = role.SecurityMode; existingRole.Status = role.Status; existingRole.IsPublic = role.IsPublic; existingRole.AutoAssignment = role.AutoAssignment; existingRole.RSVPCode = role.RSVPCode; RoleController.Instance.UpdateRole(existingRole, assignExistUsers); } else { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.BadRequest, Localization.GetString("DuplicateRole", Constants.LocalResourcesFile)); return false; } } return true; } public string DeleteRole(PortalSettings portalSettings, int roleId, out KeyValuePair<HttpStatusCode, string> message) { message = new KeyValuePair<HttpStatusCode, string>(); var role = RoleController.Instance.GetRoleById(portalSettings.PortalId, roleId); if (role == null) { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.NotFound, Localization.GetString("RoleNotFound", Constants.LocalResourcesFile)); return string.Empty; } if (role.IsSystemRole) { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.BadRequest, Localization.GetString("SecurityRoleDeleteNotAllowed", Constants.LocalResourcesFile)); return string.Empty; } if (role.RoleID == portalSettings.AdministratorRoleId && !IsAdmin(portalSettings)) { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.BadRequest, Localization.GetString("InvalidRequest", Constants.LocalResourcesFile)); return string.Empty; } RoleController.Instance.DeleteRole(role); DataCache.RemoveCache("GetRoles"); return role.RoleName; } #endregion #region Private Methods private bool IsAdmin(PortalSettings portalSettings) { var user = UserController.Instance.GetCurrentUserInfo(); return user.IsSuperUser || user.IsInRole(portalSettings.AdministratorRoleName); } #endregion } }
RichardHowells/Dnn.Platform
Dnn.AdminExperience/Extensions/Content/Dnn.PersonaBar.Extensions/Components/Roles/RolesController.cs
C#
mit
9,819
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-10 18:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0006_auto_20160616_1640'), ] operations = [ migrations.AlterField( model_name='episode', name='edit_key', field=models.CharField(blank=True, default='41086227', help_text='key to allow unauthenticated users to edit this item.', max_length=32, null=True), ), ]
xfxf/veyepar
dj/main/migrations/0007_auto_20160710_1833.py
Python
mit
560
require 'spec_helper' require 'vcr' describe FullCircle::API do let(:connection){FullCircle::Connection.new("360durango.com")} let(:api){FullCircle::API.new(connection)} describe "#fetch_events_for_ad" do it "returns an array of one event" do VCR.use_cassette "get_events_for_ad_response" do results = api.fetch_events_for_ad "81299" expect(results.length > 0).to eq(true) end end context "with no events" do it "returns an empty array" do VCR.use_cassette "empty_get_events_for_ad_response" do results = api.fetch_events_for_ad "1" expect(results.length).to eq(0) end end end end describe "#fetch_coupons_for_ad" do it "calls the appropriate method on call_api_method" do parser = instance_double("FullCircle::Parsing::ResponseParser", parse: double('result', entities: [])) mock_connection = instance_double("FullCircle::Connection") allow(mock_connection).to receive(:call_api_method) described_class.new(mock_connection, response_parser: parser).fetch_coupons_for_ad("1", page: 2) expect(mock_connection).to have_received(:call_api_method).with("ad.getCoupons",{adId: "1", page: 2, resultsPerPage: 20}) end it "returns an array of coupons" do VCR.use_cassette "get_coupons_for_ad_response" do results = api.fetch_coupons_for_ad "89588" expect(results.length > 0).to eq(true) end end context "with no coupons" do it "returns an empty array" do VCR.use_cassette "empty_get_coupons_response" do results = api.fetch_coupons_for_ad "1" expect(results.length).to eq(0) end end end end describe "#fetch_jobs_for_ad" do it "calls the appropriate method on call_api_method" do parser = instance_double("FullCircle::Parsing::ResponseParser", parse: double('result', entities: [])) mock_connection = instance_double("FullCircle::Connection") allow(mock_connection).to receive(:call_api_method) described_class.new(mock_connection, response_parser: parser).fetch_jobs_for_ad("1", page: 2) expect(mock_connection).to have_received(:call_api_method).with("ad.getJobs",{adId: "1", page: 2, resultsPerPage: 20}) end it "returns an array of jobs" do VCR.use_cassette "get_jobs_for_ad_response" do results = api.fetch_jobs_for_ad "81231" expect(results.length > 0).to eq(true) end end context "with no jobs" do it "returns an empty array" do VCR.use_cassette "empty_get_jobs_response" do results = api.fetch_jobs_for_ad "1" expect(results.length).to eq(0) end end end end describe "#fetch_event_areas" do it "returns an array of event areas" do VCR.use_cassette "event_areas_response" do results = api.fetch_event_areas expect(results.length > 0).to eq(true) end end context "with no event areas" do let(:connection){FullCircle::Connection.new("boatersbluepages.com")} it "returns an empty array" do VCR.use_cassette "empty_event_area_response" do results = api.fetch_event_areas expect(results.length).to eq(0) end end end end describe "#fetch_upcoming_events" do it "returns an array of multiple events" do VCR.use_cassette "get_upcoming_events_response" do results = api.fetch_upcoming_events expect(results.length > 1).to eq(true) end end context "with no events" do let(:connection){FullCircle::Connection.new("boatersbluepages.com")} it "returns an empty array" do VCR.use_cassette "empty_get_upcoming_events_response" do results = api.fetch_upcoming_events expect(results.length).to eq(0) end end end end describe "#fetch_ads" do it "returns an array of ads" do VCR.use_cassette "get_ads_response" do results = api.fetch_ads.results expect(results.length > 1).to eq(true) expect(results[0]['tile']['url']).to eq 'http://tours.360durango.com/89540/tile.gif' expect(results[0]['logo']['width']).to eq 250 expect(results[0]['logo2']['height']).to eq 60 end end # API server returns an error response instead of an empty array context "when no results are found when searching by org id" do it "returns_an empty array" do VCR.use_cassette "get_ads_with_nonexisted_orgId_response" do results = api.fetch_ads(orgId: 1) expect(results.length).to eq(0) end end end # context "with no events" do # let(:connection){FullCircle::Connection.new("boatersbluepages.com")} # it "returns an empty array" do # VCR.use_cassette "empty_get_upcoming_events_response" do # results = api.fetch_upcoming_events # expect(results).to eq([]) # end # end # end end end
elchingon/full_circle
spec/full_circle/api_spec.rb
Ruby
mit
5,040
// Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // #include "libcef_dll/cpptoc/views/window_delegate_cpptoc.h" #include "libcef_dll/ctocpp/views/view_ctocpp.h" #include "libcef_dll/ctocpp/views/window_ctocpp.h" namespace { // MEMBER FUNCTIONS - Body may be edited by hand. void CEF_CALLBACK window_delegate_on_window_created( struct _cef_window_delegate_t* self, cef_window_t* window) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: window; type: refptr_diff DCHECK(window); if (!window) return; // Execute CefWindowDelegateCppToC::Get(self)->OnWindowCreated( CefWindowCToCpp::Wrap(window)); } void CEF_CALLBACK window_delegate_on_window_destroyed( struct _cef_window_delegate_t* self, cef_window_t* window) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: window; type: refptr_diff DCHECK(window); if (!window) return; // Execute CefWindowDelegateCppToC::Get(self)->OnWindowDestroyed( CefWindowCToCpp::Wrap(window)); } int CEF_CALLBACK window_delegate_is_frameless( struct _cef_window_delegate_t* self, cef_window_t* window) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: window; type: refptr_diff DCHECK(window); if (!window) return 0; // Execute bool _retval = CefWindowDelegateCppToC::Get(self)->IsFrameless( CefWindowCToCpp::Wrap(window)); // Return type: bool return _retval; } int CEF_CALLBACK window_delegate_can_resize(struct _cef_window_delegate_t* self, cef_window_t* window) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: window; type: refptr_diff DCHECK(window); if (!window) return 0; // Execute bool _retval = CefWindowDelegateCppToC::Get(self)->CanResize( CefWindowCToCpp::Wrap(window)); // Return type: bool return _retval; } int CEF_CALLBACK window_delegate_can_maximize( struct _cef_window_delegate_t* self, cef_window_t* window) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: window; type: refptr_diff DCHECK(window); if (!window) return 0; // Execute bool _retval = CefWindowDelegateCppToC::Get(self)->CanMaximize( CefWindowCToCpp::Wrap(window)); // Return type: bool return _retval; } int CEF_CALLBACK window_delegate_can_minimize( struct _cef_window_delegate_t* self, cef_window_t* window) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: window; type: refptr_diff DCHECK(window); if (!window) return 0; // Execute bool _retval = CefWindowDelegateCppToC::Get(self)->CanMinimize( CefWindowCToCpp::Wrap(window)); // Return type: bool return _retval; } int CEF_CALLBACK window_delegate_can_close(struct _cef_window_delegate_t* self, cef_window_t* window) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: window; type: refptr_diff DCHECK(window); if (!window) return 0; // Execute bool _retval = CefWindowDelegateCppToC::Get(self)->CanClose( CefWindowCToCpp::Wrap(window)); // Return type: bool return _retval; } cef_size_t CEF_CALLBACK window_delegate_get_preferred_size( struct _cef_view_delegate_t* self, cef_view_t* view) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return CefSize(); // Execute cef_size_t _retval = CefWindowDelegateCppToC::Get( reinterpret_cast<cef_window_delegate_t*>(self))->GetPreferredSize( CefViewCToCpp::Wrap(view)); // Return type: simple return _retval; } cef_size_t CEF_CALLBACK window_delegate_get_minimum_size( struct _cef_view_delegate_t* self, cef_view_t* view) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return CefSize(); // Execute cef_size_t _retval = CefWindowDelegateCppToC::Get( reinterpret_cast<cef_window_delegate_t*>(self))->GetMinimumSize( CefViewCToCpp::Wrap(view)); // Return type: simple return _retval; } cef_size_t CEF_CALLBACK window_delegate_get_maximum_size( struct _cef_view_delegate_t* self, cef_view_t* view) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return CefSize(); // Execute cef_size_t _retval = CefWindowDelegateCppToC::Get( reinterpret_cast<cef_window_delegate_t*>(self))->GetMaximumSize( CefViewCToCpp::Wrap(view)); // Return type: simple return _retval; } int CEF_CALLBACK window_delegate_get_height_for_width( struct _cef_view_delegate_t* self, cef_view_t* view, int width) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return 0; // Execute int _retval = CefWindowDelegateCppToC::Get( reinterpret_cast<cef_window_delegate_t*>(self))->GetHeightForWidth( CefViewCToCpp::Wrap(view), width); // Return type: simple return _retval; } void CEF_CALLBACK window_delegate_on_parent_view_changed( struct _cef_view_delegate_t* self, cef_view_t* view, int added, cef_view_t* parent) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return; // Verify param: parent; type: refptr_diff DCHECK(parent); if (!parent) return; // Execute CefWindowDelegateCppToC::Get(reinterpret_cast<cef_window_delegate_t*>( self))->OnParentViewChanged( CefViewCToCpp::Wrap(view), added?true:false, CefViewCToCpp::Wrap(parent)); } void CEF_CALLBACK window_delegate_on_child_view_changed( struct _cef_view_delegate_t* self, cef_view_t* view, int added, cef_view_t* child) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return; // Verify param: child; type: refptr_diff DCHECK(child); if (!child) return; // Execute CefWindowDelegateCppToC::Get(reinterpret_cast<cef_window_delegate_t*>( self))->OnChildViewChanged( CefViewCToCpp::Wrap(view), added?true:false, CefViewCToCpp::Wrap(child)); } } // namespace // CONSTRUCTOR - Do not edit by hand. CefWindowDelegateCppToC::CefWindowDelegateCppToC() { GetStruct()->on_window_created = window_delegate_on_window_created; GetStruct()->on_window_destroyed = window_delegate_on_window_destroyed; GetStruct()->is_frameless = window_delegate_is_frameless; GetStruct()->can_resize = window_delegate_can_resize; GetStruct()->can_maximize = window_delegate_can_maximize; GetStruct()->can_minimize = window_delegate_can_minimize; GetStruct()->can_close = window_delegate_can_close; GetStruct()->base.base.get_preferred_size = window_delegate_get_preferred_size; GetStruct()->base.base.get_minimum_size = window_delegate_get_minimum_size; GetStruct()->base.base.get_maximum_size = window_delegate_get_maximum_size; GetStruct()->base.base.get_height_for_width = window_delegate_get_height_for_width; GetStruct()->base.base.on_parent_view_changed = window_delegate_on_parent_view_changed; GetStruct()->base.base.on_child_view_changed = window_delegate_on_child_view_changed; } template<> CefRefPtr<CefWindowDelegate> CefCppToC<CefWindowDelegateCppToC, CefWindowDelegate, cef_window_delegate_t>::UnwrapDerived( CefWrapperType type, cef_window_delegate_t* s) { NOTREACHED() << "Unexpected class type: " << type; return NULL; } #ifndef NDEBUG template<> base::AtomicRefCount CefCppToC<CefWindowDelegateCppToC, CefWindowDelegate, cef_window_delegate_t>::DebugObjCt = 0; #endif template<> CefWrapperType CefCppToC<CefWindowDelegateCppToC, CefWindowDelegate, cef_window_delegate_t>::kWrapperType = WT_WINDOW_DELEGATE;
tnelab/tchapp
src/native/libtch_dll/libcef_dll/cpptoc/views/window_delegate_cpptoc.cc
C++
mit
9,115
// ---------------------------------------------------------------------------- // Copyright (C) 2014 Bloomberg Finance L.P. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ----------------------------- END-OF-FILE ----------------------------------
seanlth/bde_verify
checks/misc/joe/joexx/joexx_traits.t.cpp
C++
mit
1,283
using System; namespace Embeddinator.Tests.Samples { public class Enums { public void SystemEnumParameter(StringComparison value) { } public StringComparison SystemEnumProperty { get; set; } } }
mono/Embeddinator-4000
tests/MonoEmbeddinator4000.Tests/Samples/Enums.cs
C#
mit
228
<div class="btn-group" style="margin: 9px 0 25px;"> <p style="margin-bottom:0;"> <a href="<?php echo base_url();?>index.php/doctor/" class="btn btn-primary" style="margin-left:0;">返回列表</a> </p> </div> <form id="rec_form" class="form-horizontal" action="<?php echo base_url();?>index.php/doctor/update" method="post"> <input type="hidden" id="id" name="id" value="<?php echo $id; ?>" /> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">中文姓名</label> <div class="controls"> <input id="cn_name" name="cn_name" type="title" class="input" value="<?php echo $cn_name; ?>" required="" onkeyup="" autocomplete="off" placeholder="不超过12个字"/> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">英文姓名</label> <div class="controls"> <input id="en_name" name="en_name" type="title" class="input" value="<?php echo $en_name; ?>" required="" onkeyup="" autocomplete="off" placeholder="不超过12个字"/> </div> </div> <div class="control-group" id=""> <label class="control-label" for="thumb">医生照片(360x450)</label> <div class="controls"> <input type="file" id="file" style="visibility:hidden;position:absolute;top:-9999em" onchange="transfer(this.files, $('#dropBox_1')[0])" /> <input name="thumb" type="hidden" id="pic1" size="50" readonly="readonly" value="<?php echo $thumb; ?>"/> <div class="drop_img"> <div class="uploadpic" id="dropBox_1" data-width="0" data-height="0" nth="1"> <label for="file" style="width:100%;height:100%;"><img style="width:100%;height:100%;" id="pic_url" src=" <?php echo base_url('attached/image/'.$thumb); ?> "></label> </div> <div class="process" style="display:"> <progress id="p_1" max="100" value="0"></progress> <span style="display:none"></span> </div> <span></span> </div> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">注册专科</label> <div class="controls"> <select name="department" id="department"> <?php foreach ($departments as $key => $value) { ?> <option value="<?php echo $value['name']?>" <?php if($department === $value['name']) { echo 'selected'; } ?> ><?php echo $value['name']?></option> <?php } ?> </select> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">电话号码</label> <div class="controls"> <input id="tel" name="tel" type="title" class="number" value="<?php echo $tel; ?>" required="" onkeyup="" autocomplete="off" placeholder="不超过12个字"/> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">联系地址</label> <div class="controls"> <input id="addr" name="addr" type="title" class="number" value="<?php echo $addr; ?>" required="" onkeyup="" autocomplete="off" placeholder="不超过100个字"/> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">收费标准</label> <div class="controls"> <input id="charge" name="charge" type="title" class="number" value="<?php echo $charge; ?>" required="" onkeyup="" autocomplete="off" placeholder="支持输入整数数字"/>$起 </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">所在城市</label> <div class="controls"> <select name="city" id="city"> <?php foreach ($citys as $key => $value) { ?> <option value="<?php echo $value['name']?>" <?php if($city === $value['name']) { echo 'selected'; } ?> ><?php echo $value['name']?></option> <?php } ?> </select> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">专业资格</label> <div class="controls"> <input id="skill" name="skill" type="title" class="text" value="<?php echo $skill; ?>" required="" onkeyup="" autocomplete="off" placeholder="请用逗号或分号分隔专业资格"/> <div> <br /> <p>填写标准范例:</p> <p>香港理工大学物理疗学士1995,澳洲麦格里大学硕士2009</p> </div> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">诊治时间</label> <div class="controls"> <input id="time" name="time" type="title" class="text" value="<?php echo $time; ?>" required="" onkeyup="" autocomplete="off" placeholder="请用逗号或分号分隔诊治时间"/> <div> <br /> <p>填写标准范例:</p> <p>星期一:9:30-10:00 10:30-11:00, 星期五:16:00</p> </div> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">提供医疗程序及手术</label> <div class="controls"> <input id="operate" name="operate" type="title" class="text" value="<?php echo $operate; ?>" required="" onkeyup="" autocomplete="off" placeholder=""/> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">使用医院或其他服务诊所</label> <div class="controls"> <input id="hospital" name="hospital" type="title" class="text" value="<?php echo $hospital; ?>" required="" onkeyup="" autocomplete="off" placeholder=""/> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">诊所以外提供的服务</label> <div class="controls"> <input id="service" name="service" type="title" class="text" value="<?php echo $service; ?>" required="" onkeyup="" autocomplete="off" placeholder=""/> </div> </div> <div class="control-group" id="aboutSearchBox"> <label class="control-label" for="name">其他资料</label> <div class="controls"> <textarea id="other" name="other"><?php echo $other; ?></textarea> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-primary" id="submit">提交</button> <button type="button" class="btn" onclick="common.hideFancyBox()" style="margin-left:14px;">取消</button> </div> </div> </form> <script charset="utf-8" src="<?php echo base_url();?>/js/upload.js"></script>
leon776/ci
update/application/admin/views/function/edit_doctor.php
PHP
mit
6,879
module.exports = require('../lib/') .extend('faker', function() { try { return require('faker/locale/zh_CN'); } catch (e) { return null; } });
etzJohn/speedboost
node_modules/json-schema-faker/locale/zh_CN.js
JavaScript
mit
179
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Converters { [TestFixture] public class StringEnumConverterTests : TestFixtureBase { public class EnumClass { public StoreColor StoreColor { get; set; } public StoreColor? NullableStoreColor1 { get; set; } public StoreColor? NullableStoreColor2 { get; set; } } public class EnumContainer<T> { public T Enum { get; set; } } [Flags] public enum FlagsTestEnum { Default = 0, First = 1, Second = 2 } public enum NegativeEnum { Negative = -1, Zero = 0, Positive = 1 } [Flags] public enum NegativeFlagsEnum { NegativeFour = -4, NegativeTwo = -2, NegativeOne = -1, Zero = 0, One = 1, Two = 2, Four = 4 } #if !NET20 public enum NamedEnum { [EnumMember(Value = "@first")] First, [EnumMember(Value = "@second")] Second, Third } public enum NamedEnumDuplicate { [EnumMember(Value = "Third")] First, [EnumMember(Value = "@second")] Second, Third } public enum NamedEnumWithComma { [EnumMember(Value = "@first")] First, [EnumMember(Value = "@second")] Second, [EnumMember(Value = ",third")] Third, [EnumMember(Value = ",")] JustComma } #endif public class NegativeEnumClass { public NegativeEnum Value1 { get; set; } public NegativeEnum Value2 { get; set; } } public class NegativeFlagsEnumClass { public NegativeFlagsEnum Value1 { get; set; } public NegativeFlagsEnum Value2 { get; set; } } [JsonConverter(typeof(StringEnumConverter), true)] public enum CamelCaseEnumObsolete { This, Is, CamelCase } [JsonConverter(typeof(StringEnumConverter), typeof(CamelCaseNamingStrategy))] public enum CamelCaseEnumNew { This, Is, CamelCase } [JsonConverter(typeof(StringEnumConverter), typeof(SnakeCaseNamingStrategy))] public enum SnakeCaseEnumNew { This, Is, SnakeCase } [JsonConverter(typeof(StringEnumConverter), typeof(CamelCaseNamingStrategy), new object[0], false)] public enum NotAllowIntegerValuesEnum { Foo = 0, Bar = 1 } [JsonConverter(typeof(StringEnumConverter), typeof(CamelCaseNamingStrategy))] public enum AllowIntegerValuesEnum { Foo = 0, Bar = 1 } [JsonConverter(typeof(StringEnumConverter), typeof(CamelCaseNamingStrategy), null)] public enum NullArgumentInAttribute { Foo = 0, Bar = 1 } [Test] public void Serialize_CamelCaseFromAttribute_Obsolete() { string json = JsonConvert.SerializeObject(CamelCaseEnumObsolete.CamelCase); Assert.AreEqual(@"""camelCase""", json); } [Test] public void NamingStrategyAndCamelCaseText() { StringEnumConverter converter = new StringEnumConverter(); Assert.IsNull(converter.NamingStrategy); #pragma warning disable CS0618 // Type or member is obsolete converter.CamelCaseText = true; #pragma warning restore CS0618 // Type or member is obsolete Assert.IsNotNull(converter.NamingStrategy); Assert.AreEqual(typeof(CamelCaseNamingStrategy), converter.NamingStrategy.GetType()); var camelCaseInstance = converter.NamingStrategy; #pragma warning disable CS0618 // Type or member is obsolete converter.CamelCaseText = true; #pragma warning restore CS0618 // Type or member is obsolete Assert.AreEqual(camelCaseInstance, converter.NamingStrategy); converter.NamingStrategy = null; #pragma warning disable CS0618 // Type or member is obsolete Assert.IsFalse(converter.CamelCaseText); #pragma warning restore CS0618 // Type or member is obsolete converter.NamingStrategy = new CamelCaseNamingStrategy(); #pragma warning disable CS0618 // Type or member is obsolete Assert.IsTrue(converter.CamelCaseText); #pragma warning restore CS0618 // Type or member is obsolete converter.NamingStrategy = new SnakeCaseNamingStrategy(); #pragma warning disable CS0618 // Type or member is obsolete Assert.IsFalse(converter.CamelCaseText); #pragma warning restore CS0618 // Type or member is obsolete #pragma warning disable CS0618 // Type or member is obsolete converter.CamelCaseText = false; #pragma warning restore CS0618 // Type or member is obsolete Assert.IsNotNull(converter.NamingStrategy); Assert.AreEqual(typeof(SnakeCaseNamingStrategy), converter.NamingStrategy.GetType()); } [Test] public void StringEnumConverter_CamelCaseTextCtor() { #pragma warning disable CS0618 // Type or member is obsolete StringEnumConverter converter = new StringEnumConverter(true); #pragma warning restore CS0618 // Type or member is obsolete Assert.IsNotNull(converter.NamingStrategy); Assert.AreEqual(typeof(CamelCaseNamingStrategy), converter.NamingStrategy.GetType()); Assert.AreEqual(true, converter.AllowIntegerValues); } [Test] public void StringEnumConverter_NamingStrategyTypeCtor() { StringEnumConverter converter = new StringEnumConverter(typeof(CamelCaseNamingStrategy), new object[] { true, true, true }, false); Assert.IsNotNull(converter.NamingStrategy); Assert.AreEqual(typeof(CamelCaseNamingStrategy), converter.NamingStrategy.GetType()); Assert.AreEqual(false, converter.AllowIntegerValues); Assert.AreEqual(true, converter.NamingStrategy.OverrideSpecifiedNames); Assert.AreEqual(true, converter.NamingStrategy.ProcessDictionaryKeys); Assert.AreEqual(true, converter.NamingStrategy.ProcessExtensionDataNames); } [Test] public void StringEnumConverter_NamingStrategyTypeCtor_Null() { ExceptionAssert.Throws<ArgumentNullException>( () => new StringEnumConverter(null), @"Value cannot be null. Parameter name: namingStrategyType"); } [Test] public void StringEnumConverter_NamingStrategyTypeWithArgsCtor_Null() { ExceptionAssert.Throws<ArgumentNullException>( () => new StringEnumConverter(null, new object[] { true, true, true }, false), @"Value cannot be null. Parameter name: namingStrategyType"); } [Test] public void Deserialize_CamelCaseFromAttribute_Obsolete() { CamelCaseEnumObsolete e = JsonConvert.DeserializeObject<CamelCaseEnumObsolete>(@"""camelCase"""); Assert.AreEqual(CamelCaseEnumObsolete.CamelCase, e); } [Test] public void Serialize_CamelCaseFromAttribute() { string json = JsonConvert.SerializeObject(CamelCaseEnumNew.CamelCase); Assert.AreEqual(@"""camelCase""", json); } [Test] public void Deserialize_CamelCaseFromAttribute() { CamelCaseEnumNew e = JsonConvert.DeserializeObject<CamelCaseEnumNew>(@"""camelCase"""); Assert.AreEqual(CamelCaseEnumNew.CamelCase, e); } [Test] public void Serialize_SnakeCaseFromAttribute() { string json = JsonConvert.SerializeObject(SnakeCaseEnumNew.SnakeCase); Assert.AreEqual(@"""snake_case""", json); } [Test] public void Deserialize_SnakeCaseFromAttribute() { SnakeCaseEnumNew e = JsonConvert.DeserializeObject<SnakeCaseEnumNew>(@"""snake_case"""); Assert.AreEqual(SnakeCaseEnumNew.SnakeCase, e); } [Test] public void Deserialize_NotAllowIntegerValuesFromAttribute() { ExceptionAssert.Throws<JsonSerializationException>(() => { NotAllowIntegerValuesEnum e = JsonConvert.DeserializeObject<NotAllowIntegerValuesEnum>(@"""9"""); }); } [Test] public void CannotPassNullArgumentToConverter() { var ex = ExceptionAssert.Throws<JsonException>(() => { JsonConvert.DeserializeObject<NullArgumentInAttribute>(@"""9"""); }); Assert.AreEqual("Cannot pass a null parameter to the constructor.", ex.InnerException.Message); } [Test] public void Deserialize_AllowIntegerValuesAttribute() { AllowIntegerValuesEnum e = JsonConvert.DeserializeObject<AllowIntegerValuesEnum>(@"""9"""); Assert.AreEqual(9, (int)e); } #if !NET20 [Test] public void NamedEnumDuplicateTest() { ExceptionAssert.Throws<Exception>(() => { EnumContainer<NamedEnumDuplicate> c = new EnumContainer<NamedEnumDuplicate> { Enum = NamedEnumDuplicate.First }; JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter()); }, "Enum name 'Third' already exists on enum 'NamedEnumDuplicate'."); } [Test] public void SerializeNameEnumTest() { EnumContainer<NamedEnum> c = new EnumContainer<NamedEnum> { Enum = NamedEnum.First }; string json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter()); StringAssert.AreEqual(@"{ ""Enum"": ""@first"" }", json); c = new EnumContainer<NamedEnum> { Enum = NamedEnum.Third }; json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter()); StringAssert.AreEqual(@"{ ""Enum"": ""Third"" }", json); } [Test] public void NamedEnumCommaTest() { EnumContainer<NamedEnumWithComma> c = new EnumContainer<NamedEnumWithComma> { Enum = NamedEnumWithComma.Third }; string json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter()); StringAssert.AreEqual(@"{ ""Enum"": "",third"" }", json); EnumContainer<NamedEnumWithComma> c2 = JsonConvert.DeserializeObject<EnumContainer<NamedEnumWithComma>>(json, new StringEnumConverter()); Assert.AreEqual(NamedEnumWithComma.Third, c2.Enum); } [Test] public void NamedEnumCommaTest2() { EnumContainer<NamedEnumWithComma> c = new EnumContainer<NamedEnumWithComma> { Enum = NamedEnumWithComma.JustComma }; string json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter()); StringAssert.AreEqual(@"{ ""Enum"": "","" }", json); EnumContainer<NamedEnumWithComma> c2 = JsonConvert.DeserializeObject<EnumContainer<NamedEnumWithComma>>(json, new StringEnumConverter()); Assert.AreEqual(NamedEnumWithComma.JustComma, c2.Enum); } [Test] public void NamedEnumCommaCaseInsensitiveTest() { EnumContainer<NamedEnumWithComma> c2 = JsonConvert.DeserializeObject<EnumContainer<NamedEnumWithComma>>(@"{""Enum"":"",THIRD""}", new StringEnumConverter()); Assert.AreEqual(NamedEnumWithComma.Third, c2.Enum); } [Test] public void DeserializeNameEnumTest() { string json = @"{ ""Enum"": ""@first"" }"; EnumContainer<NamedEnum> c = JsonConvert.DeserializeObject<EnumContainer<NamedEnum>>(json, new StringEnumConverter()); Assert.AreEqual(NamedEnum.First, c.Enum); json = @"{ ""Enum"": ""Third"" }"; c = JsonConvert.DeserializeObject<EnumContainer<NamedEnum>>(json, new StringEnumConverter()); Assert.AreEqual(NamedEnum.Third, c.Enum); } #endif [Test] public void SerializeEnumClass() { EnumClass enumClass = new EnumClass() { StoreColor = StoreColor.Red, NullableStoreColor1 = StoreColor.White, NullableStoreColor2 = null }; string json = JsonConvert.SerializeObject(enumClass, Formatting.Indented, new StringEnumConverter()); StringAssert.AreEqual(@"{ ""StoreColor"": ""Red"", ""NullableStoreColor1"": ""White"", ""NullableStoreColor2"": null }", json); } [Test] public void SerializeEnumClassWithCamelCase() { EnumClass enumClass = new EnumClass() { StoreColor = StoreColor.Red, NullableStoreColor1 = StoreColor.DarkGoldenrod, NullableStoreColor2 = null }; #pragma warning disable CS0618 // Type or member is obsolete string json = JsonConvert.SerializeObject(enumClass, Formatting.Indented, new StringEnumConverter { CamelCaseText = true }); #pragma warning restore CS0618 // Type or member is obsolete StringAssert.AreEqual(@"{ ""StoreColor"": ""red"", ""NullableStoreColor1"": ""darkGoldenrod"", ""NullableStoreColor2"": null }", json); } [Test] public void SerializeEnumClassUndefined() { EnumClass enumClass = new EnumClass() { StoreColor = (StoreColor)1000, NullableStoreColor1 = (StoreColor)1000, NullableStoreColor2 = null }; string json = JsonConvert.SerializeObject(enumClass, Formatting.Indented, new StringEnumConverter()); StringAssert.AreEqual(@"{ ""StoreColor"": 1000, ""NullableStoreColor1"": 1000, ""NullableStoreColor2"": null }", json); } [Test] public void SerializeFlagEnum() { EnumClass enumClass = new EnumClass() { StoreColor = StoreColor.Red | StoreColor.White, NullableStoreColor1 = StoreColor.White & StoreColor.Yellow, NullableStoreColor2 = StoreColor.Red | StoreColor.White | StoreColor.Black }; string json = JsonConvert.SerializeObject(enumClass, Formatting.Indented, new StringEnumConverter()); StringAssert.AreEqual(@"{ ""StoreColor"": ""Red, White"", ""NullableStoreColor1"": 0, ""NullableStoreColor2"": ""Black, Red, White"" }", json); } [Test] public void SerializeNegativeFlagsEnum() { NegativeFlagsEnumClass negativeEnumClass = new NegativeFlagsEnumClass(); negativeEnumClass.Value1 = NegativeFlagsEnum.NegativeFour | NegativeFlagsEnum.NegativeTwo; negativeEnumClass.Value2 = NegativeFlagsEnum.Two | NegativeFlagsEnum.Four; string json = JsonConvert.SerializeObject(negativeEnumClass, Formatting.Indented, new StringEnumConverter()); StringAssert.AreEqual(@"{ ""Value1"": ""NegativeTwo"", ""Value2"": ""Two, Four"" }", json); } [Test] public void DeserializeNegativeFlagsEnum() { string json = @"{ ""Value1"": ""NegativeFour,NegativeTwo"", ""Value2"": ""NegativeFour,Four"" }"; NegativeFlagsEnumClass negativeEnumClass = JsonConvert.DeserializeObject<NegativeFlagsEnumClass>(json, new StringEnumConverter()); Assert.AreEqual(NegativeFlagsEnum.NegativeFour | NegativeFlagsEnum.NegativeTwo, negativeEnumClass.Value1); Assert.AreEqual(NegativeFlagsEnum.NegativeFour | NegativeFlagsEnum.Four, negativeEnumClass.Value2); } [Test] public void SerializeNegativeEnum() { NegativeEnumClass negativeEnumClass = new NegativeEnumClass() { Value1 = NegativeEnum.Negative, Value2 = (NegativeEnum)int.MinValue }; string json = JsonConvert.SerializeObject(negativeEnumClass, Formatting.Indented, new StringEnumConverter()); StringAssert.AreEqual(@"{ ""Value1"": ""Negative"", ""Value2"": -2147483648 }", json); } [Test] public void DeserializeNegativeEnum() { string json = @"{ ""Value1"": ""Negative"", ""Value2"": -2147483648 }"; NegativeEnumClass negativeEnumClass = JsonConvert.DeserializeObject<NegativeEnumClass>(json, new StringEnumConverter()); Assert.AreEqual(NegativeEnum.Negative, negativeEnumClass.Value1); Assert.AreEqual((NegativeEnum)int.MinValue, negativeEnumClass.Value2); } [Test] public void DeserializeFlagEnum() { string json = @"{ ""StoreColor"": ""Red, White"", ""NullableStoreColor1"": 0, ""NullableStoreColor2"": ""black, Red, White"" }"; EnumClass enumClass = JsonConvert.DeserializeObject<EnumClass>(json, new StringEnumConverter()); Assert.AreEqual(StoreColor.Red | StoreColor.White, enumClass.StoreColor); Assert.AreEqual((StoreColor)0, enumClass.NullableStoreColor1); Assert.AreEqual(StoreColor.Red | StoreColor.White | StoreColor.Black, enumClass.NullableStoreColor2); } [Test] public void DeserializeEnumClass() { string json = @"{ ""StoreColor"": ""Red"", ""NullableStoreColor1"": ""White"", ""NullableStoreColor2"": null }"; EnumClass enumClass = JsonConvert.DeserializeObject<EnumClass>(json, new StringEnumConverter()); Assert.AreEqual(StoreColor.Red, enumClass.StoreColor); Assert.AreEqual(StoreColor.White, enumClass.NullableStoreColor1); Assert.AreEqual(null, enumClass.NullableStoreColor2); } [Test] public void DeserializeEnumClassUndefined() { string json = @"{ ""StoreColor"": 1000, ""NullableStoreColor1"": 1000, ""NullableStoreColor2"": null }"; EnumClass enumClass = JsonConvert.DeserializeObject<EnumClass>(json, new StringEnumConverter()); Assert.AreEqual((StoreColor)1000, enumClass.StoreColor); Assert.AreEqual((StoreColor)1000, enumClass.NullableStoreColor1); Assert.AreEqual(null, enumClass.NullableStoreColor2); } [Test] public void CamelCaseTextFlagEnumSerialization() { EnumContainer<FlagsTestEnum> c = new EnumContainer<FlagsTestEnum> { Enum = FlagsTestEnum.First | FlagsTestEnum.Second }; #pragma warning disable CS0618 // Type or member is obsolete string json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter { CamelCaseText = true }); #pragma warning restore CS0618 // Type or member is obsolete StringAssert.AreEqual(@"{ ""Enum"": ""first, second"" }", json); } [Test] public void CamelCaseTextFlagEnumDeserialization() { string json = @"{ ""Enum"": ""first, second"" }"; #pragma warning disable CS0618 // Type or member is obsolete EnumContainer<FlagsTestEnum> c = JsonConvert.DeserializeObject<EnumContainer<FlagsTestEnum>>(json, new StringEnumConverter { CamelCaseText = true }); #pragma warning restore CS0618 // Type or member is obsolete Assert.AreEqual(FlagsTestEnum.First | FlagsTestEnum.Second, c.Enum); } [Test] public void DeserializeEmptyStringIntoNullable() { string json = @"{ ""StoreColor"": ""Red"", ""NullableStoreColor1"": ""White"", ""NullableStoreColor2"": """" }"; EnumClass c = JsonConvert.DeserializeObject<EnumClass>(json, new StringEnumConverter()); Assert.IsNull(c.NullableStoreColor2); } [Test] public void DeserializeInvalidString() { string json = "{ \"Value\" : \"Three\" }"; ExceptionAssert.Throws<JsonSerializationException>(() => { var serializer = new JsonSerializer(); serializer.Converters.Add(new StringEnumConverter()); serializer.Deserialize<Bucket>(new JsonTextReader(new StringReader(json))); }, @"Error converting value ""Three"" to type 'Newtonsoft.Json.Tests.Converters.StringEnumConverterTests+MyEnum'. Path 'Value', line 1, position 19."); } public class Bucket { public MyEnum Value; } public enum MyEnum { Alpha, Beta, } [Test] public void DeserializeIntegerButNotAllowed() { string json = "{ \"Value\" : 123 }"; try { var serializer = new JsonSerializer(); serializer.Converters.Add(new StringEnumConverter { AllowIntegerValues = false }); serializer.Deserialize<Bucket>(new JsonTextReader(new StringReader(json))); } catch (JsonSerializationException ex) { Assert.AreEqual("Error converting value 123 to type 'Newtonsoft.Json.Tests.Converters.StringEnumConverterTests+MyEnum'. Path 'Value', line 1, position 15.", ex.Message); Assert.AreEqual(@"Integer value 123 is not allowed. Path 'Value', line 1, position 15.", ex.InnerException.Message); return; } Assert.Fail(); } #if !NET20 [Test] public void EnumMemberPlusFlags() { List<Foo> lfoo = new List<Foo> { Foo.Bat | Foo.SerializeAsBaz, Foo.FooBar, Foo.Bat, Foo.SerializeAsBaz, Foo.FooBar | Foo.SerializeAsBaz, (Foo)int.MaxValue }; #pragma warning disable CS0618 // Type or member is obsolete string json1 = JsonConvert.SerializeObject(lfoo, Formatting.Indented, new StringEnumConverter { CamelCaseText = true }); #pragma warning restore CS0618 // Type or member is obsolete StringAssert.AreEqual(@"[ ""Bat, baz"", ""foo_bar"", ""Bat"", ""baz"", ""foo_bar, baz"", 2147483647 ]", json1); IList<Foo> foos = JsonConvert.DeserializeObject<List<Foo>>(json1); Assert.AreEqual(6, foos.Count); Assert.AreEqual(Foo.Bat | Foo.SerializeAsBaz, foos[0]); Assert.AreEqual(Foo.FooBar, foos[1]); Assert.AreEqual(Foo.Bat, foos[2]); Assert.AreEqual(Foo.SerializeAsBaz, foos[3]); Assert.AreEqual(Foo.FooBar | Foo.SerializeAsBaz, foos[4]); Assert.AreEqual((Foo)int.MaxValue, foos[5]); List<Bar> lbar = new List<Bar>() { Bar.FooBar, Bar.Bat, Bar.SerializeAsBaz }; #pragma warning disable CS0618 // Type or member is obsolete string json2 = JsonConvert.SerializeObject(lbar, Formatting.Indented, new StringEnumConverter { CamelCaseText = true }); #pragma warning restore CS0618 // Type or member is obsolete StringAssert.AreEqual(@"[ ""foo_bar"", ""Bat"", ""baz"" ]", json2); IList<Bar> bars = JsonConvert.DeserializeObject<List<Bar>>(json2); Assert.AreEqual(3, bars.Count); Assert.AreEqual(Bar.FooBar, bars[0]); Assert.AreEqual(Bar.Bat, bars[1]); Assert.AreEqual(Bar.SerializeAsBaz, bars[2]); } [Test] public void DuplicateNameEnumTest() { ExceptionAssert.Throws<JsonSerializationException>( () => JsonConvert.DeserializeObject<DuplicateNameEnum>("'foo_bar'", new StringEnumConverter()), @"Error converting value ""foo_bar"" to type 'Newtonsoft.Json.Tests.Converters.DuplicateNameEnum'. Path '', line 1, position 9."); } // Define other methods and classes here [Flags] [JsonConverter(typeof(StringEnumConverter))] private enum Foo { [EnumMember(Value = "foo_bar")] FooBar = 0x01, Bat = 0x02, [EnumMember(Value = "baz")] SerializeAsBaz = 0x4, } [JsonConverter(typeof(StringEnumConverter))] private enum Bar { [EnumMember(Value = "foo_bar")] FooBar, Bat, [EnumMember(Value = "baz")] SerializeAsBaz } [Test] public void DataContractSerializerDuplicateNameEnumTest() { MemoryStream ms = new MemoryStream(); var s = new DataContractSerializer(typeof(DuplicateEnumNameTestClass)); ExceptionAssert.Throws<InvalidDataContractException>(() => { s.WriteObject(ms, new DuplicateEnumNameTestClass { Value = DuplicateNameEnum.foo_bar, Value2 = DuplicateNameEnum2.foo_bar_NOT_USED }); string xml = @"<DuplicateEnumNameTestClass xmlns=""http://schemas.datacontract.org/2004/07/Newtonsoft.Json.Tests.Converters"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""> <Value>foo_bar</Value> <Value2>foo_bar</Value2> </DuplicateEnumNameTestClass>"; var o = (DuplicateEnumNameTestClass)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(xml))); Assert.AreEqual(DuplicateNameEnum.foo_bar, o.Value); Assert.AreEqual(DuplicateNameEnum2.FooBar, o.Value2); }, "Type 'Newtonsoft.Json.Tests.Converters.DuplicateNameEnum' contains two members 'foo_bar' 'and 'FooBar' with the same name 'foo_bar'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using EnumMemberAttribute attribute."); } [Test] public void EnumMemberWithNumbers() { StringEnumConverter converter = new StringEnumConverter(); NumberNamesEnum e = JsonConvert.DeserializeObject<NumberNamesEnum>("\"1\"", converter); Assert.AreEqual(NumberNamesEnum.second, e); e = JsonConvert.DeserializeObject<NumberNamesEnum>("\"2\"", converter); Assert.AreEqual(NumberNamesEnum.first, e); e = JsonConvert.DeserializeObject<NumberNamesEnum>("\"3\"", converter); Assert.AreEqual(NumberNamesEnum.third, e); e = JsonConvert.DeserializeObject<NumberNamesEnum>("\"-4\"", converter); Assert.AreEqual(NumberNamesEnum.fourth, e); } [Test] public void EnumMemberWithNumbers_NoIntegerValues() { StringEnumConverter converter = new StringEnumConverter { AllowIntegerValues = false }; NumberNamesEnum e = JsonConvert.DeserializeObject<NumberNamesEnum>("\"1\"", converter); Assert.AreEqual(NumberNamesEnum.second, e); e = JsonConvert.DeserializeObject<NumberNamesEnum>("\"2\"", converter); Assert.AreEqual(NumberNamesEnum.first, e); e = JsonConvert.DeserializeObject<NumberNamesEnum>("\"3\"", converter); Assert.AreEqual(NumberNamesEnum.third, e); e = JsonConvert.DeserializeObject<NumberNamesEnum>("\"-4\"", converter); Assert.AreEqual(NumberNamesEnum.fourth, e); } #endif [Test] public void AllowIntegerValueAndStringNumber() { JsonSerializationException ex = ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<StoreColor>("\"1\"", new StringEnumConverter { AllowIntegerValues = false }); }); Assert.AreEqual("Integer string '1' is not allowed.", ex.InnerException.Message); } [Test] public void AllowIntegerValueAndNegativeStringNumber() { JsonSerializationException ex = ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<StoreColor>("\"-1\"", new StringEnumConverter { AllowIntegerValues = false }); }); Assert.AreEqual("Integer string '-1' is not allowed.", ex.InnerException.Message); } [Test] public void AllowIntegerValueAndPositiveStringNumber() { JsonSerializationException ex = ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<StoreColor>("\"+1\"", new StringEnumConverter { AllowIntegerValues = false }); }); Assert.AreEqual("Integer string '+1' is not allowed.", ex.InnerException.Message); } [Test] public void AllowIntegerValueAndDash() { JsonSerializationException ex = ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<StoreColor>("\"-\"", new StringEnumConverter { AllowIntegerValues = false }); }); Assert.AreEqual("Requested value '-' was not found.", ex.InnerException.Message); } [Test] public void AllowIntegerValueAndNonNamedValue() { ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject((StoreColor)999, new StringEnumConverter { AllowIntegerValues = false }); }, "Integer value 999 is not allowed. Path ''."); } public enum EnumWithDifferentCases { M, m } [Test] public void SerializeEnumWithDifferentCases() { string json = JsonConvert.SerializeObject(EnumWithDifferentCases.M, new StringEnumConverter()); Assert.AreEqual(@"""M""", json); json = JsonConvert.SerializeObject(EnumWithDifferentCases.m, new StringEnumConverter()); Assert.AreEqual(@"""m""", json); } [Test] public void DeserializeEnumWithDifferentCases() { EnumWithDifferentCases e = JsonConvert.DeserializeObject<EnumWithDifferentCases>(@"""M""", new StringEnumConverter()); Assert.AreEqual(EnumWithDifferentCases.M, e); e = JsonConvert.DeserializeObject<EnumWithDifferentCases>(@"""m""", new StringEnumConverter()); Assert.AreEqual(EnumWithDifferentCases.m, e); } #if !NET20 [JsonConverter(typeof(StringEnumConverter))] public enum EnumMemberDoesNotMatchName { [EnumMember(Value = "first_value")] First } [Test] public void DeserializeEnumCaseIncensitive_ByEnumMemberValue_UpperCase() { var e = JsonConvert.DeserializeObject<EnumMemberDoesNotMatchName>(@"""FIRST_VALUE""", new StringEnumConverter()); Assert.AreEqual(EnumMemberDoesNotMatchName.First, e); } [Test] public void DeserializeEnumCaseIncensitive_ByEnumMemberValue_MixedCase() { var e = JsonConvert.DeserializeObject<EnumMemberDoesNotMatchName>(@"""First_Value""", new StringEnumConverter()); Assert.AreEqual(EnumMemberDoesNotMatchName.First, e); } [Test] public void DeserializeEnumCaseIncensitive_ByName_LowerCase() { var e = JsonConvert.DeserializeObject<EnumMemberDoesNotMatchName>(@"""first""", new StringEnumConverter()); Assert.AreEqual(EnumMemberDoesNotMatchName.First, e); } [Test] public void DeserializeEnumCaseIncensitive_ByName_UperCase() { var e = JsonConvert.DeserializeObject<EnumMemberDoesNotMatchName>(@"""FIRST""", new StringEnumConverter()); Assert.AreEqual(EnumMemberDoesNotMatchName.First, e); } [Test] public void DeserializeEnumCaseIncensitive_FromAttribute() { var e = JsonConvert.DeserializeObject<EnumMemberDoesNotMatchName>(@"""FIRST_VALUE"""); Assert.AreEqual(EnumMemberDoesNotMatchName.First, e); } [JsonConverter(typeof(StringEnumConverter))] public enum EnumMemberWithDiffrentCases { [EnumMember(Value = "first_value")] First, [EnumMember(Value = "second_value")] first } [Test] public void DeserializeEnumMemberWithDifferentCasing_ByEnumMemberValue_First() { var e = JsonConvert.DeserializeObject<EnumMemberWithDiffrentCases>(@"""first_value""", new StringEnumConverter()); Assert.AreEqual(EnumMemberWithDiffrentCases.First, e); } [Test] public void DeserializeEnumMemberWithDifferentCasing_ByEnumMemberValue_Second() { var e = JsonConvert.DeserializeObject<EnumMemberWithDiffrentCases>(@"""second_value""", new StringEnumConverter()); Assert.AreEqual(EnumMemberWithDiffrentCases.first, e); } [DataContract(Name = "DateFormats")] public enum EnumMemberWithDifferentCases { [EnumMember(Value = "M")] Month, [EnumMember(Value = "m")] Minute } [Test] public void SerializeEnumMemberWithDifferentCases() { string json = JsonConvert.SerializeObject(EnumMemberWithDifferentCases.Month, new StringEnumConverter()); Assert.AreEqual(@"""M""", json); json = JsonConvert.SerializeObject(EnumMemberWithDifferentCases.Minute, new StringEnumConverter()); Assert.AreEqual(@"""m""", json); } [Test] public void DeserializeEnumMemberWithDifferentCases() { EnumMemberWithDifferentCases e = JsonConvert.DeserializeObject<EnumMemberWithDifferentCases>(@"""M""", new StringEnumConverter()); Assert.AreEqual(EnumMemberWithDifferentCases.Month, e); e = JsonConvert.DeserializeObject<EnumMemberWithDifferentCases>(@"""m""", new StringEnumConverter()); Assert.AreEqual(EnumMemberWithDifferentCases.Minute, e); } #endif } #if !NET20 [DataContract] public class DuplicateEnumNameTestClass { [DataMember] public DuplicateNameEnum Value { get; set; } [DataMember] public DuplicateNameEnum2 Value2 { get; set; } } [DataContract] public enum NumberNamesEnum { [EnumMember(Value = "2")] first, [EnumMember(Value = "1")] second, [EnumMember(Value = "3")] third, [EnumMember(Value = "-4")] fourth } [DataContract] public enum DuplicateNameEnum { [EnumMember] first = 0, [EnumMember] foo_bar = 1, [EnumMember(Value = "foo_bar")] FooBar = 2, [EnumMember] foo_bar_NOT_USED = 3 } [DataContract] public enum DuplicateNameEnum2 { [EnumMember] first = 0, [EnumMember(Value = "foo_bar")] FooBar = 1, [EnumMember] foo_bar = 2, [EnumMember(Value = "TEST")] foo_bar_NOT_USED = 3 } #endif }
brjohnstmsft/Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs
C#
mit
37,510
using System; using System.IO; using GroupDocs.Conversion.FileTypes; using GroupDocs.Conversion.Options.Convert; using GroupDocs.Conversion.Options.Load; namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage { /// <summary> /// This example demonstrates how to convert PST file into HTML format. /// For more details about Personal Storage File (.pst) to Hyper Text Markup Language (.html) conversion please check this documentation article /// https://docs.groupdocs.com/conversion/net/convert-pst-to-html /// </summary> internal static class ConvertPstToHtml { public static void Run() { string outputFolder = Constants.GetOutputDirectoryPath(); string outputFile = Path.Combine(outputFolder, "pst-converted-{0}-to.html"); // Load the source PST file using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_PST, fileType => fileType == PersonalStorageFileType.Pst ? new PersonalStorageLoadOptions() : null)) { var options = new MarkupConvertOptions(); var counter = 1; // Save converted HTML file converter.Convert( (FileType fileType) => new FileStream(string.Format(outputFile, counter++), FileMode.Create), options ); } Console.WriteLine("\nConversion to html completed successfully. \nCheck output in {0}", outputFolder); } } }
groupdocs-conversion/GroupDocs.Conversion-for-.NET
Examples/GroupDocs.Conversion.Examples.CSharp/BasicUsage/ConvertToHtml/ConvertPstToHtml.cs
C#
mit
1,751
# encoding: utf-8 require "mongoid/relations/accessors" require "mongoid/relations/auto_save" require "mongoid/relations/cascading" require "mongoid/relations/constraint" require "mongoid/relations/cyclic" require "mongoid/relations/proxy" require "mongoid/relations/bindings" require "mongoid/relations/builders" require "mongoid/relations/many" require "mongoid/relations/one" require "mongoid/relations/polymorphic" require "mongoid/relations/embedded/in" require "mongoid/relations/embedded/many" require "mongoid/relations/embedded/one" require "mongoid/relations/referenced/in" require "mongoid/relations/referenced/many" require "mongoid/relations/referenced/many_to_many" require "mongoid/relations/referenced/one" require "mongoid/relations/reflections" require "mongoid/relations/metadata" require "mongoid/relations/macros" module Mongoid # :nodoc: # All classes and modules under the relations namespace handle the # functionality that has to do with embedded and referenced (relational) # associations. module Relations extend ActiveSupport::Concern include Accessors include AutoSave include Cascading include Cyclic include Builders include Macros include Polymorphic include Reflections included do attr_accessor :metadata end # Determine if the document itself is embedded in another document via the # proper channels. (If it has a parent document.) # # @example Is the document embedded? # address.embedded? # # @return [ true, false ] True if the document has a parent document. # # @since 2.0.0.rc.1 def embedded? _parent.present? end # Determine if the document is part of an embeds_many relation. # # @example Is the document in an embeds many? # address.embedded_many? # # @return [ true, false ] True if in an embeds many. # # @since 2.0.0.rc.1 def embedded_many? metadata && metadata.macro == :embeds_many end # Determine if the document is part of an embeds_one relation. # # @example Is the document in an embeds one? # address.embedded_one? # # @return [ true, false ] True if in an embeds one. # # @since 2.0.0.rc.1 def embedded_one? metadata && metadata.macro == :embeds_one end # Determine if the document is part of an references_many relation. # # @example Is the document in a references many? # post.referenced_many? # # @return [ true, false ] True if in a references many. # # @since 2.0.0.rc.1 def referenced_many? metadata && metadata.macro == :references_many end # Determine if the document is part of an references_one relation. # # @example Is the document in a references one? # address.referenced_one? # # @return [ true, false ] True if in a references one. # # @since 2.0.0.rc.1 def referenced_one? metadata && metadata.macro == :references_one end end end
techwhizbang/mongoid
lib/mongoid/relations.rb
Ruby
mit
3,017
/******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! * jQuery JavaScript Library v3.2.1 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2017-03-20T18:59Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var document = window.document; var getProto = Object.getPrototypeOf; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; function DOMEval( code, doc ) { doc = doc || document; var script = doc.createElement( "script" ); script.text = code; doc.head.appendChild( script ).parentNode.removeChild( script ); } /* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global // unguarded in another place, it seems safer to define global only for this module var version = "3.2.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android <=4.0 only // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { // Return all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && Array.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type( obj ) === "function"; }, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // As of jQuery 3.0, isNumeric is limited to // strings and numbers (primitives or objects) // that can be coerced to finite numbers (gh-2662) var type = jQuery.type( obj ); return ( type === "number" || type === "string" ) && // parseFloat NaNs numeric-cast false positives ("") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN !isNaN( obj - parseFloat( obj ) ); }, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { /* eslint-disable no-unused-vars */ // See https://github.com/eslint/eslint/issues/6125 var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { DOMEval( code ); }, // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 13 // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Support: Android <=4.0 only trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.3 * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-08-08 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, disabledAncestor = addCombinator( function( elem ) { return elem.disabled === true && ("form" in elem || "label" in elem); }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && disabledAncestor( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( el ) { el.className = "i"; return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( el ) { el.appendChild( document.createComment("") ); return !el.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID filter and find if ( support.getById ) { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( (elem = elems[i++]) ) { node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll(":enabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( (oldCache = uniqueCache[ key ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( el ) { el.innerHTML = "<a href='#'></a>"; return el.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( el ) { el.innerHTML = "<input/>"; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( el ) { return el.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Simple selector that can be filtered directly, removing non-Elements if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } // Complex selector, compare the two sets, removing non-Elements qualifier = jQuery.filter( qualifier, elements ); return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; } ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } if ( elems.length === 1 && elem.nodeType === 1 ) { return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; } return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { if ( nodeName( elem, "iframe" ) ) { return elem.contentDocument; } // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only // Treat the template element as a regular one in browsers that // don't support it. if ( nodeName( elem, "template" ) ) { elem = elem.content || elem; } return jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject, noValue ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: // * false: [ value ].slice( 0 ) => resolve( value ) // * true: [ value ].slice( 1 ) => resolve() resolve.apply( undefined, [ value ].slice( noValue ) ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.apply( undefined, [ value ] ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( jQuery.isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onRejected ) ? onRejected : Thrower ) ); } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the master Deferred master = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, !remaining ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; jQuery.readyException = function( error ) { window.setTimeout( function() { throw error; } ); }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList .then( fn ) // Wrap jQuery.readyException in a function so that the lookup // happens at the time of error handling instead of callback // registration. .catch( function( error ) { jQuery.readyException( error ); } ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } if ( chainable ) { return elems; } // Gets if ( bulk ) { return fn.call( elems ); } return len ? fn( elems[ 0 ], key ) : emptyGet; }; var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ jQuery.camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ jQuery.camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( Array.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( jQuery.camelCase ); } else { key = jQuery.camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnothtmlwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function getData( data ) { if ( data === "true" ) { return true; } if ( data === "false" ) { return false; } if ( data === "null" ) { return null; } // Only convert to a number if it doesn't change the string if ( data === +data + "" ) { return +data; } if ( rbrace.test( data ) ) { return JSON.parse( data ); } return data; } function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || Array.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. jQuery.contains( elem.ownerDocument, elem ) && jQuery.css( elem, "display" ) === "none"; }; var swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ); display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); var rscriptType = ( /^$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE <=9 only option: [ 1, "<select multiple='multiple'>", "</select>" ], // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting <tbody> or other required elements. thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE <=9 only wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret; if ( typeof context.getElementsByTagName !== "undefined" ) { ret = context.getElementsByTagName( tag || "*" ); } else if ( typeof context.querySelectorAll !== "undefined" ) { ret = context.querySelectorAll( tag || "*" ); } else { ret = []; } if ( tag === undefined || tag && nodeName( context, tag ) ) { return jQuery.merge( [ context ], ret ); } return ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); var documentElement = document.documentElement; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 only // See #13393 for more info function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, selector ); } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = {}; } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { // Make a writable jQuery.Event from the native event object var event = jQuery.event.fix( nativeEvent ); var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers if ( delegateCount && // Support: IE <=9 // Black-hole SVG <use> instance trees (trac-13180) cur.nodeType && // Support: Firefox <=42 // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click // Support: IE 11 only // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) !( event.type === "click" && event.button >= 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { matchedHandlers = []; matchedSelectors = {}; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matchedSelectors[ sel ] === undefined ) { matchedSelectors[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matchedSelectors[ sel ] ) { matchedHandlers.push( handleObj ); } } if ( matchedHandlers.length ) { handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); } } } } // Add the remaining (directly-bound) handlers cur = this; if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: jQuery.isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { if ( button & 1 ) { return 1; } if ( button & 2 ) { return 3; } if ( button & 4 ) { return 2; } return 0; } return event.which; } }, jQuery.event.addProp ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var /* eslint-disable max-len */ // See https://github.com/eslint/eslint/issues/3229 rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, /* eslint-enable */ // Support: IE <=10 - 11, Edge 12 - 13 // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return jQuery( ">tbody", elem )[ 0 ] || elem; } return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.access( src ); pdataCur = dataPriv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1></$2>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rmargin = ( /^margin/ ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } div.style.cssText = "box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%"; div.innerHTML = ""; documentElement.appendChild( container ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = divStyle.marginLeft === "2px"; boxSizingReliableVal = divStyle.width === "4px"; // Support: Android 4.0 - 4.3 only // Some styles come back with percentage values, even though they shouldn't div.style.marginRight = "50%"; pixelMarginRightVal = divStyle.marginRight === "4px"; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute"; container.appendChild( div ); jQuery.extend( support, { pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelMarginRight: function() { computeStyleTests(); return pixelMarginRightVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, // Support: Firefox 51+ // Retrieving style before computed somehow // fixes an issue with getting wrong values // on detached elements style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is needed for: // .css('filter') (IE 9 only, #12537) // .css('--customProperty) (#3144) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE <=9 - 11 only // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( name ) { // Shortcut for names that are not vendor prefixed if ( name in emptyStyle ) { return name; } // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } // Return a property mapped along what jQuery.cssProps suggests or to // a vendor prefixed property. function finalPropName( name ) { var ret = jQuery.cssProps[ name ]; if ( !ret ) { ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; } return ret; } function setPositiveNumber( elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i, val = 0; // If we already have the right measurement, avoid augmentation if ( extra === ( isBorderBox ? "border" : "content" ) ) { i = 4; // Otherwise initialize for horizontal or vertical properties } else { i = name === "width" ? 1 : 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with computed style var valueIsBorderBox, styles = getStyles( elem ), val = curCSS( elem, name, styles ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test( val ) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Fall back to offsetWidth/Height when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) if ( val === "auto" ) { val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ]; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) if ( type === "number" ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { if ( isCustomProp ) { style.setProperty( name, value ); } else { style[ name ] = value; } } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); } ) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var matches, styles = extra && getStyles( elem ), subtract = extra && augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ); // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ name ] = value; value = jQuery.css( elem, name ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( Array.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 only // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back compat <1.8 extension point jQuery.fx.step = {}; var fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function schedule() { if ( inProgress ) { if ( document.hidden === false && window.requestAnimationFrame ) { window.requestAnimationFrame( schedule ); } else { window.setTimeout( schedule, jQuery.fx.interval ); } jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Queue-skipping animations hijack the fx hooks if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Detect show/hide animations for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.test( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // Pretend to be hidden if this is a "show" and // there is still data from a stopped show/hide if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; // Ignore all other no-op show/hide data } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } // Bail out if this is a no-op like .hide().hide() propTween = !jQuery.isEmptyObject( props ); if ( !propTween && jQuery.isEmptyObject( orig ) ) { return; } // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { // Support: IE <=9 - 11, Edge 12 - 13 // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Identify a display type, preferring old show/hide data over the CSS cascade restoreDisplay = dataShow && dataShow.display; if ( restoreDisplay == null ) { restoreDisplay = dataPriv.get( elem, "display" ); } display = jQuery.css( elem, "display" ); if ( display === "none" ) { if ( restoreDisplay ) { display = restoreDisplay; } else { // Get nonempty value(s) by temporarily forcing visibility showHide( [ elem ], true ); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css( elem, "display" ); showHide( [ elem ] ); } } // Animate inline elements as inline-block if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { if ( jQuery.css( elem, "float" ) === "none" ) { // Restore the original display value at the end of pure show/hide animations if ( !propTween ) { anim.done( function() { style.display = restoreDisplay; } ); if ( restoreDisplay == null ) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // Implement show/hide animations propTween = false; for ( prop in orig ) { // General show/hide setup for this element animation if ( !propTween ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); } // Store hidden/visible for toggle so `.stop().toggle()` "reverses" if ( toggle ) { dataShow.hidden = !hidden; } // Show elements before animating them if ( hidden ) { showHide( [ elem ], true ); } /* eslint-disable no-loop-func */ anim.done( function() { /* eslint-enable no-loop-func */ // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { showHide( [ elem ] ); } dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); } // Per-property setup propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = propTween.start; if ( hidden ) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( Array.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 only // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); // If there's more to do, yield if ( percent < 1 && length ) { return remaining; } // If this was an empty animation, synthesize a final progress notification if ( !length ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); } // Resolve the animation and report its conclusion deferred.resolveWith( elem, [ animation ] ); return false; }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( jQuery.isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = jQuery.proxy( result.stop, result ); } return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } // Attach callbacks from options animation .progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); return animation; } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnothtmlwhite ); } var prop, index = 0, length = props.length; for ( ; index < length; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; // Go to the end state if fx are off if ( jQuery.fx.off ) { opt.duration = 0; } else { if ( typeof opt.duration !== "number" ) { if ( opt.duration in jQuery.fx.speeds ) { opt.duration = jQuery.fx.speeds[ opt.duration ]; } else { opt.duration = jQuery.fx.speeds._default; } } } // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Run the timer and safely remove it when done (allowing for external removal) if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); jQuery.fx.start(); }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( inProgress ) { return; } inProgress = true; schedule(); }; jQuery.fx.stop = function() { inProgress = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, // Attribute names can contain non-HTML whitespace characters // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 attrNames = value && value.match( rnothtmlwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); if ( tabindex ) { return parseInt( tabindex, 10 ); } if ( rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ) { return 0; } return -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup // eslint rule "no-unused-expressions" is disabled for this code // since it considers such accessions noop if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); // Strip and collapse whitespace according to HTML spec // https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); } function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnothtmlwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } if ( typeof value === "string" && value ) { classes = value.match( rnothtmlwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( type === "string" ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = value.match( rnothtmlwhite ) || []; while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, isFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; // Handle most common string cases if ( typeof ret === "string" ) { return ret.replace( rreturn, "" ); } // Handle cases where value is null/undef or number return ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( Array.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace stripAndCollapse( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, i, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length; if ( index < 0 ) { i = max; } else { i = one ? index : 0; } // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && ( !option.parentNode.disabled || !nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; /* eslint-disable no-cond-assign */ if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( Array.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu" ).split( " " ), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); jQuery.fn.extend( { hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); support.focusin = "onfocusin" in window; // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = jQuery.now(); var rquery = ( /\?/ ); // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11 only // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( Array.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = jQuery.isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; // If an array was passed in, assume that it is an array of form elements. if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( i, elem ) { var val = jQuery( this ).val(); if ( val == null ) { return null; } if ( Array.isArray( val ) ) { return jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ); } return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": JSON.parse, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE <=8 - 11, Edge 12 - 13 // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 - 11 only // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, "" ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available, append data to url if ( s.data ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add or update anti-cache param if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rantiCache, "$1" ); uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change '%20' to '+' if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { s.data = s.data.replace( r20, "+" ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( -1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery._evalUrl = function( url ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", cache: true, async: false, global: false, "throws": true } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( jQuery.isFunction( html ) ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE <=9 only // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE <=9 only // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE <=9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = callback( "error" ); // Support: IE 9 only // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } } ); // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) jQuery.ajaxPrefilter( function( s ) { if ( s.crossDomain ) { s.contents.script = false; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "<script>" ).prop( { charset: s.scriptCharset, src: s.url } ).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); // Use native DOM manipulation to avoid our domManip AJAX trickery document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } } ); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup( { jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } } ); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && ( s.contentType || "" ) .indexOf( "application/x-www-form-urlencoded" ) === 0 && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters[ "script json" ] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // Force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always( function() { // If previous value didn't exist - remove it if ( overwritten === undefined ) { jQuery( window ).removeProp( callbackName ); // Otherwise restore preexisting value } else { window[ callbackName ] = overwritten; } // Save back as free if ( s[ callbackName ] ) { // Make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // Save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; } ); // Delegate to script return "script"; } } ); // Support: Safari 8 only // In Safari 8 documents created via document.implementation.createHTMLDocument // collapse sibling forms: the second one becomes a child of the first one. // Because of that, this security measure has to be disabled in Safari 8. // https://bugs.webkit.org/show_bug.cgi?id=137337 support.createHTMLDocument = ( function() { var body = document.implementation.createHTMLDocument( "" ).body; body.innerHTML = "<form></form><form></form>"; return body.childNodes.length === 2; } )(); // Argument "data" should be string of html // context (optional): If specified, the fragment will be created in this context, // defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( typeof data !== "string" ) { return []; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } var base, parsed, scripts; if ( !context ) { // Stop scripts or inline event handlers from being executed immediately // by using document.implementation if ( support.createHTMLDocument ) { context = document.implementation.createHTMLDocument( "" ); // Set the base href for the created document // so any parsed elements with URLs // are based on the document's URL (gh-2965) base = context.createElement( "base" ); base.href = document.location.href; context.head.appendChild( base ); } else { context = document; } } parsed = rsingleTag.exec( data ); scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[ 1 ] ) ]; } parsed = buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { var selector, type, response, self = this, off = url.indexOf( " " ); if ( off > -1 ) { selector = stripAndCollapse( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax( { url: url, // If "type" variable is undefined, then "GET" method will be used. // Make value of this field explicit since // user can override it through ajaxSetup method type: type || "GET", dataType: "html", data: params } ).done( function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); // If the request succeeds, this function gets "data", "status", "jqXHR" // but they are ignored because response was set above. // If it fails, this function gets "jqXHR", "status", "error" } ).always( callback && function( jqXHR, status ) { self.each( function() { callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] ); } ); } ); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; } ); jQuery.expr.pseudos.animated = function( elem ) { return jQuery.grep( jQuery.timers, function( fn ) { return elem === fn.elem; } ).length; }; jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, curOffset ) ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend( { offset: function( options ) { // Preserve chaining for setter if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var doc, docElem, rect, win, elem = this[ 0 ]; if ( !elem ) { return; } // Return zeros for disconnected and hidden (display: none) elements (gh-2310) // Support: IE <=11 only // Running getBoundingClientRect on a // disconnected node in IE throws an error if ( !elem.getClientRects().length ) { return { top: 0, left: 0 }; } rect = elem.getBoundingClientRect(); doc = elem.ownerDocument; docElem = doc.documentElement; win = doc.defaultView; return { top: rect.top + win.pageYOffset - docElem.clientTop, left: rect.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, // because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume getBoundingClientRect is there when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset = { top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ), left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) }; } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, // This method will return documentElement in the following cases: // 1) For the element inside the iframe without offsetParent, this method will return // documentElement of the parent window // 2) For the hidden or detached element // 3) For body or html element, i.e. in case of the html node - it will return itself // // but those exceptions were never presented as a real life use-cases // and might be considered as more preferable results. // // This logic, however, is not guaranteed and can change at any point in the future offsetParent: function() { return this.map( function() { var offsetParent = this.offsetParent; while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { // Coalesce documents and windows var win; if ( jQuery.isWindow( elem ) ) { win = elem; } else if ( elem.nodeType === 9 ) { win = elem.defaultView; } if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : win.pageXOffset, top ? val : win.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length ); }; } ); // Support: Safari <=7 - 9.1, Chrome <=37 - 49 // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // If curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); } ); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729) return funcName.indexOf( "outer" ) === 0 ? elem[ "inner" + name ] : elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable ); }; } ); } ); jQuery.fn.extend( { bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } } ); jQuery.holdReady = function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }; jQuery.isArray = Array.isArray; jQuery.parseJSON = JSON.parse; jQuery.nodeName = nodeName; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( true ) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return jQuery; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in AMD // (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( !noGlobal ) { window.jQuery = window.$ = jQuery; } return jQuery; } ); /***/ }), /* 1 */ /***/ (function(module, exports) { var cats = ['dave', 'henry', 'martha']; module.exports = cats; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { var cats = __webpack_require__(1); var $ = __webpack_require__(0); console.log('$(cats).length', $(cats).length); $('#app').text("cats"); console.log(cats); /***/ }) /******/ ]);
hugonasciutti/Exercises
webpack/4/bin/app.bundle.js
JavaScript
mit
271,260
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Nikon; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class NikonAVITags0x000d extends AbstractTag { protected $Id = 13; protected $Name = 'Nikon_AVITags_0x000d'; protected $FullName = 'Nikon::AVITags'; protected $GroupName = 'Nikon'; protected $g0 = 'MakerNotes'; protected $g1 = 'Nikon'; protected $g2 = 'Camera'; protected $Type = 'int16u'; protected $Writable = false; protected $Description = 'Nikon AVI Tags 0x000d'; protected $flag_Permanent = true; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Nikon/NikonAVITags0x000d.php
PHP
mit
854
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package threads; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** * * @author mars */ public class Bounce { public static void main(String[] args) { JFrame frame = new BounceFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } /** * A Ball that moves and bounces off the edges of a rectangle * */ class Ball { private static final int XSIZE = 15; private static final int YSIZE = 15; private double x = 0; private double y = 0; private double dx = 1; private double dy = 1; /** * Moves the ball to the next position,reversing direction if it hits one of * the edges */ public void move(Rectangle2D bounds) { x += dx; y += dy; if (x < bounds.getMinX()) { x = bounds.getMinX(); dx = -dx; } if (x + XSIZE >= bounds.getMaxX()) { x = bounds.getMaxX() - XSIZE; dx = -dx; } if (y < bounds.getMinY()) { y = bounds.getMinY(); dy = -dy; } if (y + YSIZE >= bounds.getMaxY()) { y = bounds.getMaxY() - YSIZE; dy = -dy; } } /** * Gets the shape of the ball at its current position */ public Ellipse2D getShape() { return new Ellipse2D.Double(x, y, XSIZE, YSIZE); } } /** * The panel that draws the balls. */ class BallPanel extends JPanel { private ArrayList<Ball> balls = new ArrayList<>(); /** * Add a ball to the panel * * @param b the ball to add */ public void add(Ball b) { balls.add(b); } @Override public void paintComponents(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; for (Ball b : balls) { g2.fill(b.getShape()); } } } /** * The frame with the panel and buttons * */ class BounceFrame extends JFrame { private BallPanel panel; private static final int DEFAULT_WIDTH = 450; private static final int DEFAULT_HEIGHT = 350; private final int STEPS = 1000; private final int DELAY = 3; /** * Constructs the frame with the panel for showing the bouncing ball and * start and close buttons */ public BounceFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setTitle("Bounce"); panel = new BallPanel(); add(panel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); addButton(buttonPanel, "Start", new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //To change body of generated methods, choose Tools | Templates. addBall(); } }); addButton(buttonPanel, "Close", new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //To change body of generated methods, choose Tools | Templates. System.exit(0); } }); add(buttonPanel, BorderLayout.SOUTH); } /** * Adds a button to a container * * @param c the container * @param title the button title * @param listener the action listener for the button */ public void addButton(Container c, String title, ActionListener listener) { JButton button = new JButton(title); c.add(button); button.addActionListener(listener); } /** * Adds a bouncing ball to the panel and makes it bounce 1,000 times */ public void addBall() { try { Ball ball = new Ball(); panel.add(ball); for (int i = 1; i <= STEPS; i++) { ball.move(panel.getBounds()); panel.paint(panel.getGraphics()); Thread.sleep(DELAY); } } catch (InterruptedException e) { } } }
devopsmwas/javapractice
NetBeansProjects/practice/src/threads/Bounce.java
Java
mit
4,470
import React, { Component, PropTypes } from 'react'; import DatePicker from 'material-ui/lib/date-picker/date-picker'; import * as layouts from '../../store/db_layouts.js'; function fmtDate( dt ) { return dt.toLocaleDateString(); } const CompFormDate = (props) => { const f = props.field; const curr_date = new Date( props.value ); // Drop the first argument, and send date in a god format for us let handleChange = ( this_is_null, new_date ) => { props.onChange( f, layouts.asYYYYMMDD( new_date )); }; return ( <DatePicker hintText={f.field} className="form_input" floatingLabelText={f.field} autoOk textFieldStyle={f.textstyle} style={f.style} formatDate={fmtDate} value={curr_date} mode="landscape" onChange={handleChange} />); }; CompFormDate.propTypes = { field: PropTypes.object.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired }; export default CompFormDate;
yabadabu/react-playground
src/components/form/CompFormDate.js
JavaScript
mit
1,011
/* RequireJS 2.2.0 Copyright jQuery Foundation and other contributors. Released under MIT license, http://github.com/requirejs/requirejs/LICENSE */ var requirejs, require, define; (function(ga) { function ka(b, c, d, g) { return g || "" } function K(b) { return "[object Function]" === Q.call(b) } function L(b) { return "[object Array]" === Q.call(b) } function y(b, c) { if (b) { var d; for (d = 0; d < b.length && (!b[d] || !c(b[d], d, b)); d += 1) ; } } function X(b, c) { if (b) { var d; for (d = b.length - 1; -1 < d && (!b[d] || !c(b[d], d, b)); --d) ; } } function x(b, c) { return la.call(b, c) } function e(b, c) { return x(b, c) && b[c] } function D(b, c) { for (var d in b) if (x(b, d) && c(b[d], d)) break } function Y(b, c, d, g) { c && D(c, function(c, e) { if (d || !x(b, e)) !g || "object" !== typeof c || !c || L(c) || K(c) || c instanceof RegExp ? b[e] = c : (b[e] || (b[e] = {}), Y(b[e], c, d, g)) }); return b } function z(b, c) { return function() { return c.apply(b, arguments) } } function ha(b) { throw b; } function ia(b) { if (!b) return b; var c = ga; y(b.split("."), function(b) { c = c[b] }); return c } function F(b, c, d, g) { c = Error(c + "\nhttp://requirejs.org/docs/errors.html#" + b); c.requireType = b; c.requireModules = g; d && (c.originalError = d); return c } function ma(b) { function c(a, n, b) { var h, k, f, c, d, l, g, r; n = n && n.split("/"); var q = p.map , m = q && q["*"]; if (a) { a = a.split("/"); k = a.length - 1; p.nodeIdCompat && U.test(a[k]) && (a[k] = a[k].replace(U, "")); "." === a[0].charAt(0) && n && (k = n.slice(0, n.length - 1), a = k.concat(a)); k = a; for (f = 0; f < k.length; f++) c = k[f], "." === c ? (k.splice(f, 1), --f) : ".." === c && 0 !== f && (1 !== f || ".." !== k[2]) && ".." !== k[f - 1] && 0 < f && (k.splice(f - 1, 2), f -= 2); a = a.join("/") } if (b && q && (n || m)) { k = a.split("/"); f = k.length; a: for (; 0 < f; --f) { d = k.slice(0, f).join("/"); if (n) for (c = n.length; 0 < c; --c) if (b = e(q, n.slice(0, c).join("/"))) if (b = e(b, d)) { h = b; l = f; break a } !g && m && e(m, d) && (g = e(m, d), r = f) } !h && g && (h = g, l = r); h && (k.splice(0, l, h), a = k.join("/")) } return (h = e(p.pkgs, a)) ? h : a } function d(a) { E && y(document.getElementsByTagName("script"), function(n) { if (n.getAttribute("data-requiremodule") === a && n.getAttribute("data-requirecontext") === l.contextName) return n.parentNode.removeChild(n), !0 }) } function m(a) { var n = e(p.paths, a); if (n && L(n) && 1 < n.length) return n.shift(), l.require.undef(a), l.makeRequire(null, { skipMap: !0 })([a]), !0 } function r(a) { var n, b = a ? a.indexOf("!") : -1; -1 < b && (n = a.substring(0, b), a = a.substring(b + 1, a.length)); return [n, a] } function q(a, n, b, h) { var k, f, d = null, g = n ? n.name : null, p = a, q = !0, m = ""; a || (q = !1, a = "_@r" + (Q += 1)); a = r(a); d = a[0]; a = a[1]; d && (d = c(d, g, h), f = e(v, d)); a && (d ? m = f && f.normalize ? f.normalize(a, function(a) { return c(a, g, h) }) : -1 === a.indexOf("!") ? c(a, g, h) : a : (m = c(a, g, h), a = r(m), d = a[0], m = a[1], b = !0, k = l.nameToUrl(m))); b = !d || f || b ? "" : "_unnormalized" + (T += 1); return { prefix: d, name: m, parentMap: n, unnormalized: !!b, url: k, originalName: p, isDefine: q, id: (d ? d + "!" + m : m) + b } } function u(a) { var b = a.id , c = e(t, b); c || (c = t[b] = new l.Module(a)); return c } function w(a, b, c) { var h = a.id , k = e(t, h); if (!x(v, h) || k && !k.defineEmitComplete) if (k = u(a), k.error && "error" === b) c(k.error); else k.on(b, c); else "defined" === b && c(v[h]) } function A(a, b) { var c = a.requireModules , h = !1; if (b) b(a); else if (y(c, function(b) { if (b = e(t, b)) b.error = a, b.events.error && (h = !0, b.emit("error", a)) }), !h) g.onError(a) } function B() { V.length && (y(V, function(a) { var b = a[0]; "string" === typeof b && (l.defQueueMap[b] = !0); G.push(a) }), V = []) } function C(a) { delete t[a]; delete Z[a] } function J(a, b, c) { var h = a.map.id; a.error ? a.emit("error", a.error) : (b[h] = !0, y(a.depMaps, function(h, f) { var d = h.id , g = e(t, d); !g || a.depMatched[f] || c[d] || (e(b, d) ? (a.defineDep(f, v[d]), a.check()) : J(g, b, c)) }), c[h] = !0) } function H() { var a, b, c = (a = 1E3 * p.waitSeconds) && l.startTime + a < (new Date).getTime(), h = [], k = [], f = !1, g = !0; if (!aa) { aa = !0; D(Z, function(a) { var l = a.map , e = l.id; if (a.enabled && (l.isDefine || k.push(a), !a.error)) if (!a.inited && c) m(e) ? f = b = !0 : (h.push(e), d(e)); else if (!a.inited && a.fetched && l.isDefine && (f = !0, !l.prefix)) return g = !1 }); if (c && h.length) return a = F("timeout", "Load timeout for modules: " + h, null, h), a.contextName = l.contextName, A(a); g && y(k, function(a) { J(a, {}, {}) }); c && !b || !f || !E && !ja || ba || (ba = setTimeout(function() { ba = 0; H() }, 50)); aa = !1 } } function I(a) { x(v, a[0]) || u(q(a[0], null, !0)).init(a[1], a[2]) } function O(a) { a = a.currentTarget || a.srcElement; var b = l.onScriptLoad; a.detachEvent && !ca ? a.detachEvent("onreadystatechange", b) : a.removeEventListener("load", b, !1); b = l.onScriptError; a.detachEvent && !ca || a.removeEventListener("error", b, !1); return { node: a, id: a && a.getAttribute("data-requiremodule") } } function P() { var a; for (B(); G.length; ) { a = G.shift(); if (null === a[0]) return A(F("mismatch", "Mismatched anonymous define() module: " + a[a.length - 1])); I(a) } l.defQueueMap = {} } var aa, da, l, R, ba, p = { waitSeconds: 7, baseUrl: "./", paths: {}, bundles: {}, pkgs: {}, shim: {}, config: {} }, t = {}, Z = {}, ea = {}, G = [], v = {}, W = {}, fa = {}, Q = 1, T = 1; R = { require: function(a) { return a.require ? a.require : a.require = l.makeRequire(a.map) }, exports: function(a) { a.usingExports = !0; if (a.map.isDefine) return a.exports ? v[a.map.id] = a.exports : a.exports = v[a.map.id] = {} }, module: function(a) { return a.module ? a.module : a.module = { id: a.map.id, uri: a.map.url, config: function() { return e(p.config, a.map.id) || {} }, exports: a.exports || (a.exports = {}) } } }; da = function(a) { this.events = e(ea, a.id) || {}; this.map = a; this.shim = e(p.shim, a.id); this.depExports = []; this.depMaps = []; this.depMatched = []; this.pluginMaps = {}; this.depCount = 0 } ; da.prototype = { init: function(a, b, c, h) { h = h || {}; if (!this.inited) { this.factory = b; if (c) this.on("error", c); else this.events.error && (c = z(this, function(a) { this.emit("error", a) })); this.depMaps = a && a.slice(0); this.errback = c; this.inited = !0; this.ignore = h.ignore; h.enabled || this.enabled ? this.enable() : this.check() } }, defineDep: function(a, b) { this.depMatched[a] || (this.depMatched[a] = !0, --this.depCount, this.depExports[a] = b) }, fetch: function() { if (!this.fetched) { this.fetched = !0; l.startTime = (new Date).getTime(); var a = this.map; if (this.shim) l.makeRequire(this.map, { enableBuildCallback: !0 })(this.shim.deps || [], z(this, function() { return a.prefix ? this.callPlugin() : this.load() })); else return a.prefix ? this.callPlugin() : this.load() } }, load: function() { var a = this.map.url; W[a] || (W[a] = !0, l.load(this.map.id, a)) }, check: function() { if (this.enabled && !this.enabling) { var a, b, c = this.map.id; b = this.depExports; var h = this.exports , k = this.factory; if (!this.inited) x(l.defQueueMap, c) || this.fetch(); else if (this.error) this.emit("error", this.error); else if (!this.defining) { this.defining = !0; if (1 > this.depCount && !this.defined) { if (K(k)) { if (this.events.error && this.map.isDefine || g.onError !== ha) try { h = l.execCb(c, k, b, h) } catch (d) { a = d } else h = l.execCb(c, k, b, h); this.map.isDefine && void 0 === h && ((b = this.module) ? h = b.exports : this.usingExports && (h = this.exports)); if (a) return a.requireMap = this.map, a.requireModules = this.map.isDefine ? [this.map.id] : null, a.requireType = this.map.isDefine ? "define" : "require", A(this.error = a) } else h = k; this.exports = h; if (this.map.isDefine && !this.ignore && (v[c] = h, g.onResourceLoad)) { var f = []; y(this.depMaps, function(a) { f.push(a.normalizedMap || a) }); g.onResourceLoad(l, this.map, f) } C(c); this.defined = !0 } this.defining = !1; this.defined && !this.defineEmitted && (this.defineEmitted = !0, this.emit("defined", this.exports), this.defineEmitComplete = !0) } } }, callPlugin: function() { var a = this.map , b = a.id , d = q(a.prefix); this.depMaps.push(d); w(d, "defined", z(this, function(h) { var k, f, d = e(fa, this.map.id), M = this.map.name, r = this.map.parentMap ? this.map.parentMap.name : null, m = l.makeRequire(a.parentMap, { enableBuildCallback: !0 }); if (this.map.unnormalized) { if (h.normalize && (M = h.normalize(M, function(a) { return c(a, r, !0) }) || ""), f = q(a.prefix + "!" + M, this.map.parentMap), w(f, "defined", z(this, function(a) { this.map.normalizedMap = f; this.init([], function() { return a }, null, { enabled: !0, ignore: !0 }) })), h = e(t, f.id)) { this.depMaps.push(f); if (this.events.error) h.on("error", z(this, function(a) { this.emit("error", a) })); h.enable() } } else d ? (this.map.url = l.nameToUrl(d), this.load()) : (k = z(this, function(a) { this.init([], function() { return a }, null, { enabled: !0 }) }), k.error = z(this, function(a) { this.inited = !0; this.error = a; a.requireModules = [b]; D(t, function(a) { 0 === a.map.id.indexOf(b + "_unnormalized") && C(a.map.id) }); A(a) }), k.fromText = z(this, function(h, c) { var d = a.name , f = q(d) , M = S; c && (h = c); M && (S = !1); u(f); x(p.config, b) && (p.config[d] = p.config[b]); try { g.exec(h) } catch (e) { return A(F("fromtexteval", "fromText eval for " + b + " failed: " + e, e, [b])) } M && (S = !0); this.depMaps.push(f); l.completeLoad(d); m([d], k) }), h.load(a.name, m, k, p)) })); l.enable(d, this); this.pluginMaps[d.id] = d }, enable: function() { Z[this.map.id] = this; this.enabling = this.enabled = !0; y(this.depMaps, z(this, function(a, b) { var c, h; if ("string" === typeof a) { a = q(a, this.map.isDefine ? this.map : this.map.parentMap, !1, !this.skipMap); this.depMaps[b] = a; if (c = e(R, a.id)) { this.depExports[b] = c(this); return } this.depCount += 1; w(a, "defined", z(this, function(a) { this.undefed || (this.defineDep(b, a), this.check()) })); this.errback ? w(a, "error", z(this, this.errback)) : this.events.error && w(a, "error", z(this, function(a) { this.emit("error", a) })) } c = a.id; h = t[c]; x(R, c) || !h || h.enabled || l.enable(a, this) })); D(this.pluginMaps, z(this, function(a) { var b = e(t, a.id); b && !b.enabled && l.enable(a, this) })); this.enabling = !1; this.check() }, on: function(a, b) { var c = this.events[a]; c || (c = this.events[a] = []); c.push(b) }, emit: function(a, b) { y(this.events[a], function(a) { a(b) }); "error" === a && delete this.events[a] } }; l = { config: p, contextName: b, registry: t, defined: v, urlFetched: W, defQueue: G, defQueueMap: {}, Module: da, makeModuleMap: q, nextTick: g.nextTick, onError: A, configure: function(a) { a.baseUrl && "/" !== a.baseUrl.charAt(a.baseUrl.length - 1) && (a.baseUrl += "/"); if ("string" === typeof a.urlArgs) { var b = a.urlArgs; a.urlArgs = function(a, c) { return (-1 === c.indexOf("?") ? "?" : "&") + b } } var c = p.shim , h = { paths: !0, bundles: !0, config: !0, map: !0 }; D(a, function(a, b) { h[b] ? (p[b] || (p[b] = {}), Y(p[b], a, !0, !0)) : p[b] = a }); a.bundles && D(a.bundles, function(a, b) { y(a, function(a) { a !== b && (fa[a] = b) }) }); a.shim && (D(a.shim, function(a, b) { L(a) && (a = { deps: a }); !a.exports && !a.init || a.exportsFn || (a.exportsFn = l.makeShimExports(a)); c[b] = a }), p.shim = c); a.packages && y(a.packages, function(a) { var b; a = "string" === typeof a ? { name: a } : a; b = a.name; a.location && (p.paths[b] = a.location); p.pkgs[b] = a.name + "/" + (a.main || "main").replace(na, "").replace(U, "") }); D(t, function(a, b) { a.inited || a.map.unnormalized || (a.map = q(b, null, !0)) }); (a.deps || a.callback) && l.require(a.deps || [], a.callback) }, makeShimExports: function(a) { return function() { var b; a.init && (b = a.init.apply(ga, arguments)); return b || a.exports && ia(a.exports) } }, makeRequire: function(a, n) { function m(c, d, f) { var e, r; n.enableBuildCallback && d && K(d) && (d.__requireJsBuild = !0); if ("string" === typeof c) { if (K(d)) return A(F("requireargs", "Invalid require call"), f); if (a && x(R, c)) return R[c](t[a.id]); if (g.get) return g.get(l, c, a, m); e = q(c, a, !1, !0); e = e.id; return x(v, e) ? v[e] : A(F("notloaded", 'Module name "' + e + '" has not been loaded yet for context: ' + b + (a ? "" : ". Use require([])"))) } P(); l.nextTick(function() { P(); r = u(q(null, a)); r.skipMap = n.skipMap; r.init(c, d, f, { enabled: !0 }); H() }); return m } n = n || {}; Y(m, { isBrowser: E, toUrl: function(b) { var d, f = b.lastIndexOf("."), g = b.split("/")[0]; -1 !== f && ("." !== g && ".." !== g || 1 < f) && (d = b.substring(f, b.length), b = b.substring(0, f)); return l.nameToUrl(c(b, a && a.id, !0), d, !0) }, defined: function(b) { return x(v, q(b, a, !1, !0).id) }, specified: function(b) { b = q(b, a, !1, !0).id; return x(v, b) || x(t, b) } }); a || (m.undef = function(b) { B(); var c = q(b, a, !0) , f = e(t, b); f.undefed = !0; d(b); delete v[b]; delete W[c.url]; delete ea[b]; X(G, function(a, c) { a[0] === b && G.splice(c, 1) }); delete l.defQueueMap[b]; f && (f.events.defined && (ea[b] = f.events), C(b)) } ); return m }, enable: function(a) { e(t, a.id) && u(a).enable() }, completeLoad: function(a) { var b, c, d = e(p.shim, a) || {}, g = d.exports; for (B(); G.length; ) { c = G.shift(); if (null === c[0]) { c[0] = a; if (b) break; b = !0 } else c[0] === a && (b = !0); I(c) } l.defQueueMap = {}; c = e(t, a); if (!b && !x(v, a) && c && !c.inited) if (!p.enforceDefine || g && ia(g)) I([a, d.deps || [], d.exportsFn]); else return m(a) ? void 0 : A(F("nodefine", "No define call for " + a, null, [a])); H() }, nameToUrl: function(a, b, c) { var d, k, f, m; (d = e(p.pkgs, a)) && (a = d); if (d = e(fa, a)) return l.nameToUrl(d, b, c); if (g.jsExtRegExp.test(a)) d = a + (b || ""); else { d = p.paths; k = a.split("/"); for (f = k.length; 0 < f; --f) if (m = k.slice(0, f).join("/"), m = e(d, m)) { L(m) && (m = m[0]); k.splice(0, f, m); break } d = k.join("/"); d += b || (/^data\:|^blob\:|\?/.test(d) || c ? "" : ".js"); d = ("/" === d.charAt(0) || d.match(/^[\w\+\.\-]+:/) ? "" : p.baseUrl) + d } return p.urlArgs && !/^blob\:/.test(d) ? d + p.urlArgs(a, d) : d }, load: function(a, b) { g.load(l, a, b) }, execCb: function(a, b, c, d) { return b.apply(d, c) }, onScriptLoad: function(a) { if ("load" === a.type || oa.test((a.currentTarget || a.srcElement).readyState)) N = null, a = O(a), l.completeLoad(a.id) }, onScriptError: function(a) { var b = O(a); if (!m(b.id)) { var c = []; D(t, function(a, d) { 0 !== d.indexOf("_@r") && y(a.depMaps, function(a) { if (a.id === b.id) return c.push(d), !0 }) }); return A(F("scripterror", 'Script error for "' + b.id + (c.length ? '", needed by: ' + c.join(", ") : '"'), a, [b.id])) } } }; l.require = l.makeRequire(); return l } function pa() { if (N && "interactive" === N.readyState) return N; X(document.getElementsByTagName("script"), function(b) { if ("interactive" === b.readyState) return N = b }); return N } var g, B, C, H, O, I, N, P, u, T, qa = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, ra = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, U = /\.js$/, na = /^\.\//; B = Object.prototype; var Q = B.toString , la = B.hasOwnProperty , E = !("undefined" === typeof window || "undefined" === typeof navigator || !window.document) , ja = !E && "undefined" !== typeof importScripts , oa = E && "PLAYSTATION 3" === navigator.platform ? /^complete$/ : /^(complete|loaded)$/ , ca = "undefined" !== typeof opera && "[object Opera]" === opera.toString() , J = {} , w = {} , V = [] , S = !1; if ("undefined" === typeof define) { if ("undefined" !== typeof requirejs) { if (K(requirejs)) return; w = requirejs; requirejs = void 0 } "undefined" === typeof require || K(require) || (w = require, require = void 0); g = requirejs = function(b, c, d, m) { var r, q = "_"; L(b) || "string" === typeof b || (r = b, L(c) ? (b = c, c = d, d = m) : b = []); r && r.context && (q = r.context); (m = e(J, q)) || (m = J[q] = g.s.newContext(q)); r && m.configure(r); return m.require(b, c, d) } ; g.config = function(b) { return g(b) } ; g.nextTick = "undefined" !== typeof setTimeout ? function(b) { setTimeout(b, 4) } : function(b) { b() } ; require || (require = g); g.version = "2.2.0"; g.jsExtRegExp = /^\/|:|\?|\.js$/; g.isBrowser = E; B = g.s = { contexts: J, newContext: ma }; g({}); y(["toUrl", "undef", "defined", "specified"], function(b) { g[b] = function() { var c = J._; return c.require[b].apply(c, arguments) } }); E && (C = B.head = document.getElementsByTagName("head")[0], H = document.getElementsByTagName("base")[0]) && (C = B.head = H.parentNode); g.onError = ha; g.createNode = function(b, c, d) { c = b.xhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "html:script") : document.createElement("script"); c.type = b.scriptType || "text/javascript"; c.charset = "utf-8"; c.async = !0; return c } ; g.load = function(b, c, d) { var m = b && b.config || {}, e; if (E) { e = g.createNode(m, c, d); e.setAttribute("data-requirecontext", b.contextName); e.setAttribute("data-requiremodule", c); !e.attachEvent || e.attachEvent.toString && 0 > e.attachEvent.toString().indexOf("[native code") || ca ? (e.addEventListener("load", b.onScriptLoad, !1), e.addEventListener("error", b.onScriptError, !1)) : (S = !0, e.attachEvent("onreadystatechange", b.onScriptLoad)); e.src = d; if (m.onNodeCreated) m.onNodeCreated(e, m, c, d); P = e; H ? C.insertBefore(e, H) : C.appendChild(e); P = null; return e } if (ja) try { setTimeout(function() {}, 0), importScripts(d), b.completeLoad(c) } catch (q) { b.onError(F("importscripts", "importScripts failed for " + c + " at " + d, q, [c])) } } ; E && !w.skipDataMain && X(document.getElementsByTagName("script"), function(b) { C || (C = b.parentNode); if (O = b.getAttribute("data-main")) return u = O, w.baseUrl || -1 !== u.indexOf("!") || (I = u.split("/"), u = I.pop(), T = I.length ? I.join("/") + "/" : "./", w.baseUrl = T), u = u.replace(U, ""), g.jsExtRegExp.test(u) && (u = O), w.deps = w.deps ? w.deps.concat(u) : [u], !0 }); define = function(b, c, d) { var e, g; "string" !== typeof b && (d = c, c = b, b = null); L(c) || (d = c, c = null); !c && K(d) && (c = [], d.length && (d.toString().replace(qa, ka).replace(ra, function(b, d) { c.push(d) }), c = (1 === d.length ? ["require"] : ["require", "exports", "module"]).concat(c))); S && (e = P || pa()) && (b || (b = e.getAttribute("data-requiremodule")), g = J[e.getAttribute("data-requirecontext")]); g ? (g.defQueue.push([b, c, d]), g.defQueueMap[b] = !0) : V.push([b, c, d]) } ; define.amd = { jQuery: !0 }; g.exec = function(b) { return eval(b) } ; g(w) } } )(this);
rlaj/tmc
source/mas/js/libs/require-min.js
JavaScript
mit
33,384
# @author Avtandil Kikabidze # @copyright Copyright (c) 2008-2015, Avtandil Kikabidze aka LONGMAN (akalongman@gmail.com) # @link http://longman.me # @license The MIT License (MIT) import os import sys import sublime import sublime_plugin st_version = 2 if sublime.version() == '' or int(sublime.version()) > 3000: st_version = 3 reloader_name = 'codeformatter.reloader' # ST3 loads each package as a module, so it needs an extra prefix if st_version == 3: reloader_name = 'CodeFormatter.' + reloader_name from imp import reload if reloader_name in sys.modules: reload(sys.modules[reloader_name]) try: # Python 3 from .codeformatter.formatter import Formatter except (ValueError): # Python 2 from codeformatter.formatter import Formatter # fix for ST2 cprint = globals()['__builtins__']['print'] debug_mode = False def plugin_loaded(): cprint('CodeFormatter: Plugin Initialized') # settings = sublime.load_settings('CodeFormatter.sublime-settings') # debug_mode = settings.get('codeformatter_debug', False) # if debug_mode: # from pprint import pprint # pprint(settings) # debug_write('Debug mode enabled') # debug_write('Platform ' + sublime.platform() + ' ' + sublime.arch()) # debug_write('Sublime Version ' + sublime.version()) # debug_write('Settings ' + pprint(settings)) if (sublime.platform() != 'windows'): import stat path = ( sublime.packages_path() + '/CodeFormatter/codeformatter/lib/phpbeautifier/fmt.phar' ) st = os.stat(path) os.chmod(path, st.st_mode | stat.S_IEXEC) if st_version == 2: plugin_loaded() class CodeFormatterCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=None, saving=None): run_formatter(self.view, edit, syntax=syntax, saving=saving) class CodeFormatterOpenTabsCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=None): window = sublime.active_window() for view in window.views(): run_formatter(view, edit, quiet=True) class CodeFormatterEventListener(sublime_plugin.EventListener): def on_pre_save(self, view): view.run_command('code_formatter', {'saving': True}) class CodeFormatterShowPhpTransformationsCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=False): import subprocess import re platform = sublime.platform() settings = sublime.load_settings('CodeFormatter.sublime-settings') opts = settings.get('codeformatter_php_options') php_path = 'php' if ('php_path' in opts and opts['php_path']): php_path = opts['php_path'] php55_compat = False if ('php55_compat' in opts and opts['php55_compat']): php55_compat = opts['php55_compat'] cmd = [] cmd.append(str(php_path)) if php55_compat: cmd.append( '{}/CodeFormatter/codeformatter/lib/phpbeautifier/fmt.phar'.format( sublime.packages_path())) else: cmd.append( '{}/CodeFormatter/codeformatter/lib/phpbeautifier/phpf.phar'.format( sublime.packages_path())) cmd.append('--list') #print(cmd) stderr = '' stdout = '' try: if (platform == 'windows'): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = subprocess.SW_HIDE p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, creationflags=subprocess.SW_HIDE) else: p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() except Exception as e: stderr = str(e) if (not stderr and not stdout): stderr = 'Error while gethering list of php transformations' if len(stderr) == 0 and len(stdout) > 0: text = stdout.decode('utf-8') text = re.sub( 'Usage:.*?PASSNAME', 'Available PHP Tranformations:', text) window = self.view.window() pt = window.get_output_panel('paneltranformations') pt.set_read_only(False) pt.insert(edit, pt.size(), text) window.run_command( 'show_panel', {'panel': 'output.paneltranformations'}) else: show_error('Formatter error:\n' + stderr) def run_formatter(view, edit, *args, **kwargs): if view.is_scratch(): show_error('File is scratch') return # default parameters syntax = kwargs.get('syntax') saving = kwargs.get('saving', False) quiet = kwargs.get('quiet', False) formatter = Formatter(view, syntax) if not formatter.exists(): if not quiet and not saving: show_error('Formatter for this file type ({}) not found.'.format( formatter.syntax)) return if (saving and not formatter.format_on_save_enabled()): return file_text = sublime.Region(0, view.size()) file_text_utf = view.substr(file_text).encode('utf-8') if (len(file_text_utf) == 0): return stdout, stderr = formatter.format(file_text_utf) if len(stderr) == 0 and len(stdout) > 0: view.replace(edit, file_text, stdout) elif not quiet: show_error('Format error:\n' + stderr) def console_write(text, prefix=False): if prefix: sys.stdout.write('CodeFormatter: ') sys.stdout.write(text + '\n') def debug_write(text, prefix=False): console_write(text, True) def show_error(text): sublime.error_message(u'CodeFormatter\n\n%s' % text)
crlang/sublime-text---front-end-config
Data/Packages/CodeFormatter/CodeFormatter.py
Python
mit
6,068
// Code generated by "stringer -type=pipeAddFlavor constants.go"; DO NOT EDIT. package bot import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[flavorSpawn-0] _ = x[flavorAdd-1] _ = x[flavorFinal-2] _ = x[flavorFail-3] } const _pipeAddFlavor_name = "flavorSpawnflavorAddflavorFinalflavorFail" var _pipeAddFlavor_index = [...]uint8{0, 11, 20, 31, 41} func (i pipeAddFlavor) String() string { if i < 0 || i >= pipeAddFlavor(len(_pipeAddFlavor_index)-1) { return "pipeAddFlavor(" + strconv.FormatInt(int64(i), 10) + ")" } return _pipeAddFlavor_name[_pipeAddFlavor_index[i]:_pipeAddFlavor_index[i+1]] }
parsley42/gopherbot
bot/pipeaddflavor_string.go
GO
mit
763
<?php namespace Apptrc\Providers; use Illuminate\Support\Facades\Event; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'Illuminate\Auth\Events\Registered' => [ 'Apptrc\Listeners\UserRegisteredListener', ], 'Apptrc\Events\PasswordUpdateEvent' => [ 'Apptrc\Listeners\PasswordUpdateListener', ], ]; /** * Register any events for your application. * * @return void */ public function boot() { parent::boot(); // } }
Autapomorph/apptrc
app/Providers/EventServiceProvider.php
PHP
mit
677
# encoding: utf-8 require_dependency "fast_ext/application_controller" module FastExt class AdminController < ApplicationController def index end end end
songgz/fast_ext
app/controllers/fast_ext/admin_controller.rb
Ruby
mit
170
<?php defined('SYSPATH') OR die('No direct access allowed.'); return array( 'driver' => 'MySQL', );
pelevesque/Kohana3_lieux
config/lieux.php
PHP
mit
107
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Animate_Current_By_Value { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync( Microsoft.ApplicationInsights.WindowsCollectors.Metadata | Microsoft.ApplicationInsights.WindowsCollectors.Session); this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
Microsoft/composition
Demos/Reference Demos/Animations_Expressions/Animate_Current_By_Value/App.xaml.cs
C#
mit
4,226
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2018 Baldur Karlsson * Copyright (c) 2014 Crytek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "driver/d3d11/d3d11_renderstate.h" #include "driver/d3d11/d3d11_context.h" #include "driver/d3d11/d3d11_device.h" #include "driver/d3d11/d3d11_resources.h" D3D11RenderState::D3D11RenderState(D3D11RenderState::EmptyInit) { RDCEraseEl(IA); RDCEraseEl(VS); RDCEraseEl(HS); RDCEraseEl(DS); RDCEraseEl(GS); RDCEraseEl(SO); RDCEraseEl(RS); RDCEraseEl(PS); RDCEraseEl(OM); RDCEraseEl(CS); RDCEraseEl(CSUAVs); Predicate = NULL; PredicateValue = FALSE; Clear(); m_ImmediatePipeline = false; m_ViewportScissorPartial = true; m_pDevice = NULL; } D3D11RenderState::D3D11RenderState(const D3D11RenderState &other) { RDCEraseEl(IA); RDCEraseEl(VS); RDCEraseEl(HS); RDCEraseEl(DS); RDCEraseEl(GS); RDCEraseEl(SO); RDCEraseEl(RS); RDCEraseEl(PS); RDCEraseEl(OM); RDCEraseEl(CS); RDCEraseEl(CSUAVs); Predicate = NULL; PredicateValue = FALSE; m_ImmediatePipeline = false; m_pDevice = NULL; CopyState(other); } void D3D11RenderState::CopyState(const D3D11RenderState &other) { ReleaseRefs(); memcpy(&IA, &other.IA, sizeof(IA)); memcpy(&VS, &other.VS, sizeof(VS)); memcpy(&HS, &other.HS, sizeof(HS)); memcpy(&DS, &other.DS, sizeof(DS)); memcpy(&GS, &other.GS, sizeof(GS)); memcpy(&SO, &other.SO, sizeof(SO)); memcpy(&RS, &other.RS, sizeof(RS)); memcpy(&PS, &other.PS, sizeof(PS)); memcpy(&OM, &other.OM, sizeof(OM)); memcpy(&CS, &other.CS, sizeof(CS)); memcpy(&CSUAVs, &other.CSUAVs, sizeof(CSUAVs)); Predicate = other.Predicate; PredicateValue = other.PredicateValue; m_ViewportScissorPartial = other.m_ViewportScissorPartial; AddRefs(); } D3D11RenderState::~D3D11RenderState() { ReleaseRefs(); } void D3D11RenderState::ReleaseRefs() { ReleaseRef(IA.IndexBuffer); ReleaseRef(IA.Layout); for(UINT i = 0; i < D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT; i++) ReleaseRef(IA.VBs[i]); Shader *stages[] = {&VS, &HS, &DS, &GS, &PS, &CS}; for(int s = 0; s < 6; s++) { Shader *sh = stages[s]; ReleaseRef(sh->Object); for(UINT i = 0; i < D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT; i++) ReleaseRef(sh->ConstantBuffers[i]); for(UINT i = 0; i < D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT; i++) ReleaseRef(sh->Samplers[i]); for(UINT i = 0; i < D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT; i++) ReleaseRef(sh->SRVs[i]); for(UINT i = 0; i < D3D11_SHADER_MAX_INTERFACES; i++) ReleaseRef(sh->Instances[i]); sh++; } for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) ReleaseRef(CSUAVs[i]); for(UINT i = 0; i < D3D11_SO_BUFFER_SLOT_COUNT; i++) ReleaseRef(SO.Buffers[i]); ReleaseRef(RS.State); ReleaseRef(OM.BlendState); ReleaseRef(OM.DepthStencilState); for(UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) ReleaseRef(OM.RenderTargets[i]); for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) ReleaseRef(OM.UAVs[i]); ReleaseRef(OM.DepthView); ReleaseRef(Predicate); RDCEraseEl(IA); RDCEraseEl(VS); RDCEraseEl(HS); RDCEraseEl(DS); RDCEraseEl(GS); RDCEraseEl(SO); RDCEraseEl(RS); RDCEraseEl(PS); RDCEraseEl(OM); RDCEraseEl(CS); RDCEraseEl(CSUAVs); Predicate = NULL; } void D3D11RenderState::MarkReferenced(WrappedID3D11DeviceContext *ctx, bool initial) const { ctx->MarkResourceReferenced(GetIDForResource(IA.Layout), initial ? eFrameRef_Unknown : eFrameRef_Read); ctx->MarkResourceReferenced(GetIDForResource(IA.IndexBuffer), initial ? eFrameRef_Unknown : eFrameRef_Read); for(UINT i = 0; i < D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT; i++) ctx->MarkResourceReferenced(GetIDForResource(IA.VBs[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); const Shader *stages[] = {&VS, &HS, &DS, &GS, &PS, &CS}; for(int s = 0; s < 6; s++) { const Shader *sh = stages[s]; ctx->MarkResourceReferenced(GetIDForResource(sh->Object), initial ? eFrameRef_Unknown : eFrameRef_Read); for(UINT i = 0; i < D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT; i++) ctx->MarkResourceReferenced(GetIDForResource(sh->ConstantBuffers[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); for(UINT i = 0; i < D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT; i++) { if(sh->SRVs[i]) { ctx->MarkResourceReferenced(GetIDForResource(sh->SRVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); ctx->MarkResourceReferenced(GetViewResourceResID(sh->SRVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); } } sh++; } for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) { if(CSUAVs[i]) { // UAVs we always assume to be partial updates ctx->MarkResourceReferenced(GetIDForResource(CSUAVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); ctx->MarkResourceReferenced(GetIDForResource(CSUAVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Write); ctx->MarkResourceReferenced(GetViewResourceResID(CSUAVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); ctx->MarkResourceReferenced(GetViewResourceResID(CSUAVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Write); } } for(UINT i = 0; i < D3D11_SO_BUFFER_SLOT_COUNT; i++) ctx->MarkResourceReferenced(GetIDForResource(SO.Buffers[i]), initial ? eFrameRef_Unknown : eFrameRef_Write); for(UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) { if(OM.RenderTargets[i]) { ctx->MarkResourceReferenced(GetIDForResource(OM.RenderTargets[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); if(m_ViewportScissorPartial) ctx->MarkResourceReferenced(GetViewResourceResID(OM.RenderTargets[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); ctx->MarkResourceReferenced(GetViewResourceResID(OM.RenderTargets[i]), initial ? eFrameRef_Unknown : eFrameRef_Write); } } for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) { if(OM.UAVs[i]) { // UAVs we always assume to be partial updates ctx->MarkResourceReferenced(GetIDForResource(OM.UAVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); ctx->MarkResourceReferenced(GetIDForResource(OM.UAVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Write); ctx->MarkResourceReferenced(GetViewResourceResID(OM.UAVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Read); ctx->MarkResourceReferenced(GetViewResourceResID(OM.UAVs[i]), initial ? eFrameRef_Unknown : eFrameRef_Write); } } if(OM.DepthView) { ctx->MarkResourceReferenced(GetIDForResource(OM.DepthView), initial ? eFrameRef_Unknown : eFrameRef_Read); if(m_ViewportScissorPartial) ctx->MarkResourceReferenced(GetViewResourceResID(OM.DepthView), initial ? eFrameRef_Unknown : eFrameRef_Read); ctx->MarkResourceReferenced(GetViewResourceResID(OM.DepthView), initial ? eFrameRef_Unknown : eFrameRef_Write); } if(Predicate) { ctx->MarkResourceReferenced(GetIDForResource(Predicate), initial ? eFrameRef_Unknown : eFrameRef_Read); } } void D3D11RenderState::CacheViewportPartial() { // tracks the min region of the enabled viewports plus scissors, to see if we could potentially // partially-update a render target (ie. we know for sure that we are only // writing to a region in one of the viewports). In this case we mark the // RT/DSV as read-write instead of just write, for initial state tracking. D3D11_RECT viewportScissorMin = {0, 0, 0xfffffff, 0xfffffff}; D3D11_RASTERIZER_DESC rsdesc; RDCEraseEl(rsdesc); rsdesc.ScissorEnable = FALSE; if(RS.State) RS.State->GetDesc(&rsdesc); for(UINT v = 0; v < RS.NumViews; v++) { D3D11_RECT scissor = {(LONG)RS.Viewports[v].TopLeftX, (LONG)RS.Viewports[v].TopLeftY, (LONG)RS.Viewports[v].Width, (LONG)RS.Viewports[v].Height}; // scissor (if set) is relative to matching viewport) if(v < RS.NumScissors && rsdesc.ScissorEnable) { scissor.left += RS.Scissors[v].left; scissor.top += RS.Scissors[v].top; scissor.right = RDCMIN(scissor.right, RS.Scissors[v].right - RS.Scissors[v].left); scissor.bottom = RDCMIN(scissor.bottom, RS.Scissors[v].bottom - RS.Scissors[v].top); } viewportScissorMin.left = RDCMAX(viewportScissorMin.left, scissor.left); viewportScissorMin.top = RDCMAX(viewportScissorMin.top, scissor.top); viewportScissorMin.right = RDCMIN(viewportScissorMin.right, scissor.right); viewportScissorMin.bottom = RDCMIN(viewportScissorMin.bottom, scissor.bottom); } m_ViewportScissorPartial = false; if(viewportScissorMin.left > 0 || viewportScissorMin.top > 0) { m_ViewportScissorPartial = true; } else { ID3D11Resource *res = NULL; if(OM.RenderTargets[0]) OM.RenderTargets[0]->GetResource(&res); else if(OM.DepthView) OM.DepthView->GetResource(&res); if(res) { D3D11_RESOURCE_DIMENSION dim; res->GetType(&dim); if(dim == D3D11_RESOURCE_DIMENSION_BUFFER) { // assume partial m_ViewportScissorPartial = true; } else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE1D) { D3D11_TEXTURE1D_DESC desc; ((ID3D11Texture1D *)res)->GetDesc(&desc); if(viewportScissorMin.right < (LONG)desc.Width) m_ViewportScissorPartial = true; } else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE2D) { D3D11_TEXTURE2D_DESC desc; ((ID3D11Texture2D *)res)->GetDesc(&desc); if(viewportScissorMin.right < (LONG)desc.Width || viewportScissorMin.bottom < (LONG)desc.Height) m_ViewportScissorPartial = true; } else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) { D3D11_TEXTURE3D_DESC desc; ((ID3D11Texture3D *)res)->GetDesc(&desc); if(viewportScissorMin.right < (LONG)desc.Width || viewportScissorMin.bottom < (LONG)desc.Height) m_ViewportScissorPartial = true; } } SAFE_RELEASE(res); } } void D3D11RenderState::AddRefs() { TakeRef(IA.IndexBuffer); TakeRef(IA.Layout); for(UINT i = 0; i < D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT; i++) TakeRef(IA.VBs[i]); Shader *stages[] = {&VS, &HS, &DS, &GS, &PS, &CS}; for(int s = 0; s < 6; s++) { Shader *sh = stages[s]; TakeRef(sh->Object); for(UINT i = 0; i < D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT; i++) TakeRef(sh->ConstantBuffers[i]); for(UINT i = 0; i < D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT; i++) TakeRef(sh->Samplers[i]); for(UINT i = 0; i < D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT; i++) TakeRef(sh->SRVs[i]); for(UINT i = 0; i < D3D11_SHADER_MAX_INTERFACES; i++) TakeRef(sh->Instances[i]); sh++; } for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) TakeRef(CSUAVs[i]); for(UINT i = 0; i < D3D11_SO_BUFFER_SLOT_COUNT; i++) TakeRef(SO.Buffers[i]); TakeRef(RS.State); TakeRef(OM.BlendState); TakeRef(OM.DepthStencilState); for(UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) TakeRef(OM.RenderTargets[i]); for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) TakeRef(OM.UAVs[i]); TakeRef(OM.DepthView); TakeRef(Predicate); } D3D11RenderState::D3D11RenderState(WrappedID3D11DeviceContext *context) { RDCEraseMem(this, sizeof(D3D11RenderState)); // IA context->IAGetInputLayout(&IA.Layout); context->IAGetPrimitiveTopology(&IA.Topo); context->IAGetVertexBuffers(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT, IA.VBs, (UINT *)IA.Strides, (UINT *)IA.Offsets); context->IAGetIndexBuffer(&IA.IndexBuffer, &IA.IndexFormat, &IA.IndexOffset); // VS context->VSGetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, VS.SRVs); context->VSGetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, VS.Samplers); context->VSGetShader((ID3D11VertexShader **)&VS.Object, VS.Instances, &VS.NumInstances); // DS context->DSGetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, DS.SRVs); context->DSGetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, DS.Samplers); context->DSGetShader((ID3D11DomainShader **)&DS.Object, DS.Instances, &DS.NumInstances); // HS context->HSGetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, HS.SRVs); context->HSGetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, HS.Samplers); context->HSGetShader((ID3D11HullShader **)&HS.Object, HS.Instances, &HS.NumInstances); // GS context->GSGetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, GS.SRVs); context->GSGetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, GS.Samplers); context->GSGetShader((ID3D11GeometryShader **)&GS.Object, GS.Instances, &GS.NumInstances); context->SOGetTargets(D3D11_SO_BUFFER_SLOT_COUNT, SO.Buffers); // RS context->RSGetState(&RS.State); RDCEraseEl(RS.Viewports); RS.NumViews = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; context->RSGetViewports(&RS.NumViews, RS.Viewports); RDCEraseEl(RS.Scissors); RS.NumScissors = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; context->RSGetScissorRects(&RS.NumScissors, RS.Scissors); // CS context->CSGetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, CS.SRVs); if(context->IsFL11_1()) context->CSGetUnorderedAccessViews(0, D3D11_1_UAV_SLOT_COUNT, CSUAVs); else context->CSGetUnorderedAccessViews(0, D3D11_PS_CS_UAV_REGISTER_COUNT, CSUAVs); context->CSGetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, CS.Samplers); context->CSGetShader((ID3D11ComputeShader **)&CS.Object, CS.Instances, &CS.NumInstances); // PS context->PSGetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, PS.SRVs); context->PSGetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, PS.Samplers); context->PSGetShader((ID3D11PixelShader **)&PS.Object, PS.Instances, &PS.NumInstances); context->VSGetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, VS.ConstantBuffers, VS.CBOffsets, VS.CBCounts); context->DSGetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, DS.ConstantBuffers, DS.CBOffsets, DS.CBCounts); context->HSGetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, HS.ConstantBuffers, HS.CBOffsets, HS.CBCounts); context->GSGetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, GS.ConstantBuffers, GS.CBOffsets, GS.CBCounts); context->CSGetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, CS.ConstantBuffers, CS.CBOffsets, CS.CBCounts); context->PSGetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, PS.ConstantBuffers, PS.CBOffsets, PS.CBCounts); // OM context->OMGetBlendState(&OM.BlendState, OM.BlendFactor, &OM.SampleMask); context->OMGetDepthStencilState(&OM.DepthStencilState, &OM.StencRef); ID3D11RenderTargetView *tmpViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT]; context->OMGetRenderTargets(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, tmpViews, NULL); OM.UAVStartSlot = 0; for(int i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) { if(tmpViews[i] != NULL) { OM.UAVStartSlot = i + 1; SAFE_RELEASE(tmpViews[i]); } } if(context->IsFL11_1()) context->OMGetRenderTargetsAndUnorderedAccessViews( OM.UAVStartSlot, OM.RenderTargets, &OM.DepthView, OM.UAVStartSlot, D3D11_1_UAV_SLOT_COUNT - OM.UAVStartSlot, OM.UAVs); else context->OMGetRenderTargetsAndUnorderedAccessViews( OM.UAVStartSlot, OM.RenderTargets, &OM.DepthView, OM.UAVStartSlot, D3D11_PS_CS_UAV_REGISTER_COUNT - OM.UAVStartSlot, OM.UAVs); context->GetPredication(&Predicate, &PredicateValue); } void D3D11RenderState::Clear() { ReleaseRefs(); OM.BlendFactor[0] = OM.BlendFactor[1] = OM.BlendFactor[2] = OM.BlendFactor[3] = 1.0f; OM.SampleMask = 0xffffffff; Predicate = NULL; PredicateValue = FALSE; for(size_t i = 0; i < ARRAY_COUNT(VS.CBCounts); i++) VS.CBCounts[i] = HS.CBCounts[i] = DS.CBCounts[i] = GS.CBCounts[i] = PS.CBCounts[i] = CS.CBCounts[i] = 4096; } bool D3D11RenderState::PredicationWouldPass() { if(Predicate == NULL) return true; BOOL data = TRUE; HRESULT hr = S_FALSE; do { hr = m_pDevice->GetImmediateContext()->GetData(Predicate, &data, sizeof(BOOL), 0); } while(hr == S_FALSE); RDCASSERTEQUAL(hr, S_OK); // From SetPredication for PredicateValue: // // "If TRUE, rendering will be affected by when the predicate's conditions are met. If FALSE, // rendering will be affected when the conditions are not met." // // Which is really confusingly worded. 'rendering will be affected' means 'no rendering will // happen', and 'conditions are met' for e.g. an occlusion query means that it passed. // Thus a passing occlusion query has value TRUE and is 'condition is met', so for a typical "skip // when occlusion query fails" the value will be FALSE. return PredicateValue != data; } void D3D11RenderState::ApplyState(WrappedID3D11DeviceContext *context) { context->ClearState(); // IA context->IASetInputLayout(IA.Layout); context->IASetPrimitiveTopology(IA.Topo); context->IASetIndexBuffer(IA.IndexBuffer, IA.IndexFormat, IA.IndexOffset); context->IASetVertexBuffers(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT, IA.VBs, IA.Strides, IA.Offsets); // VS context->VSSetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, VS.SRVs); context->VSSetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, VS.Samplers); context->VSSetShader((ID3D11VertexShader *)VS.Object, VS.Instances, VS.NumInstances); // DS context->DSSetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, DS.SRVs); context->DSSetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, DS.Samplers); context->DSSetShader((ID3D11DomainShader *)DS.Object, DS.Instances, DS.NumInstances); // HS context->HSSetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, HS.SRVs); context->HSSetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, HS.Samplers); context->HSSetShader((ID3D11HullShader *)HS.Object, HS.Instances, HS.NumInstances); // GS context->GSSetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, GS.SRVs); context->GSSetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, GS.Samplers); context->GSSetShader((ID3D11GeometryShader *)GS.Object, GS.Instances, GS.NumInstances); context->SOSetTargets(D3D11_SO_BUFFER_SLOT_COUNT, SO.Buffers, SO.Offsets); // RS context->RSSetState(RS.State); context->RSSetViewports(RS.NumViews, RS.Viewports); context->RSSetScissorRects(RS.NumScissors, RS.Scissors); UINT UAV_keepcounts[D3D11_1_UAV_SLOT_COUNT] = {(UINT)-1, (UINT)-1, (UINT)-1, (UINT)-1, (UINT)-1, (UINT)-1, (UINT)-1, (UINT)-1}; // CS context->CSSetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, CS.SRVs); context->CSSetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, CS.Samplers); if(context->IsFL11_1()) context->CSSetUnorderedAccessViews(0, D3D11_1_UAV_SLOT_COUNT, CSUAVs, UAV_keepcounts); else context->CSSetUnorderedAccessViews(0, D3D11_PS_CS_UAV_REGISTER_COUNT, CSUAVs, UAV_keepcounts); context->CSSetShader((ID3D11ComputeShader *)CS.Object, CS.Instances, CS.NumInstances); // PS context->PSSetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, PS.SRVs); context->PSSetSamplers(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, PS.Samplers); context->PSSetShader((ID3D11PixelShader *)PS.Object, PS.Instances, PS.NumInstances); context->VSSetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, VS.ConstantBuffers, VS.CBOffsets, VS.CBCounts); context->DSSetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, DS.ConstantBuffers, DS.CBOffsets, DS.CBCounts); context->HSSetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, HS.ConstantBuffers, HS.CBOffsets, HS.CBCounts); context->GSSetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, GS.ConstantBuffers, GS.CBOffsets, GS.CBCounts); context->CSSetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, CS.ConstantBuffers, CS.CBOffsets, CS.CBCounts); context->PSSetConstantBuffers1(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, PS.ConstantBuffers, PS.CBOffsets, PS.CBCounts); // OM context->OMSetBlendState(OM.BlendState, OM.BlendFactor, OM.SampleMask); context->OMSetDepthStencilState(OM.DepthStencilState, OM.StencRef); if(context->IsFL11_1()) context->OMSetRenderTargetsAndUnorderedAccessViews( OM.UAVStartSlot, OM.RenderTargets, OM.DepthView, OM.UAVStartSlot, D3D11_1_UAV_SLOT_COUNT - OM.UAVStartSlot, OM.UAVs, UAV_keepcounts); else context->OMSetRenderTargetsAndUnorderedAccessViews( OM.UAVStartSlot, OM.RenderTargets, OM.DepthView, OM.UAVStartSlot, D3D11_PS_CS_UAV_REGISTER_COUNT - OM.UAVStartSlot, OM.UAVs, UAV_keepcounts); context->SetPredication(Predicate, PredicateValue); } void D3D11RenderState::TakeRef(ID3D11DeviceChild *p) { if(p) { p->AddRef(); if(m_ImmediatePipeline) { if(WrappedID3D11RenderTargetView1::IsAlloc(p) || WrappedID3D11ShaderResourceView1::IsAlloc(p) || WrappedID3D11DepthStencilView::IsAlloc(p) || WrappedID3D11UnorderedAccessView1::IsAlloc(p)) m_pDevice->InternalRef(); m_pDevice->InternalRef(); // we can use any specialisation of device child here, as all that is templated // is the nested pointer type. Saves having another class in the inheritance // heirarchy :( ((WrappedDeviceChild11<ID3D11Buffer> *)p)->PipelineAddRef(); } } } void D3D11RenderState::ReleaseRef(ID3D11DeviceChild *p) { if(p) { p->Release(); if(m_ImmediatePipeline) { if(WrappedID3D11RenderTargetView1::IsAlloc(p) || WrappedID3D11ShaderResourceView1::IsAlloc(p) || WrappedID3D11DepthStencilView::IsAlloc(p) || WrappedID3D11UnorderedAccessView1::IsAlloc(p)) m_pDevice->InternalRelease(); m_pDevice->InternalRelease(); // see above ((WrappedDeviceChild11<ID3D11Buffer> *)p)->PipelineRelease(); } } } bool D3D11RenderState::IsRangeBoundForWrite(const ResourceRange &range) { for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) { if(CSUAVs[i] && range.Intersects(GetResourceRange(CSUAVs[i]))) { // RDCDEBUG("Resource was bound on CS UAV %u", i); return true; } } for(UINT i = 0; i < D3D11_SO_BUFFER_SLOT_COUNT; i++) { if(SO.Buffers[i] && range.Intersects(ResourceRange(SO.Buffers[i]))) { // RDCDEBUG("Resource was bound on SO buffer %u", i); return true; } } for(UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) { if(OM.RenderTargets[i] && range.Intersects(GetResourceRange(OM.RenderTargets[i]))) { // RDCDEBUG("Resource was bound on RTV %u", i); return true; } } for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) { if(OM.UAVs[i] && range.Intersects(GetResourceRange(OM.UAVs[i]))) { // RDCDEBUG("Resource was bound on OM UAV %d", i); return true; } } if(OM.DepthView) { const ResourceRange &depthRange = GetResourceRange(OM.DepthView); if(range.Intersects(depthRange)) { // RDCDEBUG("Resource was bound on OM DSV"); if(depthRange.IsDepthReadOnly() && depthRange.IsStencilReadOnly()) { // RDCDEBUG("but it's a readonly DSV, so that's fine"); } else if(depthRange.IsDepthReadOnly() && range.IsDepthReadOnly()) { // RDCDEBUG("but it's a depth readonly DSV and we're only reading depth, so that's fine"); } else if(depthRange.IsStencilReadOnly() && range.IsStencilReadOnly()) { // RDCDEBUG("but it's a stencil readonly DSV and we're only reading stencil, so that's OK"); } else { return true; } } } return false; } void D3D11RenderState::UnbindRangeForWrite(const ResourceRange &range) { for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) { if(CSUAVs[i] && range.Intersects(GetResourceRange(CSUAVs[i]))) { ReleaseRef(CSUAVs[i]); CSUAVs[i] = NULL; } } for(UINT i = 0; i < D3D11_SO_BUFFER_SLOT_COUNT; i++) { if(SO.Buffers[i] && range.Intersects(ResourceRange(SO.Buffers[i]))) { ReleaseRef(SO.Buffers[i]); SO.Buffers[i] = NULL; } } for(UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) { if(OM.RenderTargets[i] && range.Intersects(GetResourceRange(OM.RenderTargets[i]))) { ReleaseRef(OM.RenderTargets[i]); OM.RenderTargets[i] = NULL; } } for(UINT i = 0; i < D3D11_1_UAV_SLOT_COUNT; i++) { if(OM.UAVs[i] && range.Intersects(GetResourceRange(OM.UAVs[i]))) { ReleaseRef(OM.UAVs[i]); OM.UAVs[i] = NULL; } } if(OM.DepthView && range.Intersects(GetResourceRange(OM.DepthView))) { ReleaseRef(OM.DepthView); OM.DepthView = NULL; } } void D3D11RenderState::UnbindRangeForRead(const ResourceRange &range) { for(int i = 0; i < D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT; i++) { if(IA.VBs[i] && range.Intersects(ResourceRange(IA.VBs[i]))) { // RDCDEBUG("Resource was bound on IA VB %u", i); ReleaseRef(IA.VBs[i]); IA.VBs[i] = NULL; } } if(IA.IndexBuffer && range.Intersects(ResourceRange(IA.IndexBuffer))) { // RDCDEBUG("Resource was bound on IA IB"); ReleaseRef(IA.IndexBuffer); IA.IndexBuffer = NULL; } // const char *names[] = { "VS", "DS", "HS", "GS", "PS", "CS" }; Shader *stages[] = {&VS, &HS, &DS, &GS, &PS, &CS}; for(int s = 0; s < 6; s++) { Shader *sh = stages[s]; for(UINT i = 0; i < D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT; i++) { if(sh->ConstantBuffers[i] && range.Intersects(ResourceRange(sh->ConstantBuffers[i]))) { // RDCDEBUG("Resource was bound on %s CB %u", names[s], i); ReleaseRef(sh->ConstantBuffers[i]); sh->ConstantBuffers[i] = NULL; } } for(UINT i = 0; i < D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT; i++) { if(!sh->SRVs[i]) continue; const ResourceRange &srvRange = GetResourceRange(sh->SRVs[i]); if(range.Intersects(srvRange)) { // RDCDEBUG("Resource was bound on %s SRV %u", names[s], i); if(range.IsDepthReadOnly() && srvRange.IsDepthReadOnly()) { // RDCDEBUG("but it's a depth readonly DSV and we're only reading depth, so that's fine"); } else if(range.IsStencilReadOnly() && srvRange.IsStencilReadOnly()) { // RDCDEBUG("but it's a stencil readonly DSV and we're only reading stenc, so that's OK"); } else { // RDCDEBUG("Unbinding."); ReleaseRef(sh->SRVs[i]); sh->SRVs[i] = NULL; } } } sh++; } } bool D3D11RenderState::ValidOutputMerger(ID3D11RenderTargetView *const RTs[], UINT NumRTs, ID3D11DepthStencilView *depth, ID3D11UnorderedAccessView *const uavs[], UINT NumUAVs) { D3D11_RENDER_TARGET_VIEW_DESC RTDescs[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT]; D3D11_DEPTH_STENCIL_VIEW_DESC DepthDesc; RDCEraseEl(RTDescs); RDCEraseEl(DepthDesc); ID3D11Resource *Resources[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = {0}; ID3D11Resource *DepthResource = NULL; D3D11_RESOURCE_DIMENSION renderdim[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { D3D11_RESOURCE_DIMENSION_UNKNOWN}; D3D11_RESOURCE_DIMENSION depthdim = D3D11_RESOURCE_DIMENSION_UNKNOWN; for(UINT i = 0; RTs && i < NumRTs; i++) { if(RTs[i]) { RTs[i]->GetDesc(&RTDescs[i]); RTs[i]->GetResource(&Resources[i]); Resources[i]->GetType(&renderdim[i]); } } if(depth) { depth->GetDesc(&DepthDesc); depth->GetResource(&DepthResource); DepthResource->GetType(&depthdim); } bool valid = true; // check for duplicates and mark as invalid { ResourceRange rtvRanges[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, }; ResourceRange depthRange(depth); ResourceRange uavRanges[D3D11_1_UAV_SLOT_COUNT] = { ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, ResourceRange::Null, }; for(UINT i = 0; RTs && i < NumRTs; i++) { if(RTs[i]) rtvRanges[i] = GetResourceRange(RTs[i]); else break; } if(depth) depthRange = GetResourceRange(depth); int numUAVs = 0; for(UINT i = 0; uavs && i < NumUAVs; i++) { if(uavs[i]) { uavRanges[i] = GetResourceRange(uavs[i]); numUAVs = i + 1; } } // since constants are low, just do naive check for any intersecting ranges for(int i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) { if(rtvRanges[i].IsNull()) continue; // does it match any other RTV? for(int j = i + 1; j < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; j++) { if(rtvRanges[i].Intersects(rtvRanges[j])) { valid = false; m_pDevice->AddDebugMessage( MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, StringFormat::Fmt("Invalid output merger - Render targets %d and %d overlap", i, j)); break; } } // or depth? if(rtvRanges[i].Intersects(depthRange)) { valid = false; m_pDevice->AddDebugMessage( MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, StringFormat::Fmt("Invalid output merger - Render target %d and depth overlap", i)); break; } // or a UAV? for(int j = 0; j < numUAVs; j++) { if(rtvRanges[i].Intersects(uavRanges[j])) { valid = false; m_pDevice->AddDebugMessage( MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, StringFormat::Fmt("Invalid output merger - Render target %d and UAV %d overlap", i, j)); break; } } } for(int i = 0; valid && i < numUAVs; i++) { if(uavRanges[i].IsNull()) continue; // don't have to check RTVs, that's the reflection of the above check // does it match depth? if(uavRanges[i].Intersects(depthRange)) { valid = false; m_pDevice->AddDebugMessage( MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, StringFormat::Fmt("Invalid output merger - UAV %d and depth overlap", i)); break; } // or another UAV? for(int j = i + 1; j < numUAVs; j++) { if(uavRanges[i].Intersects(uavRanges[j])) { valid = false; m_pDevice->AddDebugMessage( MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, StringFormat::Fmt("Invalid output merger - UAVs %d and %d overlap", i, j)); break; } } } // don't have to check depth - it was checked against all RTs and UAVs above } ////////////////////////////////////////////////////////////////////////// // Resource dimensions of all views must be the same D3D11_RESOURCE_DIMENSION dim = D3D11_RESOURCE_DIMENSION_UNKNOWN; for(int i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) { if(renderdim[i] == D3D11_RESOURCE_DIMENSION_UNKNOWN) continue; if(dim == D3D11_RESOURCE_DIMENSION_UNKNOWN) dim = renderdim[i]; if(renderdim[i] != dim) { valid = false; m_pDevice->AddDebugMessage(MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, "Invalid output merger - Render targets of different type"); break; } } if(depthdim != D3D11_RESOURCE_DIMENSION_UNKNOWN && dim != D3D11_RESOURCE_DIMENSION_UNKNOWN && depthdim != dim) { m_pDevice->AddDebugMessage( MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, "Invalid output merger - Render target(s) and depth target of different type"); valid = false; } if(!valid) { // RDCDEBUG("Resource dimensions don't match between render targets and/or depth stencil"); } else { // pretend all resources are 3D descs just to make the code simpler // * put arraysize for 1D/2D into the depth for 3D // * use sampledesc from 2d as it will be identical for 1D/3D D3D11_TEXTURE3D_DESC desc = {0}; D3D11_TEXTURE2D_DESC desc2 = {0}; for(int i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) { if(Resources[i] == NULL) continue; D3D11_TEXTURE1D_DESC d1 = {0}; D3D11_TEXTURE2D_DESC d2 = {0}; D3D11_TEXTURE3D_DESC d3 = {0}; if(dim == D3D11_RESOURCE_DIMENSION_BUFFER) { } if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE1D) { ((ID3D11Texture1D *)Resources[i])->GetDesc(&d1); d3.Width = RDCMAX(1U, d1.Width >> RTDescs[i].Texture1D.MipSlice); if(RTDescs[i].ViewDimension == D3D11_RTV_DIMENSION_TEXTURE1D) d3.Depth = 1; else if(RTDescs[i].ViewDimension == D3D11_RTV_DIMENSION_TEXTURE1DARRAY) d3.Depth = RDCMIN(d1.ArraySize, RTDescs[i].Texture1DArray.ArraySize); } else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE2D) { ((ID3D11Texture2D *)Resources[i])->GetDesc(&d2); if(RTDescs[i].ViewDimension == D3D11_RTV_DIMENSION_TEXTURE2D) { d3.Width = RDCMAX(1U, d2.Width >> RTDescs[i].Texture2D.MipSlice); d3.Height = RDCMAX(1U, d2.Height >> RTDescs[i].Texture2D.MipSlice); d3.Depth = 1; } else if(RTDescs[i].ViewDimension == D3D11_RTV_DIMENSION_TEXTURE2DMS) { d3.Width = d2.Width; d3.Height = d2.Height; d3.Depth = 1; } else if(RTDescs[i].ViewDimension == D3D11_RTV_DIMENSION_TEXTURE2DARRAY) { d3.Width = RDCMAX(1U, d2.Width >> RTDescs[i].Texture2DArray.MipSlice); d3.Height = RDCMAX(1U, d2.Height >> RTDescs[i].Texture2DArray.MipSlice); d3.Depth = RDCMIN(d2.ArraySize, RTDescs[i].Texture2DArray.ArraySize); } else if(RTDescs[i].ViewDimension == D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY) { d3.Width = d2.Width; d3.Height = d2.Height; d3.Depth = RDCMIN(d2.ArraySize, RTDescs[i].Texture2DMSArray.ArraySize); } } else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) { ((ID3D11Texture3D *)Resources[i])->GetDesc(&d3); d3.Width = RDCMAX(1U, d3.Width >> RTDescs[i].Texture3D.MipSlice); d3.Height = RDCMAX(1U, d3.Height >> RTDescs[i].Texture3D.MipSlice); d3.Depth = RDCMAX(1U, d3.Depth >> RTDescs[i].Texture3D.MipSlice); d3.Depth = RDCMIN(d3.Depth, RTDescs[i].Texture3D.WSize); } if(desc.Width == 0) { desc = d3; desc2 = d2; continue; } if(desc.Width != d3.Width || desc.Height != d3.Height || desc.Depth != d3.Depth || desc2.SampleDesc.Count != d2.SampleDesc.Count || desc2.SampleDesc.Quality != d2.SampleDesc.Quality) { m_pDevice->AddDebugMessage( MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, "Invalid output merger - Render targets are different dimensions"); valid = false; break; } } if(DepthResource && valid) { D3D11_TEXTURE1D_DESC d1 = {0}; D3D11_TEXTURE2D_DESC d2 = {0}; D3D11_TEXTURE3D_DESC d3 = {0}; if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE1D) { ((ID3D11Texture1D *)DepthResource)->GetDesc(&d1); d3.Width = RDCMAX(1U, d1.Width >> DepthDesc.Texture1D.MipSlice); if(DepthDesc.ViewDimension == D3D11_DSV_DIMENSION_TEXTURE1D) d3.Depth = 1; else if(DepthDesc.ViewDimension == D3D11_DSV_DIMENSION_TEXTURE1DARRAY) d3.Depth = RDCMIN(d1.ArraySize, DepthDesc.Texture1DArray.ArraySize); } else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE2D) { ((ID3D11Texture2D *)DepthResource)->GetDesc(&d2); if(DepthDesc.ViewDimension == D3D11_DSV_DIMENSION_TEXTURE2D) { d3.Width = RDCMAX(1U, d2.Width >> DepthDesc.Texture2D.MipSlice); d3.Height = RDCMAX(1U, d2.Height >> DepthDesc.Texture2D.MipSlice); d3.Depth = 1; } else if(DepthDesc.ViewDimension == D3D11_DSV_DIMENSION_TEXTURE2DARRAY) { d3.Width = RDCMAX(1U, d2.Width >> DepthDesc.Texture2DArray.MipSlice); d3.Height = RDCMAX(1U, d2.Height >> DepthDesc.Texture2DArray.MipSlice); d3.Depth = RDCMIN(d2.ArraySize, DepthDesc.Texture2DArray.ArraySize); } else if(DepthDesc.ViewDimension == D3D11_DSV_DIMENSION_TEXTURE2DMS) { d3.Width = d2.Width; d3.Height = d2.Height; d3.Depth = 1; } else if(DepthDesc.ViewDimension == D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY) { d3.Width = d2.Width; d3.Height = d2.Height; d3.Depth = RDCMIN(d2.ArraySize, DepthDesc.Texture2DMSArray.ArraySize); } } else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE3D || dim == D3D11_RESOURCE_DIMENSION_BUFFER) { m_pDevice->AddDebugMessage(MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, "Invalid output merger - Depth target is Texture3D or Buffer " "(shouldn't be possible! How did you create this view?!)"); valid = false; } if(desc.Width != 0 && valid) { if(desc.Width != d3.Width || desc.Height != d3.Height || desc.Depth != d3.Depth || desc2.SampleDesc.Count != d2.SampleDesc.Count || desc2.SampleDesc.Quality != d2.SampleDesc.Quality) { valid = false; // explicitly allow over-sized depth targets if(desc.Width <= d3.Width && desc.Height <= d3.Height && desc.Depth <= d3.Depth && desc2.SampleDesc.Count == d2.SampleDesc.Count && desc2.SampleDesc.Quality == d2.SampleDesc.Quality) { valid = true; m_pDevice->AddDebugMessage( MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, "Valid but unusual output merger - Depth target is larger than render target(s)"); } else { m_pDevice->AddDebugMessage(MessageCategory::State_Setting, MessageSeverity::High, MessageSource::IncorrectAPIUse, "Invalid output merger - Depth target is different size or " "MS count to render target(s)"); } } } } } for(int i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++) SAFE_RELEASE(Resources[i]); SAFE_RELEASE(DepthResource); return valid; } bool D3D11RenderState::InputAssembler::Used_VB(WrappedID3D11Device *device, uint32_t slot) const { if(Layout == NULL) return false; const vector<D3D11_INPUT_ELEMENT_DESC> &vec = device->GetLayoutDesc(Layout); for(size_t i = 0; i < vec.size(); i++) if(vec[i].InputSlot == slot) return true; return false; } bool D3D11RenderState::Shader::Used_CB(uint32_t slot) const { if(ConstantBuffers[slot] == NULL) return false; WrappedShader *shad = (WrappedShader *)(WrappedID3D11Shader<ID3D11VertexShader> *)Object; if(shad == NULL) return false; DXBC::DXBCFile *dxbc = shad->GetDXBC(); // have to assume it's used if there's no DXBC if(dxbc == NULL) return true; for(size_t i = 0; i < dxbc->m_CBuffers.size(); i++) if(dxbc->m_CBuffers[i].reg == slot) return true; return false; } bool D3D11RenderState::Shader::Used_SRV(uint32_t slot) const { if(SRVs[slot] == NULL) return false; WrappedShader *shad = (WrappedShader *)(WrappedID3D11Shader<ID3D11VertexShader> *)Object; if(shad == NULL) return false; DXBC::DXBCFile *dxbc = shad->GetDXBC(); // have to assume it's used if there's no DXBC if(dxbc == NULL) return true; for(const DXBC::ShaderInputBind &bind : dxbc->m_SRVs) if(bind.reg == slot) return true; return false; } bool D3D11RenderState::Shader::Used_UAV(uint32_t slot) const { WrappedShader *shad = (WrappedShader *)(WrappedID3D11Shader<ID3D11VertexShader> *)Object; if(shad == NULL) return false; DXBC::DXBCFile *dxbc = shad->GetDXBC(); // have to assume it's used if there's no DXBC if(dxbc == NULL) return true; for(const DXBC::ShaderInputBind &bind : dxbc->m_UAVs) if(bind.reg == slot) return true; return false; } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11InputLayout *resource) { return false; } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11Predicate *resource) { return false; } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11ClassInstance *resource) { return false; } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11DeviceChild *shader) { return false; } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11SamplerState *resource) { return false; } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11BlendState *state) { return false; } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11RasterizerState *state) { return false; } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11DepthStencilState *state) { return false; } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11Buffer *buffer) { if(buffer == NULL) return false; return IsRangeBoundForWrite(ResourceRange(buffer)); } template <> bool D3D11RenderState::IsBoundForWrite(ID3D11ShaderResourceView *srv) { if(srv == NULL) return false; return IsRangeBoundForWrite(GetResourceRange(srv)); } template <> void D3D11RenderState::UnbindForRead(ID3D11Buffer *buffer) { if(buffer == NULL) return; UnbindRangeForRead(ResourceRange(buffer)); } template <> void D3D11RenderState::UnbindForRead(ID3D11RenderTargetView *rtv) { if(rtv == NULL) return; UnbindRangeForRead(GetResourceRange(rtv)); } template <> void D3D11RenderState::UnbindForRead(ID3D11DepthStencilView *dsv) { if(dsv == NULL) return; const ResourceRange &dsvRange = GetResourceRange(dsv); if(dsvRange.IsDepthReadOnly() && dsvRange.IsStencilReadOnly()) { // don't need to. } else { UnbindRangeForRead(dsvRange); } } template <> void D3D11RenderState::UnbindForRead(ID3D11UnorderedAccessView *uav) { if(uav == NULL) return; UnbindRangeForRead(GetResourceRange(uav)); } template <> void D3D11RenderState::UnbindForWrite(ID3D11Buffer *buffer) { if(buffer == NULL) return; UnbindRangeForWrite(ResourceRange(buffer)); } template <> void D3D11RenderState::UnbindForWrite(ID3D11RenderTargetView *rtv) { if(rtv == NULL) return; UnbindRangeForWrite(GetResourceRange(rtv)); } template <> void D3D11RenderState::UnbindForWrite(ID3D11DepthStencilView *dsv) { if(dsv == NULL) return; UnbindRangeForWrite(GetResourceRange(dsv)); } template <> void D3D11RenderState::UnbindForWrite(ID3D11UnorderedAccessView *uav) { if(uav == NULL) return; UnbindRangeForWrite(GetResourceRange(uav)); } template <class SerialiserType> void DoSerialise(SerialiserType &ser, D3D11RenderState::InputAssembler &el) { SERIALISE_MEMBER(Layout); SERIALISE_MEMBER(Topo); SERIALISE_MEMBER(VBs); SERIALISE_MEMBER(Strides); SERIALISE_MEMBER(Offsets); SERIALISE_MEMBER(IndexBuffer); SERIALISE_MEMBER(IndexFormat); SERIALISE_MEMBER(IndexOffset); } template <class SerialiserType> void DoSerialise(SerialiserType &ser, D3D11RenderState::Shader &el) { SERIALISE_MEMBER(Object); SERIALISE_MEMBER(ConstantBuffers); SERIALISE_MEMBER(CBOffsets); SERIALISE_MEMBER(CBCounts); SERIALISE_MEMBER(SRVs); SERIALISE_MEMBER(Samplers); SERIALISE_MEMBER(Instances); SERIALISE_MEMBER(NumInstances); } template <class SerialiserType> void DoSerialise(SerialiserType &ser, D3D11RenderState::StreamOut &el) { SERIALISE_MEMBER(Buffers); SERIALISE_MEMBER(Offsets); } template <class SerialiserType> void DoSerialise(SerialiserType &ser, D3D11RenderState::Rasterizer &el) { SERIALISE_MEMBER(NumViews); SERIALISE_MEMBER(NumScissors); SERIALISE_MEMBER(Viewports); SERIALISE_MEMBER(Scissors); SERIALISE_MEMBER(State); } template <class SerialiserType> void DoSerialise(SerialiserType &ser, D3D11RenderState::OutputMerger &el) { SERIALISE_MEMBER(DepthStencilState); SERIALISE_MEMBER(StencRef); SERIALISE_MEMBER(BlendState); SERIALISE_MEMBER(BlendFactor); SERIALISE_MEMBER(SampleMask); SERIALISE_MEMBER(DepthView); SERIALISE_MEMBER(RenderTargets); SERIALISE_MEMBER(UAVStartSlot); SERIALISE_MEMBER(UAVs); } template <class SerialiserType> void DoSerialise(SerialiserType &ser, D3D11RenderState &el) { SERIALISE_MEMBER(IA); SERIALISE_MEMBER(VS); SERIALISE_MEMBER(HS); SERIALISE_MEMBER(DS); SERIALISE_MEMBER(GS); SERIALISE_MEMBER(PS); SERIALISE_MEMBER(CS); SERIALISE_MEMBER(CSUAVs); SERIALISE_MEMBER(SO); SERIALISE_MEMBER(RS); SERIALISE_MEMBER(OM); SERIALISE_MEMBER(Predicate); SERIALISE_MEMBER(PredicateValue); if(ser.IsReading()) el.AddRefs(); } INSTANTIATE_SERIALISE_TYPE(D3D11RenderState); D3D11RenderStateTracker::D3D11RenderStateTracker(WrappedID3D11DeviceContext *ctx) : m_RS(*ctx->GetCurrentPipelineState()) { m_pContext = ctx; } D3D11RenderStateTracker::~D3D11RenderStateTracker() { m_RS.ApplyState(m_pContext); }
cgmb/renderdoc
renderdoc/driver/d3d11/d3d11_renderstate.cpp
C++
mit
50,139
# -*- coding:utf-8 -*- """ # Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today) # Created Time : Fri Feb 20 21:38:57 2015 # File Name: wechatService.py # Description: # :copyright: (c) 2015 by Pegasus Wang. # :license: MIT, see LICENSE for more details. """ import json import time import urllib import urllib2 from wechatUtil import MessageUtil from wechatReply import TextReply class RobotService(object): """Auto reply robot service""" KEY = 'd92d20bc1d8bb3cff585bf746603b2a9' url = 'http://www.tuling123.com/openapi/api' @staticmethod def auto_reply(req_info): query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')} headers = {'Content-type': 'text/html', 'charset': 'utf-8'} data = urllib.urlencode(query) req = urllib2.Request(RobotService.url, data) f = urllib2.urlopen(req).read() return json.loads(f).get('text').replace('<br>', '\n') #return json.loads(f).get('text') class WechatService(object): """process request""" @staticmethod def processRequest(request): """process different message types. :param request: post request message :return: None """ requestMap = MessageUtil.parseXml(request) fromUserName = requestMap.get(u'FromUserName') toUserName = requestMap.get(u'ToUserName') createTime = requestMap.get(u'CreateTime') msgType = requestMap.get(u'MsgType') msgId = requestMap.get(u'MsgId') textReply = TextReply() textReply.setToUserName(fromUserName) textReply.setFromUserName(toUserName) textReply.setCreateTime(time.time()) textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT) if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT: content = requestMap.get('Content').decode('utf-8') # note: decode first #respContent = u'您发送的是文本消息:' + content respContent = RobotService.auto_reply(content) elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE: respContent = u'您发送的是图片消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE: respContent = u'您发送的是语音消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO: respContent = u'您发送的是视频消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION: respContent = u'您发送的是地理位置消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK: respContent = u'您发送的是链接消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT: eventType = requestMap.get(u'Event') if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE: respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \ u'可以联系我,就当打发时间了.' elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE: pass elif eventType == MessageUtil.EVENT_TYPE_SCAN: # TODO pass elif eventType == MessageUtil.EVENT_TYPE_LOCATION: # TODO pass elif eventType == MessageUtil.EVENT_TYPE_CLICK: # TODO pass textReply.setContent(respContent) respXml = MessageUtil.class2xml(textReply) return respXml """ if msgType == 'text': content = requestMap.get('Content') # TODO elif msgType == 'image': picUrl = requestMap.get('PicUrl') # TODO elif msgType == 'voice': mediaId = requestMap.get('MediaId') format = requestMap.get('Format') # TODO elif msgType == 'video': mediaId = requestMap.get('MediaId') thumbMediaId = requestMap.get('ThumbMediaId') # TODO elif msgType == 'location': lat = requestMap.get('Location_X') lng = requestMap.get('Location_Y') label = requestMap.get('Label') scale = requestMap.get('Scale') # TODO elif msgType == 'link': title = requestMap.get('Title') description = requestMap.get('Description') url = requestMap.get('Url') """
PegasusWang/WeiPython
wechat/wechatService.py
Python
mit
4,478
<?php /** * @author @jenschude <jens.schulze@commercetools.de> */ namespace Commercetools\Core\Model\CartDiscount; use Commercetools\Core\Model\Common\MoneyCollection; /** * @package Commercetools\Core\Model\CartDiscount * @ramlTestIgnoreFields('money') * @method string getType() * @method RelativeCartDiscountValue setType(string $type = null) * @method int getPermyriad() * @method RelativeCartDiscountValue setPermyriad(int $permyriad = null) */ class RelativeCartDiscountValue extends CartDiscountValue { /** * @inheritDoc */ public function __construct(array $data = [], $context = null) { $data['type'] = static::TYPE_RELATIVE; parent::__construct($data, $context); } public function fieldDefinitions() { return [ 'type' => [static::TYPE => 'string'], 'permyriad' => [static::TYPE => 'int'], 'money' => [static::TYPE => MoneyCollection::class] ]; } /** * @deprecated getMoney will be removed for relative cart discounts with v3.0 * @return MoneyCollection */ public function getMoney() { return parent::getMoney(); } /** * @deprecated setMoney will be removed for relative cart discounts with v3.0 * @param MoneyCollection|null $money * @return CartDiscountValue */ public function setMoney(MoneyCollection $money = null) { return parent::setMoney($money); } }
sphereio/sphere-php-sdk
src/Core/Model/CartDiscount/RelativeCartDiscountValue.php
PHP
mit
1,473
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Sharing.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
XDSETeamA/XD_SE_TeamA
team9/1/Sharing/manage.py
Python
mit
250
module MembersHelper # Returns a `<action>_<source>_member` association, e.g.: # - admin_project_member, update_project_member, destroy_project_member # - admin_group_member, update_group_member, destroy_group_member def action_member_permission(action, member) "#{action}_#{member.type.underscore}".to_sym end def default_show_roles(member) can?(current_user, action_member_permission(:update, member), member) || can?(current_user, action_member_permission(:destroy, member), member) || can?(current_user, action_member_permission(:admin, member), member.source) end def remove_member_message(member, user: nil) user = current_user if defined?(current_user) text = 'Are you sure you want to ' action = if member.request? if member.user == user 'withdraw your access request for' else "deny #{member.user.name}'s request to join" end elsif member.invite? "revoke the invitation for #{member.invite_email} to join" else "remove #{member.user.name} from" end text << action << " the #{member.source.human_name} #{member.real_source_type.humanize(capitalize: false)}?" end def remove_member_title(member) text = " from #{member.real_source_type.humanize(capitalize: false)}" text.prepend(member.request? ? 'Deny access request' : 'Remove user') end def leave_confirmation_message(member_source) "Are you sure you want to leave the " \ "\"#{member_source.human_name}\" #{member_source.class.to_s.humanize(capitalize: false)}?" end end
Soullivaneuh/gitlabhq
app/helpers/members_helper.rb
Ruby
mit
1,601
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.containerregistry.implementation; import com.microsoft.azure.management.apigeneration.LangDefinition; import com.microsoft.azure.management.containerregistry.EventRequestMessage; import com.microsoft.azure.management.containerregistry.EventResponseMessage; import com.microsoft.azure.management.containerregistry.WebhookEventInfo; import com.microsoft.azure.management.resources.fluentcore.model.implementation.WrapperImpl; /** * Response containing the webhook event info. */ @LangDefinition public class WebhookEventInfoImpl extends WrapperImpl<EventInner> implements WebhookEventInfo { protected WebhookEventInfoImpl(EventInner innerObject) { super(innerObject); } @Override public EventRequestMessage eventRequestMessage() { return this.inner().eventRequestMessage(); } @Override public EventResponseMessage eventResponseMessage() { return this.inner().eventResponseMessage(); } }
martinsawicki/azure-sdk-for-java
azure-mgmt-containerregistry/src/main/java/com/microsoft/azure/management/containerregistry/implementation/WebhookEventInfoImpl.java
Java
mit
1,154
/*global console: false, creatis_carpenterStorage_replaceContentFromStorage: false */ $(function () { function initDesktop() { $("#accordion").accordion({ collapsible: true, active: localStorage.selectedCarpenter ? false : true, }); // Kontaktseite Suche $("#search-site-submit").click(function () { var searchQuery = $("#search-query-site").val(); if (isValidPostal(searchQuery)) { document.location = "/tischler?query=" + searchQuery; } return false; }); $("#search-query-site").on('input', function () { var isValid = isValidPostal($("#search-query-site").val()); $("#search-query-site").css('border-color', !isValid ? 'red' : '#d5d5d5'); }); $("#search-query").on('input', function () { var isValid = isValidPostal($("#search-query").val()); $("#search-query").css('border-color', !isValid ? 'red' : '#d5d5d5'); }); //Prevent default on enter $('#search-query').keypress(function (event) { if (event.keyCode == 10 || event.keyCode == 13) event.preventDefault(); }); $("#accordion").removeClass('c-hidden'); $("#search-flyout-submit").click(function () { var searchQuery = $("#search-query").val(); if (searchQuery !== null && searchQuery !== "" && isValidPostal(searchQuery)) { document.location = "/tischler?query=" + searchQuery; } return false; }); if (typeof (creatis_carpenterStorage_replaceContentFromStorage) !== "undefined") { creatis_carpenterStorage_replaceContentFromStorage(); } } function initMobile() { //code taken from https://github.com/codrops/ButtonComponentMorph/blob/master/index.html var docElem = window.document.documentElement, didScroll, scrollPosition; // trick to prevent scrolling when opening/closing button function noScrollFn() { window.scrollTo(scrollPosition ? scrollPosition.x : 0, scrollPosition ? scrollPosition.y : 0); } function noScroll() { window.removeEventListener('scroll', scrollHandler); window.addEventListener('scroll', noScrollFn); } function scrollFn() { window.addEventListener('scroll', scrollHandler); } function canScroll() { window.removeEventListener('scroll', noScrollFn); scrollFn(); } function scrollHandler() { if (!didScroll) { didScroll = true; setTimeout(function () { scrollPage(); }, 60); } }; function scrollPage() { scrollPosition = { x: window.pageXOffset || docElem.scrollLeft, y: window.pageYOffset || docElem.scrollTop }; didScroll = false; }; scrollFn(); // Mobile carpenter search button var mobileSearchButton = document.querySelector('#search-mobile .morph-button'); $('#search-mobile .morph-button').click(function (ev) { if (ev.originalEvent) { ev.originalEvent.preventDefault(); } }); var mobileSearchMorphingButton = new UIMorphingButton(mobileSearchButton, { closeEl: '.icon-close', onBeforeOpen: function () { // don't allow to scroll noScroll(); }, onAfterOpen: function () { // can scroll again canScroll(); $('.dialog-page').hide(); $('.mobile-search-page-overview').show(); }, onBeforeClose: function () { // don't allow to scroll noScroll(); }, onAfterClose: function () { // can scroll again if (window.buyWithoutCarpenter && localStorage.selectedCarpenter !== null) { $('#purchase-request-starter')[0].click(); } else { window.buyWithoutCarpenter = false; } canScroll(); } }); } (function startup() { if (isMobile()) { initMobile(); } else { if ($("#accordion").length > 0) { initDesktop(); } } //initDesktop(); //initMobile(); displaySelectedCarpenter(); })(); }); function isMobile() { return $("#search-mobile").css("visibility") === "visible"; } function displaySelectedCarpenter() { if (localStorage.selectedCarpenter) { $('#div_text').css('display', 'none'); var data = JSON.parse(localStorage.getItem('selectedCarpenter')); var cId = data.id; setTimeout(function () { $('#' + cId + ' .btn-select').first().trigger('click'); }, 50); } }
BROCKHAUS-AG/contentmonkee
MAIN/Default.WebUI/App_Themes/default/js/jquery-ui.searchflyout.js
JavaScript
mit
5,088
package com.blebail.components.core.security.cryptography; import org.apache.commons.codec.digest.DigestUtils; public class Md5 implements DigestAlgorithm { @Override public String digest(final String data) { return DigestUtils.md5Hex(data); } @Override public String toString() { return "Digest Algorithm (Md5)"; } }
Daeliin/rest-framework
components-core/src/main/java/com/blebail/components/core/security/cryptography/Md5.java
Java
mit
366
'use strict'; /* main App */ var app = angular.module('submitConformationcontroller', []); app.controller('confirmationCtrl', ['$scope', function($scope){ $scope.volunteerList = ["Joop Bakker", "Dirk Dijkstra", "Sterre Hendriks", "Hendrik Jacobs", "Hans Heuvel", "Jaap Beek", "Jan-Jaap Dijk", "Marleen Jansen", "Geert Hoek", "Beer Heuvel"]; $scope.jobTitle = ''; $scope.jobType = ''; $scope.describeWork = ''; function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } $scope.jobTitle = getParameterByName('jobTitle'); $scope.jobType = getParameterByName('jobType'); $scope.describeWork = getParameterByName('describeWork'); }]);
iamlalit/olympia-volunteer
app/organization/confirmation/confirmationController.js
JavaScript
mit
886
/* * This file is part of Prism, licensed under the MIT License (MIT). * * Copyright (c) 2015 Helion3 http://helion3.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.helion3.prism.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.data.property.block.MatterProperty; import org.spongepowered.api.data.property.block.MatterProperty.Matter; public class BlockUtil { private BlockUtil() {} /** * Get a list of all LIQUID block types. * * @return List<BlockType> */ public static List<BlockType> getLiquidBlockTypes() { List<BlockType> liquids = new ArrayList<>(); Collection<BlockType> types = Sponge.getRegistry().getAllOf(BlockType.class); for (BlockType type : types) { Optional<MatterProperty> property = type.getProperty(MatterProperty.class); if (property.isPresent() && Objects.equals(property.get().getValue(), Matter.LIQUID)) { liquids.add(type); } } // @todo Sponge has not yet implemented the MatterProperties... liquids.add(BlockTypes.LAVA); liquids.add(BlockTypes.FLOWING_LAVA); liquids.add(BlockTypes.WATER); liquids.add(BlockTypes.FLOWING_WATER); return liquids; } /** * Reject specific blocks from an applier because they're 99% going to do more harm. * * @param type BlockType * @return */ public static boolean rejectIllegalApplierBlock(BlockType type) { return (type.equals(BlockTypes.FIRE) || type.equals(BlockTypes.TNT) || type.equals(BlockTypes.LAVA) || type.equals(BlockTypes.FLOWING_LAVA)); } /** * Sponge's ChangeBlockEvent.Place covers a lot, but it also includes a lot * we don't want. So here we can setup checks to filter out block combinations. * * @param a BlockType original * @param b BlockType final * @return boolean True if combo should be rejected */ public static boolean rejectPlaceCombination(BlockType a, BlockType b) { return ( // Just basic state changes a.equals(BlockTypes.LIT_FURNACE) || b.equals(BlockTypes.LIT_FURNACE) || a.equals(BlockTypes.LIT_REDSTONE_LAMP) || b.equals(BlockTypes.LIT_REDSTONE_LAMP) || a.equals(BlockTypes.LIT_REDSTONE_ORE) || b.equals(BlockTypes.LIT_REDSTONE_ORE) || a.equals(BlockTypes.UNLIT_REDSTONE_TORCH) || b.equals(BlockTypes.UNLIT_REDSTONE_TORCH) || (a.equals(BlockTypes.POWERED_REPEATER) && b.equals(BlockTypes.UNPOWERED_REPEATER)) || (a.equals(BlockTypes.UNPOWERED_REPEATER) && b.equals(BlockTypes.POWERED_REPEATER)) || (a.equals(BlockTypes.POWERED_COMPARATOR) && b.equals(BlockTypes.UNPOWERED_COMPARATOR)) || (a.equals(BlockTypes.UNPOWERED_COMPARATOR) && b.equals(BlockTypes.POWERED_COMPARATOR)) || // It's all water... (a.equals(BlockTypes.WATER) && b.equals(BlockTypes.FLOWING_WATER)) || (a.equals(BlockTypes.FLOWING_WATER) && b.equals(BlockTypes.WATER)) || // It's all lava.... (a.equals(BlockTypes.LAVA) && b.equals(BlockTypes.FLOWING_LAVA)) || (a.equals(BlockTypes.FLOWING_LAVA) && b.equals(BlockTypes.LAVA)) || // Crap that fell into lava (a.equals(BlockTypes.LAVA) && b.equals(BlockTypes.GRAVEL)) || (a.equals(BlockTypes.FLOWING_LAVA) && b.equals(BlockTypes.GRAVEL)) || (a.equals(BlockTypes.LAVA) && b.equals(BlockTypes.SAND)) || (a.equals(BlockTypes.FLOWING_LAVA) && b.equals(BlockTypes.SAND)) || // It's fire (which didn't burn anything) (a.equals(BlockTypes.FIRE) && b.equals(BlockTypes.AIR)) || // Piston a.equals(BlockTypes.PISTON_EXTENSION) || b.equals(BlockTypes.PISTON_EXTENSION) || a.equals(BlockTypes.PISTON_HEAD) || b.equals(BlockTypes.PISTON_HEAD) || // You can't place air b.equals(BlockTypes.AIR) ); } /** * Sponge's ChangeBlockEvent.Break covers a lot, but it also includes a lot * we don't want. So here we can setup checks to filter out block combinations. * * @param a BlockType original * @param b BlockType final * @return boolean True if combo should be rejected */ public static boolean rejectBreakCombination(BlockType a, BlockType b) { return ( // You can't break these... a.equals(BlockTypes.FIRE) || a.equals(BlockTypes.AIR) || // Note, see "natural flow" comment above. ((a.equals(BlockTypes.FLOWING_WATER) || a.equals(BlockTypes.FLOWING_LAVA)) && b.equals(BlockTypes.AIR)) || // Piston a.equals(BlockTypes.PISTON_EXTENSION) || b.equals(BlockTypes.PISTON_EXTENSION) || a.equals(BlockTypes.PISTON_HEAD) || b.equals(BlockTypes.PISTON_HEAD) ); } }
Stonebound/Prism
src/main/java/com/helion3/prism/util/BlockUtil.java
Java
mit
6,277
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP 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 // HOLDER 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. // "use strict"; // these $ globals are defined by external environment // they are redefined here to make R# like tools understand them var _log = $log; var _load_module = $load_module; function log(message) { _log("PROJECTIONS (JS): " + message); } function initializeModules() { // load module load new instance of the given module every time // this is a responsibility of prelude to manage instances of modules var modules = _load_module('Modules'); // TODO: replace with createRequire($load_module) modules.$load_module = _load_module; return modules; } function initializeProjections() { var projections = _load_module('Projections'); return projections; } var modules = initializeModules(); var projections = initializeProjections(); var eventProcessor; function scope($on, $notify) { eventProcessor = projections.createEventProcessor(log, $notify); eventProcessor.register_command_handlers($on); function queryLog(message) { if (typeof message === "string") _log(message); else _log(JSON.stringify(message)); } function translateOn(handlers) { for (var name in handlers) { if (name == 0 || name === "$init") { eventProcessor.on_init_state(handlers[name]); } else if (name === "$initShared") { eventProcessor.on_init_shared_state(handlers[name]); } else if (name === "$any") { eventProcessor.on_any(handlers[name]); } else if (name === "$deleted") { eventProcessor.on_deleted_notification(handlers[name]); } else if (name === "$created") { eventProcessor.on_created_notification(handlers[name]); } else { eventProcessor.on_event(name, handlers[name]); } } } function $defines_state_transform() { eventProcessor.$defines_state_transform(); } function transformBy(by) { eventProcessor.chainTransformBy(by); return { transformBy: transformBy, filterBy: filterBy, outputState: outputState, outputTo: outputTo, }; } function filterBy(by) { eventProcessor.chainTransformBy(function (s) { var result = by(s); return result ? s : null; }); return { transformBy: transformBy, filterBy: filterBy, outputState: outputState, outputTo: outputTo, }; } function outputTo(resultStream, partitionResultStreamPattern) { eventProcessor.$defines_state_transform(); eventProcessor.options({ resultStreamName: resultStream, partitionResultStreamNamePattern: partitionResultStreamPattern, }); } function outputState() { eventProcessor.$outputState(); return { transformBy: transformBy, filterBy: filterBy, outputTo: outputTo, }; } function when(handlers) { translateOn(handlers); return { $defines_state_transform: $defines_state_transform, transformBy: transformBy, filterBy: filterBy, outputTo: outputTo, outputState: outputState, }; } function foreachStream() { eventProcessor.byStream(); return { when: when, }; } function partitionBy(byHandler) { eventProcessor.partitionBy(byHandler); return { when: when, }; } function fromCategory(category) { eventProcessor.fromCategory(category); return { partitionBy: partitionBy, foreachStream: foreachStream, when: when, outputState: outputState, }; } function fromAll() { eventProcessor.fromAll(); return { partitionBy: partitionBy, when: when, foreachStream: foreachStream, outputState: outputState, }; } function fromStream(stream) { eventProcessor.fromStream(stream); return { partitionBy: partitionBy, when: when, outputState: outputState, }; } function fromStreamCatalog(streamCatalog, transformer) { eventProcessor.fromStreamCatalog(streamCatalog, transformer ? transformer : null); return { foreachStream: foreachStream, }; } function fromStreamsMatching(filter) { eventProcessor.fromStreamsMatching(filter); return { when: when, }; } function fromStreams(streams) { var arr = Array.isArray(streams) ? streams : arguments; for (var i = 0; i < arr.length; i++) eventProcessor.fromStream(arr[i]); return { partitionBy: partitionBy, when: when, outputState: outputState, }; } function emit(streamId, eventName, eventBody, metadata) { var message = { streamId: streamId, eventName: eventName , body: JSON.stringify(eventBody), metadata: metadata, isJson: true }; eventProcessor.emit(message); } function linkTo(streamId, event, metadata) { var message = { streamId: streamId, eventName: "$>", body: event.sequenceNumber + "@" + event.streamId, metadata: metadata, isJson: false }; eventProcessor.emit(message); } function copyTo(streamId, event, metadata) { var m = {}; var em = event.metadata; if (em) for (var p1 in em) if (p1.indexOf("$") !== 0 || p1 === "$correlationId") m[p1] = em[p1]; if (metadata) for (var p2 in metadata) if (p2.indexOf("$") !== 0) m[p2] = metadata[p2]; var message = { streamId: streamId, eventName: event.eventType, body: event.bodyRaw, metadata: m }; eventProcessor.emit(message); } function linkStreamTo(streamId, linkedStreamId, metadata) { var message = { streamId: streamId, eventName: "$@", body: linkedStreamId, metadata: metadata, isJson: false }; eventProcessor.emit(message); } function options(options_object) { eventProcessor.options(options_object); } return { log: queryLog, on_any: eventProcessor.on_any, on_raw: eventProcessor.on_raw, fromAll: fromAll, fromCategory: fromCategory, fromStream: fromStream, fromStreams: fromStreams, fromStreamCatalog: fromStreamCatalog, fromStreamsMatching: fromStreamsMatching, options: options, emit: emit, linkTo: linkTo, copyTo: copyTo, linkStreamTo: linkStreamTo, require: modules.require, }; }; scope;
Narvalex/Eventing
src/Sample/Inventory.Server/EventStore/Prelude/1Prelude.js
JavaScript
mit
8,499
# Require dependencies explicitly require 'carrierwave' require 'erector' require 'geocoder' require "formbuilder/engine" require "formbuilder/entry" require "formbuilder/entry_validator" require "formbuilder/views/form" require "formbuilder/views/form_field" require "formbuilder/views/entry_dl" module Formbuilder def self.root File.expand_path('../..', __FILE__) end end
wesley1001/formbuilder-rb
lib/formbuilder.rb
Ruby
mit
384
'use strict'; var R6MStatsOpData = (function(R6MLangTerms, undefined) { var WARNING_THRESHOLD = 20, opStats = { attackers: [], defenders: [], sortInfo: { field: null, rank: null, isDescending: null } }; var getAveragesTotals = function getAveragesTotals(opRoleStats) { var count = 0, averagesTotals = {}; for (var opKey in opRoleStats) { for (var sarKey in opRoleStats[opKey].statsAllRanks) { averagesTotals[sarKey] = averagesTotals[sarKey] || {}; averagesTotals[sarKey].all = averagesTotals[sarKey].all || { total: 0, avg: 0 }; averagesTotals[sarKey].all.total += opRoleStats[opKey].statsAllRanks[sarKey]; } for (var sbrKey in opRoleStats[opKey].statsByRank) { for (var key in opRoleStats[opKey].statsByRank[sbrKey]) { averagesTotals[key] = averagesTotals[key] || {}; averagesTotals[key][sbrKey] = averagesTotals[key][sbrKey] || { total: 0, avg: 0 }; averagesTotals[key][sbrKey].total += opRoleStats[opKey].statsByRank[sbrKey][key]; } } count++; } for (var statKey in averagesTotals) { for (var operator in averagesTotals[statKey]) { averagesTotals[statKey][operator].avg = averagesTotals[statKey][operator].total / count; } } return averagesTotals; }; var getEmptyStatsObject = function getEmptyStatsObject() { return { totalKills: 0, totalDeaths: 0, totalPlays: 0, totalWins: 0, killsPerRound: 0, killsPerDeath: 0, pickRate: 0, winRate: 0, survivalRate: 0, warning: false }; }; var getCurrentStats = function getCurrentStats() { return opStats; }; var getOpRoleStats = function getOpRoleStats(apiOpData, totalRounds, opMetaData) { var opRoleStats = [], totalPlaysByRank = {}, totalPlaysAllRanks = 0; for (var opKey in apiOpData) { var newOpStats = { key: opKey, name: opMetaData[opKey].name, cssClass: opMetaData[opKey].cssClass, statsByRank: {}, statsAllRanks: getEmptyStatsObject() }; for (var rankKey in apiOpData[opKey]) { var opRankStats = getEmptyStatsObject(), apiOpRankData = apiOpData[opKey][rankKey]; ['totalWins', 'totalKills', 'totalDeaths', 'totalPlays'].forEach(function(statKey) { opRankStats[statKey] = +apiOpRankData[statKey]; newOpStats.statsAllRanks[statKey] += opRankStats[statKey]; }); totalPlaysByRank[rankKey] = totalPlaysByRank[rankKey] ? totalPlaysByRank[rankKey] + opRankStats.totalPlays : opRankStats.totalPlays; totalPlaysAllRanks += opRankStats.totalPlays; newOpStats.statsByRank[rankKey] = opRankStats; } opRoleStats.push(newOpStats); } setTallies(opRoleStats, totalRounds, totalPlaysByRank, totalPlaysAllRanks); setWarnings(opRoleStats); return { operators: opRoleStats, averagesTotals: getAveragesTotals(opRoleStats) }; }; var set = function set(apiData, totalRounds, opMetaData) { opStats.attackers = getOpRoleStats(apiData.role.Attacker, totalRounds, opMetaData); opStats.defenders = getOpRoleStats(apiData.role.Defender, totalRounds, opMetaData); }; var setTallies = function setTallies(opRoleStats, totalRounds, totalPlaysByRank, totalPlaysAllRanks) { opRoleStats.forEach(function(operator) { setTalliesForRank(operator.statsAllRanks); operator.statsAllRanks.pickRate = (!totalRounds) ? 0 : operator.statsAllRanks.totalPlays / totalRounds; for (var rankKey in operator.statsByRank) { var stats = operator.statsByRank[rankKey]; setTalliesForRank(stats); stats.pickRate = (!totalPlaysByRank[rankKey] || !operator.statsAllRanks.totalPlays || !totalPlaysAllRanks) ? 0 : (stats.totalPlays / totalPlaysByRank[rankKey]) / (operator.statsAllRanks.totalPlays / totalPlaysAllRanks) * operator.statsAllRanks.pickRate; stats.pickRate = Math.min(0.99, Math.max(0.001, stats.pickRate)); } }); }; var setTalliesForRank = function setTalliesForRank(stats) { stats.killsPerDeath = (!stats.totalDeaths) ? 0 : stats.totalKills / stats.totalDeaths; stats.killsPerRound = (!stats.totalPlays) ? 0 : stats.totalKills / stats.totalPlays; stats.survivalRate = (!stats.totalPlays) ? 0 : (stats.totalPlays - stats.totalDeaths) / stats.totalPlays; stats.winRate = (!stats.totalPlays) ? 0 : stats.totalWins / stats.totalPlays; }; var setWarnings = function setWarnings(opRoleStats) { for (var opKey in opRoleStats) { if (opRoleStats[opKey].statsAllRanks.totalPlays < WARNING_THRESHOLD) { opRoleStats[opKey].statsAllRanks.warning = true; } for (var rankKey in opRoleStats[opKey].statsByRank) { if (opRoleStats[opKey].statsByRank[rankKey].totalPlays < WARNING_THRESHOLD) { opRoleStats[opKey].statsByRank[rankKey].warning = true; } } } }; var trySort = function trySort(sortField, isDescending, optionalRank) { opStats.sortInfo.field = sortField || 'name'; opStats.sortInfo.rank = optionalRank; opStats.sortInfo.isDescending = isDescending; trySortRole(opStats.attackers.operators, sortField, isDescending, optionalRank); trySortRole(opStats.defenders.operators, sortField, isDescending, optionalRank); }; var trySortRole = function trySortRole(newOpStats, sortField, isDescending, optionalRank) { newOpStats.sort(function(a, b) { var aValue = a.name, bValue = b.name, nameCompare = true; if (sortField != 'name') { nameCompare = false; if (!optionalRank) { aValue = a.statsAllRanks[sortField]; bValue = b.statsAllRanks[sortField]; } else { aValue = (a.statsByRank[optionalRank]) ? a.statsByRank[optionalRank][sortField] : -1; bValue = (b.statsByRank[optionalRank]) ? b.statsByRank[optionalRank][sortField] : -1; } if (aValue == bValue) { aValue = a.name; bValue = b.name; nameCompare = true; } } if (nameCompare) { if (aValue > bValue) { return 1; } if (aValue < bValue) { return -1; } } else { if (aValue < bValue) { return 1; } if (aValue > bValue) { return -1; } } return 0; }); if (isDescending) { newOpStats.reverse(); } }; return { get: getCurrentStats, set: set, trySort: trySort }; })(R6MLangTerms);
capajon/r6maps
dev/js/stats/stats.operators.data.js
JavaScript
mit
6,671