code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
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("DeclareVariables")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeclareVariables")]
[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("03cc7326-ab7a-46ee-9d6d-ba6f74c414c1")]
// 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.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
LPetrova/CSharpBasic
|
03.Примитивни типове и данни/PrimitiveDataTypesAndVariables/DeclareVariables/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,408
|
'use strict'
const execa = require('execa')
const chalk = require('chalk')
const figures = require('figures')
const ora = require('ora')
module.exports = function fetchRemote(flags) {
// git fetch
let args = ['fetch']
// fetch with prune?
if (!flags.skipPrune) {
// git fetch -p
args.push('-p')
}
let spin = ora(chalk.dim('Fetching remote')).start()
return execa('git', args).then(() => {
spin.stop()
console.log(
chalk.green(figures.tick) +
chalk.dim(' Fetched remote')
)
})
}
|
migg24/git-keeper
|
lib/actions/fetchRemote.js
|
JavaScript
|
mit
| 579
|
### NSL Mod
### Will update this more in the future!
#### Changelog: <https://github.com/xToken/NSL/blob/master/Changelog.md>
#### Command Overview: <https://github.com/xToken/NSL/blob/master/Commands.md>
|
xToken/NSL
|
Readme.md
|
Markdown
|
mit
| 206
|
# RomanNumeralCalcInFSharp
Kata for Guild
|
jgartee/RomanNumeralCalcInFSharp
|
README.md
|
Markdown
|
mit
| 42
|
FILES="dlnd_image_classification.html dlnd_image_classification.ipynb helper.py problem_unittests.py"
zip image-classification.zip $FILES
|
hfoffani/deep-learning
|
image-classification/4review.sh
|
Shell
|
mit
| 140
|
package models
import controllers.routes
import play.api.data.Form
import play.api.mvc.Call
import routes.DateOfSale
import uk.gov.dvla.vehicles.presentation.common.model.{NewKeeperDetailsViewModel, VehicleAndKeeperDetailsModel}
case class DateOfSaleViewModel(form: Form[DateOfSaleFormModel],
vehicleAndKeeperDetails: VehicleAndKeeperDetailsModel,
keeperDetails: NewKeeperDetailsViewModel,
showDateOfSaleWarning: Boolean = false,
submitAction: Call = DateOfSale.submitWithDateCheck(),
disposalDate: Option[String] = None)
|
dvla/vehicles-change-keeper-online
|
app/models/DateOfSaleViewModel.scala
|
Scala
|
mit
| 679
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coq bench</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../../..">Unstable</a></li>
<li><a href=".">8.4pl4 / contrib:railroad-crossing 8.4.dev</a></li>
<li class="active"><a href="">2014-12-05 05:10:05</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../../../../../about.html">About</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href=".">« Up</a>
<h1>
contrib:railroad-crossing
<small>
8.4.dev
<span class="label label-success">5 s</span>
</small>
</h1>
<p><em><script>document.write(moment("2014-12-05 05:10:05 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2014-12-05 05:10:05 UTC)</em><p>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:railroad-crossing/coq:contrib:railroad-crossing.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>The package is valid.
</pre></dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --dry-run coq:contrib:railroad-crossing.8.4.dev coq.8.4pl4</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 s</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.4pl4).
The following actions will be performed:
- install coq:contrib:railroad-crossing.8.4.dev
=== 1 to install ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
=-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Building coq:contrib:railroad-crossing.8.4.dev:
coq_makefile -f Make -o Makefile
make -j4
make install
Installing coq:contrib:railroad-crossing.8.4.dev.
</pre></dd>
</dl>
<p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --deps-only coq:contrib:railroad-crossing.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --verbose coq:contrib:railroad-crossing.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>5 s</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- install coq:contrib:railroad-crossing.8.4.dev
=== 1 to install ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[coq:contrib:railroad-crossing] Fetching https://gforge.inria.fr/git/coq-contribs/railroad-crossing.git#v8.4
Initialized empty Git repository in /home/bench/.opam/packages.dev/coq:contrib:railroad-crossing.8.4.dev/.git/
[master (root-commit) 315f366] opam-git-init
From https://gforge.inria.fr/git/coq-contribs/railroad-crossing
* [new branch] v8.4 -> opam-ref
* [new branch] v8.4 -> origin/v8.4
LICENSE
Make
Makefile
TemporalOperators.v
bench.log
description
railroad_crossing.v
time_clocks.v
HEAD is now at 201c2b0 Sauvegarde des bench.log
=-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Building coq:contrib:railroad-crossing.8.4.dev:
coq_makefile -f Make -o Makefile
make -j4
make install
coqdep -c -slash -R . RailroadCrossing "railroad_crossing.v" > "railroad_crossing.v.d" || ( RV=$?; rm -f "railroad_crossing.v.d"; exit ${RV} )
coqdep -c -slash -R . RailroadCrossing "time_clocks.v" > "time_clocks.v.d" || ( RV=$?; rm -f "time_clocks.v.d"; exit ${RV} )
coqc -q -R . RailroadCrossing time_clocks
coqc -q -R . RailroadCrossing railroad_crossing
for i in time_clocks.vo railroad_crossing.vo; do \
install -d `dirname /home/bench/.opam/system/lib/coq/user-contrib/RailroadCrossing/$i`; \
install -m 0644 $i /home/bench/.opam/system/lib/coq/user-contrib/RailroadCrossing/$i; \
done
Installing coq:contrib:railroad-crossing.8.4.dev.
</pre></dd>
</dl>
<h2>Installation size</h2>
<p>Total: 508 K</p>
<ul>
<li>494 K <code>/home/bench/.opam/system/lib/coq/user-contrib/RailroadCrossing/railroad_crossing.vo</code></li>
<li>14 K <code>/home/bench/.opam/system/lib/coq/user-contrib/RailroadCrossing/time_clocks.vo</code></li>
<li>1 K <code>/home/bench/.opam/system/lib/coq:contrib:railroad-crossing/opam.config</code></li>
<li>1 K <code>/home/bench/.opam/system/install/coq:contrib:railroad-crossing.install</code></li>
</ul>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq:contrib:railroad-crossing.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 s</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- remove coq:contrib:railroad-crossing.8.4.dev
=== 1 to remove ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[coq:contrib:railroad-crossing] Fetching https://gforge.inria.fr/git/coq-contribs/railroad-crossing.git#v8.4
=-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Removing coq:contrib:railroad-crossing.8.4.dev.
rm -R /home/bench/.opam/system/lib/coq/user-contrib/RailroadCrossing
</pre></dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io-old
|
clean/Linux-x86_64-4.01.0-1.2.0/unstable/8.4pl4/contrib:railroad-crossing/8.4.dev/2014-12-05_05-10-05.html
|
HTML
|
mit
| 8,884
|
//
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, 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 <algorithm>
#include "misc/base_pipeline_manager.h"
#include "misc/debug.h"
#include "misc/object_tracker.h"
#include "wrappers/device.h"
#include "wrappers/graphics_pipeline_manager.h"
#include "wrappers/pipeline_cache.h"
#include "wrappers/pipeline_layout.h"
#include "wrappers/render_pass.h"
#include "wrappers/shader_module.h"
#include "wrappers/swapchain.h"
/** When baking a graphics pipeline descriptor, we currently use STL vectors to maintain storage
* for various Vulkan descriptors. These need to be stored on heap because:
*
* 1. The number of required descriptors depends on the pipeline configuration.
* 2. Some parent descriptors use pointers to point at other child descriptors.
*
* In order for vectors not to reallocate memory, we need to reserve memory up-front before
* we start pushing stuff. The number defined by N_CACHE_ITEMS tells how many items each
* vector will hold at max.
*
* This #define could be removed by handling memory allocations manually, but for simplicity
* reasons we'll go with STL vectors for now.
* */
#define N_CACHE_ITEMS 128
/* Please see header for specification */
Anvil::GraphicsPipelineManager::GraphicsPipelineManager(std::weak_ptr<Anvil::BaseDevice> device_ptr,
bool use_pipeline_cache,
std::shared_ptr<Anvil::PipelineCache> pipeline_cache_to_reuse_ptr)
:BasePipelineManager(device_ptr,
use_pipeline_cache,
pipeline_cache_to_reuse_ptr)
{
/* Register the object */
Anvil::ObjectTracker::get()->register_object(Anvil::OBJECT_TYPE_GRAPHICS_PIPELINE_MANAGER,
this);
}
/* Please see header for specification */
Anvil::GraphicsPipelineManager::~GraphicsPipelineManager()
{
m_pipelines.clear();
/* Unregister the object */
Anvil::ObjectTracker::get()->unregister_object(Anvil::OBJECT_TYPE_GRAPHICS_PIPELINE_MANAGER,
this);
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::add_derivative_pipeline_from_sibling_pipeline(bool disable_optimizations,
bool allow_derivatives,
std::shared_ptr<RenderPass> renderpass_ptr,
SubPassID subpass_id,
const ShaderModuleStageEntryPoint& fragment_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& geometry_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& tess_control_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& tess_evaluation_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& vertex_shader_shader_stage_entrypoint_info,
GraphicsPipelineID base_pipeline_id,
GraphicsPipelineID* out_graphics_pipeline_id_ptr)
{
bool result;
ShaderModuleStageEntryPoint stages[GRAPHICS_SHADER_STAGE_COUNT];
stages[GRAPHICS_SHADER_STAGE_FRAGMENT] = fragment_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_GEOMETRY] = geometry_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_TESSELLATION_CONTROL] = tess_control_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_TESSELLATION_EVALUATION] = tess_evaluation_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_VERTEX] = vertex_shader_shader_stage_entrypoint_info;
result = BasePipelineManager::add_derivative_pipeline_from_sibling_pipeline(disable_optimizations,
allow_derivatives,
GRAPHICS_SHADER_STAGE_COUNT,
stages,
base_pipeline_id,
out_graphics_pipeline_id_ptr);
anvil_assert(result);
if (result)
{
anvil_assert(m_pipeline_configurations.find(base_pipeline_id) != m_pipeline_configurations.end() );
anvil_assert(m_pipeline_configurations.find(*out_graphics_pipeline_id_ptr) == m_pipeline_configurations.end() );
m_pipeline_configurations[*out_graphics_pipeline_id_ptr] = std::shared_ptr<GraphicsPipelineConfiguration>(new GraphicsPipelineConfiguration(m_pipeline_configurations[base_pipeline_id],
renderpass_ptr,
subpass_id) );
}
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::add_derivative_pipeline_from_pipeline(bool disable_optimizations,
bool allow_derivatives,
std::shared_ptr<RenderPass> renderpass_ptr,
SubPassID subpass_id,
const ShaderModuleStageEntryPoint& fragment_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& geometry_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& tess_control_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& tess_evaluation_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& vertex_shader_shader_stage_entrypoint_info,
VkPipeline base_pipeline,
GraphicsPipelineID* out_graphics_pipeline_id_ptr)
{
bool result;
ShaderModuleStageEntryPoint stages[GRAPHICS_SHADER_STAGE_COUNT];
stages[GRAPHICS_SHADER_STAGE_FRAGMENT] = fragment_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_GEOMETRY] = geometry_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_TESSELLATION_CONTROL] = tess_control_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_TESSELLATION_EVALUATION] = tess_evaluation_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_VERTEX] = vertex_shader_shader_stage_entrypoint_info;
result = BasePipelineManager::add_derivative_pipeline_from_pipeline(disable_optimizations,
allow_derivatives,
GRAPHICS_SHADER_STAGE_COUNT,
stages,
base_pipeline,
out_graphics_pipeline_id_ptr);
anvil_assert(result);
if (result)
{
anvil_assert(m_pipeline_configurations.find(*out_graphics_pipeline_id_ptr) == m_pipeline_configurations.end() );
m_pipeline_configurations[*out_graphics_pipeline_id_ptr] = std::shared_ptr<GraphicsPipelineConfiguration>(new GraphicsPipelineConfiguration(renderpass_ptr,
subpass_id) );
}
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::add_proxy_pipeline(GraphicsPipelineID* out_proxy_graphics_pipeline_id_ptr)
{
bool result = false;
/* For proxy pipelines, we *only* need the configuration container. */
result = BasePipelineManager::add_proxy_pipeline(out_proxy_graphics_pipeline_id_ptr);
anvil_assert(result);
if (result)
{
anvil_assert(m_pipeline_configurations.find(*out_proxy_graphics_pipeline_id_ptr) == m_pipeline_configurations.end() );
m_pipeline_configurations[*out_proxy_graphics_pipeline_id_ptr] = std::shared_ptr<GraphicsPipelineConfiguration>(new GraphicsPipelineConfiguration(nullptr, /* in_renderpass_ptr */
UINT32_MAX) ); /* in_subpass_id */
}
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::add_regular_pipeline(bool disable_optimizations,
bool allow_derivatives,
std::shared_ptr<RenderPass> renderpass_ptr,
SubPassID subpass_id,
const ShaderModuleStageEntryPoint& fragment_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& geometry_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& tess_control_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& tess_evaluation_shader_stage_entrypoint_info,
const ShaderModuleStageEntryPoint& vertex_shader_shader_stage_entrypoint_info,
GraphicsPipelineID* out_graphics_pipeline_id_ptr)
{
bool result;
ShaderModuleStageEntryPoint stages[GRAPHICS_SHADER_STAGE_COUNT];
stages[GRAPHICS_SHADER_STAGE_FRAGMENT] = fragment_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_GEOMETRY] = geometry_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_TESSELLATION_CONTROL] = tess_control_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_TESSELLATION_EVALUATION] = tess_evaluation_shader_stage_entrypoint_info;
stages[GRAPHICS_SHADER_STAGE_VERTEX] = vertex_shader_shader_stage_entrypoint_info;
result = BasePipelineManager::add_regular_pipeline(disable_optimizations,
allow_derivatives,
GRAPHICS_SHADER_STAGE_COUNT,
stages,
out_graphics_pipeline_id_ptr);
anvil_assert(result);
if (result)
{
anvil_assert(m_pipeline_configurations.find(*out_graphics_pipeline_id_ptr) == m_pipeline_configurations.end() );
m_pipeline_configurations[*out_graphics_pipeline_id_ptr] = std::shared_ptr<GraphicsPipelineConfiguration>(new GraphicsPipelineConfiguration(renderpass_ptr,
subpass_id) );
}
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::add_vertex_attribute(GraphicsPipelineID graphics_pipeline_id,
uint32_t location,
VkFormat format,
uint32_t offset_in_bytes,
uint32_t stride_in_bytes,
VkVertexInputRate rate)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
/* Retrieve the pipeline config descriptor ..*/
if (pipeline_iterator == m_pipeline_configurations.end() )
{
anvil_assert(false);
goto end;
}
else
{
pipeline_config_ptr = pipeline_iterator->second;
}
#ifdef _DEBUG
{
/* Make sure the location is not already referred to by already added attributes */
for (auto attribute_iterator = pipeline_config_ptr->attributes.cbegin();
attribute_iterator != pipeline_config_ptr->attributes.cend();
++attribute_iterator)
{
anvil_assert(attribute_iterator->location != location);
}
}
#endif
/* Add a new vertex attribute descriptor. At this point, we do not differentiate between
* attributes and bindings. Actual Vulkan attributes and bindings will be created at baking
* time. */
pipeline_config_ptr->attributes.push_back(InternalVertexAttribute(format,
location,
offset_in_bytes,
rate,
stride_in_bytes));
/* All done */
result = true;
end:
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::bake()
{
std::vector<VkPipelineColorBlendAttachmentState> color_blend_attachment_states_vk_cache;
std::vector<VkPipelineColorBlendStateCreateInfo> color_blend_state_create_info_items_vk_cache;
std::vector<VkPipelineDepthStencilStateCreateInfo> depth_stencil_state_create_info_items_vk_cache;
std::vector<VkPipelineDynamicStateCreateInfo> dynamic_state_create_info_items_vk_cache;
std::vector<VkDynamicState> enabled_dynamic_states_vk_cache;
std::vector<VkGraphicsPipelineCreateInfo> graphics_pipeline_create_info_items_vk_cache;
std::vector<VkPipelineInputAssemblyStateCreateInfo> input_assembly_state_create_info_items_vk_cache;
std::vector<VkPipelineMultisampleStateCreateInfo> multisample_state_create_info_items_vk_cache;
uint32_t n_consumed_graphics_pipelines = 0;
std::vector<VkPipelineRasterizationStateCreateInfo> raster_state_create_info_items_vk_cache;
bool result = false;
std::vector<VkPipeline> result_graphics_pipelines;
VkResult result_vk;
std::vector<VkRect2D> scissor_boxes_vk_cache;
std::vector<VkPipelineShaderStageCreateInfo> shader_stage_create_info_items_vk_cache;
std::vector<VkSpecializationInfo> specialization_info_vk_cache;
std::vector<VkSpecializationMapEntry> specialization_map_entry_vk_cache;
std::vector<VkPipelineTessellationStateCreateInfo> tessellation_state_create_info_items_vk_cache;
std::vector<VkPipelineVertexInputStateCreateInfo> vertex_input_state_create_info_items_vk_cache;
std::vector<VkPipelineViewportStateCreateInfo> viewport_state_create_info_items_vk_cache;
std::vector<VkViewport> viewports_vk_cache;
std::shared_ptr<Anvil::BaseDevice> device_locked_ptr(m_device_ptr);
static const VkPipelineRasterizationStateRasterizationOrderAMD relaxed_rasterization_order_item =
{
VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD,
nullptr,
VK_RASTERIZATION_ORDER_RELAXED_AMD
};
static const VkPipelineRasterizationStateRasterizationOrderAMD strict_rasterization_order_item =
{
VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD,
nullptr,
VK_RASTERIZATION_ORDER_STRICT_AMD
};
/* Iterate over all stored pipelines, focus on the ones marked as dirty. */
typedef struct _bake_item
{
PipelineID pipeline_id;
std::shared_ptr<Pipeline> pipeline_ptr;
_bake_item(PipelineID in_pipeline_id,
std::shared_ptr<Pipeline> in_pipeline_ptr)
{
pipeline_id = in_pipeline_id;
pipeline_ptr = in_pipeline_ptr;
}
bool operator==(std::shared_ptr<Pipeline> in_pipeline_ptr)
{
return pipeline_ptr == in_pipeline_ptr;
}
} _bake_item;
std::vector<_bake_item> bake_items;
for (auto pipeline_iterator = m_pipelines.begin();
pipeline_iterator != m_pipelines.end();
++pipeline_iterator)
{
if ( pipeline_iterator->second->dirty &&
!pipeline_iterator->second->is_proxy &&
pipeline_iterator->second->is_bakeable)
{
if (pipeline_iterator->second->layout_dirty)
{
pipeline_iterator->second->layout_ptr = get_pipeline_layout(pipeline_iterator->first);
}
bake_items.push_back(_bake_item(pipeline_iterator->first,
pipeline_iterator->second) );
}
}
color_blend_attachment_states_vk_cache.reserve (N_CACHE_ITEMS);
color_blend_state_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
depth_stencil_state_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
dynamic_state_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
enabled_dynamic_states_vk_cache.reserve (N_CACHE_ITEMS);
graphics_pipeline_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
input_assembly_state_create_info_items_vk_cache.reserve(N_CACHE_ITEMS);
multisample_state_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
raster_state_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
scissor_boxes_vk_cache.reserve (N_CACHE_ITEMS);
shader_stage_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
specialization_info_vk_cache.reserve (N_CACHE_ITEMS);
specialization_map_entry_vk_cache.reserve (N_CACHE_ITEMS);
tessellation_state_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
vertex_input_state_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
viewport_state_create_info_items_vk_cache.reserve (N_CACHE_ITEMS);
viewports_vk_cache.reserve (N_CACHE_ITEMS);
for (auto bake_item_iterator = bake_items.begin();
bake_item_iterator != bake_items.end();
++bake_item_iterator)
{
bool color_blend_state_used = false;
std::shared_ptr<GraphicsPipelineConfiguration> current_pipeline_config_ptr = nullptr;
const GraphicsPipelineID current_pipeline_id = bake_item_iterator->pipeline_id;
std::shared_ptr<Pipeline> current_pipeline_ptr = bake_item_iterator->pipeline_ptr;
bool depth_stencil_state_used = false;
bool dynamic_state_used = false;
VkGraphicsPipelineCreateInfo graphics_pipeline_create_info = {};
VkPipelineInputAssemblyStateCreateInfo input_assembly_state_create_info;
bool multisample_state_used = false;
VkPipelineRasterizationStateCreateInfo raster_state_create_info;
uint32_t shader_stage_start_offset = UINT32_MAX;
uint32_t subpass_n_color_attachments = 0;
bool tessellation_state_used = false;
VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info;
bool viewport_state_used = false;
if (!current_pipeline_ptr->dirty)
{
continue;
}
if (m_pipeline_configurations.find(current_pipeline_id) == m_pipeline_configurations.end() )
{
anvil_assert(false);
goto end;
}
else
{
current_pipeline_config_ptr = m_pipeline_configurations[current_pipeline_id];
}
/* Extract subpass information */
current_pipeline_config_ptr->renderpass_ptr->get_subpass_n_attachments(current_pipeline_config_ptr->subpass_id,
ATTACHMENT_TYPE_COLOR,
&subpass_n_color_attachments);
/* Form the color blend state create info descriptor, if needed */
if (!current_pipeline_config_ptr->rasterizer_discard_enabled &&
subpass_n_color_attachments > 0)
{
VkPipelineColorBlendStateCreateInfo color_blend_state_create_info;
const uint32_t start_offset = (uint32_t) color_blend_attachment_states_vk_cache.size();
color_blend_state_create_info.attachmentCount = subpass_n_color_attachments;
color_blend_state_create_info.flags = 0;
color_blend_state_create_info.logicOp = current_pipeline_config_ptr->logic_op;
color_blend_state_create_info.logicOpEnable = static_cast<VkBool32>((current_pipeline_config_ptr->logic_op_enabled) ? VK_TRUE : VK_FALSE);
color_blend_state_create_info.pAttachments = nullptr;
color_blend_state_create_info.pNext = nullptr;
color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
memcpy(color_blend_state_create_info.blendConstants,
current_pipeline_config_ptr->blend_constant,
sizeof(color_blend_state_create_info.blendConstants) );
for (uint32_t n_subpass_color_attachment = 0;
n_subpass_color_attachment < subpass_n_color_attachments;
++n_subpass_color_attachment)
{
VkPipelineColorBlendAttachmentState blend_attachment_state;
BlendingProperties* current_attachment_blending_props_ptr = nullptr;
if (current_pipeline_config_ptr->subpass_attachment_blending_properties.find(n_subpass_color_attachment) == current_pipeline_config_ptr->subpass_attachment_blending_properties.end() )
{
/* The user has not defined blending properties for current color attachment. Use default state values .. */
current_attachment_blending_props_ptr = ¤t_pipeline_config_ptr->subpass_attachment_blending_properties[n_subpass_color_attachment];
current_attachment_blending_props_ptr->blend_enabled = false;
current_attachment_blending_props_ptr->blend_op_alpha = VK_BLEND_OP_ADD;
current_attachment_blending_props_ptr->blend_op_color = VK_BLEND_OP_ADD;
current_attachment_blending_props_ptr->channel_write_mask = VK_COLOR_COMPONENT_A_BIT |
VK_COLOR_COMPONENT_B_BIT |
VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_R_BIT;
current_attachment_blending_props_ptr->dst_alpha_blend_factor = VK_BLEND_FACTOR_ONE;
current_attachment_blending_props_ptr->dst_color_blend_factor = VK_BLEND_FACTOR_ONE;
current_attachment_blending_props_ptr->src_alpha_blend_factor = VK_BLEND_FACTOR_ONE;
current_attachment_blending_props_ptr->src_color_blend_factor = VK_BLEND_FACTOR_ONE;
}
else
{
current_attachment_blending_props_ptr = ¤t_pipeline_config_ptr->subpass_attachment_blending_properties[n_subpass_color_attachment];
}
#ifdef _DEBUG
{
if (n_subpass_color_attachment > 0)
{
const BlendingProperties& zero_attachment_blending_props = current_pipeline_config_ptr->subpass_attachment_blending_properties[0];
anvil_assert(zero_attachment_blending_props == *current_attachment_blending_props_ptr);
}
}
#endif /* _DEBUG */
/* Convert internal descriptor to Vulkan descriptor & stash it in the cache vector. */
blend_attachment_state = current_attachment_blending_props_ptr->get_vk_descriptor();
color_blend_attachment_states_vk_cache.push_back(blend_attachment_state);
}
color_blend_state_create_info.pAttachments = (subpass_n_color_attachments > 0) ? &color_blend_attachment_states_vk_cache[start_offset]
: nullptr;
color_blend_state_used = true;
color_blend_state_create_info_items_vk_cache.push_back(color_blend_state_create_info);
}
else
{
/* No color attachments available. Make sure none of the dependent modes are enabled. */
anvil_assert(!current_pipeline_config_ptr->logic_op_enabled);
color_blend_state_used = false;
}
/* Form the depth stencil state create info descriptor, if needed */
uint32_t n_depth_stencil_attachments = 0;
current_pipeline_config_ptr->renderpass_ptr->get_subpass_n_attachments(current_pipeline_config_ptr->subpass_id,
ATTACHMENT_TYPE_DEPTH_STENCIL,
&n_depth_stencil_attachments);
if (n_depth_stencil_attachments)
{
VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info;
depth_stencil_state_create_info.back = current_pipeline_config_ptr->stencil_state_back_face;
depth_stencil_state_create_info.depthBoundsTestEnable = static_cast<VkBool32>(current_pipeline_config_ptr->depth_bounds_test_enabled ? VK_TRUE : VK_FALSE);
depth_stencil_state_create_info.depthCompareOp = current_pipeline_config_ptr->depth_test_compare_op;
depth_stencil_state_create_info.depthTestEnable = static_cast<VkBool32>(current_pipeline_config_ptr->depth_test_enabled ? VK_TRUE : VK_FALSE);
depth_stencil_state_create_info.depthWriteEnable = static_cast<VkBool32>(current_pipeline_config_ptr->depth_writes_enabled ? VK_TRUE : VK_FALSE);
depth_stencil_state_create_info.flags = 0;
depth_stencil_state_create_info.front = current_pipeline_config_ptr->stencil_state_front_face;
depth_stencil_state_create_info.maxDepthBounds = current_pipeline_config_ptr->max_depth_bounds;
depth_stencil_state_create_info.minDepthBounds = current_pipeline_config_ptr->min_depth_bounds;
depth_stencil_state_create_info.pNext = nullptr;
depth_stencil_state_create_info.stencilTestEnable = static_cast<VkBool32>(current_pipeline_config_ptr->stencil_test_enabled ? VK_TRUE : VK_FALSE);
depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depth_stencil_state_used = true;
depth_stencil_state_create_info_items_vk_cache.push_back(depth_stencil_state_create_info);
}
else
{
/* No depth/stencil attachment available. Make sure none of the dependent modes are enabled. */
anvil_assert(!current_pipeline_config_ptr->depth_bounds_test_enabled);
anvil_assert(!current_pipeline_config_ptr->depth_test_enabled);
anvil_assert(!current_pipeline_config_ptr->depth_writes_enabled);
anvil_assert(!current_pipeline_config_ptr->stencil_test_enabled);
depth_stencil_state_used = false;
}
/* Form the dynamic state create info descriptor, if needed */
if (current_pipeline_config_ptr->enabled_dynamic_states != 0)
{
VkPipelineDynamicStateCreateInfo dynamic_state_create_info;
const uint32_t start_offset = (uint32_t) enabled_dynamic_states_vk_cache.size();
if ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_BLEND_CONSTANTS_BIT) != 0)
{
enabled_dynamic_states_vk_cache.push_back(VK_DYNAMIC_STATE_BLEND_CONSTANTS);
}
if ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_DEPTH_BIAS_BIT) != 0)
{
enabled_dynamic_states_vk_cache.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
}
if ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_DEPTH_BOUNDS_BIT) != 0)
{
enabled_dynamic_states_vk_cache.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS);
}
if ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_LINE_WIDTH_BIT) != 0)
{
enabled_dynamic_states_vk_cache.push_back(VK_DYNAMIC_STATE_LINE_WIDTH);
}
if ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_SCISSOR_BIT) != 0)
{
enabled_dynamic_states_vk_cache.push_back(VK_DYNAMIC_STATE_SCISSOR);
}
if ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_STENCIL_COMPARE_MASK_BIT) != 0)
{
enabled_dynamic_states_vk_cache.push_back(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK);
}
if ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_STENCIL_REFERENCE_BIT) != 0)
{
enabled_dynamic_states_vk_cache.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
}
if ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_STENCIL_WRITE_MASK_BIT) != 0)
{
enabled_dynamic_states_vk_cache.push_back(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK);
}
if ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_VIEWPORT_BIT) != 0)
{
enabled_dynamic_states_vk_cache.push_back(VK_DYNAMIC_STATE_VIEWPORT);
}
dynamic_state_create_info.dynamicStateCount = (uint32_t) (enabled_dynamic_states_vk_cache.size() - start_offset);
dynamic_state_create_info.flags = 0;
dynamic_state_create_info.pDynamicStates = (dynamic_state_create_info.dynamicStateCount > 0) ? &enabled_dynamic_states_vk_cache[start_offset]
: VK_NULL_HANDLE;
dynamic_state_create_info.pNext = nullptr;
dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamic_state_used = true;
dynamic_state_create_info_items_vk_cache.push_back(dynamic_state_create_info);
}
else
{
dynamic_state_used = false;
}
/* Form the input assembly create info descriptor */
input_assembly_state_create_info.flags = 0;
input_assembly_state_create_info.pNext = nullptr;
input_assembly_state_create_info.primitiveRestartEnable = static_cast<VkBool32>(current_pipeline_config_ptr->primitive_restart_enabled ? VK_TRUE : VK_FALSE);
input_assembly_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
input_assembly_state_create_info.topology = current_pipeline_config_ptr->primitive_topology;
input_assembly_state_create_info_items_vk_cache.push_back(input_assembly_state_create_info);
/* Form the multisample state create info descriptor, if needed */
if (!current_pipeline_config_ptr->rasterizer_discard_enabled)
{
VkPipelineMultisampleStateCreateInfo multisample_state_create_info;
multisample_state_create_info.alphaToCoverageEnable = static_cast<VkBool32>(current_pipeline_config_ptr->alpha_to_coverage_enabled ? VK_TRUE : VK_FALSE);
multisample_state_create_info.alphaToOneEnable = static_cast<VkBool32>(current_pipeline_config_ptr->alpha_to_one_enabled ? VK_TRUE : VK_FALSE);
multisample_state_create_info.flags = 0;
multisample_state_create_info.minSampleShading = current_pipeline_config_ptr->min_sample_shading;
multisample_state_create_info.pNext = nullptr;
multisample_state_create_info.pSampleMask = ¤t_pipeline_config_ptr->sample_mask;
multisample_state_create_info.rasterizationSamples = static_cast<VkSampleCountFlagBits>(current_pipeline_config_ptr->sample_count);
multisample_state_create_info.sampleShadingEnable = static_cast<VkBool32>(current_pipeline_config_ptr->sample_shading_enabled ? VK_TRUE : VK_FALSE);
multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisample_state_used = true;
multisample_state_create_info_items_vk_cache.push_back(multisample_state_create_info);
}
else
{
/* Make sure any dependent modes are disabled */
anvil_assert(!current_pipeline_config_ptr->alpha_to_coverage_enabled);
anvil_assert(!current_pipeline_config_ptr->alpha_to_one_enabled);
anvil_assert(!current_pipeline_config_ptr->sample_shading_enabled);
multisample_state_used = false;
}
/* Form the raster state create info descriptor */
raster_state_create_info.cullMode = current_pipeline_config_ptr->cull_mode;
raster_state_create_info.depthBiasClamp = current_pipeline_config_ptr->depth_bias_clamp;
raster_state_create_info.depthBiasConstantFactor = current_pipeline_config_ptr->depth_bias_constant_factor;
raster_state_create_info.depthBiasEnable = static_cast<VkBool32>(current_pipeline_config_ptr->depth_bias_enabled ? VK_TRUE : VK_FALSE);
raster_state_create_info.depthBiasSlopeFactor = current_pipeline_config_ptr->depth_bias_slope_factor;
raster_state_create_info.depthClampEnable = static_cast<VkBool32>(current_pipeline_config_ptr->depth_clamp_enabled ? VK_TRUE : VK_FALSE);
raster_state_create_info.flags = 0;
raster_state_create_info.frontFace = current_pipeline_config_ptr->front_face;
raster_state_create_info.lineWidth = current_pipeline_config_ptr->line_width;
raster_state_create_info.pNext = nullptr;
raster_state_create_info.polygonMode = current_pipeline_config_ptr->polygon_mode;
raster_state_create_info.rasterizerDiscardEnable = static_cast<VkBool32>(current_pipeline_config_ptr->rasterizer_discard_enabled ? VK_TRUE : VK_FALSE);
raster_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
if (device_locked_ptr->is_extension_enabled("VK_AMD_rasterization_order") )
{
/* Chain a predefined struct which will toggle the relaxed rasterization, as long as the device supports the
* VK_AMD_rasterization_order extension.
*/
const VkPipelineRasterizationStateRasterizationOrderAMD* chained_item_ptr = nullptr;
if (current_pipeline_config_ptr->rasterization_order != VK_RASTERIZATION_ORDER_STRICT_AMD)
{
anvil_assert(current_pipeline_config_ptr->rasterization_order == relaxed_rasterization_order_item.rasterizationOrder);
chained_item_ptr = &relaxed_rasterization_order_item;
}
else
{
chained_item_ptr = &strict_rasterization_order_item;
}
raster_state_create_info.pNext = chained_item_ptr;
}
else
if (current_pipeline_config_ptr->rasterization_order != VK_RASTERIZATION_ORDER_STRICT_AMD)
{
fprintf(stderr,
"[!] Cannot enable out-of-order rasterization - VK_AMD_rasterization_order extension not enabled at device creation time");
}
raster_state_create_info_items_vk_cache.push_back(raster_state_create_info);
/* Form stage descriptors */
shader_stage_start_offset = (uint32_t) shader_stage_create_info_items_vk_cache.size();
for (uint32_t n_shader = 0;
n_shader < GRAPHICS_SHADER_STAGE_COUNT;
++n_shader)
{
if (current_pipeline_ptr->shader_stages[n_shader].name != nullptr)
{
VkPipelineShaderStageCreateInfo current_shader_stage_create_info;
std::shared_ptr<Anvil::ShaderModule> shader_module_ptr;
if (current_pipeline_ptr->specialization_constants_map[n_shader].size() > 0)
{
bake_specialization_info_vk(current_pipeline_ptr->specialization_constants_map [n_shader],
¤t_pipeline_ptr->specialization_constant_data_buffer[0],
&specialization_map_entry_vk_cache,
&specialization_info_vk_cache[n_shader]);
}
shader_module_ptr = current_pipeline_ptr->shader_stages[n_shader].shader_module_ptr;
current_shader_stage_create_info.module = shader_module_ptr->get_module();
current_shader_stage_create_info.pName = (n_shader == GRAPHICS_SHADER_STAGE_FRAGMENT) ? shader_module_ptr->get_fs_entrypoint_name()
: (n_shader == GRAPHICS_SHADER_STAGE_GEOMETRY) ? shader_module_ptr->get_gs_entrypoint_name()
: (n_shader == GRAPHICS_SHADER_STAGE_TESSELLATION_CONTROL) ? shader_module_ptr->get_tc_entrypoint_name()
: (n_shader == GRAPHICS_SHADER_STAGE_TESSELLATION_EVALUATION) ? shader_module_ptr->get_te_entrypoint_name()
: (n_shader == GRAPHICS_SHADER_STAGE_VERTEX) ? shader_module_ptr->get_vs_entrypoint_name()
: nullptr;
current_shader_stage_create_info.flags = 0;
current_shader_stage_create_info.pNext = nullptr;
current_shader_stage_create_info.pSpecializationInfo = (current_pipeline_ptr->specialization_constants_map[n_shader].size() > 0) ? &specialization_info_vk_cache[n_shader]
: VK_NULL_HANDLE;
current_shader_stage_create_info.stage = (n_shader == GRAPHICS_SHADER_STAGE_FRAGMENT) ? VK_SHADER_STAGE_FRAGMENT_BIT
: (n_shader == GRAPHICS_SHADER_STAGE_GEOMETRY) ? VK_SHADER_STAGE_GEOMETRY_BIT
: (n_shader == GRAPHICS_SHADER_STAGE_TESSELLATION_CONTROL) ? VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT
: (n_shader == GRAPHICS_SHADER_STAGE_TESSELLATION_EVALUATION) ? VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT
: VK_SHADER_STAGE_VERTEX_BIT;
current_shader_stage_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shader_stage_create_info_items_vk_cache.push_back(current_shader_stage_create_info);
}
}
/* Form the tessellation state create info descriptor if needed */
if (current_pipeline_ptr->shader_stages[GRAPHICS_SHADER_STAGE_TESSELLATION_CONTROL].name != nullptr ||
current_pipeline_ptr->shader_stages[GRAPHICS_SHADER_STAGE_TESSELLATION_EVALUATION].name != nullptr)
{
VkPipelineTessellationStateCreateInfo tessellation_state_create_info;
tessellation_state_create_info.flags = 0;
tessellation_state_create_info.patchControlPoints = current_pipeline_config_ptr->n_patch_control_points;
tessellation_state_create_info.pNext = nullptr;
tessellation_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO;
tessellation_state_used = true;
tessellation_state_create_info_items_vk_cache.push_back(tessellation_state_create_info);
}
else
{
tessellation_state_used = false;
}
/* Form the vertex input state create info descriptor */
bake_vk_attributes_and_bindings(current_pipeline_config_ptr);
vertex_input_state_create_info.vertexAttributeDescriptionCount = (uint32_t) current_pipeline_config_ptr->vk_input_attributes.size();
vertex_input_state_create_info.vertexBindingDescriptionCount = (uint32_t) current_pipeline_config_ptr->vk_input_bindings.size();
vertex_input_state_create_info.flags = 0;
vertex_input_state_create_info.pNext = nullptr;
vertex_input_state_create_info.pVertexAttributeDescriptions = (vertex_input_state_create_info.vertexAttributeDescriptionCount > 0) ? ¤t_pipeline_config_ptr->vk_input_attributes[0]
: nullptr;
vertex_input_state_create_info.pVertexBindingDescriptions = (vertex_input_state_create_info.vertexBindingDescriptionCount > 0) ? ¤t_pipeline_config_ptr->vk_input_bindings[0]
: nullptr;
vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertex_input_state_create_info_items_vk_cache.push_back(vertex_input_state_create_info);
/* Form the viewport state create info descriptor, if needed */
if (!current_pipeline_config_ptr->rasterizer_discard_enabled)
{
const uint32_t scissor_boxes_start_offset = (uint32_t) scissor_boxes_vk_cache.size();
const uint32_t viewports_start_offset = (uint32_t) viewports_vk_cache.size();
VkPipelineViewportStateCreateInfo viewport_state_create_info;
#ifdef _DEBUG
{
const uint32_t n_scissor_boxes = (current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_SCISSOR_BIT) ? current_pipeline_config_ptr->n_dynamic_scissor_boxes
: (uint32_t) current_pipeline_config_ptr->scissor_boxes.size();
const uint32_t n_viewports = (current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_VIEWPORT_BIT) ? current_pipeline_config_ptr->n_dynamic_viewports
: (uint32_t) current_pipeline_config_ptr->viewports.size();
anvil_assert(n_scissor_boxes == n_viewports);
}
#endif /* _DEBUG */
if (current_pipeline_config_ptr->scissor_boxes.size() == 0)
{
/* No scissor boxes / viewport defined. Use default settings.. */
InternalScissorBox default_scissor_box;
InternalViewport default_viewport;
std::shared_ptr<Swapchain> swapchain_ptr = current_pipeline_config_ptr->renderpass_ptr->get_swapchain();
uint32_t window_size[2] = {0};
/* NOTE: If you hit this assertion, you either need to pass a Swapchain instance when this renderpass is being created,
* *or* specify scissor & viewport information for the GFX pipeline.
*/
anvil_assert(swapchain_ptr != nullptr);
swapchain_ptr->get_image(0)->get_image_mipmap_size(0, /* n_mipmap */
window_size + 0,
window_size + 1,
nullptr); /* opt_out_depth_ptr */
anvil_assert(window_size[0] != 0 &&
window_size[1] != 0);
default_scissor_box.height = window_size[1];
default_scissor_box.width = window_size[0];
default_scissor_box.x = 0;
default_scissor_box.y = 0;
default_viewport.height = float(window_size[1]);
default_viewport.max_depth = 1.0f;
default_viewport.min_depth = 0.0f;
default_viewport.origin_x = 0.0f;
default_viewport.origin_y = 0.0f;
default_viewport.width = float(window_size[0]);
current_pipeline_config_ptr->scissor_boxes[0] = default_scissor_box;
current_pipeline_config_ptr->viewports [0] = default_viewport;
}
/* Convert internal scissor box & viewport representations to Vulkan descriptors */
for (auto scissor_box_iterator = current_pipeline_config_ptr->scissor_boxes.cbegin();
scissor_box_iterator != current_pipeline_config_ptr->scissor_boxes.cend();
++scissor_box_iterator)
{
scissor_boxes_vk_cache.push_back(scissor_box_iterator->second.get_vk_descriptor() );
}
for (auto viewport_iterator = current_pipeline_config_ptr->viewports.cbegin();
viewport_iterator != current_pipeline_config_ptr->viewports.cend();
++viewport_iterator)
{
viewports_vk_cache.push_back(viewport_iterator->second.get_vk_descriptor() );
}
/* Bake the descriptor */
viewport_state_create_info.flags = 0;
viewport_state_create_info.pNext = nullptr;
viewport_state_create_info.pScissors = ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_SCISSOR_BIT) != 0) ? VK_NULL_HANDLE
: &scissor_boxes_vk_cache[scissor_boxes_start_offset];
viewport_state_create_info.pViewports = ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_VIEWPORT_BIT) != 0) ? VK_NULL_HANDLE
: &viewports_vk_cache [viewports_start_offset];
viewport_state_create_info.scissorCount = ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_SCISSOR_BIT) != 0) ? current_pipeline_config_ptr->n_dynamic_scissor_boxes
: (uint32_t) current_pipeline_config_ptr->scissor_boxes.size();
viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport_state_create_info.viewportCount = ((current_pipeline_config_ptr->enabled_dynamic_states & DYNAMIC_STATE_VIEWPORT_BIT) != 0) ? current_pipeline_config_ptr->n_dynamic_viewports
: (uint32_t) current_pipeline_config_ptr->viewports.size();
anvil_assert(viewport_state_create_info.scissorCount == viewport_state_create_info.viewportCount);
viewport_state_used = true;
viewport_state_create_info_items_vk_cache.push_back(viewport_state_create_info);
}
else
{
viewport_state_used = false;
}
/* Configure base pipeline handle/indices fields of the create info descriptor */
if (current_pipeline_ptr->base_pipeline_ptr != nullptr)
{
anvil_assert(current_pipeline_ptr->base_pipeline == VK_NULL_HANDLE);
/* There are three cases we need to handle separately here:
*
* 1. The base pipeline is to be baked in the call we're preparing for. Determine
* its index in the create info descriptor array and use it.
* 2. The pipeline has been baked earlier. We should be able to work around this
* by providing a handle to the pipeline, instead of the index.
* 3. The pipeline under specified index uses a different layout. This indicates
* a bug in the app or the manager.
*
* NOTE: A slightly adjusted version of this code is re-used in ComputePipelineManager::bake()
*/
auto base_bake_item_iterator = std::find(bake_items.begin(),
bake_items.end(),
current_pipeline_ptr->base_pipeline_ptr);
if (base_bake_item_iterator != bake_items.end() )
{
/* Case 1 */
graphics_pipeline_create_info.basePipelineHandle = current_pipeline_ptr->base_pipeline;
graphics_pipeline_create_info.basePipelineIndex = static_cast<int32_t>(base_bake_item_iterator - bake_items.begin() );
}
else
if (current_pipeline_ptr->base_pipeline_ptr != nullptr &&
current_pipeline_ptr->base_pipeline_ptr->baked_pipeline != VK_NULL_HANDLE)
{
/* Case 2 */
graphics_pipeline_create_info.basePipelineHandle = current_pipeline_ptr->base_pipeline_ptr->baked_pipeline;
graphics_pipeline_create_info.basePipelineIndex = -1; /* unused. */
}
else
{
/* Case 3 */
anvil_assert(false);
}
}
else
if (current_pipeline_ptr->base_pipeline != VK_NULL_HANDLE)
{
graphics_pipeline_create_info.basePipelineHandle = current_pipeline_ptr->base_pipeline;
graphics_pipeline_create_info.basePipelineIndex = -1; /* unused. */
}
else
{
/* No base pipeline requested */
graphics_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
graphics_pipeline_create_info.basePipelineIndex = -1; /* unused */
}
/* Form the rest of the create info descriptor */
anvil_assert(!current_pipeline_ptr->layout_dirty);
graphics_pipeline_create_info.flags = 0;
graphics_pipeline_create_info.layout = current_pipeline_ptr->layout_ptr->get_pipeline_layout();
graphics_pipeline_create_info.pColorBlendState = (color_blend_state_used) ? &color_blend_state_create_info_items_vk_cache[color_blend_state_create_info_items_vk_cache.size() - 1]
: VK_NULL_HANDLE;
graphics_pipeline_create_info.pDepthStencilState = (depth_stencil_state_used) ? &depth_stencil_state_create_info_items_vk_cache[depth_stencil_state_create_info_items_vk_cache.size() - 1]
: VK_NULL_HANDLE;
graphics_pipeline_create_info.pDynamicState = (dynamic_state_used) ? &dynamic_state_create_info_items_vk_cache[dynamic_state_create_info_items_vk_cache.size() - 1]
: VK_NULL_HANDLE;
graphics_pipeline_create_info.pInputAssemblyState = &input_assembly_state_create_info_items_vk_cache[input_assembly_state_create_info_items_vk_cache.size() - 1];
graphics_pipeline_create_info.pMultisampleState = (multisample_state_used) ? &multisample_state_create_info_items_vk_cache[multisample_state_create_info_items_vk_cache.size() - 1]
: VK_NULL_HANDLE;
graphics_pipeline_create_info.pNext = nullptr;
graphics_pipeline_create_info.pRasterizationState = &raster_state_create_info_items_vk_cache[raster_state_create_info_items_vk_cache.size() - 1];
graphics_pipeline_create_info.pStages = &shader_stage_create_info_items_vk_cache[shader_stage_start_offset];
graphics_pipeline_create_info.pTessellationState = (tessellation_state_used) ? &tessellation_state_create_info_items_vk_cache[tessellation_state_create_info_items_vk_cache.size() - 1]
: VK_NULL_HANDLE;
graphics_pipeline_create_info.pVertexInputState = &vertex_input_state_create_info_items_vk_cache[vertex_input_state_create_info_items_vk_cache.size() - 1];
graphics_pipeline_create_info.pViewportState = (viewport_state_used) ? &viewport_state_create_info_items_vk_cache[viewport_state_create_info_items_vk_cache.size() - 1]
: VK_NULL_HANDLE;
graphics_pipeline_create_info.renderPass = current_pipeline_config_ptr->renderpass_ptr->get_render_pass();
graphics_pipeline_create_info.stageCount = (uint32_t) shader_stage_create_info_items_vk_cache.size() - shader_stage_start_offset;
graphics_pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
graphics_pipeline_create_info.subpass = current_pipeline_config_ptr->subpass_id;
if (graphics_pipeline_create_info.basePipelineHandle != VK_NULL_HANDLE ||
graphics_pipeline_create_info.basePipelineIndex != -1)
{
graphics_pipeline_create_info.flags |= VK_PIPELINE_CREATE_DERIVATIVE_BIT;
}
graphics_pipeline_create_info.flags |= ((current_pipeline_ptr->allow_derivatives) ? VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT : 0) |
((current_pipeline_ptr->disable_optimizations) ? VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT : 0);
if (current_pipeline_config_ptr->pfn_pipeline_prebake_callback_proc != nullptr)
{
current_pipeline_config_ptr->pfn_pipeline_prebake_callback_proc(m_device_ptr,
current_pipeline_id,
&graphics_pipeline_create_info,
current_pipeline_config_ptr->pipeline_prebake_callback_user_arg);
}
/* Stash the descriptor for now. We will issue one expensive vkCreateGraphicsPipelines() call after all pipeline objects
* are iterated over. */
graphics_pipeline_create_info_items_vk_cache.push_back(graphics_pipeline_create_info);
}
#ifdef _DEBUG
{
/* If you hit any of the below assertion failures, please bump up the value under the #define.
*
* We use the vectors to hold structure instances. If more than N_CACHE_ITEMS items is ever requested from any of these vectors,
* the underlying storage will likely be reallocated. Many of the descriptors use pointers to refer to children descriptors,
* and when the data is moved around, the pointers are no longer valid.
*/
anvil_assert(color_blend_attachment_states_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(color_blend_state_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(depth_stencil_state_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(dynamic_state_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(enabled_dynamic_states_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(graphics_pipeline_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(input_assembly_state_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(multisample_state_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(raster_state_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(scissor_boxes_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(shader_stage_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(specialization_info_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(specialization_map_entry_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(tessellation_state_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(vertex_input_state_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(viewport_state_create_info_items_vk_cache.size() <= N_CACHE_ITEMS);
anvil_assert(viewports_vk_cache.size() <= N_CACHE_ITEMS);
}
#endif
/* All right. Try to bake all pipeline objects at once */
result_graphics_pipelines.resize(bake_items.size() );
result_vk = vkCreateGraphicsPipelines(device_locked_ptr->get_device_vk(),
m_pipeline_cache_ptr->get_pipeline_cache(),
(uint32_t) graphics_pipeline_create_info_items_vk_cache.size(),
&graphics_pipeline_create_info_items_vk_cache[0],
nullptr, /* pAllocator */
&result_graphics_pipelines[0]);
if (!is_vk_call_successful(result_vk) )
{
anvil_assert(result_vk);
goto end;
}
for (auto bake_item_iterator = bake_items.begin();
bake_item_iterator != bake_items.end();
++bake_item_iterator)
{
if (!bake_item_iterator->pipeline_ptr->dirty)
{
continue;
}
if (m_pipeline_configurations[bake_item_iterator->pipeline_id]->pfn_pipeline_postbake_callback_proc != nullptr)
{
m_pipeline_configurations[bake_item_iterator->pipeline_id]->pfn_pipeline_postbake_callback_proc(m_device_ptr,
bake_item_iterator->pipeline_id,
m_pipeline_configurations[bake_item_iterator->pipeline_id]->pipeline_postbake_callback_user_arg);
}
}
/* Distribute the result pipeline objects to pipeline configuration descriptors */
for (auto pipeline_iterator = m_pipelines.begin();
pipeline_iterator != m_pipelines.end();
++pipeline_iterator)
{
const GraphicsPipelineID current_pipeline_id = pipeline_iterator->first;
std::shared_ptr<Pipeline> current_pipeline_ptr = pipeline_iterator->second;
if (!current_pipeline_ptr->dirty ||
current_pipeline_ptr->is_proxy ||
!current_pipeline_ptr->is_bakeable)
{
continue;
}
m_pipelines[current_pipeline_id]->baked_pipeline = result_graphics_pipelines[n_consumed_graphics_pipelines++];
current_pipeline_ptr->dirty = false;
}
anvil_assert(n_consumed_graphics_pipelines == (uint32_t) result_graphics_pipelines.size() );
/* All done */
result = true;
end:
return result;
}
/** Converts the internal vertex attribute descriptors to one or more VkVertexInputAttributeDescription & VkVertexInputBindingDescription
* structures.
*
* The function goes an extra mile to re-use the same vertex binding for attributes whose binding properties match.
*
* @param pipeline_config_ptr Pipeline configuration descriptor to use. Must not be nullptr.
*/
void Anvil::GraphicsPipelineManager::bake_vk_attributes_and_bindings(std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr)
{
pipeline_config_ptr->vk_input_attributes.clear();
pipeline_config_ptr->vk_input_bindings.clear();
for (auto attribute_iterator = pipeline_config_ptr->attributes.cbegin();
attribute_iterator != pipeline_config_ptr->attributes.cend();
++attribute_iterator)
{
/* Identify the binding index we should use for the attribute */
VkVertexInputAttributeDescription current_attribute_vk;
uint32_t n_attribute_binding = UINT32_MAX;
bool has_found = false;
for (auto vk_input_binding_iterator = pipeline_config_ptr->vk_input_bindings.begin();
vk_input_binding_iterator != pipeline_config_ptr->vk_input_bindings.end();
++vk_input_binding_iterator)
{
if (vk_input_binding_iterator->inputRate == attribute_iterator->rate &&
vk_input_binding_iterator->stride == attribute_iterator->stride_in_bytes)
{
has_found = true;
n_attribute_binding = (uint32_t) (vk_input_binding_iterator - pipeline_config_ptr->vk_input_bindings.begin());
break;
}
}
if (!has_found)
{
/* Got to create a new binding descriptor .. */
VkVertexInputBindingDescription new_binding_vk;
new_binding_vk.binding = (uint32_t) pipeline_config_ptr->vk_input_bindings.size();
new_binding_vk.inputRate = attribute_iterator->rate;
new_binding_vk.stride = attribute_iterator->stride_in_bytes;
pipeline_config_ptr->vk_input_bindings.push_back(new_binding_vk);
n_attribute_binding = new_binding_vk.binding;
}
/* Good to convert the internal attribute descriptor to the Vulkan's input attribute descriptor */
current_attribute_vk.binding = n_attribute_binding;
current_attribute_vk.format = attribute_iterator->format;
current_attribute_vk.location = attribute_iterator->location;
current_attribute_vk.offset = attribute_iterator->offset_in_bytes;
pipeline_config_ptr->vk_input_attributes.push_back(current_attribute_vk);
}
}
/* Please see header for specification */
std::shared_ptr<Anvil::GraphicsPipelineManager> Anvil::GraphicsPipelineManager::create(std::weak_ptr<Anvil::BaseDevice> device_ptr,
bool use_pipeline_cache,
std::shared_ptr<Anvil::PipelineCache> pipeline_cache_to_reuse_ptr)
{
std::shared_ptr<Anvil::GraphicsPipelineManager> result_ptr;
result_ptr.reset(
new Anvil::GraphicsPipelineManager(device_ptr,
use_pipeline_cache,
pipeline_cache_to_reuse_ptr)
);
return result_ptr;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::delete_pipeline(GraphicsPipelineID graphics_pipeline_id)
{
GraphicsPipelineConfigurations::iterator configuration_iterator;
bool result = false;
result = BasePipelineManager::delete_pipeline(graphics_pipeline_id);
if (!result)
{
goto end;
}
configuration_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
if (configuration_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(configuration_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
m_pipeline_configurations.erase(configuration_iterator);
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_alpha_to_coverage_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->alpha_to_coverage_enabled;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_alpha_to_one_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->alpha_to_one_enabled;
}
result = true;
end:
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_blending_properties(GraphicsPipelineID graphics_pipeline_id,
float* out_opt_blend_constant_vec4_ptr,
uint32_t* out_opt_n_blend_attachments_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_blend_constant_vec4_ptr != nullptr)
{
memcpy(out_opt_blend_constant_vec4_ptr,
pipeline_config_ptr->blend_constant,
sizeof(pipeline_config_ptr->blend_constant) );
}
if (out_opt_n_blend_attachments_ptr != nullptr)
{
*out_opt_n_blend_attachments_ptr = static_cast<uint32_t>(pipeline_config_ptr->subpass_attachment_blending_properties.size() );
}
result = true;
end:
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_color_blend_attachment_properties(GraphicsPipelineID graphics_pipeline_id,
SubPassAttachmentID attachment_id,
bool* out_opt_blending_enabled_ptr,
VkBlendOp* out_opt_blend_op_color_ptr,
VkBlendOp* out_opt_blend_op_alpha_ptr,
VkBlendFactor* out_opt_src_color_blend_factor_ptr,
VkBlendFactor* out_opt_dst_color_blend_factor_ptr,
VkBlendFactor* out_opt_src_alpha_blend_factor_ptr,
VkBlendFactor* out_opt_dst_alpha_blend_factor_ptr,
VkColorComponentFlags* out_opt_channel_write_mask_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
SubPassAttachmentToBlendingPropertiesMap::const_iterator props_iterator;
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
props_iterator = pipeline_config_ptr->subpass_attachment_blending_properties.find(attachment_id);
if (props_iterator == pipeline_config_ptr->subpass_attachment_blending_properties.end() )
{
anvil_assert(!(props_iterator == pipeline_config_ptr->subpass_attachment_blending_properties.end() ) );
goto end;
}
if (out_opt_blending_enabled_ptr != nullptr)
{
*out_opt_blending_enabled_ptr = props_iterator->second.blend_enabled;
}
if (out_opt_blend_op_color_ptr != nullptr)
{
*out_opt_blend_op_color_ptr = props_iterator->second.blend_op_color;
}
if (out_opt_blend_op_alpha_ptr != nullptr)
{
*out_opt_blend_op_alpha_ptr = props_iterator->second.blend_op_alpha;
}
if (out_opt_src_color_blend_factor_ptr != nullptr)
{
*out_opt_src_color_blend_factor_ptr = props_iterator->second.src_color_blend_factor;
}
if (out_opt_dst_color_blend_factor_ptr != nullptr)
{
*out_opt_dst_color_blend_factor_ptr = props_iterator->second.dst_color_blend_factor;
}
if (out_opt_src_alpha_blend_factor_ptr != nullptr)
{
*out_opt_src_alpha_blend_factor_ptr = props_iterator->second.src_alpha_blend_factor;
}
if (out_opt_dst_alpha_blend_factor_ptr != nullptr)
{
*out_opt_dst_alpha_blend_factor_ptr = props_iterator->second.dst_alpha_blend_factor;
}
if (out_opt_channel_write_mask_ptr != nullptr)
{
*out_opt_channel_write_mask_ptr = props_iterator->second.channel_write_mask;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_depth_bias_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr,
float* out_opt_depth_bias_constant_factor_ptr,
float* out_opt_depth_bias_clamp_ptr,
float* out_opt_depth_bias_slope_factor_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->depth_bias_enabled;
}
if (out_opt_depth_bias_constant_factor_ptr != nullptr)
{
*out_opt_depth_bias_constant_factor_ptr = pipeline_config_ptr->depth_bias_constant_factor;
}
if (out_opt_depth_bias_clamp_ptr != nullptr)
{
*out_opt_depth_bias_clamp_ptr = pipeline_config_ptr->depth_bias_clamp;
}
if (out_opt_depth_bias_slope_factor_ptr != nullptr)
{
*out_opt_depth_bias_slope_factor_ptr = pipeline_config_ptr->depth_bias_slope_factor;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_depth_bounds_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr,
float* out_opt_min_depth_bounds_ptr,
float* out_opt_max_depth_bounds_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->depth_bounds_test_enabled;
}
if (out_opt_min_depth_bounds_ptr != nullptr)
{
*out_opt_min_depth_bounds_ptr = pipeline_config_ptr->min_depth_bounds;
}
if (out_opt_max_depth_bounds_ptr != nullptr)
{
*out_opt_max_depth_bounds_ptr = pipeline_config_ptr->max_depth_bounds;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_depth_clamp_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->depth_clamp_enabled;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_depth_test_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr,
VkCompareOp* out_opt_compare_op_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->depth_test_enabled;
}
if (out_opt_compare_op_ptr != nullptr)
{
*out_opt_compare_op_ptr = pipeline_config_ptr->depth_test_compare_op;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_depth_write_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->depth_writes_enabled;
}
result = true;
end:
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_dynamic_scissor_state_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t* out_opt_n_dynamic_scissor_boxes_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_n_dynamic_scissor_boxes_ptr != nullptr)
{
*out_opt_n_dynamic_scissor_boxes_ptr = pipeline_config_ptr->n_dynamic_scissor_boxes;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_dynamic_states(GraphicsPipelineID graphics_pipeline_id,
DynamicStateBitfield* out_opt_enabled_dynamic_states_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_enabled_dynamic_states_ptr != nullptr)
{
*out_opt_enabled_dynamic_states_ptr = pipeline_config_ptr->enabled_dynamic_states;
}
result = true;
end:
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_dynamic_viewport_state_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t* out_n_dynamic_viewports_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_n_dynamic_viewports_ptr!= nullptr)
{
*out_n_dynamic_viewports_ptr = pipeline_config_ptr->n_dynamic_viewports;
}
result = true;
end:
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_graphics_pipeline_properties(Anvil::GraphicsPipelineID graphics_pipeline_id,
uint32_t* out_opt_n_scissors_ptr,
uint32_t* out_opt_n_viewports_ptr,
uint32_t* out_opt_n_vertex_input_attributes_ptr,
uint32_t* out_opt_n_vertex_input_bindings_ptr,
std::shared_ptr<RenderPass>* out_opt_renderpass_ptr,
SubPassID* out_opt_subpass_id_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_n_scissors_ptr != nullptr)
{
*out_opt_n_scissors_ptr = static_cast<uint32_t>(pipeline_config_ptr->scissor_boxes.size() );
}
if (out_opt_n_viewports_ptr != nullptr)
{
*out_opt_n_viewports_ptr = static_cast<uint32_t>(pipeline_config_ptr->viewports.size() );
}
if (out_opt_n_vertex_input_attributes_ptr != nullptr)
{
*out_opt_n_vertex_input_attributes_ptr = static_cast<uint32_t>(pipeline_config_ptr->vk_input_attributes.size() );
}
if (out_opt_n_vertex_input_bindings_ptr != nullptr)
{
*out_opt_n_vertex_input_bindings_ptr = static_cast<uint32_t>(pipeline_config_ptr->vk_input_bindings.size() );
}
if (out_opt_renderpass_ptr != nullptr)
{
*out_opt_renderpass_ptr = pipeline_config_ptr->renderpass_ptr;
}
if (out_opt_subpass_id_ptr != nullptr)
{
*out_opt_subpass_id_ptr = pipeline_config_ptr->subpass_id;
}
/* All done */
result = true;
end:
return result;
}
/* Please see header for specification */
VkPipeline Anvil::GraphicsPipelineManager::get_graphics_pipeline(GraphicsPipelineID pipeline_id)
{
auto pipeline_iterator = m_pipelines.find(pipeline_id);
bool result = false;
VkPipeline result_pipeline = VK_NULL_HANDLE;
ANVIL_REDUNDANT_VARIABLE(result);
if (pipeline_iterator == m_pipelines.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end()) );
goto end;
}
if (pipeline_iterator->second->baked_pipeline == VK_NULL_HANDLE ||
pipeline_iterator->second->dirty)
{
anvil_assert(!pipeline_iterator->second->is_proxy);
result = bake();
anvil_assert(result);
anvil_assert(pipeline_iterator->second->dirty == false);
anvil_assert(pipeline_iterator->second->baked_pipeline != VK_NULL_HANDLE);
}
result_pipeline = pipeline_iterator->second->baked_pipeline;
end:
return result_pipeline;
}
/* Please see header for specification */
std::shared_ptr<Anvil::PipelineLayout> Anvil::GraphicsPipelineManager::get_graphics_pipeline_layout(GraphicsPipelineID pipeline_id)
{
return get_pipeline_layout(pipeline_id);
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_input_assembly_properties(GraphicsPipelineID graphics_pipeline_id,
VkPrimitiveTopology* out_opt_primitive_topology_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_primitive_topology_ptr != nullptr)
{
*out_opt_primitive_topology_ptr = pipeline_config_ptr->primitive_topology;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_logic_op_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr,
VkLogicOp* out_opt_logic_op_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->logic_op_enabled;
}
if (out_opt_logic_op_ptr != nullptr)
{
*out_opt_logic_op_ptr = pipeline_config_ptr->logic_op;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_multisampling_properties(GraphicsPipelineID graphics_pipeline_id,
VkSampleCountFlags* out_opt_sample_count_ptr,
VkSampleMask* out_opt_sample_mask_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_sample_count_ptr != nullptr)
{
*out_opt_sample_count_ptr = pipeline_config_ptr->sample_count;
}
if (out_opt_sample_mask_ptr != nullptr)
{
*out_opt_sample_mask_ptr = pipeline_config_ptr->sample_mask;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_primitive_restart_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->primitive_restart_enabled;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_rasterization_order(GraphicsPipelineID graphics_pipeline_id,
VkRasterizationOrderAMD* out_opt_rasterization_order_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_rasterization_order_ptr != nullptr)
{
*out_opt_rasterization_order_ptr = pipeline_config_ptr->rasterization_order;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_rasterizer_discard_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->rasterizer_discard_enabled;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_rasterization_properties(GraphicsPipelineID graphics_pipeline_id,
VkPolygonMode* out_opt_polygon_mode_ptr,
VkCullModeFlags* out_opt_cull_mode_ptr,
VkFrontFace* out_opt_front_face_ptr,
float* out_opt_line_width_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_polygon_mode_ptr != nullptr)
{
*out_opt_polygon_mode_ptr = pipeline_config_ptr->polygon_mode;
}
if (out_opt_cull_mode_ptr != nullptr)
{
*out_opt_cull_mode_ptr = pipeline_config_ptr->cull_mode;
}
if (out_opt_front_face_ptr != nullptr)
{
*out_opt_front_face_ptr = pipeline_config_ptr->front_face;
}
if (out_opt_line_width_ptr != nullptr)
{
*out_opt_line_width_ptr = pipeline_config_ptr->line_width;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_sample_shading_state(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr,
float* out_opt_min_sample_shading_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->sample_shading_enabled;
}
if (out_opt_min_sample_shading_ptr != nullptr)
{
*out_opt_min_sample_shading_ptr = pipeline_config_ptr->min_sample_shading;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_scissor_box_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t n_scissor_box,
int32_t* out_opt_x_ptr,
int32_t* out_opt_y_ptr,
uint32_t* out_opt_width_ptr,
uint32_t* out_opt_height_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
const InternalScissorBox* scissor_box_props_ptr = nullptr;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (pipeline_config_ptr->scissor_boxes.find(n_scissor_box) == pipeline_config_ptr->scissor_boxes.end() )
{
anvil_assert(!(pipeline_config_ptr->scissor_boxes.find(n_scissor_box) == pipeline_config_ptr->scissor_boxes.end()) );
goto end;
}
else
{
scissor_box_props_ptr = &pipeline_config_ptr->scissor_boxes.at(n_scissor_box);
}
if (out_opt_x_ptr != nullptr)
{
*out_opt_x_ptr = scissor_box_props_ptr->x;
}
if (out_opt_y_ptr != nullptr)
{
*out_opt_y_ptr = scissor_box_props_ptr->y;
}
if (out_opt_width_ptr != nullptr)
{
*out_opt_width_ptr = scissor_box_props_ptr->width;
}
if (out_opt_height_ptr != nullptr)
{
*out_opt_height_ptr = scissor_box_props_ptr->height;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_stencil_test_properties(GraphicsPipelineID graphics_pipeline_id,
bool* out_opt_is_enabled_ptr,
VkStencilOp* out_opt_front_stencil_fail_op_ptr,
VkStencilOp* out_opt_front_stencil_pass_op_ptr,
VkStencilOp* out_opt_front_stencil_depth_fail_op_ptr,
VkCompareOp* out_opt_front_stencil_compare_op_ptr,
uint32_t* out_opt_front_stencil_compare_mask_ptr,
uint32_t* out_opt_front_stencil_write_mask_ptr,
uint32_t* out_opt_front_stencil_reference_ptr,
VkStencilOp* out_opt_back_stencil_fail_op_ptr,
VkStencilOp* out_opt_back_stencil_pass_op_ptr,
VkStencilOp* out_opt_back_stencil_depth_fail_op_ptr,
VkCompareOp* out_opt_back_stencil_compare_op_ptr,
uint32_t* out_opt_back_stencil_compare_mask_ptr,
uint32_t* out_opt_back_stencil_write_mask_ptr,
uint32_t* out_opt_back_stencil_reference_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_is_enabled_ptr != nullptr)
{
*out_opt_is_enabled_ptr = pipeline_config_ptr->stencil_test_enabled;
}
if (out_opt_front_stencil_fail_op_ptr != nullptr)
{
*out_opt_front_stencil_fail_op_ptr = pipeline_config_ptr->stencil_state_front_face.failOp;
}
if (out_opt_front_stencil_pass_op_ptr != nullptr)
{
*out_opt_front_stencil_pass_op_ptr = pipeline_config_ptr->stencil_state_front_face.passOp;
}
if (out_opt_front_stencil_depth_fail_op_ptr != nullptr)
{
*out_opt_front_stencil_depth_fail_op_ptr = pipeline_config_ptr->stencil_state_front_face.depthFailOp;
}
if (out_opt_front_stencil_compare_op_ptr != nullptr)
{
*out_opt_front_stencil_compare_op_ptr = pipeline_config_ptr->stencil_state_front_face.compareOp;
}
if (out_opt_front_stencil_compare_mask_ptr != nullptr)
{
*out_opt_front_stencil_compare_mask_ptr = pipeline_config_ptr->stencil_state_front_face.compareMask;
}
if (out_opt_front_stencil_write_mask_ptr != nullptr)
{
*out_opt_front_stencil_write_mask_ptr = pipeline_config_ptr->stencil_state_front_face.writeMask;
}
if (out_opt_front_stencil_reference_ptr != nullptr)
{
*out_opt_front_stencil_reference_ptr = pipeline_config_ptr->stencil_state_front_face.reference;
}
if (out_opt_back_stencil_fail_op_ptr != nullptr)
{
*out_opt_back_stencil_fail_op_ptr = pipeline_config_ptr->stencil_state_back_face.failOp;
}
if (out_opt_back_stencil_pass_op_ptr != nullptr)
{
*out_opt_back_stencil_pass_op_ptr = pipeline_config_ptr->stencil_state_back_face.passOp;
}
if (out_opt_back_stencil_depth_fail_op_ptr != nullptr)
{
*out_opt_back_stencil_depth_fail_op_ptr = pipeline_config_ptr->stencil_state_back_face.depthFailOp;
}
if (out_opt_back_stencil_compare_op_ptr != nullptr)
{
*out_opt_back_stencil_compare_op_ptr = pipeline_config_ptr->stencil_state_back_face.compareOp;
}
if (out_opt_back_stencil_compare_mask_ptr != nullptr)
{
*out_opt_back_stencil_compare_mask_ptr = pipeline_config_ptr->stencil_state_back_face.compareMask;
}
if (out_opt_back_stencil_write_mask_ptr != nullptr)
{
*out_opt_back_stencil_write_mask_ptr = pipeline_config_ptr->stencil_state_back_face.writeMask;
}
if (out_opt_back_stencil_reference_ptr != nullptr)
{
*out_opt_back_stencil_reference_ptr = pipeline_config_ptr->stencil_state_back_face.reference;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_tessellation_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t* out_opt_n_patch_control_points_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (out_opt_n_patch_control_points_ptr != nullptr)
{
*out_opt_n_patch_control_points_ptr = pipeline_config_ptr->n_patch_control_points;
}
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_vertex_input_attribute_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t n_vertex_input_attribute,
uint32_t* out_opt_location_ptr,
uint32_t* out_opt_binding_ptr,
VkFormat* out_opt_format_ptr,
uint32_t* out_opt_offset_ptr) const
{
VkVertexInputAttributeDescription* attribute_ptr;
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (pipeline_config_ptr->vk_input_attributes.size() <= n_vertex_input_attribute)
{
anvil_assert(!(pipeline_config_ptr->vk_input_attributes.size() <= n_vertex_input_attribute) );
goto end;
}
else
{
attribute_ptr = &pipeline_config_ptr->vk_input_attributes.at(n_vertex_input_attribute);
}
if (out_opt_location_ptr != nullptr)
{
*out_opt_location_ptr = attribute_ptr->location;
}
if (out_opt_binding_ptr != nullptr)
{
*out_opt_binding_ptr = attribute_ptr->binding;
}
if (out_opt_format_ptr != nullptr)
{
*out_opt_format_ptr = attribute_ptr->format;
}
if (out_opt_offset_ptr != nullptr)
{
*out_opt_offset_ptr = attribute_ptr->offset;
}
/* All done */
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_vertex_input_binding_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t n_vertex_input_binding,
uint32_t* out_opt_binding_ptr,
uint32_t* out_opt_stride_ptr,
VkVertexInputRate* out_opt_input_rate_ptr) const
{
VkVertexInputBindingDescription* binding_ptr;
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (pipeline_config_ptr->vk_input_bindings.size() <= n_vertex_input_binding)
{
anvil_assert(!(pipeline_config_ptr->vk_input_bindings.size() <= n_vertex_input_binding) );
goto end;
}
else
{
binding_ptr = &pipeline_config_ptr->vk_input_bindings.at(n_vertex_input_binding);
}
if (out_opt_binding_ptr != nullptr)
{
*out_opt_binding_ptr = binding_ptr->binding;
}
if (out_opt_stride_ptr != nullptr)
{
*out_opt_stride_ptr = binding_ptr->stride;
}
if (out_opt_input_rate_ptr != nullptr)
{
*out_opt_input_rate_ptr = binding_ptr->inputRate;
}
/* All done */
result = true;
end:
return result;
}
/** Please see header for specification */
bool Anvil::GraphicsPipelineManager::get_viewport_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t n_viewport,
float* out_opt_origin_x_ptr,
float* out_opt_origin_y_ptr,
float* out_opt_width_ptr,
float* out_opt_height_ptr,
float* out_opt_min_depth_ptr,
float* out_opt_max_depth_ptr) const
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
bool result = false;
InternalViewport* viewport_props_ptr;
if (pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (pipeline_config_ptr->viewports.find(n_viewport) == pipeline_config_ptr->viewports.end() )
{
anvil_assert(!(pipeline_config_ptr->viewports.find(n_viewport) == pipeline_config_ptr->viewports.end()) );
goto end;
}
else
{
viewport_props_ptr = &pipeline_config_ptr->viewports.at(n_viewport);
}
if (out_opt_origin_x_ptr != nullptr)
{
*out_opt_origin_x_ptr = viewport_props_ptr->origin_x;
}
if (out_opt_origin_y_ptr != nullptr)
{
*out_opt_origin_y_ptr = viewport_props_ptr->origin_y;
}
if (out_opt_width_ptr != nullptr)
{
*out_opt_width_ptr = viewport_props_ptr->width;
}
if (out_opt_height_ptr != nullptr)
{
*out_opt_height_ptr = viewport_props_ptr->height;
}
if (out_opt_min_depth_ptr != nullptr)
{
*out_opt_min_depth_ptr = viewport_props_ptr->min_depth;
}
if (out_opt_max_depth_ptr != nullptr)
{
*out_opt_max_depth_ptr = viewport_props_ptr->max_depth;
}
result = true;
end:
return result;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_blending_properties(GraphicsPipelineID graphics_pipeline_id,
const float* blend_constant_vec4)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
memcpy(pipeline_config_ptr->blend_constant,
blend_constant_vec4,
sizeof(pipeline_config_ptr->blend_constant) );
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_color_blend_attachment_properties(GraphicsPipelineID graphics_pipeline_id,
SubPassAttachmentID attachment_id,
bool blending_enabled,
VkBlendOp blend_op_color,
VkBlendOp blend_op_alpha,
VkBlendFactor src_color_blend_factor,
VkBlendFactor dst_color_blend_factor,
VkBlendFactor src_alpha_blend_factor,
VkBlendFactor dst_alpha_blend_factor,
VkColorComponentFlags channel_write_mask)
{
BlendingProperties* attachment_blending_props_ptr = nullptr;
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
/* Retrieve and update the attachment descriptor. */
attachment_blending_props_ptr = &pipeline_config_ptr->subpass_attachment_blending_properties[attachment_id];
attachment_blending_props_ptr->blend_enabled = blending_enabled;
attachment_blending_props_ptr->blend_op_alpha = blend_op_alpha;
attachment_blending_props_ptr->blend_op_color = blend_op_color;
attachment_blending_props_ptr->channel_write_mask = channel_write_mask;
attachment_blending_props_ptr->dst_alpha_blend_factor = dst_alpha_blend_factor;
attachment_blending_props_ptr->dst_color_blend_factor = dst_color_blend_factor;
attachment_blending_props_ptr->src_alpha_blend_factor = src_alpha_blend_factor;
attachment_blending_props_ptr->src_color_blend_factor = src_color_blend_factor;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_dynamic_scissor_state_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t n_dynamic_scissor_boxes)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->n_dynamic_scissor_boxes = n_dynamic_scissor_boxes;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_dynamic_viewport_state_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t n_dynamic_viewports)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->n_dynamic_viewports = n_dynamic_viewports;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_input_assembly_properties(GraphicsPipelineID graphics_pipeline_id,
VkPrimitiveTopology primitive_topology)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->primitive_topology = primitive_topology;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_multisampling_properties(GraphicsPipelineID graphics_pipeline_id,
VkSampleCountFlagBits sample_count,
float min_sample_shading,
const VkSampleMask sample_mask)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
anvil_assert(sample_count <= VK_SAMPLE_COUNT_32_BIT);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->min_sample_shading = min_sample_shading;
pipeline_config_ptr->sample_count = sample_count;
pipeline_config_ptr->sample_mask = sample_mask;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::set_pipeline_post_bake_callback(GraphicsPipelineID graphics_pipeline_id,
PFNPIPELINEPOSTBAKECALLBACKPROC pfn_pipeline_post_bake_proc,
void* user_arg)
{
bool result = false;
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->pfn_pipeline_postbake_callback_proc = pfn_pipeline_post_bake_proc;
pipeline_config_ptr->pipeline_postbake_callback_user_arg = user_arg;
result = true;
end:
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::set_pipeline_pre_bake_callback(GraphicsPipelineID graphics_pipeline_id,
PFNPIPELINEPREBAKECALLBACKPROC pfn_pipeline_pre_bake_proc,
void* user_arg)
{
bool result = false;
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->pfn_pipeline_prebake_callback_proc = pfn_pipeline_pre_bake_proc;
pipeline_config_ptr->pipeline_prebake_callback_user_arg = user_arg;
result = true;
end:
return result;
}
/* Please see header for specification */
bool Anvil::GraphicsPipelineManager::set_pipeline_state_from_pipeline(GraphicsPipelineID target_pipeline_id,
GraphicsPipelineID source_pipeline_id)
{
std::shared_ptr<RenderPass> cached_renderpass_ptr;
SubPassID cached_subpass_id = UINT32_MAX;
bool result = false;
std::shared_ptr<GraphicsPipelineConfiguration> source_pipeline_config_ptr;
if (m_pipelines.find(target_pipeline_id) == m_pipelines.end() )
{
anvil_assert(!(m_pipelines.find(target_pipeline_id) == m_pipelines.end()) );
goto end;
}
if (m_pipeline_configurations.find(target_pipeline_id) == m_pipeline_configurations.end() )
{
anvil_assert(!(m_pipeline_configurations.find(target_pipeline_id) == m_pipeline_configurations.end() ));
goto end;
}
if (m_pipeline_configurations.find(source_pipeline_id) == m_pipeline_configurations.end() )
{
anvil_assert(!(m_pipeline_configurations.find(source_pipeline_id) == m_pipeline_configurations.end() ));
goto end;
}
cached_renderpass_ptr = m_pipeline_configurations[target_pipeline_id]->renderpass_ptr;
cached_subpass_id = m_pipeline_configurations[target_pipeline_id]->subpass_id;
m_pipeline_configurations[target_pipeline_id] = m_pipeline_configurations[source_pipeline_id];
m_pipelines [target_pipeline_id]->dsg_ptr = m_pipelines[source_pipeline_id]->dsg_ptr;
m_pipelines [target_pipeline_id]->dirty = true;
m_pipeline_configurations[target_pipeline_id]->renderpass_ptr = cached_renderpass_ptr;
m_pipeline_configurations[target_pipeline_id]->subpass_id = cached_subpass_id;
result = true;
end:
return result;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_rasterization_order(GraphicsPipelineID graphics_pipeline_id,
VkRasterizationOrderAMD rasterization_order)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (pipeline_config_ptr->rasterization_order != rasterization_order)
{
pipeline_config_ptr->rasterization_order = rasterization_order;
pipeline_iterator->second->dirty = true;
}
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_rasterization_properties(GraphicsPipelineID graphics_pipeline_id,
VkPolygonMode polygon_mode,
VkCullModeFlags cull_mode,
VkFrontFace front_face,
float line_width)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->cull_mode = cull_mode;
pipeline_config_ptr->front_face = front_face;
pipeline_config_ptr->line_width = line_width;
pipeline_config_ptr->polygon_mode = polygon_mode;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_scissor_box_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t n_scissor_box,
int32_t x,
int32_t y,
uint32_t width,
uint32_t height)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->scissor_boxes[n_scissor_box] = InternalScissorBox(x,
y,
width,
height);
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_stencil_test_properties(GraphicsPipelineID graphics_pipeline_id,
bool update_front_face_state,
VkStencilOp stencil_fail_op,
VkStencilOp stencil_pass_op,
VkStencilOp stencil_depth_fail_op,
VkCompareOp stencil_compare_op,
uint32_t stencil_compare_mask,
uint32_t stencil_write_mask,
uint32_t stencil_reference)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
VkStencilOpState* stencil_op_state_ptr = nullptr;
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
stencil_op_state_ptr = (update_front_face_state) ? &pipeline_config_ptr->stencil_state_front_face
: &pipeline_config_ptr->stencil_state_back_face;
stencil_op_state_ptr->compareMask = stencil_compare_mask;
stencil_op_state_ptr->compareOp = stencil_compare_op;
stencil_op_state_ptr->depthFailOp = stencil_depth_fail_op;
stencil_op_state_ptr->failOp = stencil_fail_op;
stencil_op_state_ptr->passOp = stencil_pass_op;
stencil_op_state_ptr->reference = stencil_reference;
stencil_op_state_ptr->writeMask = stencil_write_mask;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_tessellation_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t n_patch_control_points)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->n_patch_control_points = n_patch_control_points;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::set_viewport_properties(GraphicsPipelineID graphics_pipeline_id,
uint32_t n_viewport,
float origin_x,
float origin_y,
float width,
float height,
float min_depth,
float max_depth)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->viewports[n_viewport] = InternalViewport(origin_x,
origin_y,
width,
height,
min_depth,
max_depth);
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_alpha_to_coverage(GraphicsPipelineID graphics_pipeline_id,
bool should_enable)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->alpha_to_coverage_enabled = should_enable;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_alpha_to_one(GraphicsPipelineID graphics_pipeline_id,
bool should_enable)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->alpha_to_one_enabled = should_enable;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_depth_bounds_test(GraphicsPipelineID graphics_pipeline_id,
bool should_enable,
float min_depth_bounds,
float max_depth_bounds)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->depth_bounds_test_enabled = should_enable;
pipeline_config_ptr->max_depth_bounds = max_depth_bounds;
pipeline_config_ptr->min_depth_bounds = min_depth_bounds;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_depth_bias(GraphicsPipelineID graphics_pipeline_id,
bool should_enable,
float depth_bias_constant_factor,
float depth_bias_clamp,
float depth_bias_slope_factor)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->depth_bias_constant_factor = depth_bias_constant_factor;
pipeline_config_ptr->depth_bias_clamp = depth_bias_clamp;
pipeline_config_ptr->depth_bias_enabled = should_enable;
pipeline_config_ptr->depth_bias_slope_factor = depth_bias_slope_factor;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_depth_clamp(GraphicsPipelineID graphics_pipeline_id,
bool should_enable)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->depth_clamp_enabled = should_enable;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_depth_test(GraphicsPipelineID graphics_pipeline_id,
bool should_enable,
VkCompareOp compare_op)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->depth_test_enabled = should_enable;
pipeline_config_ptr->depth_test_compare_op = compare_op;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_depth_writes(GraphicsPipelineID graphics_pipeline_id,
bool should_enable)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->depth_writes_enabled = should_enable;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_dynamic_states(GraphicsPipelineID graphics_pipeline_id,
bool should_enable,
DynamicStateBitfield dynamic_state_bits)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
if (should_enable)
{
pipeline_config_ptr->enabled_dynamic_states |= dynamic_state_bits;
}
else
{
pipeline_config_ptr->enabled_dynamic_states &= ~dynamic_state_bits;
}
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_logic_op(GraphicsPipelineID graphics_pipeline_id,
bool should_enable,
VkLogicOp logic_op)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->logic_op = logic_op;
pipeline_config_ptr->logic_op_enabled = should_enable;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_primitive_restart(GraphicsPipelineID graphics_pipeline_id,
bool should_enable)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->primitive_restart_enabled = should_enable;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_rasterizer_discard(GraphicsPipelineID graphics_pipeline_id,
bool should_enable)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->rasterizer_discard_enabled = should_enable;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_sample_shading(GraphicsPipelineID graphics_pipeline_id,
bool should_enable)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->sample_shading_enabled = should_enable;
pipeline_iterator->second->dirty = true;
end:
;
}
/* Please see header for specification */
void Anvil::GraphicsPipelineManager::toggle_stencil_test(GraphicsPipelineID graphics_pipeline_id,
bool should_enable)
{
std::shared_ptr<GraphicsPipelineConfiguration> pipeline_config_ptr;
auto pipeline_config_iterator = m_pipeline_configurations.find(graphics_pipeline_id);
auto pipeline_iterator = m_pipelines.find (graphics_pipeline_id);
if (pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end() )
{
anvil_assert(!(pipeline_iterator == m_pipelines.end() ||
pipeline_config_iterator == m_pipeline_configurations.end()) );
goto end;
}
else
{
pipeline_config_ptr = pipeline_config_iterator->second;
}
pipeline_config_ptr->stencil_test_enabled = should_enable;
pipeline_iterator->second->dirty = true;
end:
;
}
|
baxtea/Anvil
|
src/wrappers/graphics_pipeline_manager.cpp
|
C++
|
mit
| 154,814
|
LIVE WEBSITE HERE: http://students.washington.edu/gmanci/info343/challenges/shooting-map/
# Map Challenge: Police Shootings
This folder contains your submission for the [map challenge](http://info343-joelross.rhcloud.com/challenges/map). The below questions should be answered with details about your submission!
##### 1. What information does your visualization show? What 'argument' are you making? #####
It shows the numbers of armed and unarmed victims of police shootings along with summaries of the events. Unarmed victims show in a more noticible, darker color to bring attention to the situations that most likely could have been handled in a less violent manner.
##### 2. Did you complete any advanced extensions to this challenge? If so, what? #####
n/a
##### 3. Did you receive any help from others (classmates, etc)? If so, please list who. #####
I collaborated a couple of times on this project with Halle Friedman, Quinn Mau and Casey Lee.
##### 4. Approximately how many hours did it take you to complete this challenge? #####
~12 hr
##### 5. Did you encounter any problems in this challenge we should warn students about in the future? How can we make the challenge better? #####
I think this challenge needs more explanation on how to associate information between the HTML and JS files.
|
gmanci/INFO343-Projects-Public
|
shooting-map/README.md
|
Markdown
|
mit
| 1,314
|
<?php
namespace Cyh\Jose\Signing\Signer;
use Cyh\Jose\Signing\Exception\UnexpectedValueException;
use Cyh\Jose\Signing\Exception\InvalidSignatureException;
abstract class PublicKey implements SignerInterface
{
/**
* @param resource $private_or_public_key_resource
* @return bool
* @throws UnexpectedValueException
*/
abstract protected function validateKey($private_or_public_key_resource);
/**
* Generate signature
*
* @link http://php.net/manual/en/function.openssl-sign.php
*
* @param string $message
* @param resource|string $private_key
* @param string $pass_phrase default null
* @return string
* @throws InvalidSignatureException
*/
public function sign($message, $private_key, $pass_phrase=null)
{
if (!is_resource($private_key)) {
$private_key = openssl_pkey_get_private($private_key, $pass_phrase);
if (!is_resource($private_key)) {
throw new UnexpectedValueException('Unable to load private key: ' . openssl_error_string());
}
}
$this->validateKey($private_key);
$signature = '';
$success = openssl_sign($message, $signature, $private_key, $this->getHashAlgorithm());
if (true === $success) {
return $signature;
}
throw new InvalidSignatureException('Unable to sign data: ' . openssl_error_string());
}
/**
* Verify signature
*
* @link http://php.net/manual/en/function.openssl-verify.php
*
* @param string $message
* @param string $signature
* @param resource|string $public_key
* @return bool
* @throws InvalidSignatureException
*/
public function verify($message, $signature, $public_key)
{
if (!is_resource($public_key)) {
$public_key = openssl_pkey_get_public($public_key);
if (!is_resource($public_key)) {
throw new UnexpectedValueException('Unable to load public key: ' . openssl_error_string());
}
}
$this->validateKey($public_key);
$success = openssl_verify($message, $signature, $public_key, $this->getHashAlgorithm());
if (1 === $success) {
return true;
}
throw new InvalidSignatureException('Unable verify signature: ' . openssl_error_string());
}
}
|
closeyourhead/jose
|
src/Cyh/Jose/Signing/Signer/PublicKey.php
|
PHP
|
mit
| 2,391
|
-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: 2018-08-30 15:34:36
-- æå¡å¨çæ¬ï¼ 5.5.47
-- PHP Version: 7.0.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- 表çç»æ `cmf_common_apps`
--
CREATE TABLE `cmf_common_apps` (
`id` int(11) NOT NULL,
`app` char(50) NOT NULL COMMENT 'åºç¨æ è¯',
`title` char(50) NOT NULL COMMENT 'åºç¨æ é¢',
`description` varchar(255) NOT NULL COMMENT 'åºç¨æè¿°',
`createTime` int(10) UNSIGNED NOT NULL COMMENT 'å建æ¶é´',
`entryUrl` varchar(255) DEFAULT NULL COMMENT 'åå°å°å',
`manageEntryUrl` varchar(255) DEFAULT NULL COMMENT 'åå°å°å',
`logo` varchar(255) NOT NULL COMMENT '徿 å°å',
`sort` smallint(5) UNSIGNED NOT NULL COMMENT 'æåºå·',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1æ£å¸¸ 0å é¤',
`logoColor` varchar(30) DEFAULT NULL COMMENT 'logoèæ¯è²'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='åºç¨è¡¨';
--
-- 转å表ä¸çæ°æ® `cmf_common_apps`
--
INSERT INTO `cmf_common_apps` (`id`, `app`, `title`, `description`, `createTime`, `entryUrl`, `manageEntryUrl`, `logo`, `sort`, `status`, `logoColor`) VALUES
(1, 'manage', 'åå°ç®¡ç', 'åºç¨åå°ç®¡çï¼ç¨æ·ç®¡çï¼åæ·ç®¡çç\', 0, '', 'manage/apps/index', 'fa fa-gears', 1, 1, 'red'),
(2, 'asdasd', 'å宿å®ç\', '', 1535637950, '', 'asda/asd/asdas', 'fa fa-video-camera', 2, 1, '');
-- --------------------------------------------------------
--
-- 表çç»æ `cmf_common_company`
--
CREATE TABLE `cmf_common_company` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL COMMENT 'åæ·åç§°',
`address` varchar(100) NOT NULL COMMENT 'å°å',
`contact` char(50) NOT NULL COMMENT 'è系人',
`phone` char(13) NOT NULL COMMENT 'èç³»çµè¯',
`parentId` int(11) NOT NULL DEFAULT '0' COMMENT 'ä¸çº§id',
`apps` varchar(255) NOT NULL COMMENT 'å¯ç¨åºç¨id',
`createTime` int(10) UNSIGNED NOT NULL COMMENT 'å建æ¶é´',
`createUserId` int(11) NOT NULL COMMENT 'å建人id',
`modifyUserId` int(11) DEFAULT NULL COMMENT 'æåä¿®æ¹äººid',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1弿¾ 0å
³é'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='åæ·è¡¨';
--
-- 转å表ä¸çæ°æ® `cmf_common_company`
--
INSERT INTO `cmf_common_company` (`id`, `name`, `address`, `contact`, `phone`, `parentId`, `apps`, `createTime`, `createUserId`, `modifyUserId`, `status`) VALUES
(1, 'ç³»ç»åå°åæ·', '', '', '', 0, '', 0, 1, 0, 1);
-- --------------------------------------------------------
--
-- 表çç»æ `cmf_common_menu`
--
CREATE TABLE `cmf_common_menu` (
`id` int(11) NOT NULL,
`typeId` tinyint(4) NOT NULL COMMENT '1:èå 2:æä½',
`parentId` int(11) NOT NULL COMMENT 'ä¸çº§id',
`appId` int(11) NOT NULL COMMENT 'åºç¨id',
`title` char(50) NOT NULL COMMENT 'åç§°',
`app` varchar(50) NOT NULL COMMENT 'åºç¨æ è¯',
`controller` varchar(50) NOT NULL COMMENT 'æ§å¶å¨',
`action` varchar(50) NOT NULL COMMENT 'æ¹æ³',
`createTime` int(10) UNSIGNED NOT NULL COMMENT 'å建æ¶é´',
`sort` smallint(5) UNSIGNED NOT NULL COMMENT 'æåº',
`className` varchar(255) DEFAULT NULL COMMENT 'æ ·å¼',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1æ£å¸¸ 0å é¤',
`askSure` tinyint(4) NOT NULL DEFAULT '0' COMMENT '1æä½è¯¢é®',
`requestType` tinyint(4) NOT NULL DEFAULT '0' COMMENT '请æ±ç±»å',
`param` varchar(30) DEFAULT NULL COMMENT '跳转带çåæ°',
`field` varchar(30) DEFAULT NULL COMMENT '忰弿å±å段'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='åè½è¡¨';
--
-- 转å表ä¸çæ°æ® `cmf_common_menu`
--
INSERT INTO `cmf_common_menu` (`id`, `typeId`, `parentId`, `appId`, `title`, `app`, `controller`, `action`, `createTime`, `sort`, `className`, `status`, `askSure`, `requestType`, `param`, `field`) VALUES
(1, 1, 0, 1, 'åºç¨ç®¡ç', 'manage', 'Apps', 'index', 0, 1, NULL, 1, 0, 0, NULL, NULL),
(2, 1, 0, 1, 'åæ·ç®¡ç', 'manage', 'Company', 'index', 0, 3, NULL, 1, 0, 0, NULL, NULL),
(3, 1, 0, 1, 'åè½èå', 'manage', 'Apps', 'menu', 0, 2, NULL, 1, 0, 0, NULL, NULL),
(4, 1, 0, 1, 'ç¨æ·ç®¡ç', 'manage', 'Company', 'user', 0, 4, NULL, 1, 0, 0, NULL, NULL),
(5, 1, 0, 1, 'è§è²ç®¡ç', 'manage', 'Company', 'role', 0, 5, NULL, 1, 0, 0, NULL, NULL),
(6, 3, 3, 1, 'æ·»å ', 'manage', 'Apps', 'menus', 0, 1, 'layui-btn layui-btn-normal', 1, 0, 2, NULL, NULL),
(7, 3, 1, 1, 'æ·»å ', 'manage', 'Apps', 'addApp', 0, 1, 'layui-btn layui-btn-normal', 1, 0, 2, NULL, NULL),
(8, 2, 1, 1, 'ç¼è¾', 'manage', 'Apps', 'editApp', 0, 1, 'layui-btn layui-btn-xs', 1, 0, 2, NULL, NULL);
-- --------------------------------------------------------
--
-- 表çç»æ `cmf_common_user`
--
CREATE TABLE `cmf_common_user` (
`id` int(11) NOT NULL,
`account` char(50) NOT NULL COMMENT 'è´¦å·',
`name` char(30) NOT NULL COMMENT 'å§å',
`password` char(40) NOT NULL COMMENT 'å¯ç ',
`createTime` int(10) UNSIGNED NOT NULL COMMENT 'å建æ¶é´',
`roleId` int(11) NOT NULL COMMENT 'è§è²id',
`companyId` int(11) NOT NULL COMMENT 'åæ·id',
`phone` char(20) NOT NULL COMMENT 'çµè¯',
`createUserId` int(11) NOT NULL DEFAULT '0' COMMENT 'å建人id',
`loginErrorTimes` int(11) NOT NULL DEFAULT '0' COMMENT 'ç»å½é误次æ°',
`passwordExpiration` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'å¼å¯å¯ç è¿æ 0å¦ 1æ¯',
`modifyPasswordTime` int(10) UNSIGNED DEFAULT NULL COMMENT 'ä¿®æ¹å¯ç æ¶é´',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1æ£å¸¸ 0å°ç¦'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='åæ·ç¨æ·è¡¨';
--
-- 转å表ä¸çæ°æ® `cmf_common_user`
--
INSERT INTO `cmf_common_user` (`id`, `account`, `name`, `password`, `createTime`, `roleId`, `companyId`, `phone`, `createUserId`, `loginErrorTimes`, `passwordExpiration`, `modifyPasswordTime`, `status`) VALUES
(1, 'lxjez', 'æç¸æ±\', '462bf95cb00e1f620a8e1e7eab7f40cdb93701b5', 0, 1, 1, '', 1, 0, 0, NULL, 1);
-- --------------------------------------------------------
--
-- 表çç»æ `cmf_common_user_role`
--
CREATE TABLE `cmf_common_user_role` (
`id` int(11) NOT NULL,
`name` char(20) NOT NULL COMMENT 'è§è²åç§°',
`companyId` int(11) NOT NULL COMMENT 'åæ·id',
`apps` varchar(255) NOT NULL COMMENT 'å¯ç¨appid',
`menuId` text NOT NULL COMMENT 'è½ä½¿ç¨çåè½id',
`createTime` int(10) UNSIGNED NOT NULL COMMENT 'å建æ¶é´',
`createUserId` int(11) NOT NULL COMMENT 'å建人id',
`modifyUserId` int(11) DEFAULT NULL COMMENT 'ä¿®æ¹äººid'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='åæ·ç¨æ·è§è²è¡¨';
--
-- 转å表ä¸çæ°æ® `cmf_common_user_role`
--
INSERT INTO `cmf_common_user_role` (`id`, `name`, `companyId`, `apps`, `menuId`, `createTime`, `createUserId`, `modifyUserId`) VALUES
(1, 'è¶
级管çå\', 1, '', '', 0, 1, NULL);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `cmf_common_apps`
--
ALTER TABLE `cmf_common_apps`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `app` (`app`);
--
-- Indexes for table `cmf_common_company`
--
ALTER TABLE `cmf_common_company`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `cmf_common_menu`
--
ALTER TABLE `cmf_common_menu`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `app` (`app`,`controller`,`action`) USING BTREE;
--
-- Indexes for table `cmf_common_user`
--
ALTER TABLE `cmf_common_user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `account` (`account`);
--
-- Indexes for table `cmf_common_user_role`
--
ALTER TABLE `cmf_common_user_role`
ADD PRIMARY KEY (`id`);
--
-- å¨å¯¼åºç表使ç¨AUTO_INCREMENT
--
--
-- 使ç¨è¡¨AUTO_INCREMENT `cmf_common_apps`
--
ALTER TABLE `cmf_common_apps`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- 使ç¨è¡¨AUTO_INCREMENT `cmf_common_company`
--
ALTER TABLE `cmf_common_company`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- 使ç¨è¡¨AUTO_INCREMENT `cmf_common_menu`
--
ALTER TABLE `cmf_common_menu`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- 使ç¨è¡¨AUTO_INCREMENT `cmf_common_user`
--
ALTER TABLE `cmf_common_user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- 使ç¨è¡¨AUTO_INCREMENT `cmf_common_user_role`
--
ALTER TABLE `cmf_common_user_role`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
uej/EZ
|
sql_bk/test (7).sql
|
SQL
|
mit
| 8,984
|
uxtest
======
Python library for writing automated user interface non-regression tests with Sikuli.
|
egroise/uxtest
|
README.md
|
Markdown
|
mit
| 101
|
package io.dummymaker.util;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Contains basic date util methods and functions
*
* @author GoodforGod
* @since 25.02.2018
*/
public class DateUtils {
private static final Logger logger = LoggerFactory.getLogger(DateUtils.class);
private static final String ZONE_ID = "Europe/Moscow";
private DateUtils() {}
private static Calendar genCalendar() {
return Calendar.getInstance(TimeZone.getTimeZone(ZONE_ID));
}
public static Timestamp convertToTimestamp(final Date date) {
if (date == null)
return null;
final Calendar cal = genCalendar();
cal.setTime(date);
cal.set(Calendar.MILLISECOND, 0);
return new Timestamp(date.getTime());
}
public static Timestamp convertToTimestamp(final LocalDate localDate) {
return (localDate == null)
? null
: Timestamp.valueOf(localDate.atStartOfDay());
}
public static Timestamp convertToTimestamp(final LocalTime localTime) {
return (localTime == null)
? null
: Timestamp.valueOf(LocalDateTime.of(LocalDate.of(1970, 1, 1), localTime));
}
public static Timestamp convertToTimestamp(final LocalDateTime localDateTime) {
return (localDateTime == null)
? null
: Timestamp.valueOf(localDateTime);
}
public static Date parseSimpleDateLong(final String date) {
try {
return new Date(Long.parseLong(date));
} catch (NumberFormatException e) {
logger.warn(e.getMessage());
return null;
}
}
public static LocalDateTime parseDateTime(final String dateTime) {
try {
return LocalDateTime.parse(dateTime);
} catch (Exception e) {
logger.warn("Can not parse date time: {}", e.getMessage());
return null;
}
}
public static LocalTime parseTime(final String time) {
try {
return LocalTime.parse(time);
} catch (Exception e) {
logger.warn("Can not parse time: {}", e.getMessage());
return null;
}
}
public static LocalDate parseDate(final String date) {
try {
return LocalDate.parse(date);
} catch (Exception e) {
logger.warn("Can not parse date: {}", e.getMessage());
return null;
}
}
}
|
GoodforGod/dummymaker
|
src/main/java/io/dummymaker/util/DateUtils.java
|
Java
|
mit
| 2,676
|
require_relative 'base'
module OverpassAPI
# builds queries in overpass ql format
class QL < Base
def initialize(args = {})
super
@maxsize = args[:maxsize]
end
def build_query(query)
header = ''
header << "[bbox:#{@bbox}]" if @bbox
header << "[timeout:#{@timeout}]" if @timeout
header << "[maxsize:#{@maxsize}]" if @maxsize
header << '[out:json]'
"#{header};#{query}"
end
end
end
|
BrunoSalerno/overpass-api-ruby
|
lib/ql.rb
|
Ruby
|
mit
| 454
|
# polylock [](https://travis-ci.org/mwri/polylock) [](https://coveralls.io/github/mwri/polylock?branch=master)
Resource locking is not often a subject with Javascript/NodeJS, because
it is largely a single process asynchronous world. However async operations
can give rise to the same problems as threads, because all objects within
the scope of two or more async functions represent, in effect, shared data.
Polylock is a resource locking library that allows operations to block/wait
until the requested locks are granted, allowing
[critical sections](https://en.wikipedia.org/wiki/Critical_section) to be
made safe.
## Contents
1. [Promises example](#promises-example).
2. [Async/await example](#async-await-example).
3. [Callback example](#callback-example).
4. [Resource contention](#resource-contention).
## Promises example
A 'resource' is just a name, and can be read locked (shared), or write
locked (exclusive).
The basic formula for running a critical section to run, after locks are
granted is as follows:
```javascript
const polylock = require('polylock');
let resource_manager = new polylock();
resource_manager
.wait(locks)
.then((release) => {
// critical section here
release();
});
```
Here `locks` is an object where the keys are resource names and the
values are `read` or `write`. So `{'foo': 'read', 'bar': 'write'}`
would mean that a read lock on "foo" and a write lock on "bar"
must be granted, and `wait` returns a promise which resolves when
the locks are granted. It's then certified that nothing will change
"foo" and nothing will even look at "bar" in the critical section
until `release()` is called, which releases the locks.
A simple illustration of this is [promises_hello.js](./examples/promises_hello.js)
where three async operations are created (A, B and C) each artificially made to
take 2 seconds by way of `setTimeout`. Each async operation requires a write lock
on "resource_a" so they each have to take it in turns to run:
```javascript
const polylock = require('polylock');
let resource_manager = new polylock();
let start_ms = (new Date()).getTime();
console.log(`${new Date()} waiting A`);
resource_manager
.wait({'resource_a': 'write'})
.then((release) => {
console.log(`${new Date()} begin A`);
return new Promise((resolve) => {
setTimeout(resolve, 2000);
}).then(() => {
console.log(`${new Date()} end A`);
release();
});
});
console.log(`${new Date()} waiting B`);
resource_manager
.wait({'resource_a': 'write'})
.then((release) => {
console.log(`${new Date()} begin B`);
return new Promise((resolve) => {
setTimeout(resolve, 2000);
}).then(() => {
console.log(`${new Date()} end B`);
release();
});
});
console.log(`${new Date()} waiting C`);
resource_manager
.wait({'resource_a': 'write'})
.then((release) => {
console.log(`${new Date()} begin C`);
return new Promise((resolve) => {
setTimeout(resolve, 2000);
}).then(() => {
console.log(`${new Date()} end C`);
release();
});
});
```
The result is something like (each operation can only begin when
another one releases its locks):
```text
Sat Aug 03 2019 13:40:30 GMT+0100 (BST) waiting A
Sat Aug 03 2019 13:40:30 GMT+0100 (BST) waiting B
Sat Aug 03 2019 13:40:30 GMT+0100 (BST) waiting C
Sat Aug 03 2019 13:40:30 GMT+0100 (BST) begin A
Sat Aug 03 2019 13:40:32 GMT+0100 (BST) end A
Sat Aug 03 2019 13:40:32 GMT+0100 (BST) begin B
Sat Aug 03 2019 13:40:34 GMT+0100 (BST) end B
Sat Aug 03 2019 13:40:34 GMT+0100 (BST) begin C
Sat Aug 03 2019 13:40:36 GMT+0100 (BST) end C
```
A more extensive example with read and write locks on different
resources is [promises_more.js](./examples/promises_more.js).
The `critical_section` function is again a time delay time delay
using `setTimeout`, this time random 1-2 seconds. The `contended`
function waits for the required locks and then calls `critical_section`.
A `ts` function returns the number of milliseconds since the start, so
we can see more clearly what's going on. Finally, a set of results for
six contended operations, with various different locks required for
each, is accumulated, and when they are all complete the results are
displayed:
```javascript
const polylock = require('polylock');
let resource_manager = new polylock();
let start_ms = (new Date()).getTime();
let results = Promise.all([
contended({'resource_a': 'read', 'resource_b': 'write'}, 'A_read_B_write_1'),
contended({'resource_a': 'read', 'resource_b': 'write'}, 'A_read_B_write_2'),
contended({'resource_a': 'read', 'resource_b': 'write'}, 'A_read_B_write_3'),
contended({'resource_a': 'read', 'resource_c': 'write'}, 'A_read_C_write_4'),
contended({'resource_a': 'read', 'resource_d': 'write'}, 'A_read_D_write_5'),
contended({'resource_a': 'write', 'resource_e': 'read' }, 'A_write_E_read_6'),
]).then((results) => {
console.log(results);
});
function contended (locks, descr) {
console.log(`${ts()}\tWAIT\t${descr}\twaiting for locks`);
return resource_manager
.wait(locks)
.then((release) => {
console.log(`${ts()}\tGRANT\t${descr}\tlocks granted, starting critical section`);
return critical_section(descr)
.then((retval) => {
console.log(`${ts()}\tRELEASE\t${descr}\tlocks granted, starting critical section`);
release();
return retval;
});
});
}
function critical_section (descr) {
console.log(`${ts()}\tBEGIN\t${descr}\tstarting async operation`);
return new Promise((resolve) => {
setTimeout(
function () {
resolve(Math.floor(Math.random() * 100)),
console.log(`${ts()}\tCOMMIT\t${descr}\tfinished async operation`);
},
1000 + Math.floor(Math.random() * 1000)
);
}).then((retval) => {
return {
'operation': descr,
'result': retval,
};
});
}
function ts () {
return `${(new Date()).getTime() - start_ms}ms`;
}
```
If you run this, the result is as follows (timings will vary of course):
```text
0ms WAIT A_read_B_write_1 waiting for locks
2ms WAIT A_read_B_write_2 waiting for locks
2ms WAIT A_read_B_write_3 waiting for locks
2ms WAIT A_read_C_write_4 waiting for locks
2ms WAIT A_read_D_write_5 waiting for locks
2ms WAIT A_write_E_read_6 waiting for locks
3ms GRANT A_read_B_write_1 locks granted, starting critical section
3ms BEGIN A_read_B_write_1 starting async operation
3ms GRANT A_read_C_write_4 locks granted, starting critical section
3ms BEGIN A_read_C_write_4 starting async operation
3ms GRANT A_read_D_write_5 locks granted, starting critical section
3ms BEGIN A_read_D_write_5 starting async operation
1417ms COMMIT A_read_C_write_4 finished async operation
1417ms RELEASE A_read_C_write_4 critical section done, releasing locks
1691ms COMMIT A_read_B_write_1 finished async operation
1691ms RELEASE A_read_B_write_1 critical section done, releasing locks
1691ms GRANT A_read_B_write_2 locks granted, starting critical section
1691ms BEGIN A_read_B_write_2 starting async operation
1970ms COMMIT A_read_D_write_5 finished async operation
1970ms RELEASE A_read_D_write_5 critical section done, releasing locks
3352ms COMMIT A_read_B_write_2 finished async operation
3352ms RELEASE A_read_B_write_2 critical section done, releasing locks
3353ms GRANT A_read_B_write_3 locks granted, starting critical section
3353ms BEGIN A_read_B_write_3 starting async operation
4959ms COMMIT A_read_B_write_3 finished async operation
4959ms RELEASE A_read_B_write_3 critical section done, releasing locks
4959ms GRANT A_write_E_read_6 locks granted, starting critical section
4959ms BEGIN A_write_E_read_6 starting async operation
6306ms COMMIT A_write_E_read_6 finished async operation
6306ms RELEASE A_write_E_read_6 critical section done, releasing locks
[ { operation: 'A_read_B_write_1', result: 73 },
{ operation: 'A_read_B_write_2', result: 54 },
{ operation: 'A_read_B_write_3', result: 7 },
{ operation: 'A_read_C_write_4', result: 49 },
{ operation: 'A_read_D_write_5', result: 58 },
{ operation: 'A_write_E_read_6', result: 31 } ]
```
This clearly demonstrates the lock contention; all six operations immediately
begin waiting for locks, and operations *A_read_B_write_1*, *A_read_C_write_4*
and *A_read_D_write_5* immediately get their locks granted.
Operation *A_read_B_write_1* gets a grant simply because it was first, and
that means *A_read_B_write_2* and *A_read_B_write_3* can't be granted locks
because they both want a *write lock* on *resource_b*, which is why
*A_read_C_write_4* and *A_read_D_write_5* are next, since the only lock
in common with *A_read_B_write_1* is a *read lock* on *resource_a* and
read locks aren't exclusive.
In this example *A_read_C_write_4* finishes next, which allows no other
operation to have locks granted. Then *A_read_B_write_1* finishes, which
was holding the *write lock* on *resource_b*, so *A_read_B_write_2* is
immediately granted locks when this happens.
Next *A_read_D_write_5* finishes, then *A_read_B_write_2*, which allows
*A_read_B_write_3* to proceed (which was blocked waiting for a *write
lock* on *resource_b*).
Finally when *A_read_B_write_3* finishes *A_write_E_read_6* can get a
look in, after being blocked the whole time waiting for a *write lock*
on *resource_a* which has been tied up by every other operation getting
read locks on it.
This example is run in the unit tests, but with shorter timeouts (100ms
to 200ms instead of 1s to 2s).
## Async/await example
A 'resource' is just a name, and can be read locked (shared), or write
locked (exclusive).
The basic formula for running a critical section to run, after locks are
granted is as follows:
```javascript
const polylock = require('polylock');
let resource_manager = new polylock();
let release = resource_manager.wait(locks);
// critical section here
release();
```
Here `locks` is an object where the keys are resource names and the
values are `read` or `write`. So `{'foo': 'read', 'bar': 'write'}`
would mean that a read lock on "foo" and a write lock on "bar"
must be granted, and `wait` returns a promise which resolves when
the locks are granted. It's then certified that nothing will change
"foo" and nothing will even look at "bar" in the critical section
until `release()` is called, which releases the locks.
A simple illustration of this is [asyncawait_hello.js](./examples/asyncawait_hello.js)
where three async operations are created (A, B and C) each artificially made to
take 2 seconds by way of `setTimeout`. Each async operation requires a write lock
on "resource_a" so they each have to take it in turns to run:
```javascript
const polylock = require('polylock');
let resource_manager = new polylock();
let start_ms = (new Date()).getTime();
async function contend (op) {
console.log(`${new Date()} waiting ${op}`);
let release = await resource_manager.wait({'resource_a': 'write'});
console.log(`${new Date()} begin A`);
await new Promise((resolve) => setTimeout(resolve, 2000));
console.log(`${new Date()} end A`);
release();
}
contend('A');
contend('B');
contend('C');
```
The result is something like (each operation can only begin when
another one releases its locks):
```text
Sat Aug 03 2019 13:57:13 GMT+0100 (BST) waiting A
Sat Aug 03 2019 13:57:13 GMT+0100 (BST) waiting B
Sat Aug 03 2019 13:57:13 GMT+0100 (BST) waiting C
Sat Aug 03 2019 13:57:13 GMT+0100 (BST) begin A
Sat Aug 03 2019 13:57:15 GMT+0100 (BST) end A
Sat Aug 03 2019 13:57:15 GMT+0100 (BST) begin A
Sat Aug 03 2019 13:57:17 GMT+0100 (BST) end A
Sat Aug 03 2019 13:57:17 GMT+0100 (BST) begin A
Sat Aug 03 2019 13:57:19 GMT+0100 (BST) end A
```
A more extensive example with read and write locks on different
resources is [asyncawait_more.js](./examples/asyncawait_more.js).
The `critical_section` function is again a time delay time delay
using `setTimeout`, this time random 1-2 seconds. The `contended`
function waits for the required locks and then calls `critical_section`.
A `ts` function returns the number of milliseconds since the start, so
we can see more clearly what's going on. Finally, a set of results for
six contended operations, with various different locks required for
each, is accumulated, and when they are all complete the results are
displayed:
```javascript
const polylock = require('polylock');
let resource_manager = new polylock();
let start_ms = (new Date()).getTime();
let results = Promise.all([
contended({'resource_a': 'read', 'resource_b': 'write'}, 'A_read_B_write_1'),
contended({'resource_a': 'read', 'resource_b': 'write'}, 'A_read_B_write_2'),
contended({'resource_a': 'read', 'resource_b': 'write'}, 'A_read_B_write_3'),
contended({'resource_a': 'read', 'resource_c': 'write'}, 'A_read_C_write_4'),
contended({'resource_a': 'read', 'resource_d': 'write'}, 'A_read_D_write_5'),
contended({'resource_a': 'write', 'resource_e': 'read' }, 'A_write_E_read_6'),
]).then((results) => {
console.log(results);
});
async function contended (locks, descr) {
console.log(`${ts()}\tWAIT\t${descr}\twaiting for locks`);
let release = await resource_manager.wait(locks);
console.log(`${ts()}\tGRANT\t${descr}\tlocks granted, starting critical section`);
let result = await critical_section(descr);
console.log(`${ts()}\tRELEASE\t${descr}\tlocks granted, starting critical section`);
release();
return result;
}
async function critical_section (descr) {
console.log(`${ts()}\tBEGIN\t${descr}\tstarting async operation`);
await new Promise((resolve) => setTimeout(resolve, 1000 + Math.floor(Math.random() * 1000)));
console.log(`${ts()}\tCOMMIT\t${descr}\tfinished async operation`);
return {
'operation': descr,
'result': Math.floor(Math.random() * 100),
};
}
function ts () {
return `${(new Date()).getTime() - start_ms}ms`;
}
```
If you run this, the result is as follows (timings will vary of course):
```text
0ms WAIT A_read_B_write_1 waiting for locks
2ms WAIT A_read_B_write_2 waiting for locks
2ms WAIT A_read_B_write_3 waiting for locks
2ms WAIT A_read_C_write_4 waiting for locks
2ms WAIT A_read_D_write_5 waiting for locks
2ms WAIT A_write_E_read_6 waiting for locks
3ms GRANT A_read_B_write_1 locks granted, starting critical section
3ms BEGIN A_read_B_write_1 starting async operation
3ms GRANT A_read_C_write_4 locks granted, starting critical section
3ms BEGIN A_read_C_write_4 starting async operation
3ms GRANT A_read_D_write_5 locks granted, starting critical section
3ms BEGIN A_read_D_write_5 starting async operation
1417ms COMMIT A_read_C_write_4 finished async operation
1417ms RELEASE A_read_C_write_4 critical section done, releasing locks
1691ms COMMIT A_read_B_write_1 finished async operation
1691ms RELEASE A_read_B_write_1 critical section done, releasing locks
1691ms GRANT A_read_B_write_2 locks granted, starting critical section
1691ms BEGIN A_read_B_write_2 starting async operation
1970ms COMMIT A_read_D_write_5 finished async operation
1970ms RELEASE A_read_D_write_5 critical section done, releasing locks
3352ms COMMIT A_read_B_write_2 finished async operation
3352ms RELEASE A_read_B_write_2 critical section done, releasing locks
3353ms GRANT A_read_B_write_3 locks granted, starting critical section
3353ms BEGIN A_read_B_write_3 starting async operation
4959ms COMMIT A_read_B_write_3 finished async operation
4959ms RELEASE A_read_B_write_3 critical section done, releasing locks
4959ms GRANT A_write_E_read_6 locks granted, starting critical section
4959ms BEGIN A_write_E_read_6 starting async operation
6306ms COMMIT A_write_E_read_6 finished async operation
6306ms RELEASE A_write_E_read_6 critical section done, releasing locks
[ { operation: 'A_read_B_write_1', result: 73 },
{ operation: 'A_read_B_write_2', result: 54 },
{ operation: 'A_read_B_write_3', result: 7 },
{ operation: 'A_read_C_write_4', result: 49 },
{ operation: 'A_read_D_write_5', result: 58 },
{ operation: 'A_write_E_read_6', result: 31 } ]
```
This clearly demonstrates the lock contention; all six operations immediately
begin waiting for locks, and operations *A_read_B_write_1*, *A_read_C_write_4*
and *A_read_D_write_5* immediately get their locks granted.
Operation *A_read_B_write_1* gets a grant simply because it was first, and
that means *A_read_B_write_2* and *A_read_B_write_3* can't be granted locks
because they both want a *write lock* on *resource_b*, which is why
*A_read_C_write_4* and *A_read_D_write_5* are next, since the only lock
in common with *A_read_B_write_1* is a *read lock* on *resource_a* and
read locks aren't exclusive.
In this example *A_read_C_write_4* finishes next, which allows no other
operation to have locks granted. Then *A_read_B_write_1* finishes, which
was holding the *write lock* on *resource_b*, so *A_read_B_write_2* is
immediately granted locks when this happens.
Next *A_read_D_write_5* finishes, then *A_read_B_write_2*, which allows
*A_read_B_write_3* to proceed (which was blocked waiting for a *write
lock* on *resource_b*).
Finally when *A_read_B_write_3* finishes *A_write_E_read_6* can get a
look in, after being blocked the whole time waiting for a *write lock*
on *resource_a* which has been tied up by every other operation getting
read locks on it.
This example is run in the unit tests, but with shorter timeouts (100ms
to 200ms instead of 1s to 2s).
## Callback example
A 'resource' is just a name, and can be read locked (shared), or write
locked (exclusive).
The basic formula for running a critical section to run, after locks are
granted is as follows:
```javascript
const polylock = require('polylock');
let resource_manager = new polylock();
let release = resource_manager.exec(callback, locks);
function callback () {
// critical section in this function
}
```
Here `locks` is an object where the keys are resource names and the
values are `read` or `write`. So `{'foo': 'read', 'bar': 'write'}`
would mean that a read lock on "foo" and a write lock on "bar"
must be granted, and `callback` is a function which is called when
the locks are granted. It's then certified that nothing will change
"foo" and nothing will even look at "bar" until `callback` returns.
Unlike the promises based formats, no release function is required
because the locks are released when the `callback` function returns.
A simple illustration of this is [callback_hello.js](./examples/callback_hello.js)
where three async operations are created (A, B and C) each artificially made to
take 2 seconds by way of `setTimeout`. Each async operation requires a write lock
on "resource_a" so they each have to take it in turns to run:
```javascript
const polylock = require('polylock');
let resource_manager = new polylock();
let start_ms = (new Date()).getTime();
console.log(`${new Date()} waiting A`);
resource_manager.exec(
function (done, fail) {
console.log(`${new Date()} begin A`);
setTimeout(function () {
console.log(`${new Date()} end A`);
done();
}, 2000);
},
{'resource_a': 'write'}
);
console.log(`${new Date()} waiting B`);
resource_manager.exec(
function (done, fail) {
console.log(`${new Date()} begin B`);
setTimeout(function () {
console.log(`${new Date()} end B`);
done();
}, 2000);
},
{'resource_a': 'write'}
);
console.log(`${new Date()} waiting C`);
resource_manager.exec(
function (done, fail) {
console.log(`${new Date()} begin C`);
setTimeout(function () {
console.log(`${new Date()} end C`);
done();
}, 2000);
},
{'resource_a': 'write'}
);
```
The result is something like (each operation can only begin when
another one releases its locks):
```text
Sat Aug 03 2019 14:14:03 GMT+0100 (BST) waiting A
Sat Aug 03 2019 14:14:03 GMT+0100 (BST) begin A
Sat Aug 03 2019 14:14:03 GMT+0100 (BST) waiting B
Sat Aug 03 2019 14:14:03 GMT+0100 (BST) waiting C
Sat Aug 03 2019 14:14:05 GMT+0100 (BST) end A
Sat Aug 03 2019 14:14:05 GMT+0100 (BST) begin B
Sat Aug 03 2019 14:14:07 GMT+0100 (BST) end B
Sat Aug 03 2019 14:14:07 GMT+0100 (BST) begin C
Sat Aug 03 2019 14:14:09 GMT+0100 (BST) end C
```
A more extensive example with read and write locks on different
resources is [asyncawait_more.js](./examples/asyncawait_more.js).
The `critical_section` function is again a time delay time delay
using `setTimeout`, this time random 1-2 seconds. The `contended`
function waits for the required locks and then calls `critical_section`.
A `ts` function returns the number of milliseconds since the start, so
we can see more clearly what's going on. Finally, a set of results for
six contended operations, with various different locks required for
each, is accumulated, and when they are all complete the results are
displayed:
```javascript
const polylock = require('polylock');
let resource_manager = new polylock();
let start_ms = (new Date()).getTime();
contended({'resource_a': 'read', 'resource_b': 'write'}, 'A_read_B_write_1');
contended({'resource_a': 'read', 'resource_b': 'write'}, 'A_read_B_write_2');
contended({'resource_a': 'read', 'resource_b': 'write'}, 'A_read_B_write_3');
contended({'resource_a': 'read', 'resource_c': 'write'}, 'A_read_C_write_4');
contended({'resource_a': 'read', 'resource_d': 'write'}, 'A_read_D_write_5');
contended({'resource_a': 'write', 'resource_e': 'read' }, 'A_write_E_read_6');
function contended (locks, descr) {
console.log(`${ts()}\tWAIT\t${descr}\twaiting for locks`);
return resource_manager.exec(critical_section.bind(undefined, descr), locks);
}
function critical_section (descr, done, fail) {
console.log(`${ts()}\tGRANT\t${descr}\tlocks granted, starting critical section`);
console.log(`${ts()}\tBEGIN\t${descr}\tstarting async operation`);
setTimeout(
function () {
console.log(`${ts()}\tCOMMIT\t${descr}\tfinished async operation`);
console.log({
'operation': descr,
'result': Math.floor(Math.random() * 100),
});
done();
console.log(`${ts()}\tRELEASE\t${descr}\treturning, locks will be released`);
},
1000 + Math.floor(Math.random() * 1000)
);
}
function ts () {
return `${(new Date()).getTime() - start_ms}ms`;
}
```
Unlike the promise versions, the result set is not accumulated
because there is no return chain as such, though, if you want you
can employ a hybrid to get a return value, because `exec` actually
does return a promise which is resolved to the value that that
`callback` passes to `done`.
Running this, the result is as follows (timings will vary of course):
```text
0ms WAIT A_read_B_write_1 waiting for locks
2ms GRANT A_read_B_write_1 locks granted, starting critical section
2ms BEGIN A_read_B_write_1 starting async operation
2ms WAIT A_read_B_write_2 waiting for locks
2ms WAIT A_read_B_write_3 waiting for locks
3ms WAIT A_read_C_write_4 waiting for locks
3ms GRANT A_read_C_write_4 locks granted, starting critical section
3ms BEGIN A_read_C_write_4 starting async operation
3ms WAIT A_read_D_write_5 waiting for locks
3ms GRANT A_read_D_write_5 locks granted, starting critical section
3ms BEGIN A_read_D_write_5 starting async operation
3ms WAIT A_write_E_read_6 waiting for locks
1501ms COMMIT A_read_C_write_4 finished async operation
{ operation: 'A_read_C_write_4', result: 64 }
1504ms RELEASE A_read_C_write_4 returning, locks will be released
1625ms COMMIT A_read_B_write_1 finished async operation
{ operation: 'A_read_B_write_1', result: 79 }
1625ms RELEASE A_read_B_write_1 returning, locks will be released
1625ms GRANT A_read_B_write_2 locks granted, starting critical section
1625ms BEGIN A_read_B_write_2 starting async operation
1839ms COMMIT A_read_D_write_5 finished async operation
{ operation: 'A_read_D_write_5', result: 23 }
1840ms RELEASE A_read_D_write_5 returning, locks will be released
3626ms COMMIT A_read_B_write_2 finished async operation
{ operation: 'A_read_B_write_2', result: 34 }
3626ms RELEASE A_read_B_write_2 returning, locks will be released
3626ms GRANT A_read_B_write_3 locks granted, starting critical section
3626ms BEGIN A_read_B_write_3 starting async operation
4843ms COMMIT A_read_B_write_3 finished async operation
{ operation: 'A_read_B_write_3', result: 84 }
4843ms RELEASE A_read_B_write_3 returning, locks will be released
4844ms GRANT A_write_E_read_6 locks granted, starting critical section
4844ms BEGIN A_write_E_read_6 starting async operation
6109ms COMMIT A_write_E_read_6 finished async operation
{ operation: 'A_write_E_read_6', result: 85 }
6109ms RELEASE A_write_E_read_6 returning, locks will be released
```
This clearly demonstrates the lock contention; all six operations immediately
begin waiting for locks, and operations *A_read_B_write_1*, *A_read_C_write_4*
and *A_read_D_write_5* immediately get their locks granted.
Operation *A_read_B_write_1* gets a grant simply because it was first, and
that means *A_read_B_write_2* and *A_read_B_write_3* can't be granted locks
because they both want a *write lock* on *resource_b*, which is why
*A_read_C_write_4* and *A_read_D_write_5* are next, since the only lock
in common with *A_read_B_write_1* is a *read lock* on *resource_a* and
read locks aren't exclusive.
In this example *A_read_C_write_4* finishes next, which allows no other
operation to have locks granted. Then *A_read_B_write_1* finishes, which
was holding the *write lock* on *resource_b*, so *A_read_B_write_2* is
immediately granted locks when this happens.
Next *A_read_D_write_5* finishes, then *A_read_B_write_2*, which allows
*A_read_B_write_3* to proceed (which was blocked waiting for a *write
lock* on *resource_b*).
Finally when *A_read_B_write_3* finishes *A_write_E_read_6* can get a
look in, after being blocked the whole time waiting for a *write lock*
on *resource_a* which has been tied up by every other operation getting
read locks on it.
This example is run in the unit tests, but with shorter timeouts (100ms
to 200ms instead of 1s to 2s).
If your operation is purely synchronous (indicated by accepting no
arguments) it can return the result instead of calling `done`, like this:
```javascript
resource_manager.exec(
function () {
// locks have been granted
console.log("starting operation");
console.log("finishing operation");
return retval;
// locks are released
},
{'resource_a': 'read', 'resource_b': 'write'}
);
```
## Resource contention
There is no limit to the number of resources that may be locked at
once, though more resources all contended may make lock grants more
difficult and operations that require a lot of locks on many different
resources may wait longer whilst they are kept out by many other less
greedy operations claiming locks in a continuous overlapping stream.
Write locks are especially vulnerable to being locked out since they
must wait for there to be no read locks on any of the resources they
are writing. For this reason there is a 'write priority' mode which
may be enabled like this:
```javascript
let resource_manager = new polylock({'write_priority': true});
```
When enabled, once a write lock on a resource has been requested no
more read locks will be granted on it, thus existing operations with
read locks will gradually complete and the write lock may then be
granted at the earliest possible time.
This will of course increase the average wait time for read locks
but in some cases this will only be a slight increase in return for
a (sometimes) huge improvement in write latency.
The unit tests create scenarios to test this; tests/compound.js runs
800 operations which randomly lock three resources read and write
for various times, here's a (currently) typical result:
```
INFO LOG: '800 ops read priority 58 max concurrent 9ms average read wait 324ms average write wait'
INFO LOG: '800 ops read priority 59 max concurrent 9ms average read wait 324ms average write wait'
INFO LOG: '800 ops write priority 37 max concurrent 10ms average read wait 48ms average write wait'
```
Here read operation wait times go from 9ms to 10ms but write
operation wait times are almost seven times smaller. The load is
random so results will vary each time but more or less inevitably
in this case read wait times will increase and write wait times
will decrease.
The 'max concurrent' figure is the maximum number of operations
running in parallel during the test, and sometimes write priority
results in higher peaks, sometimes lower.
|
mwri/polylock
|
README.md
|
Markdown
|
mit
| 30,126
|
/*
* ngtcp2
*
* Copyright (c) 2022 ngtcp2 contributors
*
* 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.
*/
#ifndef NGTCP2_OBJALLOC_H
#define NGTCP2_OBJALLOC_H
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
#include <ngtcp2/ngtcp2.h>
#include "ngtcp2_balloc.h"
#include "ngtcp2_opl.h"
#include "ngtcp2_macro.h"
#include "ngtcp2_mem.h"
/*
* ngtcp2_objalloc combines ngtcp2_balloc and ngtcp2_opl, and provides
* an object pool with the custom allocator to reduce the allocation
* and deallocation overheads for small objects.
*/
typedef struct ngtcp2_objalloc {
ngtcp2_balloc balloc;
ngtcp2_opl opl;
} ngtcp2_objalloc;
/*
* ngtcp2_objalloc_init initializes |objalloc|. |blklen| is directly
* passed to ngtcp2_balloc_init.
*/
void ngtcp2_objalloc_init(ngtcp2_objalloc *objalloc, size_t blklen,
const ngtcp2_mem *mem);
/*
* ngtcp2_objalloc_free releases all allocated resources.
*/
void ngtcp2_objalloc_free(ngtcp2_objalloc *objalloc);
/*
* ngtcp2_objalloc_clear releases all allocated resources and
* initializes its state.
*/
void ngtcp2_objalloc_clear(ngtcp2_objalloc *objalloc);
#ifndef NOMEMPOOL
# define ngtcp2_objalloc_def(NAME, TYPE, OPLENTFIELD) \
inline static void ngtcp2_objalloc_##NAME##_init( \
ngtcp2_objalloc *objalloc, size_t nmemb, const ngtcp2_mem *mem) { \
ngtcp2_objalloc_init(objalloc, \
((sizeof(TYPE) + 0xfllu) & ~0xfllu) * nmemb, mem); \
} \
\
inline static TYPE *ngtcp2_objalloc_##NAME##_get( \
ngtcp2_objalloc *objalloc) { \
ngtcp2_opl_entry *oplent = ngtcp2_opl_pop(&objalloc->opl); \
TYPE *obj; \
int rv; \
\
if (!oplent) { \
rv = \
ngtcp2_balloc_get(&objalloc->balloc, (void **)&obj, sizeof(TYPE)); \
if (rv != 0) { \
return NULL; \
} \
\
return obj; \
} \
\
return ngtcp2_struct_of(oplent, TYPE, OPLENTFIELD); \
} \
\
inline static TYPE *ngtcp2_objalloc_##NAME##_len_get( \
ngtcp2_objalloc *objalloc, size_t len) { \
ngtcp2_opl_entry *oplent = ngtcp2_opl_pop(&objalloc->opl); \
TYPE *obj; \
int rv; \
\
if (!oplent) { \
rv = ngtcp2_balloc_get(&objalloc->balloc, (void **)&obj, len); \
if (rv != 0) { \
return NULL; \
} \
\
return obj; \
} \
\
return ngtcp2_struct_of(oplent, TYPE, OPLENTFIELD); \
} \
\
inline static void ngtcp2_objalloc_##NAME##_release( \
ngtcp2_objalloc *objalloc, TYPE *obj) { \
ngtcp2_opl_push(&objalloc->opl, &obj->OPLENTFIELD); \
}
#else /* NOMEMPOOL */
# define ngtcp2_objalloc_def(NAME, TYPE, OPLENTFIELD) \
inline static void ngtcp2_objalloc_##NAME##_init( \
ngtcp2_objalloc *objalloc, size_t nmemb, const ngtcp2_mem *mem) { \
ngtcp2_objalloc_init(objalloc, \
((sizeof(TYPE) + 0xfllu) & ~0xfllu) * nmemb, mem); \
} \
\
inline static TYPE *ngtcp2_objalloc_##NAME##_get( \
ngtcp2_objalloc *objalloc) { \
return ngtcp2_mem_malloc(objalloc->balloc.mem, sizeof(TYPE)); \
} \
\
inline static TYPE *ngtcp2_objalloc_##NAME##_len_get( \
ngtcp2_objalloc *objalloc, size_t len) { \
return ngtcp2_mem_malloc(objalloc->balloc.mem, len); \
} \
\
inline static void ngtcp2_objalloc_##NAME##_release( \
ngtcp2_objalloc *objalloc, TYPE *obj) { \
ngtcp2_mem_free(objalloc->balloc.mem, obj); \
}
#endif /* NOMEMPOOL */
#endif /* NGTCP2_OBJALLOC_H */
|
ngtcp2/ngtcp2
|
lib/ngtcp2_objalloc.h
|
C
|
mit
| 7,719
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_13) on Mon Dec 14 15:25:07 MSK 2009 -->
<TITLE>
Uses of Class org.apache.poi.hssf.usermodel.HSSFFontFormatting (POI API Documentation)
</TITLE>
<META NAME="date" CONTENT="2009-12-14">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.hssf.usermodel.HSSFFontFormatting (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hssf/usermodel/HSSFFontFormatting.html" title="class in org.apache.poi.hssf.usermodel"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hssf/usermodel/\class-useHSSFFontFormatting.html" target="_top"><B>FRAMES</B></A>
<A HREF="HSSFFontFormatting.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.hssf.usermodel.HSSFFontFormatting</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/poi/hssf/usermodel/HSSFFontFormatting.html" title="class in org.apache.poi.hssf.usermodel">HSSFFontFormatting</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.hssf.usermodel"><B>org.apache.poi.hssf.usermodel</B></A></TD>
<TD>usermodel package maps HSSF low level strutures to familiar workbook/sheet model </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.hssf.usermodel"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/poi/hssf/usermodel/HSSFFontFormatting.html" title="class in org.apache.poi.hssf.usermodel">HSSFFontFormatting</A> in <A HREF="../../../../../../org/apache/poi/hssf/usermodel/package-summary.html">org.apache.poi.hssf.usermodel</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/poi/hssf/usermodel/package-summary.html">org.apache.poi.hssf.usermodel</A> that return <A HREF="../../../../../../org/apache/poi/hssf/usermodel/HSSFFontFormatting.html" title="class in org.apache.poi.hssf.usermodel">HSSFFontFormatting</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/poi/hssf/usermodel/HSSFFontFormatting.html" title="class in org.apache.poi.hssf.usermodel">HSSFFontFormatting</A></CODE></FONT></TD>
<TD><CODE><B>HSSFConditionalFormattingRule.</B><B><A HREF="../../../../../../org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.html#createFontFormatting()">createFontFormatting</A></B>()</CODE>
<BR>
create a new font formatting structure if it does not exist,
otherwise just return existing object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/poi/hssf/usermodel/HSSFFontFormatting.html" title="class in org.apache.poi.hssf.usermodel">HSSFFontFormatting</A></CODE></FONT></TD>
<TD><CODE><B>HSSFConditionalFormattingRule.</B><B><A HREF="../../../../../../org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.html#getFontFormatting()">getFontFormatting</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hssf/usermodel/HSSFFontFormatting.html" title="class in org.apache.poi.hssf.usermodel"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hssf/usermodel/\class-useHSSFFontFormatting.html" target="_top"><B>FRAMES</B></A>
<A HREF="HSSFFontFormatting.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2009 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
|
tobyclemson/msci-project
|
vendor/poi-3.6/doc/apidocs/org/apache/poi/hssf/usermodel/class-use/HSSFFontFormatting.html
|
HTML
|
mit
| 9,218
|
# Measure core temperature
- https://medium.com/@kevalpatel2106/monitor-the-core-temperature-of-your-raspberry-pi-3ddfdf82989f
~~~~
/opt/vc/bin/vcgencmd measure_temp
~~~~
|
denglert/manuals
|
unix/os/raspbian/temperature.md
|
Markdown
|
mit
| 173
|
/*
RequireJS 2.1.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
Available via the MIT or new BSD license.
see: http://github.com/jrburke/requirejs for details
*/
var requirejs,require,define;
(function(global){var req,s,head,baseElement,dataMain,src,interactiveScript,currentlyAddingScript,mainScript,subPath,version="2.1.6",commentRegExp=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,cjsRequireRegExp=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,jsSuffixRegExp=/\.js$/,currDirRegExp=/^\.\//,op=Object.prototype,ostring=op.toString,hasOwn=op.hasOwnProperty,ap=Array.prototype,apsp=ap.splice,isBrowser=!!(typeof window!=="undefined"&&navigator&&window.document),isWebWorker=!isBrowser&&typeof importScripts!==
"undefined",readyRegExp=isBrowser&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,defContextName="_",isOpera=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",contexts={},cfg={},globalDefQueue=[],useInteractive=false;function isFunction(it){return ostring.call(it)==="[object Function]"}function isArray(it){return ostring.call(it)==="[object Array]"}function each(ary,func){if(ary){var i;for(i=0;i<ary.length;i+=1)if(ary[i]&&func(ary[i],i,ary))break}}function eachReverse(ary,
func){if(ary){var i;for(i=ary.length-1;i>-1;i-=1)if(ary[i]&&func(ary[i],i,ary))break}}function hasProp(obj,prop){return hasOwn.call(obj,prop)}function getOwn(obj,prop){return hasProp(obj,prop)&&obj[prop]}function eachProp(obj,func){var prop;for(prop in obj)if(hasProp(obj,prop))if(func(obj[prop],prop))break}function mixin(target,source,force,deepStringMixin){if(source)eachProp(source,function(value,prop){if(force||!hasProp(target,prop))if(deepStringMixin&&typeof value!=="string"){if(!target[prop])target[prop]=
{};mixin(target[prop],value,force,deepStringMixin)}else target[prop]=value});return target}function bind(obj,fn){return function(){return fn.apply(obj,arguments)}}function scripts(){return document.getElementsByTagName("script")}function defaultOnError(err){throw err;}function getGlobal(value){if(!value)return value;var g=global;each(value.split("."),function(part){g=g[part]});return g}function makeError(id,msg,err,requireModules){var e=new Error(msg+"\nhttp://requirejs.org/docs/errors.html#"+id);
e.requireType=id;e.requireModules=requireModules;if(err)e.originalError=err;return e}if(typeof define!=="undefined")return;if(typeof requirejs!=="undefined"){if(isFunction(requirejs))return;cfg=requirejs;requirejs=undefined}if(typeof require!=="undefined"&&!isFunction(require)){cfg=require;require=undefined}function newContext(contextName){var inCheckLoaded,Module,context,handlers,checkLoadedTimeoutId,config={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},shim:{},config:{}},registry={},enabledRegistry=
{},undefEvents={},defQueue=[],defined={},urlFetched={},requireCounter=1,unnormalizedCounter=1;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part==="..")if(i===1&&(ary[2]===".."||ary[0]===".."))break;else if(i>0){ary.splice(i-1,2);i-=2}}}function normalize(name,baseName,applyMap){var pkgName,pkgConfig,mapValue,nameParts,i,j,nameSegment,foundMap,foundI,foundStarMap,starI,baseParts=baseName&&baseName.split("/"),normalizedBaseParts=baseParts,
map=config.map,starMap=map&&map["*"];if(name&&name.charAt(0)===".")if(baseName){if(getOwn(config.pkgs,baseName))normalizedBaseParts=baseParts=[baseName];else normalizedBaseParts=baseParts.slice(0,baseParts.length-1);name=normalizedBaseParts.concat(name.split("/"));trimDots(name);pkgConfig=getOwn(config.pkgs,pkgName=name[0]);name=name.join("/");if(pkgConfig&&name===pkgName+"/"+pkgConfig.main)name=pkgName}else if(name.indexOf("./")===0)name=name.substring(2);if(applyMap&&map&&(baseParts||starMap)){nameParts=
name.split("/");for(i=nameParts.length;i>0;i-=1){nameSegment=nameParts.slice(0,i).join("/");if(baseParts)for(j=baseParts.length;j>0;j-=1){mapValue=getOwn(map,baseParts.slice(0,j).join("/"));if(mapValue){mapValue=getOwn(mapValue,nameSegment);if(mapValue){foundMap=mapValue;foundI=i;break}}}if(foundMap)break;if(!foundStarMap&&starMap&&getOwn(starMap,nameSegment)){foundStarMap=getOwn(starMap,nameSegment);starI=i}}if(!foundMap&&foundStarMap){foundMap=foundStarMap;foundI=starI}if(foundMap){nameParts.splice(0,
foundI,foundMap);name=nameParts.join("/")}}return name}function removeScript(name){if(isBrowser)each(scripts(),function(scriptNode){if(scriptNode.getAttribute("data-requiremodule")===name&&scriptNode.getAttribute("data-requirecontext")===context.contextName){scriptNode.parentNode.removeChild(scriptNode);return true}})}function hasPathFallback(id){var pathConfig=getOwn(config.paths,id);if(pathConfig&&isArray(pathConfig)&&pathConfig.length>1){removeScript(id);pathConfig.shift();context.require.undef(id);
context.require([id]);return true}}function splitPrefix(name){var prefix,index=name?name.indexOf("!"):-1;if(index>-1){prefix=name.substring(0,index);name=name.substring(index+1,name.length)}return[prefix,name]}function makeModuleMap(name,parentModuleMap,isNormalized,applyMap){var url,pluginModule,suffix,nameParts,prefix=null,parentName=parentModuleMap?parentModuleMap.name:null,originalName=name,isDefine=true,normalizedName="";if(!name){isDefine=false;name="_@r"+(requireCounter+=1)}nameParts=splitPrefix(name);
prefix=nameParts[0];name=nameParts[1];if(prefix){prefix=normalize(prefix,parentName,applyMap);pluginModule=getOwn(defined,prefix)}if(name)if(prefix)if(pluginModule&&pluginModule.normalize)normalizedName=pluginModule.normalize(name,function(name){return normalize(name,parentName,applyMap)});else normalizedName=normalize(name,parentName,applyMap);else{normalizedName=normalize(name,parentName,applyMap);nameParts=splitPrefix(normalizedName);prefix=nameParts[0];normalizedName=nameParts[1];isNormalized=
true;url=context.nameToUrl(normalizedName)}suffix=prefix&&!pluginModule&&!isNormalized?"_unnormalized"+(unnormalizedCounter+=1):"";return{prefix:prefix,name:normalizedName,parentMap:parentModuleMap,unnormalized:!!suffix,url:url,originalName:originalName,isDefine:isDefine,id:(prefix?prefix+"!"+normalizedName:normalizedName)+suffix}}function getModule(depMap){var id=depMap.id,mod=getOwn(registry,id);if(!mod)mod=registry[id]=new context.Module(depMap);return mod}function on(depMap,name,fn){var id=depMap.id,
mod=getOwn(registry,id);if(hasProp(defined,id)&&(!mod||mod.defineEmitComplete)){if(name==="defined")fn(defined[id])}else{mod=getModule(depMap);if(mod.error&&name==="error")fn(mod.error);else mod.on(name,fn)}}function onError(err,errback){var ids=err.requireModules,notified=false;if(errback)errback(err);else{each(ids,function(id){var mod=getOwn(registry,id);if(mod){mod.error=err;if(mod.events.error){notified=true;mod.emit("error",err)}}});if(!notified)req.onError(err)}}function takeGlobalQueue(){if(globalDefQueue.length){apsp.apply(defQueue,
[defQueue.length-1,0].concat(globalDefQueue));globalDefQueue=[]}}handlers={"require":function(mod){if(mod.require)return mod.require;else return mod.require=context.makeRequire(mod.map)},"exports":function(mod){mod.usingExports=true;if(mod.map.isDefine)if(mod.exports)return mod.exports;else return mod.exports=defined[mod.map.id]={}},"module":function(mod){if(mod.module)return mod.module;else return mod.module={id:mod.map.id,uri:mod.map.url,config:function(){var c,pkg=getOwn(config.pkgs,mod.map.id);
c=pkg?getOwn(config.config,mod.map.id+"/"+pkg.main):getOwn(config.config,mod.map.id);return c||{}},exports:defined[mod.map.id]}}};function cleanRegistry(id){delete registry[id];delete enabledRegistry[id]}function breakCycle(mod,traced,processed){var id=mod.map.id;if(mod.error)mod.emit("error",mod.error);else{traced[id]=true;each(mod.depMaps,function(depMap,i){var depId=depMap.id,dep=getOwn(registry,depId);if(dep&&!mod.depMatched[i]&&!processed[depId])if(getOwn(traced,depId)){mod.defineDep(i,defined[depId]);
mod.check()}else breakCycle(dep,traced,processed)});processed[id]=true}}function checkLoaded(){var map,modId,err,usingPathFallback,waitInterval=config.waitSeconds*1E3,expired=waitInterval&&context.startTime+waitInterval<(new Date).getTime(),noLoads=[],reqCalls=[],stillLoading=false,needCycleCheck=true;if(inCheckLoaded)return;inCheckLoaded=true;eachProp(enabledRegistry,function(mod){map=mod.map;modId=map.id;if(!mod.enabled)return;if(!map.isDefine)reqCalls.push(mod);if(!mod.error)if(!mod.inited&&expired)if(hasPathFallback(modId)){usingPathFallback=
true;stillLoading=true}else{noLoads.push(modId);removeScript(modId)}else if(!mod.inited&&mod.fetched&&map.isDefine){stillLoading=true;if(!map.prefix)return needCycleCheck=false}});if(expired&&noLoads.length){err=makeError("timeout","Load timeout for modules: "+noLoads,null,noLoads);err.contextName=context.contextName;return onError(err)}if(needCycleCheck)each(reqCalls,function(mod){breakCycle(mod,{},{})});if((!expired||usingPathFallback)&&stillLoading)if((isBrowser||isWebWorker)&&!checkLoadedTimeoutId)checkLoadedTimeoutId=
setTimeout(function(){checkLoadedTimeoutId=0;checkLoaded()},50);inCheckLoaded=false}Module=function(map){this.events=getOwn(undefEvents,map.id)||{};this.map=map;this.shim=getOwn(config.shim,map.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};Module.prototype={init:function(depMaps,factory,errback,options){options=options||{};if(this.inited)return;this.factory=factory;if(errback)this.on("error",errback);else if(this.events.error)errback=bind(this,function(err){this.emit("error",
err)});this.depMaps=depMaps&&depMaps.slice(0);this.errback=errback;this.inited=true;this.ignore=options.ignore;if(options.enabled||this.enabled)this.enable();else this.check()},defineDep:function(i,depExports){if(!this.depMatched[i]){this.depMatched[i]=true;this.depCount-=1;this.depExports[i]=depExports}},fetch:function(){if(this.fetched)return;this.fetched=true;context.startTime=(new Date).getTime();var map=this.map;if(this.shim)context.makeRequire(this.map,{enableBuildCallback:true})(this.shim.deps||
[],bind(this,function(){return map.prefix?this.callPlugin():this.load()}));else return map.prefix?this.callPlugin():this.load()},load:function(){var url=this.map.url;if(!urlFetched[url]){urlFetched[url]=true;context.load(this.map.id,url)}},check:function(){if(!this.enabled||this.enabling)return;var err,cjsModule,id=this.map.id,depExports=this.depExports,exports=this.exports,factory=this.factory;if(!this.inited)this.fetch();else if(this.error)this.emit("error",this.error);else if(!this.defining){this.defining=
true;if(this.depCount<1&&!this.defined){if(isFunction(factory)){if(this.events.error&&this.map.isDefine||req.onError!==defaultOnError)try{exports=context.execCb(id,factory,depExports,exports)}catch(e){err=e}else exports=context.execCb(id,factory,depExports,exports);if(this.map.isDefine){cjsModule=this.module;if(cjsModule&&cjsModule.exports!==undefined&&cjsModule.exports!==this.exports)exports=cjsModule.exports;else if(exports===undefined&&this.usingExports)exports=this.exports}if(err){err.requireMap=
this.map;err.requireModules=this.map.isDefine?[this.map.id]:null;err.requireType=this.map.isDefine?"define":"require";return onError(this.error=err)}}else exports=factory;this.exports=exports;if(this.map.isDefine&&!this.ignore){defined[id]=exports;if(req.onResourceLoad)req.onResourceLoad(context,this.map,this.depMaps)}cleanRegistry(id);this.defined=true}this.defining=false;if(this.defined&&!this.defineEmitted){this.defineEmitted=true;this.emit("defined",this.exports);this.defineEmitComplete=true}}},
callPlugin:function(){var map=this.map,id=map.id,pluginMap=makeModuleMap(map.prefix);this.depMaps.push(pluginMap);on(pluginMap,"defined",bind(this,function(plugin){var load,normalizedMap,normalizedMod,name=this.map.name,parentName=this.map.parentMap?this.map.parentMap.name:null,localRequire=context.makeRequire(map.parentMap,{enableBuildCallback:true});if(this.map.unnormalized){if(plugin.normalize)name=plugin.normalize(name,function(name){return normalize(name,parentName,true)})||"";normalizedMap=
makeModuleMap(map.prefix+"!"+name,this.map.parentMap);on(normalizedMap,"defined",bind(this,function(value){this.init([],function(){return value},null,{enabled:true,ignore:true})}));normalizedMod=getOwn(registry,normalizedMap.id);if(normalizedMod){this.depMaps.push(normalizedMap);if(this.events.error)normalizedMod.on("error",bind(this,function(err){this.emit("error",err)}));normalizedMod.enable()}return}load=bind(this,function(value){this.init([],function(){return value},null,{enabled:true})});load.error=
bind(this,function(err){this.inited=true;this.error=err;err.requireModules=[id];eachProp(registry,function(mod){if(mod.map.id.indexOf(id+"_unnormalized")===0)cleanRegistry(mod.map.id)});onError(err)});load.fromText=bind(this,function(text,textAlt){var moduleName=map.name,moduleMap=makeModuleMap(moduleName),hasInteractive=useInteractive;if(textAlt)text=textAlt;if(hasInteractive)useInteractive=false;getModule(moduleMap);if(hasProp(config.config,id))config.config[moduleName]=config.config[id];try{req.exec(text)}catch(e){return onError(makeError("fromtexteval",
"fromText eval for "+id+" failed: "+e,e,[id]))}if(hasInteractive)useInteractive=true;this.depMaps.push(moduleMap);context.completeLoad(moduleName);localRequire([moduleName],load)});plugin.load(map.name,localRequire,load,config)}));context.enable(pluginMap,this);this.pluginMaps[pluginMap.id]=pluginMap},enable:function(){enabledRegistry[this.map.id]=this;this.enabled=true;this.enabling=true;each(this.depMaps,bind(this,function(depMap,i){var id,mod,handler;if(typeof depMap==="string"){depMap=makeModuleMap(depMap,
this.map.isDefine?this.map:this.map.parentMap,false,!this.skipMap);this.depMaps[i]=depMap;handler=getOwn(handlers,depMap.id);if(handler){this.depExports[i]=handler(this);return}this.depCount+=1;on(depMap,"defined",bind(this,function(depExports){this.defineDep(i,depExports);this.check()}));if(this.errback)on(depMap,"error",bind(this,this.errback))}id=depMap.id;mod=registry[id];if(!hasProp(handlers,id)&&mod&&!mod.enabled)context.enable(depMap,this)}));eachProp(this.pluginMaps,bind(this,function(pluginMap){var mod=
getOwn(registry,pluginMap.id);if(mod&&!mod.enabled)context.enable(pluginMap,this)}));this.enabling=false;this.check()},on:function(name,cb){var cbs=this.events[name];if(!cbs)cbs=this.events[name]=[];cbs.push(cb)},emit:function(name,evt){each(this.events[name],function(cb){cb(evt)});if(name==="error")delete this.events[name]}};function callGetModule(args){if(!hasProp(defined,args[0]))getModule(makeModuleMap(args[0],null,true)).init(args[1],args[2])}function removeListener(node,func,name,ieName){if(node.detachEvent&&
!isOpera){if(ieName)node.detachEvent(ieName,func)}else node.removeEventListener(name,func,false)}function getScriptData(evt){var node=evt.currentTarget||evt.srcElement;removeListener(node,context.onScriptLoad,"load","onreadystatechange");removeListener(node,context.onScriptError,"error");return{node:node,id:node&&node.getAttribute("data-requiremodule")}}function intakeDefines(){var args;takeGlobalQueue();while(defQueue.length){args=defQueue.shift();if(args[0]===null)return onError(makeError("mismatch",
"Mismatched anonymous define() module: "+args[args.length-1]));else callGetModule(args)}}context={config:config,contextName:contextName,registry:registry,defined:defined,urlFetched:urlFetched,defQueue:defQueue,Module:Module,makeModuleMap:makeModuleMap,nextTick:req.nextTick,onError:onError,configure:function(cfg){if(cfg.baseUrl)if(cfg.baseUrl.charAt(cfg.baseUrl.length-1)!=="/")cfg.baseUrl+="/";var pkgs=config.pkgs,shim=config.shim,objs={paths:true,config:true,map:true};eachProp(cfg,function(value,
prop){if(objs[prop])if(prop==="map"){if(!config.map)config.map={};mixin(config[prop],value,true,true)}else mixin(config[prop],value,true);else config[prop]=value});if(cfg.shim){eachProp(cfg.shim,function(value,id){if(isArray(value))value={deps:value};if((value.exports||value.init)&&!value.exportsFn)value.exportsFn=context.makeShimExports(value);shim[id]=value});config.shim=shim}if(cfg.packages){each(cfg.packages,function(pkgObj){var location;pkgObj=typeof pkgObj==="string"?{name:pkgObj}:pkgObj;location=
pkgObj.location;pkgs[pkgObj.name]={name:pkgObj.name,location:location||pkgObj.name,main:(pkgObj.main||"main").replace(currDirRegExp,"").replace(jsSuffixRegExp,"")}});config.pkgs=pkgs}eachProp(registry,function(mod,id){if(!mod.inited&&!mod.map.unnormalized)mod.map=makeModuleMap(id)});if(cfg.deps||cfg.callback)context.require(cfg.deps||[],cfg.callback)},makeShimExports:function(value){function fn(){var ret;if(value.init)ret=value.init.apply(global,arguments);return ret||value.exports&&getGlobal(value.exports)}
return fn},makeRequire:function(relMap,options){options=options||{};function localRequire(deps,callback,errback){var id,map,requireMod;if(options.enableBuildCallback&&callback&&isFunction(callback))callback.__requireJsBuild=true;if(typeof deps==="string"){if(isFunction(callback))return onError(makeError("requireargs","Invalid require call"),errback);if(relMap&&hasProp(handlers,deps))return handlers[deps](registry[relMap.id]);if(req.get)return req.get(context,deps,relMap,localRequire);map=makeModuleMap(deps,
relMap,false,true);id=map.id;if(!hasProp(defined,id))return onError(makeError("notloaded",'Module name "'+id+'" has not been loaded yet for context: '+contextName+(relMap?"":". Use require([])")));return defined[id]}intakeDefines();context.nextTick(function(){intakeDefines();requireMod=getModule(makeModuleMap(null,relMap));requireMod.skipMap=options.skipMap;requireMod.init(deps,callback,errback,{enabled:true});checkLoaded()});return localRequire}mixin(localRequire,{isBrowser:isBrowser,toUrl:function(moduleNamePlusExt){var ext,
index=moduleNamePlusExt.lastIndexOf("."),segment=moduleNamePlusExt.split("/")[0],isRelative=segment==="."||segment==="..";if(index!==-1&&(!isRelative||index>1)){ext=moduleNamePlusExt.substring(index,moduleNamePlusExt.length);moduleNamePlusExt=moduleNamePlusExt.substring(0,index)}return context.nameToUrl(normalize(moduleNamePlusExt,relMap&&relMap.id,true),ext,true)},defined:function(id){return hasProp(defined,makeModuleMap(id,relMap,false,true).id)},specified:function(id){id=makeModuleMap(id,relMap,
false,true).id;return hasProp(defined,id)||hasProp(registry,id)}});if(!relMap)localRequire.undef=function(id){takeGlobalQueue();var map=makeModuleMap(id,relMap,true),mod=getOwn(registry,id);delete defined[id];delete urlFetched[map.url];delete undefEvents[id];if(mod){if(mod.events.defined)undefEvents[id]=mod.events;cleanRegistry(id)}};return localRequire},enable:function(depMap){var mod=getOwn(registry,depMap.id);if(mod)getModule(depMap).enable()},completeLoad:function(moduleName){var found,args,mod,
shim=getOwn(config.shim,moduleName)||{},shExports=shim.exports;takeGlobalQueue();while(defQueue.length){args=defQueue.shift();if(args[0]===null){args[0]=moduleName;if(found)break;found=true}else if(args[0]===moduleName)found=true;callGetModule(args)}mod=getOwn(registry,moduleName);if(!found&&!hasProp(defined,moduleName)&&mod&&!mod.inited)if(config.enforceDefine&&(!shExports||!getGlobal(shExports)))if(hasPathFallback(moduleName))return;else return onError(makeError("nodefine","No define call for "+
moduleName,null,[moduleName]));else callGetModule([moduleName,shim.deps||[],shim.exportsFn]);checkLoaded()},nameToUrl:function(moduleName,ext,skipExt){var paths,pkgs,pkg,pkgPath,syms,i,parentModule,url,parentPath;if(req.jsExtRegExp.test(moduleName))url=moduleName+(ext||"");else{paths=config.paths;pkgs=config.pkgs;syms=moduleName.split("/");for(i=syms.length;i>0;i-=1){parentModule=syms.slice(0,i).join("/");pkg=getOwn(pkgs,parentModule);parentPath=getOwn(paths,parentModule);if(parentPath){if(isArray(parentPath))parentPath=
parentPath[0];syms.splice(0,i,parentPath);break}else if(pkg){if(moduleName===pkg.name)pkgPath=pkg.location+"/"+pkg.main;else pkgPath=pkg.location;syms.splice(0,i,pkgPath);break}}url=syms.join("/");url+=ext||(/\?/.test(url)||skipExt?"":".js");url=(url.charAt(0)==="/"||url.match(/^[\w\+\.\-]+:/)?"":config.baseUrl)+url}return config.urlArgs?url+((url.indexOf("?")===-1?"?":"&")+config.urlArgs):url},load:function(id,url){req.load(context,id,url)},execCb:function(name,callback,args,exports){return callback.apply(exports,
args)},onScriptLoad:function(evt){if(evt.type==="load"||readyRegExp.test((evt.currentTarget||evt.srcElement).readyState)){interactiveScript=null;var data=getScriptData(evt);context.completeLoad(data.id)}},onScriptError:function(evt){var data=getScriptData(evt);if(!hasPathFallback(data.id))return onError(makeError("scripterror","Script error for: "+data.id,evt,[data.id]))}};context.require=context.makeRequire();return context}req=requirejs=function(deps,callback,errback,optional){var context,config,
contextName=defContextName;if(!isArray(deps)&&typeof deps!=="string"){config=deps;if(isArray(callback)){deps=callback;callback=errback;errback=optional}else deps=[]}if(config&&config.context)contextName=config.context;context=getOwn(contexts,contextName);if(!context)context=contexts[contextName]=req.s.newContext(contextName);if(config)context.configure(config);return context.require(deps,callback,errback)};req.config=function(config){return req(config)};req.nextTick=typeof setTimeout!=="undefined"?
function(fn){setTimeout(fn,4)}:function(fn){fn()};if(!require)require=req;req.version=version;req.jsExtRegExp=/^\/|:|\?|\.js$/;req.isBrowser=isBrowser;s=req.s={contexts:contexts,newContext:newContext};req({});each(["toUrl","undef","defined","specified"],function(prop){req[prop]=function(){var ctx=contexts[defContextName];return ctx.require[prop].apply(ctx,arguments)}});if(isBrowser){head=s.head=document.getElementsByTagName("head")[0];baseElement=document.getElementsByTagName("base")[0];if(baseElement)head=
s.head=baseElement.parentNode}req.onError=defaultOnError;req.load=function(context,moduleName,url){var config=context&&context.config||{},node;if(isBrowser){node=config.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");node.type=config.scriptType||"text/javascript";node.charset="utf-8";node.async=true;node.setAttribute("data-requirecontext",context.contextName);node.setAttribute("data-requiremodule",moduleName);if(node.attachEvent&&!(node.attachEvent.toString&&
node.attachEvent.toString().indexOf("[native code")<0)&&!isOpera){useInteractive=true;node.attachEvent("onreadystatechange",context.onScriptLoad)}else{node.addEventListener("load",context.onScriptLoad,false);node.addEventListener("error",context.onScriptError,false)}node.src=url;currentlyAddingScript=node;if(baseElement)head.insertBefore(node,baseElement);else head.appendChild(node);currentlyAddingScript=null;return node}else if(isWebWorker)try{importScripts(url);context.completeLoad(moduleName)}catch(e){context.onError(makeError("importscripts",
"importScripts failed for "+moduleName+" at "+url,e,[moduleName]))}};function getInteractiveScript(){if(interactiveScript&&interactiveScript.readyState==="interactive")return interactiveScript;eachReverse(scripts(),function(script){if(script.readyState==="interactive")return interactiveScript=script});return interactiveScript}if(isBrowser)eachReverse(scripts(),function(script){if(!head)head=script.parentNode;dataMain=script.getAttribute("data-main");if(dataMain){mainScript=dataMain;if(!cfg.baseUrl){src=
mainScript.split("/");mainScript=src.pop();subPath=src.length?src.join("/")+"/":"./";cfg.baseUrl=subPath}mainScript=mainScript.replace(jsSuffixRegExp,"");if(req.jsExtRegExp.test(mainScript))mainScript=dataMain;cfg.deps=cfg.deps?cfg.deps.concat(mainScript):[mainScript];return true}});define=function(name,deps,callback){var node,context;if(typeof name!=="string"){callback=deps;deps=name;name=null}if(!isArray(deps)){callback=deps;deps=null}if(!deps&&isFunction(callback)){deps=[];if(callback.length){callback.toString().replace(commentRegExp,
"").replace(cjsRequireRegExp,function(match,dep){deps.push(dep)});deps=(callback.length===1?["require"]:["require","exports","module"]).concat(deps)}}if(useInteractive){node=currentlyAddingScript||getInteractiveScript();if(node){if(!name)name=node.getAttribute("data-requiremodule");context=contexts[node.getAttribute("data-requirecontext")]}}(context?context.defQueue:globalDefQueue).push([name,deps,callback])};define.amd={jQuery:true};req.exec=function(text){return eval(text)};req(cfg)})(this);
|
arthur-e/flux-server
|
public/app/require.js
|
JavaScript
|
mit
| 24,470
|
import * as React from "react";
import { VirtualFarmBotProps } from "../../interfaces";
import { BooleanSetting } from "../../../../session_keys";
import { BotFigure } from "./bot_figure";
import { BotTrail } from "./bot_trail";
import { BotPeripherals } from "./bot_peripherals";
import { NegativePositionLabel } from "./negative_position_labels";
export function VirtualFarmBot(props: VirtualFarmBotProps) {
const {
mapTransformProps, plantAreaOffset, peripherals, eStopStatus, getConfigValue
} = props;
const displayTrail = !!getConfigValue(BooleanSetting.display_trail);
const encoderFigure = !!getConfigValue(BooleanSetting.encoder_figure);
return <g id="virtual-farmbot">
<NegativePositionLabel
position={props.botLocationData.position}
mapTransformProps={mapTransformProps}
plantAreaOffset={plantAreaOffset} />
<BotPeripherals
position={props.botLocationData.position}
mapTransformProps={mapTransformProps}
plantAreaOffset={plantAreaOffset}
peripherals={peripherals}
getConfigValue={getConfigValue} />
<BotFigure name={"motor-position"}
position={props.botLocationData.position}
mapTransformProps={mapTransformProps}
plantAreaOffset={plantAreaOffset}
eStopStatus={eStopStatus} />
{encoderFigure &&
<BotFigure name={"encoder-position"}
position={props.botLocationData.scaled_encoders}
mapTransformProps={mapTransformProps}
plantAreaOffset={plantAreaOffset} />}
{displayTrail &&
<BotTrail
position={props.botLocationData.position}
mapTransformProps={mapTransformProps}
peripherals={peripherals} />}
</g>;
}
|
RickCarlino/farmbot-web-app
|
frontend/farm_designer/map/layers/farmbot/index.tsx
|
TypeScript
|
mit
| 1,682
|
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Examples
{
class Program
{
[STAThread]
static void Main(string[] args)
{
SolidEdgeFramework.Application application = null;
SolidEdgePart.PartDocument partDocument = null;
SolidEdgePart.Models models = null;
SolidEdgePart.Model model = null;
try
{
// See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register();
// Attempt to connect to a running instance of Solid Edge.
application = (SolidEdgeFramework.Application)Marshal.GetActiveObject("SolidEdge.Application");
partDocument = application.ActiveDocument as SolidEdgePart.PartDocument;
models = partDocument.Models;
model = models.Item(1);
var loftedFlanges = model.LoftedFlanges;
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleMessageFilter.Unregister();
}
}
}
}
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.Model.LoftedFlanges.cs
|
C#
|
mit
| 1,268
|
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2014 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxPhysicsAPI.h"
#include "SampleCharacterCloth.h"
static PxFilterFlags filter(PxFilterObjectAttributes attributes0,
PxFilterData filterData0,
PxFilterObjectAttributes attributes1,
PxFilterData filterData1,
PxPairFlags& pairFlags,
const void* constantBlock,
PxU32 constantBlockSize)
{
pairFlags |= PxPairFlag::eCONTACT_DEFAULT;
return PxFilterFlags();
}
void SampleCharacterCloth::customizeSceneDesc(PxSceneDesc& sceneDesc)
{
sceneDesc.gravity = PxVec3(0,-9.81,0);
sceneDesc.filterShader = filter;
sceneDesc.flags |= PxSceneFlag::eREQUIRE_RW_LOCK;
}
|
JayStilla/AIEPhysics
|
PhysX-3.2.4_PC_SDK_Core/Samples/SampleCharacterCloth/SampleCharacterCloth_FilterShader.cpp
|
C++
|
mit
| 2,358
|
#include <sal/net/async/service.hpp>
#include <sal/net/internet.hpp>
#include <sal/common.test.hpp>
namespace {
struct net_async_service
: public sal_test::fixture
{
sal::net::async::service_t service{};
};
TEST_F(net_async_service, io_pool_size)
{
EXPECT_EQ(0U, service.io_pool_size());
(void)service.make_io();
EXPECT_LT(0U, service.io_pool_size());
}
TEST_F(net_async_service, io_pool_size_increases_after_exhaustion_and_alloc)
{
EXPECT_EQ(0U, service.io_pool_size());
// alloc first
std::vector<sal::net::async::io_ptr> io_list;
io_list.emplace_back(service.make_io());
auto size_after_first_alloc = service.io_pool_size();
EXPECT_LT(0U, size_after_first_alloc);
// exhaust pool
while (io_list.size() < size_after_first_alloc)
{
io_list.emplace_back(service.make_io());
}
EXPECT_EQ(size_after_first_alloc, service.io_pool_size());
// alloc again to increase pool
io_list.emplace_back(service.make_io());
EXPECT_LT(size_after_first_alloc, service.io_pool_size());
}
TEST_F(net_async_service, io_pool_size_remains_same_after_exhaustion_and_release)
{
EXPECT_EQ(0U, service.io_pool_size());
// alloc first
std::vector<sal::net::async::io_ptr> io_list;
io_list.emplace_back(service.make_io());
auto size_after_first_alloc = service.io_pool_size();
EXPECT_LT(0U, size_after_first_alloc);
// exhaust pool
while (io_list.size() < size_after_first_alloc)
{
io_list.emplace_back(service.make_io());
}
EXPECT_EQ(size_after_first_alloc, service.io_pool_size());
// release all and alloc again
io_list.clear();
io_list.emplace_back(service.make_io());
EXPECT_EQ(size_after_first_alloc, service.io_pool_size());
}
} // namespace
|
svens/sal
|
sal/net/async/service.test.cpp
|
C++
|
mit
| 1,715
|
/*
The MIT License
Copyright (c) 2010-2021 Paul R. Holser, Jr.
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.pholser.junit.quickcheck;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import com.pholser.junit.quickcheck.generator.InRange;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
import java.time.Clock;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import org.junit.Test;
import org.junit.runner.RunWith;
public class ClockPropertyParameterTypesTest {
@Test public void clock() {
assertThat(testResult(Clocks.class), isSuccessful());
}
@RunWith(JUnitQuickcheck.class)
public static class Clocks {
@Property public void shouldHold(Clock c) {
}
}
@Test public void rangedClock() {
assertThat(testResult(RangedClock.class), isSuccessful());
}
@RunWith(JUnitQuickcheck.class)
public static class RangedClock {
@Property public void shouldHold(
@InRange(
min = "2012-01-01T00:00:00.0Z",
max = "2012-12-31T23:59:59.999999999Z")
Clock c) {
assertThat(
c.instant(),
allOf(
greaterThanOrEqualTo(
Instant.parse("2012-01-01T00:00:00.0Z")),
lessThanOrEqualTo(
Instant.parse("2012-12-31T23:59:59.999999999Z"))));
}
}
@Test public void malformedMin() {
assertThat(
testResult(MalformedMinClock.class),
hasSingleFailureContaining(
DateTimeParseException.class.getName()));
}
@RunWith(JUnitQuickcheck.class)
public static class MalformedMinClock {
@Property public void shouldHold(
@InRange(
min = "@#!@#@",
max = "2012-12-31T23:59:59.999999999Z")
Clock c) {
}
}
@Test public void malformedMax() {
assertThat(
testResult(MalformedMaxClock.class),
hasSingleFailureContaining(
DateTimeParseException.class.getName()));
}
@RunWith(JUnitQuickcheck.class)
public static class MalformedMaxClock {
@Property public void shouldHold(
@InRange(
min = "06/01/2011T23:59:59.999999999Z",
max = "*&@^#%$")
Clock c) {
}
}
@Test public void missingMin() {
assertThat(testResult(MissingMin.class), isSuccessful());
}
@RunWith(JUnitQuickcheck.class)
public static class MissingMin {
@Property public void shouldHold(
@InRange(max = "2012-12-31T23:59:59.999999999Z") Clock c) {
assertThat(
c.instant(),
lessThanOrEqualTo(
Instant.parse("2012-12-31T23:59:59.999999999Z")));
}
}
@Test public void missingMax() {
assertThat(testResult(MissingMax.class), isSuccessful());
}
@RunWith(JUnitQuickcheck.class)
public static class MissingMax {
@Property public void shouldHold(
@InRange(min = "2012-12-31T23:59:59.999999999Z") Clock c) {
assertThat(
c.instant(),
greaterThanOrEqualTo(
Instant.parse("2012-12-31T23:59:59.999999999Z")));
}
}
@Test public void backwardsRange() {
assertThat(
testResult(BackwardsRange.class),
hasSingleFailureContaining(
DateTimeParseException.class.getName()));
}
@RunWith(JUnitQuickcheck.class)
public static class BackwardsRange {
@Property public void shouldHold(
@InRange(
min = "2012-12-31T23:59:59.999999999Z",
max = "12/01/2012T00:00:00.0Z")
Clock c) {
}
}
}
|
pholser/junit-quickcheck
|
generators/src/test/java/com/pholser/junit/quickcheck/ClockPropertyParameterTypesTest.java
|
Java
|
mit
| 5,264
|
package com.nrg.kelly.config.actors;
/**
* Created by Andrew on 11/06/2015.
*/
public class ImageScaleConfig extends CoordinatesConfig {
}
|
nashrockgames/kelly
|
core/src/com/nrg/kelly/config/actors/ImageScaleConfig.java
|
Java
|
mit
| 142
|
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Video extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library(array('form_validation', 'email', 'session'));
$this->load->helper(array('text', 'url'));
$this->load->model('datamodel');
}
public function index() {
if ($this->session->userdata('username') == '') {
redirect(base_url());
} else {
$data['pos']=$this->datamodel->get_all_pos();
$data['pos2']=$this->datamodel->get_all_pos();
$data['vid']=$this->datamodel->get_all_vid();
$data['posvid']=$this->datamodel->get_pos_vid();
$data['link']='video';
$this->load->view('backend/Video',$data);
}
}
public function cctv(){
if ($this->session->userdata('username') == '') {
redirect(base_url());
} else {
redirect('backend/video','refresh');
}
}
public function savevideo(){
$idpos = $_POST['idpos'];
$namavideo = $_FILES['userfile']['name'];
$this->datamodel->save_video($idpos,$namavideo);
$config['upload_path'] = './assets/video';
$config['allowed_types'] = 'mp4|MP4';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
redirect('backend/video','refresh');
}
else
{
$data = array('upload_data' => $this->upload->data());
redirect('backend/video','refresh');
}
//
//
// $target_dir = base_url()."assets/video/";
// $target_file = $target_dir . basename($_FILES["file"]["name"]);
// $bendera = 1;
// $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// echo $imageFileType;
// if (file_exists($target_file)) {
// echo "Maaf file sudah ada";
// $bendera = 0;
// }
//
// if($imageFileType != "mp4" && $imageFileType != "MP4" ) {
// echo "Maaf hanya format mp4 yang bisa diupload";
// $bendera = 0;
// }
//
// if ($bendera == 0) {
// echo "File anda tidak terupload.";
//
// } else {
// if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// echo "File ". basename( $_FILES["file"]["name"]). " telah di upload.";
// } else {
// echo "Ada kesalahan saat upload";
// }
// }
}
}
?>
|
Nurcahya/forecastPU
|
application/controllers/backend/Video.php
|
PHP
|
mit
| 2,680
|
using System;
namespace HelloWorld.Common
{
[Serializable]
public class Message
{
public Message(string text)
{
Text = text;
}
public string Text { get; set; }
}
}
|
derekgreer/rabbitBusExamples
|
src/HelloWorld/HelloWorld.Common/Message.cs
|
C#
|
mit
| 239
|
<h1>{.title} {{edit}}</h1>
{.text}
|
ramainen/doit-cms
|
app/mod_pages/_show.html
|
HTML
|
mit
| 37
|
<form name="reviewForm" class="form-horizontal" ng-submit="reviewFormCtrl.addReview(reviewForm, reviewFormCtrl.book)">
<section class="row well live-preview" ng-show="reviewFormCtrl.book.isbn">
<aside class="col-sm-3">
<!-- no, no! <book-cover></book-cover> -->
<a href="http://www.amazon.com/gp/product/{{reviewFormCtrl.book.isbn}}">
<img ng-src="http://images.amazon.com/images/P/{{reviewFormCtrl.book.isbn}}.01.ZTZZZZZZ.jpg" alt="Cover of {{reviewFormCtrl.book.title}}" class="full">
</a>
<p>{{reviewFormCtrl.book.rating}}/5</p>
</aside>
<div class="col-sm-9">
<h3>
<a href="http://www.amazon.com/gp/product/{{reviewFormCtrl.book.isbn}}">
{{reviewFormCtrl.book.title}}
</a>
</h3>
<cite class="text-muted">Written by {{reviewFormCtrl.book.author}}</cite>
<p>{{reviewFormCtrl.book.review}}</p>
<ul class="list-unstyled">
<li ng-repeat="(genre, state) in reviewFormCtrl.book.genres">
<span class="label label-primary" ng-show="state">{{genre}}</span>
</li>
</ul>
</div>
</section>
<div class="input-container">
<fieldset class="form-group">
<label for="title" class="col-sm-2 control-label">Title:</label>
<span class="col-sm-9">
<input type="text" class="form-control" id="title" placeholder="Book Title" ng-model="reviewFormCtrl.book.title">
</span>
</fieldset>
<fieldset class="form-group">
<label for="isbn" class="control-label col-sm-2">ISBN:</label>
<span class="col-sm-9">
<input type="text" id="isbn" class="form-control"
maxLength="10" placeholder="ISBN-10" ng-model="reviewFormCtrl.book.isbn">
</span>
</fieldset>
<fieldset class="form-group">
<label class="control-label col-sm-2" for="author">Author</label>
<span class="col-sm-9">
<input type="text" id="author" class="form-control"
placeholder="Name of the Author" ng-model="reviewFormCtrl.book.author"></span>
</fieldset>
<fieldset class="form-group">
<label class="control-label col-sm-2" for="review">Review</label>
<span class="col-sm-9">
<textarea id="review" class="form-control" cols="30" rows="3"
placeholder="Book Review" ng-model="reviewFormCtrl.book.review"></textarea>
</span>
</fieldset>
<fieldset class="form-group">
<label for="rating" class="control-label col-sm-2">Rating:</label>
<span class="col-sm-9">
<select class="form-control" id="rating" value="5" ng-model="reviewFormCtrl.book.rating">
<option>5</option>
<option>4</option>
<option>3</option>
<option>2</option>
<option>1</option>
</select>
</span>
</fieldset>
<fieldset class="form-group">
<label class="control-label col-sm-2" >Genre:</label>
<div class="genre">
<label for="{{genre}}" class="genre-label form-control" ng-repeat="genre in genres">
<input type="checkbox" name="genre" id="{{genre}}" ng-model="reviewFormCtrl.book.genres[genre]"/>
{{genre}}
</label>
</div>
</fieldset>
<fieldset class="form-group">
<span class="col-sm-9 col-sm-offset-2 button-from-hell">
<button class="btn btn-primary">Save Review</button>
</span>
</fieldset>
</div>
</form>
|
tgrud/stb_suwa
|
app/partials/review-form.html
|
HTML
|
mit
| 3,373
|
require 'soap/rpc/router'
module Soap4r
module Middleware
include SOAP
def self.included(klass)
klass.send(:extend, ::Soap4r::Middleware::ClassMethods)
end
def initialize(app = nil)
@app = app
end
def call(env)
if env['PATH_INFO'].match(self.class.endpoint)
handle(env)
else
# we can act as both a middleware and an app
@app ?
@app.call(env) :
[ 404, { "Content-Type" => "text/html" }, ["Not Found"] ]
end
end
def handle(env)
# yeah, all soap calls are over POST
if env['REQUEST_METHOD'] != 'POST'
return 405, { 'Content-Length' => '0',
'Allow' => 'POST',
'Content-Type' => 'text/plain' }, []
end
conn_data = ::SOAP::StreamHandler::ConnectionData.new
setup_request(conn_data, env)
conn_data = self.class.router.route(conn_data)
status, headers, body = setup_response(conn_data, env)
[ status, headers, body ]
rescue
raise # TODO -- do we 500 right here, or let the exception bubble up?
end
def setup_request(conn_data, env)
# TODO: we're reading the whole input here, which kind of stinks if rack is
# reading from the client on demand. We can't just pass in the rack input
# object, since REXML needs an IO that responds to :eof? -- we'd need a
# wrapper IO-like object.
conn_data.receive_string = env['rack.input'].read
conn_data.receive_contenttype = env['CONTENT_TYPE']
conn_data.soapaction = parse_soapaction(env['HTTP_SOAPAction'])
end
def setup_response(conn_data, env)
status = 200
headers = {}
body = []
headers['content-type'] = conn_data.send_contenttype
# TODO: cookies?
if conn_data.is_nocontent
status = 202 # ACCEPTED
elsif conn_data.is_fault
# rather than sending the 500 here, let's bubble up the exception so the
# parent application can do with it what it will. The only downside is
# soap4r has already converted the exception into a soap response body at
# this point, which isn't what we want at all.
# maybe someday i'll re-parse the response or something. but not today.
raise conn_data.send_string
else
body << conn_data.send_string
end
return status, headers, body
end
def parse_soapaction(soapaction)
if !soapaction.nil? and !soapaction.empty?
if /\A"(.+)"\z/ =~ soapaction
return $1
end
end
nil
end
module ClassMethods
def setup
@router = ::SOAP::RPC::Router.new(self.class.name)
yield self
end
def router
@router
end
def endpoint=(regex)
@endpoint = regex
end
def endpoint
@endpoint
end
# SOAP interface
def mapping_registry
router.mapping_registry
end
def mapping_registry=(mapping_registry)
router.mapping_registry = mapping_registry
end
def literal_mapping_registry
router.literal_mapping_registry
end
def literal_mapping_registry=(literal_mapping_registry)
router.literal_mapping_registry = literal_mapping_registry
end
def generate_explicit_type
router.generate_explicit_type
end
def generate_explicit_type=(generate_explicit_type)
router.generate_explicit_type = generate_explicit_type
end
# servant entry interface
def add_rpc_servant(obj, namespace = self.default_namespace)
router.add_rpc_servant(obj, namespace)
end
alias add_servant add_rpc_servant
def add_headerhandler(obj)
router.add_headerhandler(obj)
end
alias add_rpc_headerhandler add_headerhandler
def filterchain
router.filterchain
end
# method entry interface
def add_rpc_method(obj, name, *param)
add_rpc_method_with_namespace_as(default_namespace, obj, name, name, *param)
end
alias add_method add_rpc_method
def add_rpc_method_as(obj, name, name_as, *param)
add_rpc_method_with_namespace_as(default_namespace, obj, name, name_as, *param)
end
alias add_method_as add_rpc_method_as
def add_rpc_method_with_namespace(namespace, obj, name, *param)
add_rpc_method_with_namespace_as(namespace, obj, name, name, *param)
end
alias add_method_with_namespace add_rpc_method_with_namespace
def add_rpc_method_with_namespace_as(namespace, obj, name, name_as, *param)
qname = XSD::QName.new(namespace, name_as)
soapaction = nil
param_def = SOAPMethod.derive_rpc_param_def(obj, name, *param)
router.add_rpc_operation(obj, qname, soapaction, name, param_def)
end
alias add_method_with_namespace_as add_rpc_method_with_namespace_as
def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})
router.add_rpc_operation(receiver, qname, soapaction, name, param_def, opt)
end
def add_document_operation(receiver, soapaction, name, param_def, opt = {})
router.add_document_operation(receiver, soapaction, name, param_def, opt)
end
end # ClassMethods
end
end
require 'soap4r-middleware/base'
|
instructure/soap4r-middleware
|
lib/soap4r-middleware.rb
|
Ruby
|
mit
| 5,331
|
package ninja.mpnguyen.bisque.views.comments;
import android.view.View;
import android.widget.TextView;
import ninja.mpnguyen.bisque.R;
public class CommentViewHolder extends StoryViewHolder {
public final View padding, content, container;
public final TextView comment_text, comment_author;
public CommentViewHolder(View itemView) {
super(itemView);
this.content = itemView.findViewById(R.id.comment_content);
this.container = itemView.findViewById(R.id.comment_container);
this.padding = itemView.findViewById(R.id.comment_padding);
this.comment_text = (TextView) itemView.findViewById(R.id.comment_text);
this.comment_author = (TextView) itemView.findViewById(R.id.comment_author);
}
}
|
nguyenmp/bisque
|
app/src/main/java/ninja/mpnguyen/bisque/views/comments/CommentViewHolder.java
|
Java
|
mit
| 757
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn cvtdq2ps_1() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 210], OperandSize::Dword)
}
#[test]
fn cvtdq2ps_2() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 829617393, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 52, 77, 241, 244, 114, 49], OperandSize::Dword)
}
#[test]
fn cvtdq2ps_3() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 244], OperandSize::Qword)
}
#[test]
fn cvtdq2ps_4() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Two, 1952076968, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 20, 93, 168, 84, 90, 116], OperandSize::Qword)
}
|
GregoryComer/rust-x86asm
|
src/test/instruction_tests/instr_cvtdq2ps.rs
|
Rust
|
mit
| 1,632
|
<?php
/**
* PHP version 5.6
*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
namespace CodeUp\ReadIt\Links;
/**
* A Readitor can post links to the site, and upvote and downvote other
* readitors links.
*/
class Readitor
{
/** @var int */
private $id;
/** @var string */
private $name;
/**
* @param int $id
* @param string $name
*/
private function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
/**
* @param ReaditorInformation $information
* @return Readitor
*/
public static function from(ReaditorInformation $information)
{
return new Readitor($information->id(), $information->name());
}
/**
* @param int $id
* @param string $name
* @return Readitor
*/
public static function with($id, $name)
{
return new Readitor($id, $name);
}
/**
* @return int
*/
public function id()
{
return $this->id;
}
/**
* @return ReaditorInformation
*/
public function information()
{
return new ReaditorInformation([
'readitor_id' => $this->id,
'name' => $this->name,
]);
}
/**
* @param string $url
* @param string $title
* @param int $timestamp
* @return Link
*/
public function post($url, $title, $timestamp)
{
return Link::post($url, $title, $this, $timestamp);
}
/**
* @param Link $link
* @return Vote
*/
public function upvoteLink(Link $link)
{
$link->upvote();
return Vote::upvote($link, $this);
}
/**
* @param Link $link
* @return Vote
*/
public function downvoteLink(Link $link)
{
$link->downvote();
return Vote::downvote($link, $this);
}
/**
* It cancel either an upvote or a downvote by updating a link's votes count
*
* @param Link $link
* @param Vote $vote
*/
public function cancelVote(Link $link, Vote $vote)
{
$link->cancel($vote);
}
/**
* It toggles upvotes and downvotes and updates link's votes count
*
* @param Link $link
* @param Vote $vote
*/
public function toggleVote(Link $link, Vote $vote)
{
$link->toggle($vote);
$vote->toggle();
}
}
|
MontealegreLuis/readit
|
src/ReadIt/Links/Readitor.php
|
PHP
|
mit
| 2,434
|
const { massiveHide } = require('../coreFunctions');
const header = {
init: () => {
constructor();
setupLogo();
},
};
const constructor = () => {
headerContainer = body.find('#header');
const breadcrumbContainer = body.find('.bread-container')
const hideElements = [
headerContainer.find('#station-logo'),
headerContainer.find('#header-menu'),
headerContainer.find('#header-actions-ul'),
headerContainer.find('#header-facebook-like'),
];
massiveHide(hideElements);
headerContainer.addClass('mo-header-container');
breadcrumbContainer.addClass('mo-breadcrumb-container');
}
const setupLogo = () => {
const logoContainer = `
<a href="/vale-tudo_f_57" class="mo-logo-container">
<div class="mo-logo-image sprite-vtMini"></div>
<div class="mo-logo-text">VT Mobile</div>
</a>
<div class="mo-login-container">
<a href="https://acesso.uol.com.br/login.html?skin=forum-jogos&dest=REDIR|mlocal.forum.jogos.uol.com.br" class="mo-login-button fa fa-user fa-2x"></a>
</div>
`;
headerContainer.append(logoContainer);
}
module.exports = header;
|
pt-br/vt-mobile
|
app/scripts/sections/header.js
|
JavaScript
|
mit
| 1,119
|
"use strict";
const btc = require("./coins/btc.js");
module.exports = {
"BTC": btc,
"coins":["BTC"]
};
|
janoside/btc-rpc-explorer
|
app/coins.js
|
JavaScript
|
mit
| 107
|
"use strict";
module.exports = {
test_page: "tests/index.html?hidepassed",
disable_watching: true,
launch_in_ci: ["Chrome"],
launch_in_dev: [],
browser_start_timeout: 120,
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? "--no-sandbox" : null,
"--headless",
"--disable-dev-shm-usage",
"--disable-software-rasterizer",
"--mute-audio",
"--remote-debugging-port=0",
"--window-size=1440,900",
].filter(Boolean),
},
},
};
|
adfinis-sygroup/ember-validated-form
|
testem.js
|
JavaScript
|
mit
| 581
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./a4b6b685941f3271cfbc32c80586ac1143811d797b6345e9623db4cf2dadf676.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html>
|
simonmysun/praxis
|
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/ee973c9984ea417cd31ac27f49065918de4bd82acc2bf17bb5353a48435e4427.html
|
HTML
|
mit
| 550
|
# v1.1.3
* Original: [Release electron v1.1.3 - electron/electron](https://github.com/electron/electron/releases/tag/v1.1.3)
Changelog:
**Windows**
* Fix crash caused by linking with VC++ statically. [#5658](https://github.com/electron/electron/issues/5658)
* VC++ で静的リンクするとクラッシュする問題を修正しました
* リンク先に静的リンクの話とか見当たらないのだけど、release notes が間違っている?
|
akabekobeko/electron-release-notes-ja-private-edition
|
v1.x/v1.1/v1.1.3.ja.md
|
Markdown
|
mit
| 465
|
package io.xunyss.commons.reflect;
import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
/**
*
* @author XUNYSS
*/
public class ClassPathUtils {
private static final URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
public static void add(URL url) {
try {
Method method = URLClassLoader.class
.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(systemClassLoader, url);
}
catch (Exception ex) {
// ignore exception
}
}
public static void add(File file) {
try {
add(file.toURI().toURL());
}
catch (Exception ex) {
// ignore exception
}
}
public static void addDirectory(File directory) {
if (directory.isDirectory()) {
File[] jars = directory.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".jar");
}
});
for (File jar : jars) {
add(jar);
}
}
}
}
|
xunyss/commons
|
commons-base/src/main/java/io/xunyss/commons/reflect/ClassPathUtils.java
|
Java
|
mit
| 1,143
|
/**
* Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.datasource.expression;
import java.util.List;
/**
* A list of expressions to read at the rate of the source.
* <p>
* Don't implement objects with this interface, use {@link SourceRateExpressionListImpl}.
*
* @param <R> type of the read payload
* @author carcassi
*/
public interface SourceRateExpressionList<R> {
/**
* Adds the given expressions to this list.
*
* @param expressions a list of expressions
* @return this
*/
public SourceRateExpressionList<R> and(SourceRateExpressionList<? extends R> expressions);
/**
* The expressions of this list.
*
* @return a list of expressions
*/
public List<SourceRateExpression<R>> getSourceRateExpressions();
}
|
diirt/diirt
|
pvmanager/datasource/src/main/java/org/diirt/datasource/expression/SourceRateExpressionList.java
|
Java
|
mit
| 887
|
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="no-js ie6"><![endif]-->
<!--[if IE 7 ]><html class="no-js ie7"><![endif]-->
<!--[if IE 8 ]><html class="no-js ie8"><![endif]-->
<!--[if IE 9 ]><html class="no-js ie9"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1,maximum-scale=1">
<title>StringReplace - Expreduce</title>
<meta property="og:url" content="None">
<meta property="og:title" content="Expreduce">
<meta property="og:image" content="None/../../../assets/images/logo.png">
<meta name="apple-mobile-web-app-title" content="Expreduce">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="apple-touch-icon" href="../../../assets/images/logo.png">
<link rel="shortcut icon" type="image/x-icon" href="../../../assets/images/favicon-e565ddfa3b.ico">
<link rel="icon" type="image/x-icon" href="../../../assets/images/favicon-e565ddfa3b.ico">
<style>
@font-face {
font-family: 'Icon';
src: url('../../../assets/fonts/icon.eot?52m981');
src: url('../../../assets/fonts/icon.eot?#iefix52m981')
format('embedded-opentype'),
url('../../../assets/fonts/icon.woff?52m981')
format('woff'),
url('../../../assets/fonts/icon.ttf?52m981')
format('truetype'),
url('../../../assets/fonts/icon.svg?52m981#icon')
format('svg');
font-weight: normal;
font-style: normal;
}
</style>
<link rel="stylesheet" href="../../../assets/stylesheets/application-a422ff04cc.css">
<link rel="stylesheet" href="../../../assets/stylesheets/mma.css">
<link rel="stylesheet" href="../../../assets/stylesheets/palettes-05ab2406df.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700|Roboto+Mono">
<style>
body, input {
font-family: 'Roboto', Helvetica, Arial, sans-serif;
}
pre, code {
font-family: 'Roboto Mono', 'Courier New', 'Courier', monospace;
}
</style>
<script src="../../../assets/javascripts/modernizr-4ab42b99fd.js"></script>
</head>
<body class="palette-primary-red palette-accent-light-blue">
<div class="backdrop">
<div class="backdrop-paper"></div>
</div>
<input class="toggle" type="checkbox" id="toggle-drawer">
<input class="toggle" type="checkbox" id="toggle-search">
<label class="toggle-button overlay" for="toggle-drawer"></label>
<header class="header">
<nav aria-label="Header">
<div class="bar default">
<div class="button button-menu" role="button" aria-label="Menu">
<label class="toggle-button icon icon-menu" for="toggle-drawer">
<span></span>
</label>
</div>
<div class="stretch">
<div class="title">
<span class="path">
Language reference <i class="icon icon-link"></i>
</span>
StringReplace
</div>
</div>
<div class="button button-search" role="button" aria-label="Search">
<label class="toggle-button icon icon-search" title="Search" for="toggle-search"></label>
</div>
</div>
<div class="bar search">
<div class="button button-close" role="button" aria-label="Close">
<label class="toggle-button icon icon-back" for="toggle-search"></label>
</div>
<div class="stretch">
<div class="field">
<input class="query" type="text" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck>
</div>
</div>
<div class="button button-reset" role="button" aria-label="Search">
<button class="toggle-button icon icon-close" id="reset-search"></button>
</div>
</div>
</nav>
</header>
<main class="main">
<div class="drawer">
<nav aria-label="Navigation">
<a href="https://github.com/corywalker/expreduce" class="project">
<div class="banner">
<div class="logo">
<img src="../../../assets/images/logo.png">
</div>
<div class="name">
<strong>
Expreduce
<span class="version">
</span>
</strong>
<br>
corywalker/expreduce
</div>
</div>
</a>
<div class="scrollable">
<div class="wrapper">
<ul class="repo">
<li class="repo-download">
<a href="https://github.com/corywalker/expreduce/archive/master.zip" target="_blank" title="Download" data-action="download">
<i class="icon icon-download"></i> Download
</a>
</li>
<li class="repo-stars">
<a href="https://github.com/corywalker/expreduce/stargazers" target="_blank" title="Stargazers" data-action="star">
<i class="icon icon-star"></i> Stars
<span class="count">–</span>
</a>
</li>
</ul>
<hr>
<div class="toc">
<ul>
<li>
<a class="" title="Home" href="../../..">
Home
</a>
</li>
<li>
<span class="section">Language reference</span>
<ul>
<li>
<a class="" title="combinatorics" href="../../combinatorics/">
combinatorics
</a>
</li>
<li>
<a class="" title="calculus" href="../../calculus/">
calculus
</a>
</li>
<li>
<a class="" title="comparison" href="../../comparison/">
comparison
</a>
</li>
<li>
<a class="" title="atoms" href="../../atoms/">
atoms
</a>
</li>
<li>
<a class="" title="functional" href="../../functional/">
functional
</a>
</li>
<li>
<a class="" title="expression" href="../../expression/">
expression
</a>
</li>
<li>
<a class="" title="equationdata" href="../../equationdata/">
equationdata
</a>
</li>
<li>
<a class="" title="solve" href="../../solve/">
solve
</a>
</li>
<li>
<a class="" title="flowcontrol" href="../../flowcontrol/">
flowcontrol
</a>
</li>
<li>
<a class="" title="list" href="../../list/">
list
</a>
</li>
<li>
<a class="" title="matrix" href="../../matrix/">
matrix
</a>
</li>
<li>
<a class="" title="arithmetic" href="../../arithmetic/">
arithmetic
</a>
</li>
<li>
<a class="" title="specialsyms" href="../../specialsyms/">
specialsyms
</a>
</li>
<li>
<a class="" title="power" href="../../power/">
power
</a>
</li>
<li>
<a class="" title="random" href="../../random/">
random
</a>
</li>
<li>
<a class="" title="replacement" href="../../replacement/">
replacement
</a>
</li>
<li>
<a class="" title="sort" href="../../sort/">
sort
</a>
</li>
<li>
<a class="" title="system" href="../../system/">
system
</a>
</li>
<li>
<a class="" title="trig" href="../../trig/">
trig
</a>
</li>
<li>
<a class="" title="plot" href="../../plot/">
plot
</a>
</li>
<li>
<a class="" title="string" href="../">
string
</a>
</li>
<li>
<a class="" title="time" href="../../time/">
time
</a>
</li>
<li>
<a class="" title="pattern" href="../../pattern/">
pattern
</a>
</li>
<li>
<a class="" title="boolean" href="../../boolean/">
boolean
</a>
</li>
<li>
<a class="" title="simplify" href="../../simplify/">
simplify
</a>
</li>
<li>
<a class="" title="numbertheory" href="../../numbertheory/">
numbertheory
</a>
</li>
<li>
<a class="" title="stats" href="../../stats/">
stats
</a>
</li>
<li>
<a class="" title="manip" href="../../manip/">
manip
</a>
</li>
<li>
<a class="" title="rubi" href="../../rubi/">
rubi
</a>
</li>
<li>
<a class="" title="tests" href="../../tests/">
tests
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</nav>
</div>
<article class="article">
<div class="wrapper">
<h1 id="stringreplace">StringReplace</h1>
<p><code>StringReplace[str, before->after]</code> replaces any occurrence of <code>before</code> with <code>after</code> in <code>str</code>.</p>
<p><code>Attributes[StringReplace] := {Protected}</code></p>
<h2 id="simple-examples">Simple examples</h2>
<div class="language-wl"><pre><span></span><span class="nb">In</span><span class="p">[</span><span class="m">1</span><span class="p">]</span><span class="o">:=</span><span class="w"> </span><span class="nb">StringReplace</span><span class="p">[</span><span class="s">"hello world"</span><span class="p">,</span><span class="w"> </span><span class="s">"world"</span><span class="w"> </span><span class="o">-></span><span class="w"> </span><span class="s">"foo"</span><span class="p">]</span><span class="w"></span>
<span class="nb">Out</span><span class="p">[</span><span class="m">1</span><span class="p">]</span><span class="o">=</span><span class="w"> </span><span class="s">"hello foo"</span><span class="w"></span>
</pre></div>
<aside class="copyright" role="note">
Documentation built with
<a href="http://www.mkdocs.org" target="_blank">MkDocs</a>
using the
<a href="http://squidfunk.github.io/mkdocs-material/" target="_blank">
Material
</a>
theme.
</aside>
<footer class="footer">
<nav class="pagination" aria-label="Footer">
<div class="previous">
<a href="../stringtake/" title="StringTake ">
<span class="direction">
Previous
</span>
<div class="page">
<div class="button button-previous" role="button" aria-label="Previous">
<i class="icon icon-back"></i>
</div>
<div class="stretch">
<div class="title">
StringTake
</div>
</div>
</div>
</a>
</div>
<div class="next">
<a href="../exportstring/" title="ExportString ">
<span class="direction">
Next
</span>
<div class="page">
<div class="stretch">
<div class="title">
ExportString
</div>
</div>
<div class="button button-next" role="button" aria-label="Next">
<i class="icon icon-forward"></i>
</div>
</div>
</a>
</div>
</nav>
</footer>
</div>
</article>
<div class="results" role="status" aria-live="polite">
<div class="scrollable">
<div class="wrapper">
<div class="meta"></div>
<div class="list"></div>
</div>
</div>
</div>
</main>
<script>
var base_url = '../../..';
var repo_id = 'corywalker/expreduce';
</script>
<script src="../../../assets/javascripts/application-997097ee0c.js"></script>
</body>
</html>
|
corywalker/expreduce-docs
|
docs/builtin/string/stringreplace/index.html
|
HTML
|
mit
| 18,433
|
# [Snow Report for China Peak](http://alexa.amazon.com/#skills/amzn1.ask.skill.b8dff5d2-32d1-4bb7-b88b-dff4b27fa5ea)
 0
To use the Snow Report for China Peak skill, try saying...
* *Alexa, ask China Peak for the snow report*
* *Alexa, open China Peak*
* *Alexa, ask China Peak for latest conditions*
The China Peak Snow Report brought to you by SnoCountry brings you the latest snow fall, snow surface conditions, base depth, trail, and lift operations information.
***
### Skill Details
* **Invocation Name:** china peak
* **Category:** null
* **ID:** amzn1.ask.skill.b8dff5d2-32d1-4bb7-b88b-dff4b27fa5ea
* **ASIN:** B01LXFKGBA
* **Author:** SnoCountry
* **Release Date:** October 20, 2016 @ 03:15:02
* **In-App Purchasing:** No
|
dale3h/alexa-skills-list
|
skills/B01LXFKGBA/README.md
|
Markdown
|
mit
| 1,024
|
<?php
/**
* Data Export FailuteException
*
* @package Nails
* @subpackage module-admin
* @category Exceptions
* @author Nails Dev Team
* @link
*/
namespace Nails\Admin\Exception\DataExport;
use Nails\Admin\Exception\AdminException;
class FailureException extends AdminException
{
}
|
nailsapp/module-admin
|
src/Exception/DataExport/FailureException.php
|
PHP
|
mit
| 307
|
const greeting = (name) => {
const element = document.querySelector('.js-greeting');
if (element) {
element.innerHTML = name;
}
};
export default greeting;
|
xfiveco/generator-chisel
|
docs/src/scripts/modules/greeting.js
|
JavaScript
|
mit
| 168
|
define(function(require,exports, module) {
var $ = require('jquery');
var React = require('react');
var Backbone = require('backbone');
var MyTable = require('./components/table/Table');
var ReactApp={
getJsonData:function(data){
alert('收集数据!'+data);
},
getInstance:function(model,options){
var modelData = new Backbone.Model(model);
React.render(React.createElement(MyTable, {data: modelData, onGetJsonData: this.getJsonData}), $('#example')[0]);
}
};
return ReactApp;
});
|
zhangzhaoaaa/mybackbone-react-ui
|
app/scripts/react/index.js
|
JavaScript
|
mit
| 532
|
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<title>pythongis.vector.data API documentation</title>
<meta name="description" content="Module containing the data structures and interfaces for operating with vector datasets." />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300' rel='stylesheet' type='text/css'>
<style type="text/css">
* {
box-sizing: border-box;
}
/*! normalize.css v1.1.1 | MIT License | git.io/normalize */
/* ==========================================================================
HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined in IE 6/7/8/9 and Firefox 3.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
/**
* Correct `inline-block` display not defined in IE 6/7/8/9 and Firefox 3.
*/
audio,
canvas,
video {
display: inline-block;
*display: inline;
*zoom: 1;
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address styling not present in IE 7/8/9, Firefox 3, and Safari 4.
* Known issue: no IE 6 support.
*/
[hidden] {
display: none;
}
/* ==========================================================================
Base
========================================================================== */
/**
* 1. Prevent system color scheme's background color being used in Firefox, IE,
* and Opera.
* 2. Prevent system color scheme's text color being used in Firefox, IE, and
* Opera.
* 3. Correct text resizing oddly in IE 6/7 when body `font-size` is set using
* `em` units.
* 4. Prevent iOS text size adjust after orientation change, without disabling
* user zoom.
*/
html {
background: #fff; /* 1 */
color: #000; /* 2 */
font-size: 100%; /* 3 */
-webkit-text-size-adjust: 100%; /* 4 */
-ms-text-size-adjust: 100%; /* 4 */
}
/**
* Address `font-family` inconsistency between `textarea` and other form
* elements.
*/
html,
button,
input,
select,
textarea {
font-family: sans-serif;
}
/**
* Address margins handled incorrectly in IE 6/7.
*/
body {
margin: 0;
}
/* ==========================================================================
Links
========================================================================== */
/**
* Address `outline` inconsistency between Chrome and other browsers.
*/
a:focus {
outline: thin dotted;
}
/**
* Improve readability when focused and also mouse hovered in all browsers.
*/
a:active,
a:hover {
outline: 0;
}
/* ==========================================================================
Typography
========================================================================== */
/**
* Address font sizes and margins set differently in IE 6/7.
* Address font sizes within `section` and `article` in Firefox 4+, Safari 5,
* and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
h2 {
font-size: 1.5em;
margin: 0.83em 0;
}
h3 {
font-size: 1.17em;
margin: 1em 0;
}
h4 {
font-size: 1em;
margin: 1.33em 0;
}
h5 {
font-size: 0.83em;
margin: 1.67em 0;
}
h6 {
font-size: 0.67em;
margin: 2.33em 0;
}
/**
* Address styling not present in IE 7/8/9, Safari 5, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 3+, Safari 4/5, and Chrome.
*/
b,
strong {
font-weight: bold;
}
blockquote {
margin: 1em 40px;
}
/**
* Address styling not present in Safari 5 and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address differences between Firefox and other browsers.
* Known issue: no IE 6/7 normalization.
*/
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
/**
* Address styling not present in IE 6/7/8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address margins set differently in IE 6/7.
*/
p,
pre {
margin: 1em 0;
}
/**
* Correct font family set oddly in IE 6, Safari 4/5, and Chrome.
*/
code,
kbd,
pre,
samp {
font-family: monospace, serif;
_font-family: 'courier new', monospace;
font-size: 1em;
}
/**
* Improve readability of pre-formatted text in all browsers.
*/
pre {
white-space: pre;
white-space: pre-wrap;
word-wrap: break-word;
}
/**
* Address CSS quotes not supported in IE 6/7.
*/
q {
quotes: none;
}
/**
* Address `quotes` property not supported in Safari 4.
*/
q:before,
q:after {
content: '';
content: none;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* ==========================================================================
Lists
========================================================================== */
/**
* Address margins set differently in IE 6/7.
*/
dl,
menu,
ol,
ul {
margin: 1em 0;
}
dd {
margin: 0 0 0 40px;
}
/**
* Address paddings set differently in IE 6/7.
*/
menu,
ol,
ul {
padding: 0 0 0 40px;
}
/**
* Correct list images handled incorrectly in IE 7.
*/
nav ul,
nav ol {
list-style: none;
list-style-image: none;
}
/* ==========================================================================
Embedded content
========================================================================== */
/**
* 1. Remove border when inside `a` element in IE 6/7/8/9 and Firefox 3.
* 2. Improve image quality when scaled in IE 7.
*/
img {
border: 0; /* 1 */
-ms-interpolation-mode: bicubic; /* 2 */
}
/**
* Correct overflow displayed oddly in IE 9.
*/
svg:not(:root) {
overflow: hidden;
}
/* ==========================================================================
Figures
========================================================================== */
/**
* Address margin not present in IE 6/7/8/9, Safari 5, and Opera 11.
*/
figure {
margin: 0;
}
/* ==========================================================================
Forms
========================================================================== */
/**
* Correct margin displayed oddly in IE 6/7.
*/
form {
margin: 0;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct color not being inherited in IE 6/7/8/9.
* 2. Correct text not wrapping in Firefox 3.
* 3. Correct alignment displayed oddly in IE 6/7.
*/
legend {
border: 0; /* 1 */
padding: 0;
white-space: normal; /* 2 */
*margin-left: -7px; /* 3 */
}
/**
* 1. Correct font size not being inherited in all browsers.
* 2. Address margins set differently in IE 6/7, Firefox 3+, Safari 5,
* and Chrome.
* 3. Improve appearance and consistency in all browsers.
*/
button,
input,
select,
textarea {
font-size: 100%; /* 1 */
margin: 0; /* 2 */
vertical-align: baseline; /* 3 */
*vertical-align: middle; /* 3 */
}
/**
* Address Firefox 3+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
button,
input {
line-height: normal;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Chrome, Safari 5+, and IE 6+.
* Correct `select` style inheritance in Firefox 4+ and Opera.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
* 4. Remove inner spacing in IE 7 without affecting normal text inputs.
* Known issue: inner spacing remains in IE 6.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
*overflow: visible; /* 4 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* 1. Address box sizing set to content-box in IE 8/9.
* 2. Remove excess padding in IE 8/9.
* 3. Remove excess padding in IE 7.
* Known issue: excess padding remains in IE 6.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
*height: 13px; /* 3 */
*width: 13px; /* 3 */
}
/**
* 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
* (include `-moz` to future-proof).
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box; /* 2 */
box-sizing: content-box;
}
/**
* Remove inner padding and search cancel button in Safari 5 and Chrome
* on OS X.
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Remove inner padding and border in Firefox 3+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* 1. Remove default vertical scrollbar in IE 6/7/8/9.
* 2. Improve readability and alignment in all browsers.
*/
textarea {
overflow: auto; /* 1 */
vertical-align: top; /* 2 */
}
/* ==========================================================================
Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
</style>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body {
background: #fff;
font-family: "Source Sans Pro", "Helvetica Neueue", Helvetica, sans;
font-weight: 300;
font-size: 16px;
line-height: 1.6em;
}
#content {
width: 70%;
max-width: 850px;
float: left;
padding: 30px 60px;
border-left: 1px solid #ddd;
}
#sidebar {
width: 25%;
float: left;
padding: 30px;
overflow: hidden;
}
#nav {
font-size: 130%;
margin: 0 0 15px 0;
}
#top {
display: block;
position: fixed;
bottom: 5px;
left: 5px;
font-size: .85em;
text-transform: uppercase;
}
#footer {
font-size: .75em;
padding: 5px 30px;
border-top: 1px solid #ddd;
text-align: right;
}
#footer p {
margin: 0 0 0 30px;
display: inline-block;
}
h1, h2, h3, h4, h5 {
font-weight: 300;
}
h1 {
font-size: 2.5em;
line-height: 1.1em;
margin: 0 0 .50em 0;
}
h2 {
font-size: 1.75em;
margin: 1em 0 .50em 0;
}
h3 {
margin: 25px 0 10px 0;
}
h4 {
margin: 0;
font-size: 105%;
}
a {
color: #058;
text-decoration: none;
transition: color .3s ease-in-out;
}
a:hover {
color: #e08524;
transition: color .3s ease-in-out;
}
pre, code, .mono, .name {
font-family: "Ubuntu Mono", "Cousine", "DejaVu Sans Mono", monospace;
}
.title .name {
font-weight: bold;
}
.section-title {
margin-top: 2em;
}
.ident {
color: #900;
}
code {
background: #f9f9f9;
}
pre {
background: #fefefe;
border: 1px solid #ddd;
box-shadow: 2px 2px 0 #f3f3f3;
margin: 0 30px;
padding: 15px 30px;
}
.codehilite {
margin: 0 30px 10px 30px;
}
.codehilite pre {
margin: 0;
}
.codehilite .err { background: #ff3300; color: #fff !important; }
table#module-list {
font-size: 110%;
}
table#module-list tr td:first-child {
padding-right: 10px;
white-space: nowrap;
}
table#module-list td {
vertical-align: top;
padding-bottom: 8px;
}
table#module-list td p {
margin: 0 0 7px 0;
}
.def {
display: table;
}
.def p {
display: table-cell;
vertical-align: top;
text-align: left;
}
.def p:first-child {
white-space: nowrap;
}
.def p:last-child {
width: 100%;
}
#index {
list-style-type: none;
margin: 0;
padding: 0;
}
ul#index .class_name {
/* font-size: 110%; */
font-weight: bold;
}
#index ul {
margin: 0;
}
.item {
margin: 0 0 15px 0;
}
.item .class {
margin: 0 0 25px 30px;
}
.item .class ul.class_list {
margin: 0 0 20px 0;
}
.item .name {
background: #fafafa;
margin: 0;
font-weight: bold;
padding: 5px 10px;
border-radius: 3px;
display: inline-block;
min-width: 40%;
}
.item .name:hover {
background: #f6f6f6;
}
.item .empty_desc {
margin: 0 0 5px 0;
padding: 0;
}
.item .inheritance {
margin: 3px 0 0 30px;
}
.item .inherited {
color: #666;
}
.item .desc {
padding: 0 8px;
margin: 0;
}
.item .desc p {
margin: 0 0 10px 0;
}
.source_cont {
margin: 0;
padding: 0;
}
.source_link a {
background: #ffc300;
font-weight: 400;
font-size: .75em;
text-transform: uppercase;
color: #fff;
text-shadow: 1px 1px 0 #f4b700;
padding: 3px 8px;
border-radius: 2px;
transition: background .3s ease-in-out;
}
.source_link a:hover {
background: #FF7200;
text-shadow: none;
transition: background .3s ease-in-out;
}
.source {
display: none;
max-height: 600px;
overflow-y: scroll;
margin-bottom: 15px;
}
.source .codehilite {
margin: 0;
}
.desc h1, .desc h2, .desc h3 {
font-size: 100% !important;
}
.clear {
clear: both;
}
@media all and (max-width: 950px) {
#sidebar {
width: 35%;
}
#content {
width: 65%;
}
}
@media all and (max-width: 650px) {
#top {
display: none;
}
#sidebar {
float: none;
width: auto;
}
#content {
float: none;
width: auto;
padding: 30px;
}
#index ul {
padding: 0;
margin-bottom: 15px;
}
#index ul li {
display: inline-block;
margin-right: 30px;
}
#footer {
text-align: left;
}
#footer p {
display: block;
margin: inherit;
}
}
/*****************************/
</style>
<style type="text/css">
/* ==========================================================================
EXAMPLE Media Queries for Responsive Design.
These examples override the primary ('mobile first') styles.
Modify as content requires.
========================================================================== */
@media only screen and (min-width: 35em) {
/* Style adjustments for viewports that meet the condition */
}
@media print,
(-o-min-device-pixel-ratio: 5/4),
(-webkit-min-device-pixel-ratio: 1.25),
(min-resolution: 120dpi) {
/* Style adjustments for high resolution devices */
}
/* ==========================================================================
Print styles.
Inlined to avoid required HTTP connection: h5bp.com/r
========================================================================== */
@media print {
* {
background: transparent !important;
color: #000 !important; /* Black prints faster: h5bp.com/s */
box-shadow: none !important;
text-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
/*
* Don't show links for images, or javascript/internal links
*/
.ir a:after,
a[href^="javascript:"]:after,
a[href^="#"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group; /* h5bp.com/t */
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
@page {
margin: 0.5cm;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
}
</style>
<script type="text/javascript">
function toggle(id, $link) {
$node = document.getElementById(id);
if (!$node)
return;
if (!$node.style.display || $node.style.display == 'none') {
$node.style.display = 'block';
$link.innerHTML = 'Hide source ≢';
} else {
$node.style.display = 'none';
$link.innerHTML = 'Show source ≡';
}
}
</script>
</head>
<body>
<a href="#" id="top">Top</a>
<div id="container">
<div id="sidebar">
<h1>Index</h1>
<ul id="index">
<li class="set"><h3><a href="#header-functions">Functions</a></h3>
<ul>
<li class="mono"><a href="#pythongis.vector.data.ID_generator">ID_generator</a></li>
<li class="mono"><a href="#pythongis.vector.data.Name_generator">Name_generator</a></li>
<li class="mono"><a href="#pythongis.vector.data.is_missing">is_missing</a></li>
</ul>
</li>
<li class="set"><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li class="mono">
<span class="class_name"><a href="#pythongis.vector.data.Feature">Feature</a></span>
<ul>
<li class="mono"><a href="#pythongis.vector.data.Feature.__init__">__init__</a></li>
<li class="mono"><a href="#pythongis.vector.data.Feature.copy">copy</a></li>
<li class="mono"><a href="#pythongis.vector.data.Feature.dataset">dataset</a></li>
<li class="mono"><a href="#pythongis.vector.data.Feature.get_shapely">get_shapely</a></li>
<li class="mono"><a href="#pythongis.vector.data.Feature.iter_points">iter_points</a></li>
<li class="mono"><a href="#pythongis.vector.data.Feature.map">map</a></li>
<li class="mono"><a href="#pythongis.vector.data.Feature.transform">transform</a></li>
<li class="mono"><a href="#pythongis.vector.data.Feature.view">view</a></li>
</ul>
</li>
<li class="mono">
<span class="class_name"><a href="#pythongis.vector.data.VectorData">VectorData</a></span>
<ul>
<li class="mono"><a href="#pythongis.vector.data.VectorData.__init__">__init__</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.add_feature">add_feature</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.add_field">add_field</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.aggregate">aggregate</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.browse">browse</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.compute">compute</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.convert_field">convert_field</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.copy">copy</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.create_spatial_index">create_spatial_index</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.describe">describe</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.drop_field">drop_field</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.drop_fields">drop_fields</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.duplicates">duplicates</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.field_type">field_type</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.field_values">field_values</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.get">get</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.group">group</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.has_geometry">has_geometry</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.histogram">histogram</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.interpolate">interpolate</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.join">join</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.keep_fields">keep_fields</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.map">map</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.moving_window">moving_window</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.quick_disjoint">quick_disjoint</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.quick_nearest">quick_nearest</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.quick_overlap">quick_overlap</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.rename_field">rename_field</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.save">save</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.select">select</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.sort">sort</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.summarystats">summarystats</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.tab">tab</a></li>
<li class="mono"><a href="#pythongis.vector.data.VectorData.view">view</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<article id="content">
<header id="section-intro">
<h1 class="title"><span class="name">pythongis.vector.data</span> module</h1>
<p>Module containing the data structures and interfaces for operating with vector datasets.</p>
</header>
<section id="section-items">
<h2 class="section-title" id="header-functions">Functions</h2>
<div class="item">
<div class="name def" id="pythongis.vector.data.ID_generator">
<p>def <span class="ident">ID_generator</span>(</p><p>)</p>
</div>
<div class="desc"><p>Used internally for ensuring default feature IDs are unique for each VectorData instance.
TODO: Maybe make private.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.Name_generator">
<p>def <span class="ident">Name_generator</span>(</p><p>)</p>
</div>
<div class="desc"><p>Used internally for ensuring default data names are unique for each Python session.
TODO: Maybe make private.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.is_missing">
<p>def <span class="ident">is_missing</span>(</p><p>val)</p>
</div>
<div class="source_cont">
</div>
</div>
<h2 class="section-title" id="header-classes">Classes</h2>
<div class="item">
<p id="pythongis.vector.data.Feature" class="name">class <span class="ident">Feature</span></p>
<div class="desc"><p>Class representing a vector data feature.
A feature object contains attributes/properties describing the feature,
equivalent to a row in a table, and a geometry describing its spatial representation. </p>
<p>Supports getting and setting feature properties/attributes via indexing, e.g. feat["name"]
gets or sets the feature's value for the name field. Raises an error if no such field name exists. </p>
<p>Supports the <strong>geo_interface</strong> protocol, returning a GeoJSON feature object dictionary. </p>
<p>TODO:
- Change the geometry property, represented as a Geometry class instead of a pure GeoJSON dictinoary.
- Move all geometry calculations such as length, area, etc., to the geometry class. </p>
<p>Attributes:
row: A list of values describing the feature properties as listed in the parent dataset's fields.
geometry: A GeoJSON dictionary describing the feature geometry, or None for features without geometry.
bbox: The bounding box of the feature, as a list of [xmin,ymin,xmax,ymax].
_cached_bbox: A cached version of the feature's bounding box, to avoid having to repeat the calculation each time.
All methods that change the feature's geometry should reset this cache to None in order to recalculate the bbox.
In case of errors, the user may reset this themselves by setting it to None. </p>
<pre><code> TODO:
- Make sure all methods that alter the geometry indeed does reset the cache.
length: Returns the cartesian length of the feature geometry, expressed in units of the coordinate system.
See Shapely docs for more.
geodetic_length: Returns the geodetic length of the feature geometry, expressed as km distance as calculated by the
vincenty algorithm.
area: Returns the cartesian area of the feature geometry, expressed in units of the coordinate system.
See Shapely docs for more.
id: The feature's ID in the parent vector dataset.
_data: The parent vector dataset to which the feature belongs.
</code></pre></div>
<div class="source_cont">
</div>
<div class="class">
<h3>Ancestors (in MRO)</h3>
<ul class="class_list">
<li><a href="#pythongis.vector.data.Feature">Feature</a></li>
</ul>
<h3>Methods</h3>
<div class="item">
<div class="name def" id="pythongis.vector.data.Feature.__init__">
<p>def <span class="ident">__init__</span>(</p><p>self, data, row=None, geometry=None, id=None)</p>
</div>
<div class="desc"><p>Creates new feature class.
Mostly used internally by the VectorData class.
The user should instead use the VectorData's add_feature() method. </p>
<p>Args:
data: The parent vector dataset to which the feature belongs. Necessary in order to access the feature row's field names.
row (optional): A list or dictionary of values describing the feature properties as listed in the parent dataset's fields.
Lists must be of the same sequence and length as the dataset fields.
Dictionaries sets only the specified fields, the rest defaulting to None.
geometry (optional): A GeoJSON dictionary describing the feature geometry, or None.
id (optional): If given, manually sets the feature's ID in the parent vector dataset. Otherwise, automatically assigned.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.Feature.copy">
<p>def <span class="ident">copy</span>(</p><p>self)</p>
</div>
<div class="desc"><p>Copies the feature and returns a new instance.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.Feature.dataset">
<p>def <span class="ident">dataset</span>(</p><p>self)</p>
</div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.Feature.get_shapely">
<p>def <span class="ident">get_shapely</span>(</p><p>self)</p>
</div>
<div class="desc"><p>Creates and returns the shapely object of the feature geometry. </p>
<p>NOTE:
- Repeated calling of this method can cause considerable overhead.
- Will be depreceated once all geometry operations are outsourced to a Geometry class.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.Feature.iter_points">
<p>def <span class="ident">iter_points</span>(</p><p>self)</p>
</div>
<div class="desc"><p>Yields every point in the geometry as a flat generator,
useful for quick inspecting of dimensions so don't have to
worry about nested coordinates and geometry types. For polygons
this includes the coordinates of both exterior and holes.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.Feature.map">
<p>def <span class="ident">map</span>(</p><p>self, width=None, height=None, bbox=None, title='', background=None, **styleoptions)</p>
</div>
<div class="desc"><p>Shortcut for easily creating a Map instance containing this feature as a layer.</p>
<p>Args:
width/height (optional): Desired width/height of the map. This can be changed again later.
bbox (optional): If given, only renders the given bbox, specified as (xmin,ymin,xmax,ymax).
title (optional): Title to be shown on the map.
background (optional): Background color of the map.
**styleoptions (optional): How to style the feature geometry, as documented in "renderer.VectorLayer".</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.Feature.transform">
<p>def <span class="ident">transform</span>(</p><p>self, func)</p>
</div>
<div class="desc"><p>Transforms the feature geometry in place.
Func is a function that takes a flat list of coordinates, does something, and returns them.
For points, the function is applied to a list containing a single coordinate, separately for each multipart.
For linestrings, the function is applied to each multipart.
For polygons, the function is applied to the exterior, and to each hole if any.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.Feature.view">
<p>def <span class="ident">view</span>(</p><p>self, bbox=None, title='', background=None, **styleoptions)</p>
</div>
<div class="desc"><p>Opens a Tkinter window for viewing and interacting with the feature on a map.</p>
<p>Args are same as for "map()".</p></div>
<div class="source_cont">
</div>
</div>
</div>
</div>
<div class="item">
<p id="pythongis.vector.data.VectorData" class="name">class <span class="ident">VectorData</span></p>
<div class="desc"><p>Class representing a vector dataset. </p>
<p>Calling len() returns the number of features in the dataset, and iterating over the dataset
loops through the dataset features one by one. </p>
<p>Supports getting and setting feature instances via indexing, e.g. feat[13] gets or sets the feature
located at the given index position. </p>
<p>Supports the <strong>geo_interface</strong> protocol, returning a GeoJSON feature collection object dictionary. </p>
<p>TODO:
- Currently, loads all features into memory. Maybe outsource to format-specific classes that iterate over each feature
without loading into memory (or allow via streaming option or a separate Streaming class). </p>
<p>Attributes:
filepath:
name:
type:
fields:
features:
crs:
bbox: </p>
<pre><code>manage: Access all methods from the manager module, passing self as first arg.
analyze: Access all methods from the analyzer module, passing self as first arg.
convert: Access all methods from the converter module, passing self as first arg.
</code></pre></div>
<div class="source_cont">
</div>
<div class="class">
<h3>Ancestors (in MRO)</h3>
<ul class="class_list">
<li><a href="#pythongis.vector.data.VectorData">VectorData</a></li>
</ul>
<h3>Methods</h3>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.__init__">
<p>def <span class="ident">__init__</span>(</p><p>self, filepath=None, type=None, name=None, fields=None, rows=None, geometries=None, features=None, crs=None, **kwargs)</p>
</div>
<div class="desc"><p>A vector dataset can be created in several ways. </p>
<p>To create an empty dataset, simply initiate the class with no args. A list of field names can be set with the fields arg,
or set after creation. </p>
<p>To load from a file, specify the filepath argument. The "select" option can be used to only populate the data with a subsample of
features instead of the entire dataset. When loading non-spatial file formats, the "x/yfield" and "geokey" args can be set to calculate
the geometry based on the attributes of each row. Optional **kwargs can be used to pass on format-specific loading options.
Supported reading fileformats include:
- fdsfds...</p>
<p>TODO:
- Ensure that select applies to all file formats, not just the non-spatial ones. </p>
<p>To initiate from a list of existing Feature instances, pass in to the features arg.
Alternatively, to load a dataset from separate lists of row values and geometry GeoJSON dictionaries, pass in the rows and geometries args
as lists of equal length. </p>
<p>Optional metadata can also be specified with args such as name, type, and crs. </p>
<p>Args:
fields: List of field names. </p>
<pre><code>rows: List of row lists to load from, of equal length and sequence as geometries.
geometries: List of GeoJSON dictionaries to load from, of equal length and sequence as rows.
features: List of Feature instances to load from.
filepath: Filepath of the dataset to load.
name (optional): Gives the dataset a name, which is used mostly for esthetic reasons and identification in visual lists.
TODO: Make this more meaningful, so that various functions can make use of the names to reference specific datasets.
type (optional): Geometry type of the dataset. If set, will make the features ensure that all geometries are of the
specified type. Otherwise, type enforcement will be based on first geometry found.
crs (optional): The coordinate system specified as a Proj4 string, defaults to unprojected WGS84.
TODO: Currently holds no meaning, makes no difference for any methods or functions. Maybe add on-the-fly reprojection?
select (optional): Function that takes a fieldname-value dictionary mapping and returns True for features that should be loaded.
x/yfield (optional): Specifies the field name containing the x/y coordinates of each feature, used for creating the feature
geometries of non-spatial fileformat point data.
geokey (optional): Function for creating more advanced types of geometries of non-spatial fileformats. The function takes
a fieldname-value dictionary mapping and returns a GeoJSON dictionary, or None for null-geometries.
**kwargs: File-format specific loading options. See `vector.loader` for details.
</code></pre></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.add_feature">
<p>def <span class="ident">add_feature</span>(</p><p>self, row=None, geometry=None)</p>
</div>
<div class="desc"><p>Adds and returns a new feature, given a row list or dict, and a geometry GeoJSON dictionary.
If neither are set, populates row with None values, and empty geometry.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.add_field">
<p>def <span class="ident">add_field</span>(</p><p>self, field, index=None)</p>
</div>
<div class="desc"><p>Adds a new field by the name of 'field', optionally at the specified index position.
All existing feature rows are updated accordingly.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.aggregate">
<p>def <span class="ident">aggregate</span>(</p><p>self, key, geomfunc=None, fieldmapping=[])</p>
</div>
<div class="desc"><p>Aggregate values and geometries within key groupings.</p>
<p>Arguments:
key: List of field names or a function to group by.
geomfunc (optional): Specifies how to aggregate geometries, either intersection, union, difference,
or a function that takes all geometries to aggregate. If not set (default), does not aggregate geometries,
returning a non-spatial table with only null-geometries.
fieldmapping: Specifies a set of aggregation rules used to calculate the new value for each group.
Specified as a list of (outfield,valuefield,stat) tuples, where outfield is the field name
of a new or existing field to write, valuefield is the field name or function that retrieves the value
to calculate statistics on, and stat is the name of the statistic to calculate or a function that takes
the list of values from the group as defined by valuefield.
Valid stat values include:
- fdsf...</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.browse">
<p>def <span class="ident">browse</span>(</p><p>self, limit=None)</p>
</div>
<div class="desc"><p>Opens a Tkinter window for viewing and interacting with the rows contained in this dataset.</p>
<p>Args:
limit (optional): Limits the number of rows to be displayed, in case of very large datasets.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.compute">
<p>def <span class="ident">compute</span>(</p><p>self, field, value, by=None, stat=None)</p>
</div>
<div class="desc"><p>Loops through all features and sets the row field to the given value.
If the value is a function, it will take each Feature object as input and uses it to calculate and return a new value.
If the field name does not already exist, one will be created.
If by and stat is given, 'by' will be used to group features, and for each group, 'stat' will be used to calculate a
statistic and write the results to the members of the group. </p>
<p>Arguments:
field: Name of the field to compute. Existing name will overwrite all values, new name will create new field.
value: Any value or object to be written to the field, or a callable that expects a Feature as its input and outputs
the value to write.
by: A field name by which to group, or a callable that expects a Feature as its input and outputs the group-by value.
stat: The name of a summary statistic to calculate and write for each by-group, or a callable that expects a list of
Feature instances as input and returns the aggregated value to write.
Valid stat values include:
- fdsf...</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.convert_field">
<p>def <span class="ident">convert_field</span>(</p><p>self, field, valfunc)</p>
</div>
<div class="desc"><p>Applies the given valfunc function to force convert all values in a field.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.copy">
<p>def <span class="ident">copy</span>(</p><p>self)</p>
</div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.create_spatial_index">
<p>def <span class="ident">create_spatial_index</span>(</p><p>self, type=None, backend=None, **kwargs)</p>
</div>
<div class="desc"><p>Creates spatial index to allow quick overlap search methods.
If features are changed, added, or dropped, the index must be created again.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.describe">
<p>def <span class="ident">describe</span>(</p><p>self)</p>
</div>
<div class="desc"><p>Prints a description of the dataset, such as geometry type, length, bbox, and lists each
field along with their name, type, valid, and missing.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.drop_field">
<p>def <span class="ident">drop_field</span>(</p><p>self, field)</p>
</div>
<div class="desc"><p>Drops the specified field, changing the dataset in-place.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.drop_fields">
<p>def <span class="ident">drop_fields</span>(</p><p>self, fields)</p>
</div>
<div class="desc"><p>Drops all of the specified fields, changing the dataset in-place.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.duplicates">
<p>def <span class="ident">duplicates</span>(</p><p>self, subkey=None, fieldmapping=[])</p>
</div>
<div class="desc"><p>Removes duplicate geometries by grouping and aggregating their values.</p>
<p>Arguments:
subkey (optional): If specified, for each set of duplicate geometries will perform separate aggregations
for each subgroup defined by subkey. Geometry duplicates will continue to exist if they have more than
one subkey grouping.
fieldmapping: Defines the value aggregations. See aggregate().</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.field_type">
<p>def <span class="ident">field_type</span>(</p><p>self, field)</p>
</div>
<div class="desc"><p>Determines and returns field type of field based on its values (ignoring missing values).
For now, only detects int, float, and text.</p>
<p>TODO: also detect other types eg datetime, etc.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.field_values">
<p>def <span class="ident">field_values</span>(</p><p>self, field)</p>
</div>
<div class="desc"><p>Returns sorted list of all the unique values in this field.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.get">
<p>def <span class="ident">get</span>(</p><p>self, func)</p>
</div>
<div class="desc"><p>Iterates over features that meet filter conditions.
Func takes a Feature instance as input and yield only those where it returns True.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.group">
<p>def <span class="ident">group</span>(</p><p>self, key)</p>
</div>
<div class="desc"><p>Iterates over keyvalue-group pairs based on key</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.has_geometry">
<p>def <span class="ident">has_geometry</span>(</p><p>self)</p>
</div>
<div class="desc"><p>Returns True if at least one feature has non-null geometry.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.histogram">
<p>def <span class="ident">histogram</span>(</p><p>self, field, width=None, height=None, bins=10)</p>
</div>
<div class="desc"><p>Renders the value distribution of a given field in a histogram plot,
returned as a PyAgg Canvas of size width/height. This canvas can be used
to call "save()" or "view()". Default histogram bins is 10.</p>
<p>TODO:
- Should it return Canvas, or just straight view() it?</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.interpolate">
<p>def <span class="ident">interpolate</span>(</p><p>self, step)</p>
</div>
<div class="desc"><p>Interpolates missing values between known values.</p>
<p>NOT YET IMPLEMENTED.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.join">
<p>def <span class="ident">join</span>(</p><p>self, other, key, fieldmapping=[], collapse=False, keepall=True)</p>
</div>
<div class="desc"><p>Matches and joins the features in this dataset with the features in another dataset.
Returns a new joined dataset.</p>
<p>Note: if the other dataset has fields with the same name as the main dataset, those will not be joined, keeping
only the ones in the main dataset. </p>
<p>Arguments:
other: The other VectorData dataset to join to this one.
key: Can be a single fieldname, multiple fieldnames, or function that returns the link for both tables.</p>
<pre><code> TODO:
- Maybe introduce separate lkey and rkey args...
collapse (optional): If True, collapses and aggregates all matching features in the other dataset (default), otherwise
adds a new row for each matching pair.
fieldmapping (optional): If collapse is True, this determines the aggregation rules. See aggregate().
keepall (optional): If True, keeps all features in the main dataset regardless (default), otherwise only keeps the
ones that match.
</code></pre></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.keep_fields">
<p>def <span class="ident">keep_fields</span>(</p><p>self, fields)</p>
</div>
<div class="desc"><p>Keeps only the fields specified, changing the dataset in-place.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.map">
<p>def <span class="ident">map</span>(</p><p>self, width=None, height=None, bbox=None, title='', background=None, crs=None, **styleoptions)</p>
</div>
<div class="desc"><p>Shortcut for easily creating a Map instance containing this dataset as a layer.</p>
<p>Args:
width/height (optional): Desired width/height of the map. This can be changed again later.
bbox (optional): If given, only renders the given bbox, specified as (xmin,ymin,xmax,ymax).
title (optional): Title to be shown on the map.
background (optional): Background color of the map.
**styleoptions (optional): How to style the feature geometry, as documented in "renderer.VectorLayer".</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.moving_window">
<p>def <span class="ident">moving_window</span>(</p><p>self, n, fieldmapping, groupby=None)</p>
</div>
<div class="desc"><p>Loops through the features in the dataset, and calculates one or more new values based
on aggregate statistics of a moving window of previously visited rows.</p>
<p>Arguments:
n: Size of the moving window specified as number of rows.
fieldmapping: Specifies a set of aggregation rules used to calculate the new values based on the moving
window. Specified as a list of (outfield,valuefield,stat) tuples, where outfield is the field name
of a new or existing field to write, valuefield is the field name or function that retrieves the value
to calculate statistics on, and stat is the name of the statistic to calculate or a function that takes
the list of values from the moving window as defined by valuefield.
Valid stat values include:
- fdsf...
groupby (optional): If specified, the moving window will run separately for each group of features as defined
by the groupby field name or grouping function.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.quick_disjoint">
<p>def <span class="ident">quick_disjoint</span>(</p><p>self, bbox)</p>
</div>
<div class="desc"><p>Quickly get features whose bbox do -not- overlap the specified bbox via the spatial index.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.quick_nearest">
<p>def <span class="ident">quick_nearest</span>(</p><p>self, bbox, n=None, radius=None)</p>
</div>
<div class="desc"><p>Quickly get n features whose bbox are nearest the specified bbox via the spatial index.</p>
<p>TODO: radius option not yet implemented.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.quick_overlap">
<p>def <span class="ident">quick_overlap</span>(</p><p>self, bbox)</p>
</div>
<div class="desc"><p>Quickly get features whose bbox overlap the specified bbox via the spatial index.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.rename_field">
<p>def <span class="ident">rename_field</span>(</p><p>self, oldname, newname)</p>
</div>
<div class="desc"><p>Changes the name of a field from oldname to newname.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.save">
<p>def <span class="ident">save</span>(</p><p>self, savepath, **kwargs)</p>
</div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.select">
<p>def <span class="ident">select</span>(</p><p>self, func)</p>
</div>
<div class="desc"><p>Returns new filtered VectorData instance.
Func takes a Feature instance as input and keeps only those where it returns True.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.sort">
<p>def <span class="ident">sort</span>(</p><p>self, key, reverse=False)</p>
</div>
<div class="desc"><p>Sorts the feature order in-place using a key function and optional reverse flag.</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.summarystats">
<p>def <span class="ident">summarystats</span>(</p><p>self, *fields)</p>
</div>
<div class="desc"><p>Prints summary statistics for all fields.
If specified, only calculates for the fields listed in *fields.</p>
<p>TODO: maybe also return a dict?</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.tab">
<p>def <span class="ident">tab</span>(</p><p>self, field)</p>
</div>
<div class="desc"><p>Prints a frequency count of the unique values for a single field.</p>
<p>TODO: split into multiple methods, eg field_stats vs field_values/frequencies
TODO: standardize table string formatting, eg as a vectordata.stringformat() method, and simply populate a stats vectordata table and call its method
TODO: sort freq table by percentages
TODO: fix unicode print error
TODO: maybe also return a dict?</p></div>
<div class="source_cont">
</div>
</div>
<div class="item">
<div class="name def" id="pythongis.vector.data.VectorData.view">
<p>def <span class="ident">view</span>(</p><p>self, width=None, height=None, bbox=None, title='', background=None, crs=None, **styleoptions)</p>
</div>
<div class="desc"><p>Opens a Tkinter window for viewing and interacting with the dataset on a map.</p>
<p>Args are same as for "map()".</p></div>
<div class="source_cont">
</div>
</div>
</div>
</div>
</section>
</article>
<div class="clear"> </div>
<footer id="footer">
<p>
Documentation generated by
<a href="https://github.com/BurntSushi/pdoc">pdoc 0.3.2</a>
</p>
<p>pdoc is in the public domain with the
<a href="http://unlicense.org">UNLICENSE</a></p>
<p>Design by <a href="http://nadh.in">Kailash Nadh</a></p>
</footer>
</div>
</body>
</html>
|
karimbahgat/PythonGis
|
docs/vector/data.m.html
|
HTML
|
mit
| 53,934
|
// an almost totally original program by Erin Fitzpatrick
// vertical print inspired by the IOCCC (international obfuscated C code contest) and the demoscene of the 1980's
import java.io.*;
import java.util.*;
public class madSkillz
{
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Give me a string of whatever: ");
String silly = kbReader.nextLine();
int x = silly.length(); //This and the FOR loop cause whatever you typed to be printed vertically
for(int i=0; i<x; i++)
{
System.out.println(silly.charAt(i)); //Strings still use index 0!
}
}
}
|
caffeinatedDrummer/BlueJ-Code
|
madSkillz.java
|
Java
|
mit
| 791
|
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
#if MASM
using System.Collections.Generic;
using Iced.Intel;
using Iced.UnitTests.Intel.DecoderTests;
using Xunit;
namespace Iced.UnitTests.Intel.FormatterTests.Masm {
public sealed class FormatterTest64 : FormatterTest {
[Theory]
[MemberData(nameof(Format_Data_MemAlways))]
void Format_MemAlways(int index, InstructionInfo info, string formattedString) => FormatBase(index, info, formattedString, FormatterFactory.Create_MemAlways());
public static IEnumerable<object[]> Format_Data_MemAlways => FormatterTestCases.GetFormatData(64, "Masm", "MemAlways");
[Theory]
[MemberData(nameof(Format_Data_MemDefault))]
void Format_MemDefault(int index, InstructionInfo info, string formattedString) => FormatBase(index, info, formattedString, FormatterFactory.Create_MemDefault());
public static IEnumerable<object[]> Format_Data_MemDefault => FormatterTestCases.GetFormatData(64, "Masm", "MemDefault");
[Theory]
[MemberData(nameof(Format_Data_MemMinimum))]
void Format_MemMinimum(int index, InstructionInfo info, string formattedString) => FormatBase(index, info, formattedString, FormatterFactory.Create_MemMinimum());
public static IEnumerable<object[]> Format_Data_MemMinimum => FormatterTestCases.GetFormatData(64, "Masm", "MemMinimum");
#if ENCODER
[Theory]
[MemberData(nameof(Format_Data_NonDec_MemAlways))]
void Format_NonDec_MemAlways(int index, Instruction info, string formattedString) => FormatBase(index, info, formattedString, FormatterFactory.Create_MemAlways());
public static IEnumerable<object[]> Format_Data_NonDec_MemAlways => FormatterTestCases.GetFormatData(64, NonDecodedInstructions.Infos64, "Masm", "NonDec_MemAlways");
[Theory]
[MemberData(nameof(Format_Data_NonDec_MemDefault))]
void Format_NonDec_MemDefault(int index, Instruction info, string formattedString) => FormatBase(index, info, formattedString, FormatterFactory.Create_MemDefault());
public static IEnumerable<object[]> Format_Data_NonDec_MemDefault => FormatterTestCases.GetFormatData(64, NonDecodedInstructions.Infos64, "Masm", "NonDec_MemDefault");
[Theory]
[MemberData(nameof(Format_Data_NonDec_MemMinimum))]
void Format_NonDec_MemMinimum(int index, Instruction info, string formattedString) => FormatBase(index, info, formattedString, FormatterFactory.Create_MemMinimum());
public static IEnumerable<object[]> Format_Data_NonDec_MemMinimum => FormatterTestCases.GetFormatData(64, NonDecodedInstructions.Infos64, "Masm", "NonDec_MemMinimum");
#endif
[Theory]
[MemberData(nameof(Format_Data_Misc))]
void Format_Misc(int index, InstructionInfo info, string formattedString) => FormatBase(index, info, formattedString, FormatterFactory.Create());
public static IEnumerable<object[]> Format_Data_Misc => FormatterTestCases.GetFormatData(64, "Masm", "Misc", isMisc: true);
}
}
#endif
|
0xd4d/iced
|
src/csharp/Intel/Iced.UnitTests/Intel/FormatterTests/Masm/FormatterTest64.cs
|
C#
|
mit
| 2,923
|
# -*- coding: utf-8 -*-
from django.conf.urls import url
from dictionaries.items.views import DicItemsListView, DicItemsCreateView, \
DicItemsDetailView, DicItemsUpdateView, DicItemsDeleteView
urlpatterns = [
url(r'^$', DicItemsListView.as_view(), name='items-list'),
url(r'^add/$', DicItemsCreateView.as_view(), name='items-add'),
url(r'^(?P<dictionary_id>[0-9]+)/$', DicItemsDetailView.as_view(), name='items-detail'),
url(r'^(?P<dictionary_id>[0-9]+)/edit/$', DicItemsUpdateView.as_view(), name='items-edit'),
url(r'^(?P<dictionary_id>[0-9]+)/delete/$', DicItemsDeleteView.as_view(), name='items-delete'),
]
|
mitrofun/kids2
|
src/apps/dictionaries/items/urls.py
|
Python
|
mit
| 637
|
//
// MLSEnum.h
// MinLison
//
// Created by minlison on 2017/9/27.
// Copyright © 2017年 minlison. All rights reserved.
//
#ifndef MLSEnum_h
#define MLSEnum_h
/**
tabbar的位置
- MLSTabbarIndexHome: 首页
- MLSTabbarIndexYard: 场地预定
- MLSTabbarIndexEvent: 赛事活动
- MLSTabbarIndexMine: 我的
*/
typedef NS_ENUM(NSInteger,MLSTabbarIndex)
{
MLSTabbarIndexHome = 0,
MLSTabbarIndexYard = 1,
MLSTabbarIndexEvent = 2,
MLSTabbarIndexMine = 3,
};
/**
内容类型, 针对全局的所有内容的类型说明
// 1热门产品 2促销信息 3新闻动态 4体育项目的赛事活动 5体育项目的新闻 6体育项目的活动介绍
- MLSArticleContentTypeHot: 热门产品
- MLSArticleContentTypePromotion: 促销信息
- MLSArticleContentTypeNews: 新闻动态
- MLSArticleContentTypeSportActivity: 体育项目的赛事活动
- MLSArticleContentTypeSportNews: 体育项目的新闻
- MLSArticleContentTypeSportIntroduce: 体育项目的活动介绍
*/
typedef NS_ENUM(NSInteger,MLSArticleContentType)
{
MLSArticleContentTypeHot = 1,
MLSArticleContentTypePromotion = 2,
MLSArticleContentTypeNews = 3,
MLSArticleContentTypeSportActivity = 4,
MLSArticleContentTypeSportNews = 5,
MLSArticleContentTypeSportIntroduce = 6,
};
/**
订单类型
- MLSOrderStatusTypeWaitingPay: 等待付款
- MLSOrderStatusTypePayed: 已付款但为确认
- MLSOrderStatusTypeCanceled: 已取消
- MLSOrderStatusTypeCompleted: 已完成
*/
typedef NS_ENUM(NSInteger,MLSOrderStatusType)
{
MLSOrderStatusTypeWaitingPay,
MLSOrderStatusTypePayed,
MLSOrderStatusTypeCanceled,
MLSOrderStatusTypeCompleted,
MLSOrderStatusTypeAll,
MLSOrderStatusTypeMax,
};
static inline NSString *MLSOrderStatusDesForType(MLSOrderStatusType type)
{
NSString *des = nil;
switch (type) {
case MLSOrderStatusTypeWaitingPay:
{
des = @"待支付";
}
break;
case MLSOrderStatusTypePayed:
{
des = @"已支付";
}
break;
case MLSOrderStatusTypeCanceled:
{
des = @"已取消";
}
break;
case MLSOrderStatusTypeCompleted:
{
des = @"已完成";
}
break;
default:
des = nil;
break;
}
return des;
};
typedef NS_ENUM(NSInteger, MLSPersonalTrainerOrderStatus)
{
MLSPersonalTrainerOrderStatusWaitingReview,
MLSPersonalTrainerOrderStatusReviewing,
MLSPersonalTrainerOrderStatusReviewPass,
MLSPersonalTrainerOrderStatusReviewNotPass,
MLSPersonalTrainerOrderStatusMax,
};
static inline NSString *MLSPersonalTrainerOrderDesForType(MLSPersonalTrainerOrderStatus type)
{
NSString *des = nil;
switch (type) {
case MLSPersonalTrainerOrderStatusWaitingReview:
{
des = @"等待审核";
}
break;
case MLSPersonalTrainerOrderStatusReviewing:
{
des = @"审核中";
}
break;
case MLSPersonalTrainerOrderStatusReviewPass:
{
des = @"审核通过";
}
break;
case MLSPersonalTrainerOrderStatusReviewNotPass:
{
des = @"审核未通过";
}
break;
default:
des = nil;
break;
}
return des;
};
/**
会员类型
后台对应 service_id
- MLSVipServiceKindTypeCreateCardAndCharge: 办卡充值
- MLSVipServiceKindTypeSiteBooking: 场地预订
- MLSVipServiceKindTypeBuyTickets: 购买门票
- MLSVipServiceKindTypeSportsClass: 体育培训
- MLSVipServiceKindTypeMatchSignUp: 赛事报名
- MLSVipServiceKindTypeSportShop: 运动商城
- MLSVipServiceKindTypeParkingCar: 停车缴费
*/
typedef NS_ENUM(NSInteger, MLSVipServiceKindType)
{
MLSVipServiceKindTypeCreateCardAndCharge = 1,
MLSVipServiceKindTypeSiteBooking = 2,
MLSVipServiceKindTypeBuyTickets = 3,
MLSVipServiceKindTypeSportsClass = 4,
MLSVipServiceKindTypeMatchSignUp = 5,
MLSVipServiceKindTypeSportShop = 6,
MLSVipServiceKindTypeParkingCar = 7,
MLSVipServiceKindTypeMax,
};
/**
购物车类型
根据后台定义
- MLSShopCartTypeShopping: 运动商城商品
- MLSShopCartTypeBuyTickets: 购买门票
*/
typedef NS_ENUM(NSInteger, MLSShopCartType)
{
MLSShopCartTypeShopping = 1,
MLSShopCartTypeBuyTickets = 2
};
/**
门票类型
- MLSBuyTicketsTypeSwimChildTicket: 儿童游泳馆
- MLSBuyTicketsTypeParentChildTicket: 亲子运动员门票
*/
typedef NS_ENUM(NSInteger, MLSBuyTicketsType)
{
MLSBuyTicketsTypeSwimChildTicket = 1,
MLSBuyTicketsTypeParentChildTicket = 2
};
/**
专题中内容类型
1~99的部分ID是预留给“内容类型”的,以保持一致
- WGTopicContentTypeArticle: 文章
- WGTopicContentTypePic: 图片
- WGTopicContentTypeVideo: 视频
- WGTopicContentTypeMusci: 音乐
- WGTopicContentTypeBrief: 简讯
- WGTopicContentTypeUrl: 网页
- WGTopicContentTypeAD: 广告
- WGTopicContentTypeSubTopic: 子专题列表入口, 此类型用于实现专题的嵌套,即专题里的专题列表(树形结构的专题列表),一个专题里可能返回此列表里的一个或多个内容类型。
*/
typedef NS_ENUM(NSInteger, WGTopicContentType)
{
WGTopicContentTypeArticle = 1,
WGTopicContentTypePic = 2,
WGTopicContentTypeVideo = 3,
WGTopicContentTypeMusci = 4,
WGTopicContentTypeBrief = 5,
WGTopicContentTypeUrl = 100,
WGTopicContentTypeAD = 101,
WGTopicContentTypeSubTopic = 102,
};
/**
评论的内容类型
- WGCommentTypeArticle: 文章
- WGCommentTypeePic: 图片
- WGCommentTypeVideo: 视频
- WGCommentTypeMusci: 音乐
- WGCommentTypeBrief: 简讯
- WGCommentTypeFeedBack:反馈
*/
typedef NS_ENUM(NSInteger, WGCommentContentType)
{
WGCommentContentTypeArticle = 1,
WGCommentContentTypeePic = 2,
WGCommentContentTypeVideo = 3,
WGCommentContentTypeMusci = 4,
WGCommentContentTypeBrief = 5,
WGCommentContentTypeFeedBack = 6,
};
/**
专题的显示类型
- WGTopicShowTypeRound: 轮播图
- WGTopicShowTypeTopic: 专题
*/
typedef NS_ENUM(NSInteger, WGTopicShowType)
{
WGTopicShowTypeRound = 1,
WGTopicShowTypeTopic = 2,
};
/**
专题的页面类型(可能会在同一页面的多个位置显示不同的专题列表)
- WGTopicPageAll: 所有页面(默认值)
*/
typedef NS_ENUM(NSInteger, WGTopicPageType)
{
WGTopicPageAll = 1,
};
/**
首页简讯底部toolBar按钮类型
- WGToolBarViewTypeLike: 喜欢
- WGToolBarViewTypeComment: 评论
- WGToolBarViewTypeShare: 分享
*/
typedef NS_ENUM(NSInteger,WGToolBarViewType)
{
WGToolBarViewTypeUnLike = 0,
WGToolBarViewTypeLike,
WGToolBarViewTypeComment,
WGToolBarViewTypeShare,
};
/**
跳转浏览器类型
- WGBrowserTypeBuiltIn: 内置浏览器
- WGBrowserTypeOther: 外部浏览器
*/
typedef NS_ENUM(NSInteger, WGBrowserType)
{
WGBrowserTypeBuiltIn = 1,
WGBrowserTypeOther = 2,
};
/**
视频清晰度
- WGVideoDefinitionUnKnown: 未知
- WGVideoDefinition720p: 720p
- WGVideoDefinition1080p: 1080p
- WGVideoDefinition2k: 2k
- WGVideoDefinition4k: 4k
*/
typedef NS_ENUM(NSInteger, WGVideoDefinition)
{
WGVideoDefinitionUnKnown = 0,
WGVideoDefinition720p = 1,
WGVideoDefinition1080p = 2,
WGVideoDefinition2k = 3,
WGVideoDefinition4k = 4,
};
/**
cell点击状态类型
- WGCellTouchTypeBegan: 开始触摸
- WGCellTouchTypeEnd: 结束触摸
*/
typedef NS_ENUM(NSInteger, WGCellTouchType)
{
WGCellTouchTypeBegan = 1,
WGCellTouchTypeEnd = 2,
};
/**
用户权限角色
- WGUserRoleTypeNormal: 普通用户
- WGUserRoleTypeAdmin: 管理员
*/
typedef NS_ENUM(NSInteger, WGUserRoleType)
{
WGUserRoleTypeNormal = 0,
WGUserRoleTypeAdmin = 1,
};
/**
三方登录类型
- MLSLoginTypePhone: 手机
- MLSLoginTypeQQ: QQ
- MLSLoginTypeWebchat: 微信
- MLSLoginTypeWeibo: 微博
*/
typedef NS_ENUM(NSInteger, MLSLoginType)
{
MLSLoginTypePhone = -1,
MLSLoginTypeUnKnown = 0,
/// 服务器定义 begin
MLSLoginTypeQQ = 3,
MLSLoginTypeWebchat = 4,
MLSLoginTypeWeibo = 5,
/// 服务器定义 end
};
/**
分享网站类型
- WGThirdShareWebTypeWebTimeLine: 朋友圈
- WGThirdShareWebTypeWebchat: 微信
- WGThirdShareWebTypeQQ: QQ
- WGThirdShareWebTypeQQZone: QQ 空间
- WGThirdShareWebTypeWeibo: 微博
*/
typedef NS_ENUM(NSInteger, WGThirdShareWebType)
{
WGThirdShareWebTypeWebTimeLine = 1,
WGThirdShareWebTypeWebchat = 2,
WGThirdShareWebTypeQQ = 3,
WGThirdShareWebTypeQQZone = 4,
WGThirdShareWebTypeWeibo = 5,
};
/**
图片上传类型
- WGImageUploadTypeUnKnown: 未知
- WGImageUploadTypeUserHead: 头像
*/
typedef NS_ENUM(NSInteger, WGImageUploadType)
{
WGImageUploadTypeUnKnown,
WGImageUploadTypeUserHead,
};
/**
评论列表类型
- WGCommentListTypeNormal: 0:普通评论列表(按时间倒序排列)
- WGCommentListTypeWonderful: 1:精彩评论列表(按点赞数倒序排列,页数默认为1,没分页)
- WGCommentListTypeStickTop: 2:置顶评论列表(按后台设置排列)
*/
typedef NS_ENUM(NSInteger, WGCommentListType)
{
WGCommentListTypeNormal,
WGCommentListTypeWonderful,
WGCommentListTypeStickTop,
};
/**
删除评论的类型
- WGBanCommentTypeWithOutBanUser: 删除评论,不封禁用户
- WGBanCommentTypeWithBanUser: 删除评论,并且封禁用户
*/
typedef NS_ENUM(NSInteger, WGBanCommentType)
{
WGBanCommentTypeWithOutBanUser,
WGBanCommentTypeWithBanUser,
};
/////// MARK: - Request Type
/**
文章列表请求类型
- MLSArticleListRequestTypeHome: 首页
- MLSArticleListRequestTypeSport: 运动馆
*/
typedef NS_ENUM(NSInteger,MLSArticleListRequestType)
{
MLSArticleListRequestTypeHome,
MLSArticleListRequestTypeSport,
};
/**
轮播图请求类型
- MLSBannerRequestTypeHome: 首页
- MLSBannerRequestTypeSport: 运动馆
*/
typedef NS_ENUM(NSInteger,MLSBannerRequestType)
{
MLSBannerRequestTypeHome,
MLSBannerRequestTypeSport,
};
#endif /* MLSEnum_h */
|
Minlison/MLSProject
|
MLSProject/MLSProject/Unit/Enum/MLSEnum.h
|
C
|
mit
| 11,110
|
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Qualcomm;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class R2TL84GreenCtbl31 extends AbstractTag
{
protected $Id = 'r2_tl84_green_ctbl[31]';
protected $Name = 'R2TL84GreenCtbl31';
protected $FullName = 'Qualcomm::Main';
protected $GroupName = 'Qualcomm';
protected $g0 = 'MakerNotes';
protected $g1 = 'Qualcomm';
protected $g2 = 'Camera';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'R2 TL84 Green Ctbl 31';
protected $flag_Permanent = true;
}
|
romainneutron/PHPExiftool
|
lib/PHPExiftool/Driver/Tag/Qualcomm/R2TL84GreenCtbl31.php
|
PHP
|
mit
| 873
|
#!/bin/csh
bsub -n 1 openmpi-mpirun ~/Research/dark_arts_local/build/dark_arts Refinement_8_Cell.xml
bsub -n 1 openmpi-mpirun ~/Research/dark_arts_local/build/dark_arts Refinement_16_Cell.xml
bsub -n 1 openmpi-mpirun ~/Research/dark_arts_local/build/dark_arts Refinement_32_Cell.xml
bsub -n 1 openmpi-mpirun ~/Research/dark_arts_local/build/dark_arts Refinement_64_Cell.xml
bsub -n 1 openmpi-mpirun ~/Research/dark_arts_local/build/dark_arts Refinement_128_Cell.xml
bsub -n 1 openmpi-mpirun ~/Research/dark_arts_local/build/dark_arts Refinement_256_Cell.xml
bsub -n 1 openmpi-mpirun ~/Research/dark_arts_local/build/dark_arts Refinement_512_Cell.xml
|
pgmaginot/DARK_ARTS
|
inputs/Refinement_Inputs/P1_SL_Lobatto/launch_refinements.sh
|
Shell
|
mit
| 660
|
import Backend from 'i18next-xhr-backend';
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.plugin('aurelia-i18n', (i18n) => {
i18n.i18next.use(Backend);
return i18n.setup({
backend: {
loadPath: './locales/{{lng}}/{{ns}}.json',
},
lng : 'en',
fallbackLng : 'en'
});
});
}
|
manuel-guilbault/Learning-Aurelia
|
appendix-a/using-jspm/test/unit/configuration.js
|
JavaScript
|
mit
| 375
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using CefSharp.WinForms;
using HCDU.API;
namespace HCDU.Windows
{
public class WinFormsPlatformAdapter : IPlatformAdapter
{
public string OpenFolderBrowserDialog(WindowHandle parent, bool allowCreateFolder)
{
Form parentForm = (Form) parent.NativeWindow;
if (parentForm.InvokeRequired)
{
return (string) parentForm.Invoke(new Func<WindowHandle, bool, string>(OpenFolderBrowserDialog), parent, allowCreateFolder);
}
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.ShowNewFolderButton = allowCreateFolder;
if (dlg.ShowDialog(parentForm) != DialogResult.OK)
{
return null;
}
return dlg.SelectedPath;
}
public WindowHandle CreateWindow(WindowPrototype prototype)
{
return ConstructDialog(prototype);
}
public WindowHandle ShowDialog(WindowHandle parent, WindowPrototype prototype)
{
Form parentForm = (Form) parent.NativeWindow;
if (parentForm.InvokeRequired)
{
return (WindowHandle) parentForm.Invoke(new Func<WindowHandle, WindowPrototype, WindowHandle>(ShowDialog), parent, prototype);
}
WindowHandle handle = ConstructDialog(prototype);
Form window = (Form) handle.NativeWindow;
window.Closed += (sender, args) => prototype.OnClose(handle);
//todo: use ShowDialog when CefSharp 43 is released (now it freezes the application)
window.Show(parentForm);
//todo: this would conflict with window.ShowDialog
return handle;
}
public void CloseDialog(WindowHandle win)
{
Form form = (Form) win.NativeWindow;
if (form.InvokeRequired)
{
form.Invoke(new Action<WindowHandle>(CloseDialog), win);
return;
}
form.Close();
}
public void NavigateTo(WindowHandle window, string url)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser) window.NativeBrowser;
browser.Load(url);
}
public void ReloadPage(WindowHandle window)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser) window.NativeBrowser;
browser.Reload(true);
}
public void ShowDevTools(WindowHandle window)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser) window.NativeBrowser;
browser.ShowDevTools();
}
private WindowHandle ConstructDialog(WindowPrototype prototype)
{
Form form = new Form();
form.Size = new Size(prototype.Width, prototype.Height);
ChromiumWebBrowser webBrowser = new ChromiumWebBrowser("about:blank");
//todo: usage of WindowHandle is a little bit cumbersome
WindowHandle handle = new WindowHandle(form, webBrowser);
//todo: is SuspendLayout/ResumeLayout required?
form.SuspendLayout();
int occupiedHeight = 0;
if (prototype.Menu != null && prototype.Menu.Any())
{
MenuStrip menu = CreateMenu(handle, prototype.Menu);
const int menuHeight = 24;
menu.Size = new Size(form.ClientSize.Width, menuHeight);
menu.Location = new Point(0, 0);
menu.TabIndex = 0;
form.Controls.Add(menu);
occupiedHeight += menuHeight;
}
form.Controls.Add(webBrowser);
webBrowser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
webBrowser.Location = new Point(0, occupiedHeight);
webBrowser.Size = new Size(form.ClientSize.Width, form.ClientSize.Height - occupiedHeight);
webBrowser.TabIndex = 1;
form.Controls.Add(webBrowser);
//todo: is SuspendLayout/ResumeLayout required?
form.ResumeLayout();
webBrowser.TitleChanged += (sender, args) =>
{
if (form.InvokeRequired)
{
form.Invoke(new Action<string>(title => { form.Text = title; }), webBrowser.Title);
}
};
webBrowser.Load(prototype.Url);
return handle;
}
private MenuStrip CreateMenu(WindowHandle handle, List<MenuPrototype> menuItemsProt)
{
MenuStrip menu = new MenuStrip();
foreach (MenuPrototype menuItemProt in menuItemsProt)
{
menu.Items.Add(CreateMenuItem(handle, menuItemProt));
}
return menu;
}
private ToolStripMenuItem CreateMenuItem(WindowHandle handle, MenuPrototype menuItemProt)
{
ToolStripMenuItem menuItem = new ToolStripMenuItem(menuItemProt.Text);
if (menuItemProt.OnAction != null)
{
menuItem.Click += (sender, args) => menuItemProt.OnAction(handle);
}
if (menuItemProt.Items != null && menuItemProt.Items.Any())
{
foreach (MenuPrototype menuSubItemProt in menuItemProt.Items)
{
menuItem.DropDownItems.Add(CreateMenuItem(handle, menuSubItemProt));
}
}
return menuItem;
}
}
}
|
yu-kopylov/html-csharp-desktop-ui
|
HCDU.Windows/WinFormsPlatformAdapter.cs
|
C#
|
mit
| 5,807
|
from flask.ext.sqlalchemy import SQLAlchemy
from . import db
class Role(db.Model):
__tablename__='roles'
id=db.Column(db.Integer,primary_key=True)
name=db.Column(db.String(64),unique=True)
users=db.relationship('User',backref='role')
def __repr__(self):
return '<Role>{}</Role>'.format(self.name)
class User(db.Model):
__tablename__='users'
id=db.Column(db.Integer,primary_key=True)
role_id=db.Column(db.Integer,db.ForeignKey('roles.id'))
username=db.Column(db.String(64),unique=True,index=True)
def __repr__(self):
return '<Username>{}</Username>'.format(self.username)
|
zhangmingkai4315/Flask-Web-App
|
app/models.py
|
Python
|
mit
| 628
|
//doc icons
const doc = {
'px-doc-chart': '<g id="px-doc-chart"><g><path stroke-linejoin="round" d="M1.5 5.5h3v7h-3zm5 2h3v5h-3zm5-6h3v11h-3zM0 14.5h16"/></g></g>',
'px-doc-document': '<g id="px-doc-document"><g><path stroke-linejoin="round" d="M2.5.5v15h11v-12l-3-3h-8z"/><path stroke-linejoin="round" d="M9.5.5v4h4"/></g></g>',
'px-doc-document-csv': '<g id="px-doc-document-csv"><g><path stroke-linejoin="round" d="M3.5 14v1.5h12v-12l-3-3h-9V7"/><path stroke-linejoin="round" d="M11.5.5v4h4"/><text transform="translate(-.32 13.23)" font-size="7" font-weight="700" letter-spacing=".07em">C<tspan x="4.86" y="0" letter-spacing=".06em">S</tspan><tspan x="9.27" y="0" letter-spacing=".03em">V</tspan></text></g></g>',
'px-doc-document-pdf': '<g id="px-doc-document-pdf"><g><path stroke-linejoin="round" d="M3.5 14v1.5h12v-12l-3-3h-9V7"/><path stroke-linejoin="round" d="M11.5.5v4h4"/><text transform="translate(-.32 13.23)" font-size="7" font-weight="700" letter-spacing=".06em">PD<tspan x="9.83" y="0" letter-spacing=".04em">F</tspan></text></g></g>',
'px-doc-document-word': '<g id="px-doc-document-word"><g><path stroke-linejoin="round" d="M1.5 15.5h13v-12l-3-3h-10v15z"/><path stroke-linejoin="round" d="M10.5.5v4h4"/><text transform="translate(3.68 12.23)" font-size="8" font-weight="700" letter-spacing=".03em">W</text></g></g>',
'px-doc-document-xls': '<g id="px-doc-document-xls"><g><path stroke-linejoin="round" d="M3.5 14v1.5h12v-12l-3-3h-9V7"/><path stroke-linejoin="round" d="M11.5.5v4h4"/><text transform="translate(-.32 13.23)" font-size="7" font-weight="700" letter-spacing=".06em">X<tspan x="4.7" y="0" letter-spacing=".07em">L</tspan><tspan x="8.78" y="0">S</tspan></text></g></g>',
'px-doc-image': '<g id="px-doc-image"><g><path stroke-linejoin="round" d="M.5 1.5h15v13H.5z"/><path d="M2.5 11.5c1.56-4.95 2.67-5.68 4-3.77 1 1.45 1.89.23 2.67-2.24s3.33-.27 4.33 6z" stroke-linejoin="round"/></g></g>',
'px-doc-note': '<g id="px-doc-note"><g><path stroke-linejoin="round" d="M15.5 1.5H.5v13h12l3-3v-10z"/><path stroke-linejoin="round" d="M11.5 14.5v-4h4M3 4.5h10m-10 3h7m-7 3h4"/></g></g>',
'px-doc-website': '<g id="px-doc-website"><g><path stroke-linejoin="round" d="M.5 1.5h15v13H.5zm0 3h15m-12 0v-3"/></g></g>'
};
//done
export default doc
|
jonniespratley/px-components-react
|
src/px-icon-set/px-icon-set-document.js
|
JavaScript
|
mit
| 2,377
|
class MessageContactList < ActiveRecord::Base
belongs_to :contact_list
belongs_to :message
end
|
boy-jer/santhathi-appointment
|
app/models/message_contact_list.rb
|
Ruby
|
mit
| 96
|
#!/bin/bash
docker images | grep "<none>" | awk '{print $3}' | xargs docker rmi -f
exit
|
xxaxxelxx/xx_bridgehead
|
docker_cleanup_unusedimages.sh
|
Shell
|
mit
| 88
|
import React, { Component } from 'react';
import Hawk from '../src/';
// For your app, import Hawk like so
// import Hawk from 'hawk-graph';
export default class App extends Component {
state = {
nodes: [
{
nid: 1,
type: 'Users',
x: 200,
y: 100,
fields: {
in: [
{ name: 'user_id' },
{ name: 'role_id' },
],
out: [{ name: 'out' }]
}
},
{
nid: 2,
type: 'Photos',
x: 800,
y: 100,
fields: {
in: [
{ name: 'user_id' },
{ name: 'photo' },
],
out: [{ name: 'out' }]
}
},
{
nid: 3,
type: 'Role',
x: 400,
y: 500,
fields: {
in: [
{ name: 'user_id' },
{ name: 'role' },
],
out: [{ name: 'out' }]
}
}
],
connections: [
{ from_node: 1, from: 'out', to_node: 2, to: 'user_id' },
{ from_node: 2, from: 'out', to_node: 3, to: 'user_id' },
]
}
onNewConnector(fromNode, fromPin, toNode, toPin) {
let connections = [
...this.state.connections,
{
from_node: fromNode,
from: fromPin,
to_node: toNode,
to: toPin
}
];
this.setState({ connections: connections });
}
onRemoveConnector(connector) {
let connections = [...this.state.connections];
connections = connections.filter(connection => {
return connection != connector;
});
this.setState({ connections: connections });
}
onNodeMove(nid, pos) {
console.log('end move : ' + nid, pos);
}
onNodeStartMove(nid) {
console.log('start move : ' + nid);
}
handleNodeSelect(nid) {
console.log('node selected : ' + nid);
}
handleNodeDeselect(nid) {
console.log('node deselected : ' + nid);
}
render() {
return (
<Hawk
data={this.state}
onNodeMove={(nid, pos) => this.onNodeMove(nid, pos)}
onNodeStartMove={nid => this.onNodeStartMove(nid)}
onNewConnector={(n1, o, n2, i) => this.onNewConnector(n1, o, n2, i)}
onRemoveConnector={connector => this.onRemoveConnector(connector)}
onNodeSelect={nid => {
this.handleNodeSelect(nid);
}}
onNodeDeselect={nid => {
this.handleNodeDeselect(nid);
}}
/>
);
}
}
|
falcon-client/hawk
|
example/App.js
|
JavaScript
|
mit
| 2,441
|
import React from 'react';
import PropTypes from 'prop-types';
import { View, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { TextAmount, TextInfo } from '../../Atoms/Text';
import theme from '../../../theme';
import styles from './styles';
const { color } = theme;
const Balance = ({ balance, sendMessage }) => (
<View style={styles.containerBalance}>
<View style={styles.containerSubBalance}>
<View style={styles.containerAvailable}>
<TextInfo value="Disponible" />
<View style={styles.amount}>
<TextAmount value={`$${balance.wallet.toLocaleString()}`} />
</View>
</View>
<View style={styles.containerGoals}>
<TextInfo value="Metas" />
<View style={styles.amount}>
<TextAmount value={`$${balance.goals.toLocaleString()}`} />
</View>
</View>
</View>
<View style={styles.line} />
<View style={styles.containerTotal}>
<View style={styles.containerSubTotal}>
<TouchableOpacity
onPress={() => sendMessage({ type: 'APPLICATION', value: 'WELCOME' })}
>
<View style={styles.buttom}>
<Icon name="minus" color={color.pink} size={24} />
</View>
</TouchableOpacity>
<View style={styles.containerSubTotalData}>
<View style={styles.bigAmount}>
<TextAmount value={`$${balance.total.toLocaleString()}`} big />
</View>
<TextInfo value="Total" />
</View>
<TouchableOpacity
onPress={() => sendMessage({ type: 'APPLICATION', value: 'WELCOME' })}
>
<View style={styles.buttom}>
<Icon name="plus" color={color.pink} size={24} />
</View>
</TouchableOpacity>
</View>
</View>
</View>
);
Balance.propTypes = {
balance: PropTypes.shape({}).isRequired,
sendMessage: PropTypes.func.isRequired,
};
export default Balance;
|
martinvarelaaaa/tintina
|
app/Components/Resume/Balance/Balance.js
|
JavaScript
|
mit
| 1,992
|
package net.ar.persistence.mongodb.morphia;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.NoSuchElementException;
import java.util.Optional;
public class DateString {
private final String text;
private final TemporalAccessor temporalAccessor;
private DateString(String text, TemporalAccessor temporalAccessor) {
this.text = text;
this.temporalAccessor = temporalAccessor;
}
public static DateString of(String text) {
return new DateString(text, null);
}
public DateString parse(DateTimeFormatter formatter) {
try {
return new DateString(text, (formatter.parse(text)));
} catch (DateTimeParseException e) {
return new DateString(text, null);
}
}
public DateString orElse(DateTimeFormatter formatter) {
return temporalAccessor != null ? this : parse(formatter);
}
/**
* Returns an Optional describing the parsed date as LocalDate, if text
* could get parsed, otherwise returns an empty Optional.
*
* @return
*/
public Optional<LocalDate> mayBeLocalDate() {
return Optional.ofNullable(LocalDate.from(temporalAccessor));
}
/**
* If the text could get parsed in this DateString, returns the value as
* LocalDate, otherwise throws NoSuchElementException.
*
* @return the non-null value held by this {@code Optional}
* @throws NoSuchElementException if the text could not get parsed
*/
public LocalDate toLocalDate() {
return mayBeLocalDate().get();
}
}
|
jumpingElephant/potential-octo-broccoli
|
src/main/java/net/ar/persistence/mongodb/morphia/DateString.java
|
Java
|
mit
| 1,705
|
!function(){"use strict"}();
//# sourceMappingURL=app.js.map
|
gasolinewaltz/smauckart.com
|
assets/js-dist/app.js
|
JavaScript
|
mit
| 60
|
# mson-to-schemas
[](https://travis-ci.org/madewithlove/mson-to-schemas)
This is a package made to accept the path to an APIB files containing data structures, and convert those to a folder of JSON schemas.
## Installation
```shell
$ npm install mson-to-schemas
```
## Usage
```shell
$ mson-to-schemas path/to/file.apib output-folder [--only some-structure,some-other-structure]
```
## Testing
```shell
$ npm test
$ npm run lint
```
|
madewithlove/mson-to-schemas
|
README.md
|
Markdown
|
mit
| 526
|
/*!
* CanJS - 2.2.5
* http://canjs.com/
* Copyright (c) 2015 Bitovi
* Wed, 22 Apr 2015 15:03:29 GMT
* Licensed MIT
*/
/*can@2.2.5#util/fixture/fixture*/
define([
'can/util/library',
'can/util/string',
'can/util/object'
], function (can) {
if (!can.Object) {
throw new Error('can.fixture depends on can.Object. Please include it before can.fixture.');
}
var getUrl = function (url) {
if (typeof steal !== 'undefined') {
if (steal.joinURIs) {
var base = steal.config('baseUrl');
var joined = steal.joinURIs(base, url);
return joined;
}
if (can.isFunction(steal.config)) {
if (steal.System) {
return steal.joinURIs(steal.config('baseURL'), url);
} else {
return steal.config().root.mapJoin(url).toString();
}
}
return steal.root.join(url).toString();
}
return (can.fixture.rootUrl || '') + url;
};
var updateSettings = function (settings, originalOptions) {
if (!can.fixture.on || settings.fixture === false) {
return;
}
var log = function () {
};
settings.type = settings.type || settings.method || 'GET';
var data = overwrite(settings);
if (!settings.fixture) {
if (window.location.protocol === 'file:') {
log('ajax request to ' + settings.url + ', no fixture found');
}
return;
}
if (typeof settings.fixture === 'string' && can.fixture[settings.fixture]) {
settings.fixture = can.fixture[settings.fixture];
}
if (typeof settings.fixture === 'string') {
var url = settings.fixture;
if (/^\/\//.test(url)) {
url = getUrl(settings.fixture.substr(2));
}
if (data) {
url = can.sub(url, data);
}
delete settings.fixture;
settings.url = url;
settings.data = null;
settings.type = 'GET';
if (!settings.error) {
settings.error = function (xhr, error, message) {
throw 'fixtures.js Error ' + error + ' ' + message;
};
}
} else {
if (settings.dataTypes) {
settings.dataTypes.splice(0, 0, 'fixture');
}
if (data && originalOptions) {
originalOptions.data = originalOptions.data || {};
can.extend(originalOptions.data, data);
}
}
}, extractResponse = function (status, statusText, responses, headers) {
if (typeof status !== 'number') {
headers = statusText;
responses = status;
statusText = 'success';
status = 200;
}
if (typeof statusText !== 'string') {
headers = responses;
responses = statusText;
statusText = 'success';
}
if (status >= 400 && status <= 599) {
this.dataType = 'text';
}
return [
status,
statusText,
extractResponses(this, responses),
headers
];
}, extractResponses = function (settings, responses) {
var next = settings.dataTypes ? settings.dataTypes[0] : settings.dataType || 'json';
if (!responses || !responses[next]) {
var tmp = {};
tmp[next] = responses;
responses = tmp;
}
return responses;
};
if (can.ajaxPrefilter && can.ajaxTransport) {
can.ajaxPrefilter(updateSettings);
can.ajaxTransport('fixture', function (s, original) {
s.dataTypes.shift();
var timeout, stopped = false;
return {
send: function (headers, callback) {
timeout = setTimeout(function () {
var success = function () {
if (stopped === false) {
callback.apply(null, extractResponse.apply(s, arguments));
}
}, result = s.fixture(original, success, headers, s);
if (result !== undefined) {
callback(200, 'success', extractResponses(s, result), {});
}
}, can.fixture.delay);
},
abort: function () {
stopped = true;
clearTimeout(timeout);
}
};
});
} else {
var AJAX = can.ajax;
can.ajax = function (settings) {
updateSettings(settings, settings);
if (settings.fixture) {
var timeout, deferred = new can.Deferred(), stopped = false;
deferred.getResponseHeader = function () {
};
deferred.then(settings.success, settings.fail);
deferred.abort = function () {
clearTimeout(timeout);
stopped = true;
deferred.reject(deferred);
};
timeout = setTimeout(function () {
var success = function () {
var response = extractResponse.apply(settings, arguments), status = response[0];
if ((status >= 200 && status < 300 || status === 304) && stopped === false) {
deferred.resolve(response[2][settings.dataType]);
} else {
deferred.reject(deferred, 'error', response[1]);
}
}, result = settings.fixture(settings, success, settings.headers, settings);
if (result !== undefined) {
deferred.resolve(result);
}
}, can.fixture.delay);
return deferred;
} else {
return AJAX(settings);
}
};
}
var overwrites = [], find = function (settings, exact) {
for (var i = 0; i < overwrites.length; i++) {
if ($fixture._similar(settings, overwrites[i], exact)) {
return i;
}
}
return -1;
}, overwrite = function (settings) {
var index = find(settings);
if (index > -1) {
settings.fixture = overwrites[index].fixture;
return $fixture._getData(overwrites[index].url, settings.url);
}
}, getId = function (settings) {
var id = settings.data.id;
if (id === undefined && typeof settings.data === 'number') {
id = settings.data;
}
if (id === undefined) {
settings.url.replace(/\/(\d+)(\/|$|\.)/g, function (all, num) {
id = num;
});
}
if (id === undefined) {
id = settings.url.replace(/\/(\w+)(\/|$|\.)/g, function (all, num) {
if (num !== 'update') {
id = num;
}
});
}
if (id === undefined) {
id = Math.round(Math.random() * 1000);
}
return id;
};
var $fixture = can.fixture = function (settings, fixture) {
if (fixture !== undefined) {
if (typeof settings === 'string') {
var matches = settings.match(/(GET|POST|PUT|DELETE) (.+)/i);
if (!matches) {
settings = { url: settings };
} else {
settings = {
url: matches[2],
type: matches[1]
};
}
}
var index = find(settings, !!fixture);
if (index > -1) {
overwrites.splice(index, 1);
}
if (fixture == null) {
return;
}
settings.fixture = fixture;
overwrites.push(settings);
} else {
can.each(settings, function (fixture, url) {
$fixture(url, fixture);
});
}
};
var replacer = can.replacer;
can.extend(can.fixture, {
_similar: function (settings, overwrite, exact) {
if (exact) {
return can.Object.same(settings, overwrite, { fixture: null });
} else {
return can.Object.subset(settings, overwrite, can.fixture._compare);
}
},
_compare: {
url: function (a, b) {
return !!$fixture._getData(b, a);
},
fixture: null,
type: 'i'
},
_getData: function (fixtureUrl, url) {
var order = [], fixtureUrlAdjusted = fixtureUrl.replace('.', '\\.').replace('?', '\\?'), res = new RegExp(fixtureUrlAdjusted.replace(replacer, function (whole, part) {
order.push(part);
return '([^/]+)';
}) + '$').exec(url), data = {};
if (!res) {
return null;
}
res.shift();
can.each(order, function (name) {
data[name] = res.shift();
});
return data;
},
store: function (count, make, filter) {
var currentId = 0, findOne = function (id) {
for (var i = 0; i < items.length; i++) {
if (id == items[i].id) {
return items[i];
}
}
}, methods = {}, types, items, reset;
if (can.isArray(count) && typeof count[0] === 'string') {
types = count;
count = make;
make = filter;
filter = arguments[3];
} else if (typeof count === 'string') {
types = [
count + 's',
count
];
count = make;
make = filter;
filter = arguments[3];
}
if (typeof count === 'number') {
items = [];
reset = function () {
items = [];
for (var i = 0; i < count; i++) {
var item = make(i, items);
if (!item.id) {
item.id = i;
}
currentId = Math.max(item.id + 1, currentId + 1) || items.length;
items.push(item);
}
if (can.isArray(types)) {
can.fixture['~' + types[0]] = items;
can.fixture['-' + types[0]] = methods.findAll;
can.fixture['-' + types[1]] = methods.findOne;
can.fixture['-' + types[1] + 'Update'] = methods.update;
can.fixture['-' + types[1] + 'Destroy'] = methods.destroy;
can.fixture['-' + types[1] + 'Create'] = methods.create;
}
};
} else {
filter = make;
var initialItems = count;
reset = function () {
items = initialItems.slice(0);
};
}
can.extend(methods, {
findAll: function (request) {
request = request || {};
var retArr = items.slice(0);
request.data = request.data || {};
can.each((request.data.order || []).slice(0).reverse(), function (name) {
var split = name.split(' ');
retArr = retArr.sort(function (a, b) {
if (split[1].toUpperCase() !== 'ASC') {
if (a[split[0]] < b[split[0]]) {
return 1;
} else if (a[split[0]] === b[split[0]]) {
return 0;
} else {
return -1;
}
} else {
if (a[split[0]] < b[split[0]]) {
return -1;
} else if (a[split[0]] === b[split[0]]) {
return 0;
} else {
return 1;
}
}
});
});
can.each((request.data.group || []).slice(0).reverse(), function (name) {
var split = name.split(' ');
retArr = retArr.sort(function (a, b) {
return a[split[0]] > b[split[0]];
});
});
var offset = parseInt(request.data.offset, 10) || 0, limit = parseInt(request.data.limit, 10) || items.length - offset, i = 0;
for (var param in request.data) {
i = 0;
if (request.data[param] !== undefined && (param.indexOf('Id') !== -1 || param.indexOf('_id') !== -1)) {
while (i < retArr.length) {
if (request.data[param] != retArr[i][param]) {
retArr.splice(i, 1);
} else {
i++;
}
}
}
}
if (typeof filter === 'function') {
i = 0;
while (i < retArr.length) {
if (!filter(retArr[i], request)) {
retArr.splice(i, 1);
} else {
i++;
}
}
} else if (typeof filter === 'object') {
i = 0;
while (i < retArr.length) {
if (!can.Object.subset(retArr[i], request.data, filter)) {
retArr.splice(i, 1);
} else {
i++;
}
}
}
return {
'count': retArr.length,
'limit': request.data.limit,
'offset': request.data.offset,
'data': retArr.slice(offset, offset + limit)
};
},
findOne: function (request, response) {
var item = findOne(getId(request));
if (typeof item === 'undefined') {
return response(404, 'Requested resource not found');
}
response(item);
},
update: function (request, response) {
var id = getId(request), item = findOne(id);
if (typeof item === 'undefined') {
return response(404, 'Requested resource not found');
}
can.extend(item, request.data);
response({ id: id }, { location: request.url || '/' + getId(request) });
},
destroy: function (request, response) {
var id = getId(request), item = findOne(id);
if (typeof item === 'undefined') {
return response(404, 'Requested resource not found');
}
for (var i = 0; i < items.length; i++) {
if (items[i].id == id) {
items.splice(i, 1);
break;
}
}
return {};
},
create: function (settings, response) {
var item = typeof make === 'function' ? make(items.length, items) : {};
can.extend(item, settings.data);
if (!item.id) {
item.id = currentId++;
}
items.push(item);
response({ id: item.id }, { location: settings.url + '/' + item.id });
}
});
reset();
return can.extend({
getId: getId,
find: function (settings) {
return findOne(getId(settings));
},
reset: reset
}, methods);
},
rand: function randomize(arr, min, max) {
if (typeof arr === 'number') {
if (typeof min === 'number') {
return arr + Math.floor(Math.random() * (min - arr));
} else {
return Math.floor(Math.random() * arr);
}
}
var rand = randomize;
if (min === undefined) {
return rand(arr, rand(arr.length + 1));
}
var res = [];
arr = arr.slice(0);
if (!max) {
max = min;
}
max = min + Math.round(rand(max - min));
for (var i = 0; i < max; i++) {
res.push(arr.splice(rand(arr.length), 1)[0]);
}
return res;
},
xhr: function (xhr) {
return can.extend({}, {
abort: can.noop,
getAllResponseHeaders: function () {
return '';
},
getResponseHeader: function () {
return '';
},
open: can.noop,
overrideMimeType: can.noop,
readyState: 4,
responseText: '',
responseXML: null,
send: can.noop,
setRequestHeader: can.noop,
status: 200,
statusText: 'OK'
}, xhr);
},
on: true
});
can.fixture.delay = 200;
can.fixture.rootUrl = getUrl('');
can.fixture['-handleFunction'] = function (settings) {
if (typeof settings.fixture === 'string' && can.fixture[settings.fixture]) {
settings.fixture = can.fixture[settings.fixture];
}
if (typeof settings.fixture === 'function') {
setTimeout(function () {
if (settings.success) {
settings.success.apply(null, settings.fixture(settings, 'success'));
}
if (settings.complete) {
settings.complete.apply(null, settings.fixture(settings, 'complete'));
}
}, can.fixture.delay);
return true;
}
return false;
};
can.fixture.overwrites = overwrites;
can.fixture.make = can.fixture.store;
return can.fixture;
});
|
tka/goyangi
|
frontend/canjs/static/bower_components/canjs/amd/can/util/fixture.js
|
JavaScript
|
mit
| 20,040
|
require 'bundler/setup'
require 'rspec'
require 'rack/test'
require 'webmock/rspec'
require 'omniauth-coinbase'
RSpec.configure do |config|
config.include WebMock::API
config.include Rack::Test::Methods
config.extend OmniAuth::Test::StrategyMacros, :type => :strategy
end
|
prudhvi/omniauth-coinbase
|
spec/spec_helper.rb
|
Ruby
|
mit
| 279
|
(function (global) {
var babelHelpers = global.babelHelpers = {};
babelHelpers.typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
babelHelpers.jsx = function () {
var REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") || 0xeac7;
return function createRawReactElement(type, props, key, children) {
var defaultProps = type && type.defaultProps;
var childrenLength = arguments.length - 3;
if (!props && childrenLength !== 0) {
props = {};
}
if (props && defaultProps) {
for (var propName in defaultProps) {
if (props[propName] === void 0) {
props[propName] = defaultProps[propName];
}
}
} else if (!props) {
props = defaultProps || {};
}
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 3];
}
props.children = childArray;
}
return {
$$typeof: REACT_ELEMENT_TYPE,
type: type,
key: key === undefined ? null : '' + key,
ref: null,
props: props,
_owner: null
};
};
}();
babelHelpers.asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
return step("next", value);
}, function (err) {
return step("throw", err);
});
}
}
return step("next");
});
};
};
babelHelpers.classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
babelHelpers.createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
babelHelpers.defineEnumerableProperties = function (obj, descs) {
for (var key in descs) {
var desc = descs[key];
desc.configurable = desc.enumerable = true;
if ("value" in desc) desc.writable = true;
Object.defineProperty(obj, key, desc);
}
return obj;
};
babelHelpers.defaults = function (obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = Object.getOwnPropertyDescriptor(defaults, key);
if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}
return obj;
};
babelHelpers.defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
babelHelpers.extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
babelHelpers.get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
babelHelpers.inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
babelHelpers.instanceof = function (left, right) {
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
return right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
};
babelHelpers.interopRequireDefault = function (obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
};
babelHelpers.interopRequireWildcard = function (obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
};
babelHelpers.newArrowCheck = function (innerThis, boundThis) {
if (innerThis !== boundThis) {
throw new TypeError("Cannot instantiate an arrow function");
}
};
babelHelpers.objectDestructuringEmpty = function (obj) {
if (obj == null) throw new TypeError("Cannot destructure undefined");
};
babelHelpers.objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
babelHelpers.possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
babelHelpers.selfGlobal = typeof global === "undefined" ? self : global;
babelHelpers.set = function set(object, property, value, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent !== null) {
set(parent, property, value, receiver);
}
} else if ("value" in desc && desc.writable) {
desc.value = value;
} else {
var setter = desc.set;
if (setter !== undefined) {
setter.call(receiver, value);
}
}
return value;
};
babelHelpers.slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
babelHelpers.slicedToArrayLoose = function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
var _arr = [];
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
_arr.push(_step.value);
if (i && _arr.length === i) break;
}
return _arr;
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
babelHelpers.taggedTemplateLiteral = function (strings, raw) {
return Object.freeze(Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw)
}
}));
};
babelHelpers.taggedTemplateLiteralLoose = function (strings, raw) {
strings.raw = raw;
return strings;
};
babelHelpers.temporalRef = function (val, name, undef) {
if (val === undef) {
throw new ReferenceError(name + " is not defined - temporal dead zone");
} else {
return val;
}
};
babelHelpers.temporalUndefined = {};
babelHelpers.toArray = function (arr) {
return Array.isArray(arr) ? arr : Array.from(arr);
};
babelHelpers.toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
})(typeof global === "undefined" ? self : global);;
(function(exports) {
'use strict';
var headEl = document.getElementsByTagName('head')[0],
ie = /MSIE/.test(navigator.userAgent);
/*
normalizeName() is inspired by Ember's loader:
https://github.com/emberjs/ember.js/blob/0591740685ee2c444f2cfdbcebad0bebd89d1303/packages/loader/lib/main.js#L39-L53
*/
function normalizeName(child, parentBase) {
if (child.charAt(0) === '/') {
child = child.slice(1);
}
if (child.charAt(0) !== '.') {
return child;
}
var parts = child.split('/');
while (parts[0] === '.' || parts[0] === '..') {
if (parts.shift() === '..') {
parentBase.pop();
}
}
return parentBase.concat(parts).join('/');
}
var seen = Object.create(null);
var internalRegistry = Object.create(null);
var externalRegistry = Object.create(null);
var anonymousEntry;
function ensuredExecute(name) {
var mod = internalRegistry[name];
if (mod && !seen[name]) {
seen[name] = true;
// one time operation to execute the module body
mod.execute();
}
return mod && mod.proxy;
}
function set(name, values) {
externalRegistry[name] = values;
}
function get(name) {
return externalRegistry[name] || ensuredExecute(name);
}
function has(name) {
return !!externalRegistry[name] || !!internalRegistry[name];
}
function createScriptNode(src, callback) {
var node = document.createElement('script');
// use async=false for ordered async?
// parallel-load-serial-execute http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
if (node.async) {
node.async = false;
}
if (ie) {
node.onreadystatechange = function() {
if (/loaded|complete/.test(this.readyState)) {
this.onreadystatechange = null;
callback();
}
};
} else {
node.onload = node.onerror = callback;
}
node.setAttribute('src', src);
headEl.appendChild(node);
}
function load(name) {
return new Promise(function(resolve, reject) {
createScriptNode((System.baseURL || '/') + name + '.js', function(err) {
if (anonymousEntry) {
System.register(name, anonymousEntry[0], anonymousEntry[1]);
anonymousEntry = undefined;
}
var mod = internalRegistry[name];
if (!mod) {
reject(new Error('Error loading module ' + name));
return;
}
Promise.all(mod.deps.map(function (dep) {
if (externalRegistry[dep] || internalRegistry[dep]) {
return Promise.resolve();
}
return load(dep);
})).then(resolve, reject);
});
});
}
var System = {
set: set,
get: get,
has: has,
import: function(name) {
return new Promise(function(resolve, reject) {
var normalizedName = normalizeName(name, []);
var mod = get(normalizedName);
return mod ? resolve(mod) : load(name).then(function () {
return get(normalizedName);
});
});
},
register: function(name, deps, wrapper) {
if (Array.isArray(name)) {
// anounymous module
anonymousEntry = [];
anonymousEntry.push.apply(anonymousEntry, arguments);
return; // breaking to let the script tag to name it.
}
var proxy = Object.create(null),
values = Object.create(null),
mod, meta;
// creating a new entry in the internal registry
internalRegistry[name] = mod = {
// live bindings
proxy: proxy,
// exported values
values: values,
// normalized deps
deps: deps.map(function(dep) {
return normalizeName(dep, name.split('/').slice(0, -1));
}),
// other modules that depends on this so we can push updates into those modules
dependants: [],
// method used to push updates of deps into the module body
update: function(moduleName, moduleObj) {
meta.setters[mod.deps.indexOf(moduleName)](moduleObj);
},
execute: function() {
mod.deps.map(function(dep) {
var imports = externalRegistry[dep];
if (imports) {
mod.update(dep, imports);
} else {
imports = get(dep) && internalRegistry[dep].values; // optimization to pass plain values instead of bindings
if (imports) {
internalRegistry[dep].dependants.push(name);
mod.update(dep, imports);
}
}
});
meta.execute();
}
};
// collecting execute() and setters[]
meta = wrapper(function(identifier, value) {
values[identifier] = value;
mod.lock = true; // locking down the updates on the module to avoid infinite loop
mod.dependants.forEach(function(moduleName) {
if (internalRegistry[moduleName] && !internalRegistry[moduleName].lock) {
internalRegistry[moduleName].update(name, values);
}
});
mod.lock = false;
if (!Object.getOwnPropertyDescriptor(proxy, identifier)) {
Object.defineProperty(proxy, identifier, {
enumerable: true,
get: function() {
return values[identifier];
}
});
}
return value;
});
}
};
// exporting the System object
exports.System = System;
})(window);
;
;(function (global, factory) { // eslint-disable-line
"use strict"
/* eslint-disable no-undef */
var m = factory(global)
if (typeof module === "object" && module != null && module.exports) {
module.exports = m
} else if (typeof define === "function" && define.amd) {
define(function () { return m })
} else {
global.m = m
}
/* eslint-enable no-undef */
})(typeof window !== "undefined" ? window : {}, function (global, undefined) { // eslint-disable-line
"use strict"
m.version = function () {
return "v0.2.3"
}
var hasOwn = {}.hasOwnProperty
var type = {}.toString
function isFunction(object) {
return typeof object === "function"
}
function isObject(object) {
return type.call(object) === "[object Object]"
}
function isString(object) {
return type.call(object) === "[object String]"
}
var isArray = Array.isArray || function (object) {
return type.call(object) === "[object Array]"
}
function noop() {}
var voidElements = {
AREA: 1,
BASE: 1,
BR: 1,
COL: 1,
COMMAND: 1,
EMBED: 1,
HR: 1,
IMG: 1,
INPUT: 1,
KEYGEN: 1,
LINK: 1,
META: 1,
PARAM: 1,
SOURCE: 1,
TRACK: 1,
WBR: 1
}
// caching commonly used variables
var $document, $location, $requestAnimationFrame, $cancelAnimationFrame
// self invoking function needed because of the way mocks work
function initialize(mock) {
$document = mock.document
$location = mock.location
$cancelAnimationFrame = mock.cancelAnimationFrame || mock.clearTimeout
$requestAnimationFrame = mock.requestAnimationFrame || mock.setTimeout
}
// testing API
m.deps = function (mock) {
initialize(global = mock || window)
return global
}
m.deps(global)
/**
* @typedef {String} Tag
* A string that looks like -> div.classname#id[param=one][param2=two]
* Which describes a DOM node
*/
function parseTagAttrs(cell, tag) {
var classes = []
var parser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[.+?\])/g
var match
while ((match = parser.exec(tag))) {
if (match[1] === "" && match[2]) {
cell.tag = match[2]
} else if (match[1] === "#") {
cell.attrs.id = match[2]
} else if (match[1] === ".") {
classes.push(match[2])
} else if (match[3][0] === "[") {
var pair = /\[(.+?)(?:=("|'|)(.*?)\2)?\]/.exec(match[3])
cell.attrs[pair[1]] = pair[3] || (pair[2] ? "" : true)
}
}
return classes
}
function getVirtualChildren(args, hasAttrs) {
var children = hasAttrs ? args.slice(1) : args
if (children.length === 1 && isArray(children[0])) {
return children[0]
} else {
return children
}
}
function assignAttrs(target, attrs, classes) {
var classAttr = "class" in attrs ? "class" : "className"
for (var attrName in attrs) {
if (hasOwn.call(attrs, attrName)) {
if (attrName === classAttr &&
attrs[attrName] != null &&
attrs[attrName] !== "") {
classes.push(attrs[attrName])
// create key in correct iteration order
target[attrName] = ""
} else {
target[attrName] = attrs[attrName]
}
}
}
if (classes.length) target[classAttr] = classes.join(" ")
}
/**
*
* @param {Tag} The DOM node tag
* @param {Object=[]} optional key-value pairs to be mapped to DOM attrs
* @param {...mNode=[]} Zero or more Mithril child nodes. Can be an array,
* or splat (optional)
*/
function m(tag, pairs) {
var args = [].slice.call(arguments, 1)
if (isObject(tag)) return parameterize(tag, args)
if (!isString(tag)) {
throw new Error("selector in m(selector, attrs, children) should " +
"be a string")
}
var hasAttrs = pairs != null && isObject(pairs) &&
!("tag" in pairs || "view" in pairs || "subtree" in pairs)
var attrs = hasAttrs ? pairs : {}
var cell = {
tag: "div",
attrs: {},
children: getVirtualChildren(args, hasAttrs)
}
assignAttrs(cell.attrs, attrs, parseTagAttrs(cell, tag))
return cell
}
function forEach(list, f) {
for (var i = 0; i < list.length && !f(list[i], i++);) {
// function called in condition
}
}
function forKeys(list, f) {
forEach(list, function (attrs, i) {
return (attrs = attrs && attrs.attrs) &&
attrs.key != null &&
f(attrs, i)
})
}
// This function was causing deopts in Chrome.
function dataToString(data) {
// data.toString() might throw or return null if data is the return
// value of Console.log in some versions of Firefox (behavior depends on
// version)
try {
if (data != null && data.toString() != null) return data
} catch (e) {
// silently ignore errors
}
return ""
}
// This function was causing deopts in Chrome.
function injectTextNode(parentElement, first, index, data) {
try {
insertNode(parentElement, first, index)
first.nodeValue = data
} catch (e) {
// IE erroneously throws error when appending an empty text node
// after a null
}
}
function flatten(list) {
// recursively flatten array
for (var i = 0; i < list.length; i++) {
if (isArray(list[i])) {
list = list.concat.apply([], list)
// check current index again and flatten until there are no more
// nested arrays at that index
i--
}
}
return list
}
function insertNode(parentElement, node, index) {
parentElement.insertBefore(node,
parentElement.childNodes[index] || null)
}
var DELETION = 1
var INSERTION = 2
var MOVE = 3
function handleKeysDiffer(data, existing, cached, parentElement) {
forKeys(data, function (key, i) {
existing[key = key.key] = existing[key] ? {
action: MOVE,
index: i,
from: existing[key].index,
element: cached.nodes[existing[key].index] ||
$document.createElement("div")
} : {action: INSERTION, index: i}
})
var actions = []
for (var prop in existing) if (hasOwn.call(existing, prop)) {
actions.push(existing[prop])
}
var changes = actions.sort(sortChanges)
var newCached = new Array(cached.length)
newCached.nodes = cached.nodes.slice()
forEach(changes, function (change) {
var index = change.index
if (change.action === DELETION) {
clear(cached[index].nodes, cached[index])
newCached.splice(index, 1)
}
if (change.action === INSERTION) {
var dummy = $document.createElement("div")
dummy.key = data[index].attrs.key
insertNode(parentElement, dummy, index)
newCached.splice(index, 0, {
attrs: {key: data[index].attrs.key},
nodes: [dummy]
})
newCached.nodes[index] = dummy
}
if (change.action === MOVE) {
var changeElement = change.element
var maybeChanged = parentElement.childNodes[index]
if (maybeChanged !== changeElement && changeElement !== null) {
parentElement.insertBefore(changeElement,
maybeChanged || null)
}
newCached[index] = cached[change.from]
newCached.nodes[index] = changeElement
}
})
return newCached
}
function diffKeys(data, cached, existing, parentElement) {
var keysDiffer = data.length !== cached.length
if (!keysDiffer) {
forKeys(data, function (attrs, i) {
var cachedCell = cached[i]
return keysDiffer = cachedCell &&
cachedCell.attrs &&
cachedCell.attrs.key !== attrs.key
})
}
if (keysDiffer) {
return handleKeysDiffer(data, existing, cached, parentElement)
} else {
return cached
}
}
function diffArray(data, cached, nodes) {
// diff the array itself
// update the list of DOM nodes by collecting the nodes from each item
forEach(data, function (_, i) {
if (cached[i] != null) nodes.push.apply(nodes, cached[i].nodes)
})
// remove items from the end of the array if the new array is shorter
// than the old one. if errors ever happen here, the issue is most
// likely a bug in the construction of the `cached` data structure
// somewhere earlier in the program
forEach(cached.nodes, function (node, i) {
if (node.parentNode != null && nodes.indexOf(node) < 0) {
clear([node], [cached[i]])
}
})
if (data.length < cached.length) cached.length = data.length
cached.nodes = nodes
}
function buildArrayKeys(data) {
var guid = 0
forKeys(data, function () {
forEach(data, function (attrs) {
if ((attrs = attrs && attrs.attrs) && attrs.key == null) {
attrs.key = "__mithril__" + guid++
}
})
return 1
})
}
function isDifferentEnough(data, cached, dataAttrKeys) {
if (data.tag !== cached.tag) return true
if (dataAttrKeys.sort().join() !==
Object.keys(cached.attrs).sort().join()) {
return true
}
if (data.attrs.id !== cached.attrs.id) {
return true
}
if (data.attrs.key !== cached.attrs.key) {
return true
}
if (m.redraw.strategy() === "all") {
return !cached.configContext || cached.configContext.retain !== true
}
if (m.redraw.strategy() === "diff") {
return cached.configContext && cached.configContext.retain === false
}
return false
}
function maybeRecreateObject(data, cached, dataAttrKeys) {
// if an element is different enough from the one in cache, recreate it
if (isDifferentEnough(data, cached, dataAttrKeys)) {
if (cached.nodes.length) clear(cached.nodes)
if (cached.configContext &&
isFunction(cached.configContext.onunload)) {
cached.configContext.onunload()
}
if (cached.controllers) {
forEach(cached.controllers, function (controller) {
if (controller.onunload) controller.onunload({preventDefault: noop});
});
}
}
}
function getObjectNamespace(data, namespace) {
if (data.attrs.xmlns) return data.attrs.xmlns
if (data.tag === "svg") return "http://www.w3.org/2000/svg"
if (data.tag === "math") return "http://www.w3.org/1998/Math/MathML"
return namespace
}
var pendingRequests = 0
m.startComputation = function () { pendingRequests++ }
m.endComputation = function () {
if (pendingRequests > 1) {
pendingRequests--
} else {
pendingRequests = 0
m.redraw()
}
}
function unloadCachedControllers(cached, views, controllers) {
if (controllers.length) {
cached.views = views
cached.controllers = controllers
forEach(controllers, function (controller) {
if (controller.onunload && controller.onunload.$old) {
controller.onunload = controller.onunload.$old
}
if (pendingRequests && controller.onunload) {
var onunload = controller.onunload
controller.onunload = noop
controller.onunload.$old = onunload
}
})
}
}
function scheduleConfigsToBeCalled(configs, data, node, isNew, cached) {
// schedule configs to be called. They are called after `build` finishes
// running
if (isFunction(data.attrs.config)) {
var context = cached.configContext = cached.configContext || {}
// bind
configs.push(function () {
return data.attrs.config.call(data, node, !isNew, context,
cached)
})
}
}
function buildUpdatedNode(
cached,
data,
editable,
hasKeys,
namespace,
views,
configs,
controllers
) {
var node = cached.nodes[0]
if (hasKeys) {
setAttributes(node, data.tag, data.attrs, cached.attrs, namespace)
}
cached.children = build(
node,
data.tag,
undefined,
undefined,
data.children,
cached.children,
false,
0,
data.attrs.contenteditable ? node : editable,
namespace,
configs
)
cached.nodes.intact = true
if (controllers.length) {
cached.views = views
cached.controllers = controllers
}
return node
}
function handleNonexistentNodes(data, parentElement, index) {
var nodes
if (data.$trusted) {
nodes = injectHTML(parentElement, index, data)
} else {
nodes = [$document.createTextNode(data)]
if (!(parentElement.nodeName in voidElements)) {
insertNode(parentElement, nodes[0], index)
}
}
var cached
if (typeof data === "string" ||
typeof data === "number" ||
typeof data === "boolean") {
cached = new data.constructor(data)
} else {
cached = data
}
cached.nodes = nodes
return cached
}
function reattachNodes(
data,
cached,
parentElement,
editable,
index,
parentTag
) {
var nodes = cached.nodes
if (!editable || editable !== $document.activeElement) {
if (data.$trusted) {
clear(nodes, cached)
nodes = injectHTML(parentElement, index, data)
} else if (parentTag === "textarea") {
// <textarea> uses `value` instead of `nodeValue`.
parentElement.value = data
} else if (editable) {
// contenteditable nodes use `innerHTML` instead of `nodeValue`.
editable.innerHTML = data
} else {
// was a trusted string
if (nodes[0].nodeType === 1 || nodes.length > 1 ||
(nodes[0].nodeValue.trim &&
!nodes[0].nodeValue.trim())) {
clear(cached.nodes, cached)
nodes = [$document.createTextNode(data)]
}
injectTextNode(parentElement, nodes[0], index, data)
}
}
cached = new data.constructor(data)
cached.nodes = nodes
return cached
}
function handleTextNode(
cached,
data,
index,
parentElement,
shouldReattach,
editable,
parentTag
) {
if (!cached.nodes.length) {
return handleNonexistentNodes(data, parentElement, index)
} else if (cached.valueOf() !== data.valueOf() || shouldReattach) {
return reattachNodes(data, cached, parentElement, editable, index,
parentTag)
} else {
return (cached.nodes.intact = true, cached)
}
}
function getSubArrayCount(item) {
if (item.$trusted) {
// fix offset of next element if item was a trusted string w/ more
// than one html element
// the first clause in the regexp matches elements
// the second clause (after the pipe) matches text nodes
var match = item.match(/<[^\/]|\>\s*[^<]/g)
if (match != null) return match.length
} else if (isArray(item)) {
return item.length
}
return 1
}
function buildArray(
data,
cached,
parentElement,
index,
parentTag,
shouldReattach,
editable,
namespace,
configs
) {
data = flatten(data)
var nodes = []
var intact = cached.length === data.length
var subArrayCount = 0
// keys algorithm: sort elements without recreating them if keys are
// present
//
// 1) create a map of all existing keys, and mark all for deletion
// 2) add new keys to map and mark them for addition
// 3) if key exists in new list, change action from deletion to a move
// 4) for each key, handle its corresponding action as marked in
// previous steps
var existing = {}
var shouldMaintainIdentities = false
forKeys(cached, function (attrs, i) {
shouldMaintainIdentities = true
existing[cached[i].attrs.key] = {action: DELETION, index: i}
})
buildArrayKeys(data)
if (shouldMaintainIdentities) {
cached = diffKeys(data, cached, existing, parentElement)
}
// end key algorithm
var cacheCount = 0
// faster explicitly written
for (var i = 0, len = data.length; i < len; i++) {
// diff each item in the array
var item = build(
parentElement,
parentTag,
cached,
index,
data[i],
cached[cacheCount],
shouldReattach,
index + subArrayCount || subArrayCount,
editable,
namespace,
configs)
if (item !== undefined) {
intact = intact && item.nodes.intact
subArrayCount += getSubArrayCount(item)
cached[cacheCount++] = item
}
}
if (!intact) diffArray(data, cached, nodes)
return cached
}
function makeCache(data, cached, index, parentIndex, parentCache) {
if (cached != null) {
if (type.call(cached) === type.call(data)) return cached
if (parentCache && parentCache.nodes) {
var offset = index - parentIndex
var end = offset + (isArray(data) ? data : cached.nodes).length
clear(
parentCache.nodes.slice(offset, end),
parentCache.slice(offset, end))
} else if (cached.nodes) {
clear(cached.nodes, cached)
}
}
cached = new data.constructor()
// if constructor creates a virtual dom element, use a blank object as
// the base cached node instead of copying the virtual el (#277)
if (cached.tag) cached = {}
cached.nodes = []
return cached
}
function constructNode(data, namespace) {
if (data.attrs.is) {
if (namespace == null) {
return $document.createElement(data.tag, data.attrs.is)
} else {
return $document.createElementNS(namespace, data.tag,
data.attrs.is)
}
} else if (namespace == null) {
return $document.createElement(data.tag)
} else {
return $document.createElementNS(namespace, data.tag)
}
}
function constructAttrs(data, node, namespace, hasKeys) {
if (hasKeys) {
return setAttributes(node, data.tag, data.attrs, {}, namespace)
} else {
return data.attrs
}
}
function constructChildren(
data,
node,
cached,
editable,
namespace,
configs
) {
if (data.children != null && data.children.length > 0) {
return build(
node,
data.tag,
undefined,
undefined,
data.children,
cached.children,
true,
0,
data.attrs.contenteditable ? node : editable,
namespace,
configs)
} else {
return data.children
}
}
function reconstructCached(
data,
attrs,
children,
node,
namespace,
views,
controllers
) {
var cached = {
tag: data.tag,
attrs: attrs,
children: children,
nodes: [node]
}
unloadCachedControllers(cached, views, controllers)
if (cached.children && !cached.children.nodes) {
cached.children.nodes = []
}
// edge case: setting value on <select> doesn't work before children
// exist, so set it again after children have been created
if (data.tag === "select" && "value" in data.attrs) {
setAttributes(node, data.tag, {value: data.attrs.value}, {},
namespace)
}
return cached
}
function getController(views, view, cachedControllers, controller) {
var controllerIndex
if (m.redraw.strategy() === "diff" && views) {
controllerIndex = views.indexOf(view)
} else {
controllerIndex = -1
}
if (controllerIndex > -1) {
return cachedControllers[controllerIndex]
} else if (isFunction(controller)) {
return new controller()
} else {
return {}
}
}
var unloaders = []
function updateLists(views, controllers, view, controller) {
if (controller.onunload != null && unloaders.map(function(u) {return u.handler}).indexOf(controller.onunload) < 0) {
unloaders.push({
controller: controller,
handler: controller.onunload
})
}
views.push(view)
controllers.push(controller)
}
var forcing = false
function checkView(data, view, cached, cachedControllers, controllers, views) {
var controller = getController(cached.views, view, cachedControllers, data.controller)
var key = data && data.attrs && data.attrs.key
data = pendingRequests === 0 || forcing || cachedControllers && cachedControllers.indexOf(controller) > -1 ? data.view(controller) : {tag: "placeholder"}
if (data.subtree === "retain") return data;
data.attrs = data.attrs || {}
data.attrs.key = key
updateLists(views, controllers, view, controller)
return data
}
function markViews(data, cached, views, controllers) {
var cachedControllers = cached && cached.controllers
while (data.view != null) {
data = checkView(
data,
data.view.$original || data.view,
cached,
cachedControllers,
controllers,
views)
}
return data
}
function buildObject( // eslint-disable-line max-statements
data,
cached,
editable,
parentElement,
index,
shouldReattach,
namespace,
configs
) {
var views = []
var controllers = []
data = markViews(data, cached, views, controllers)
if (data.subtree === "retain") return cached
if (!data.tag && controllers.length) {
throw new Error("Component template must return a virtual " +
"element, not an array, string, etc.")
}
data.attrs = data.attrs || {}
cached.attrs = cached.attrs || {}
var dataAttrKeys = Object.keys(data.attrs)
var hasKeys = dataAttrKeys.length > ("key" in data.attrs ? 1 : 0)
maybeRecreateObject(data, cached, dataAttrKeys)
if (!isString(data.tag)) return
var isNew = cached.nodes.length === 0
namespace = getObjectNamespace(data, namespace)
var node
if (isNew) {
node = constructNode(data, namespace)
// set attributes first, then create children
var attrs = constructAttrs(data, node, namespace, hasKeys)
var children = constructChildren(data, node, cached, editable,
namespace, configs)
cached = reconstructCached(
data,
attrs,
children,
node,
namespace,
views,
controllers)
} else {
node = buildUpdatedNode(
cached,
data,
editable,
hasKeys,
namespace,
views,
configs,
controllers)
}
if (isNew || shouldReattach === true && node != null) {
insertNode(parentElement, node, index)
}
// The configs are called after `build` finishes running
scheduleConfigsToBeCalled(configs, data, node, isNew, cached)
return cached
}
function build(
parentElement,
parentTag,
parentCache,
parentIndex,
data,
cached,
shouldReattach,
index,
editable,
namespace,
configs
) {
/*
* `build` is a recursive function that manages creation/diffing/removal
* of DOM elements based on comparison between `data` and `cached` the
* diff algorithm can be summarized as this:
*
* 1 - compare `data` and `cached`
* 2 - if they are different, copy `data` to `cached` and update the DOM
* based on what the difference is
* 3 - recursively apply this algorithm for every array and for the
* children of every virtual element
*
* The `cached` data structure is essentially the same as the previous
* redraw's `data` data structure, with a few additions:
* - `cached` always has a property called `nodes`, which is a list of
* DOM elements that correspond to the data represented by the
* respective virtual element
* - in order to support attaching `nodes` as a property of `cached`,
* `cached` is *always* a non-primitive object, i.e. if the data was
* a string, then cached is a String instance. If data was `null` or
* `undefined`, cached is `new String("")`
* - `cached also has a `configContext` property, which is the state
* storage object exposed by config(element, isInitialized, context)
* - when `cached` is an Object, it represents a virtual element; when
* it's an Array, it represents a list of elements; when it's a
* String, Number or Boolean, it represents a text node
*
* `parentElement` is a DOM element used for W3C DOM API calls
* `parentTag` is only used for handling a corner case for textarea
* values
* `parentCache` is used to remove nodes in some multi-node cases
* `parentIndex` and `index` are used to figure out the offset of nodes.
* They're artifacts from before arrays started being flattened and are
* likely refactorable
* `data` and `cached` are, respectively, the new and old nodes being
* diffed
* `shouldReattach` is a flag indicating whether a parent node was
* recreated (if so, and if this node is reused, then this node must
* reattach itself to the new parent)
* `editable` is a flag that indicates whether an ancestor is
* contenteditable
* `namespace` indicates the closest HTML namespace as it cascades down
* from an ancestor
* `configs` is a list of config functions to run after the topmost
* `build` call finishes running
*
* there's logic that relies on the assumption that null and undefined
* data are equivalent to empty strings
* - this prevents lifecycle surprises from procedural helpers that mix
* implicit and explicit return statements (e.g.
* function foo() {if (cond) return m("div")}
* - it simplifies diffing code
*/
data = dataToString(data)
if (data.subtree === "retain") return cached
cached = makeCache(data, cached, index, parentIndex, parentCache)
if (isArray(data)) {
return buildArray(
data,
cached,
parentElement,
index,
parentTag,
shouldReattach,
editable,
namespace,
configs)
} else if (data != null && isObject(data)) {
return buildObject(
data,
cached,
editable,
parentElement,
index,
shouldReattach,
namespace,
configs)
} else if (!isFunction(data)) {
return handleTextNode(
cached,
data,
index,
parentElement,
shouldReattach,
editable,
parentTag)
} else {
return cached
}
}
function sortChanges(a, b) {
return a.action - b.action || a.index - b.index
}
function copyStyleAttrs(node, dataAttr, cachedAttr) {
for (var rule in dataAttr) if (hasOwn.call(dataAttr, rule)) {
if (cachedAttr == null || cachedAttr[rule] !== dataAttr[rule]) {
node.style[rule] = dataAttr[rule]
}
}
for (rule in cachedAttr) if (hasOwn.call(cachedAttr, rule)) {
if (!hasOwn.call(dataAttr, rule)) node.style[rule] = ""
}
}
var shouldUseSetAttribute = {
list: 1,
style: 1,
form: 1,
type: 1,
width: 1,
height: 1
}
function setSingleAttr(
node,
attrName,
dataAttr,
cachedAttr,
tag,
namespace
) {
if (attrName === "config" || attrName === "key") {
// `config` isn't a real attribute, so ignore it
return true
} else if (isFunction(dataAttr) && attrName.slice(0, 2) === "on") {
// hook event handlers to the auto-redrawing system
node[attrName] = autoredraw(dataAttr, node)
} else if (attrName === "style" && dataAttr != null &&
isObject(dataAttr)) {
// handle `style: {...}`
copyStyleAttrs(node, dataAttr, cachedAttr)
} else if (namespace != null) {
// handle SVG
if (attrName === "href") {
node.setAttributeNS("http://www.w3.org/1999/xlink",
"href", dataAttr)
} else {
node.setAttribute(
attrName === "className" ? "class" : attrName,
dataAttr)
}
} else if (attrName in node && !shouldUseSetAttribute[attrName]) {
// handle cases that are properties (but ignore cases where we
// should use setAttribute instead)
//
// - list and form are typically used as strings, but are DOM
// element references in js
//
// - when using CSS selectors (e.g. `m("[style='']")`), style is
// used as a string, but it's an object in js
//
// #348 don't set the value if not needed - otherwise, cursor
// placement breaks in Chrome
try {
if (tag !== "input" || node[attrName] !== dataAttr) {
node[attrName] = dataAttr
}
} catch (e) {
node.setAttribute(attrName, dataAttr)
}
}
else node.setAttribute(attrName, dataAttr)
}
function trySetAttr(
node,
attrName,
dataAttr,
cachedAttr,
cachedAttrs,
tag,
namespace
) {
if (!(attrName in cachedAttrs) || (cachedAttr !== dataAttr)) {
cachedAttrs[attrName] = dataAttr
try {
return setSingleAttr(
node,
attrName,
dataAttr,
cachedAttr,
tag,
namespace)
} catch (e) {
// swallow IE's invalid argument errors to mimic HTML's
// fallback-to-doing-nothing-on-invalid-attributes behavior
if (e.message.indexOf("Invalid argument") < 0) throw e
}
} else if (attrName === "value" && tag === "input" &&
node.value !== dataAttr) {
// #348 dataAttr may not be a string, so use loose comparison
node.value = dataAttr
}
}
function setAttributes(node, tag, dataAttrs, cachedAttrs, namespace) {
for (var attrName in dataAttrs) if (hasOwn.call(dataAttrs, attrName)) {
if (trySetAttr(
node,
attrName,
dataAttrs[attrName],
cachedAttrs[attrName],
cachedAttrs,
tag,
namespace)) {
continue
}
}
return cachedAttrs
}
function clear(nodes, cached) {
for (var i = nodes.length - 1; i > -1; i--) {
if (nodes[i] && nodes[i].parentNode) {
try {
nodes[i].parentNode.removeChild(nodes[i])
} catch (e) {
/* eslint-disable max-len */
// ignore if this fails due to order of events (see
// http://stackoverflow.com/questions/21926083/failed-to-execute-removechild-on-node)
/* eslint-enable max-len */
}
cached = [].concat(cached)
if (cached[i]) unload(cached[i])
}
}
// release memory if nodes is an array. This check should fail if nodes
// is a NodeList (see loop above)
if (nodes.length) {
nodes.length = 0
}
}
function unload(cached) {
if (cached.configContext && isFunction(cached.configContext.onunload)) {
cached.configContext.onunload()
cached.configContext.onunload = null
}
if (cached.controllers) {
forEach(cached.controllers, function (controller) {
if (isFunction(controller.onunload)) {
controller.onunload({preventDefault: noop})
}
})
}
if (cached.children) {
if (isArray(cached.children)) forEach(cached.children, unload)
else if (cached.children.tag) unload(cached.children)
}
}
function appendTextFragment(parentElement, data) {
try {
parentElement.appendChild(
$document.createRange().createContextualFragment(data))
} catch (e) {
parentElement.insertAdjacentHTML("beforeend", data)
}
}
function injectHTML(parentElement, index, data) {
var nextSibling = parentElement.childNodes[index]
if (nextSibling) {
var isElement = nextSibling.nodeType !== 1
var placeholder = $document.createElement("span")
if (isElement) {
parentElement.insertBefore(placeholder, nextSibling || null)
placeholder.insertAdjacentHTML("beforebegin", data)
parentElement.removeChild(placeholder)
} else {
nextSibling.insertAdjacentHTML("beforebegin", data)
}
} else {
appendTextFragment(parentElement, data)
}
var nodes = []
while (parentElement.childNodes[index] !== nextSibling) {
nodes.push(parentElement.childNodes[index])
index++
}
return nodes
}
function autoredraw(callback, object) {
return function (e) {
e = e || event
m.redraw.strategy("diff")
m.startComputation()
try {
return callback.call(object, e)
} finally {
endFirstComputation()
}
}
}
var html
var documentNode = {
appendChild: function (node) {
if (html === undefined) html = $document.createElement("html")
if ($document.documentElement &&
$document.documentElement !== node) {
$document.replaceChild(node, $document.documentElement)
} else {
$document.appendChild(node)
}
this.childNodes = $document.childNodes
},
insertBefore: function (node) {
this.appendChild(node)
},
childNodes: []
}
var nodeCache = []
var cellCache = {}
m.render = function (root, cell, forceRecreation) {
if (!root) {
throw new Error("Ensure the DOM element being passed to " +
"m.route/m.mount/m.render is not undefined.")
}
var configs = []
var id = getCellCacheKey(root)
var isDocumentRoot = root === $document
var node
if (isDocumentRoot || root === $document.documentElement) {
node = documentNode
} else {
node = root
}
if (isDocumentRoot && cell.tag !== "html") {
cell = {tag: "html", attrs: {}, children: cell}
}
if (cellCache[id] === undefined) clear(node.childNodes)
if (forceRecreation === true) reset(root)
cellCache[id] = build(
node,
null,
undefined,
undefined,
cell,
cellCache[id],
false,
0,
null,
undefined,
configs)
forEach(configs, function (config) { config() })
}
function getCellCacheKey(element) {
var index = nodeCache.indexOf(element)
return index < 0 ? nodeCache.push(element) - 1 : index
}
m.trust = function (value) {
value = new String(value) // eslint-disable-line no-new-wrappers
value.$trusted = true
return value
}
function gettersetter(store) {
function prop() {
if (arguments.length) store = arguments[0]
return store
}
prop.toJSON = function () {
return store
}
return prop
}
m.prop = function (store) {
if ((store != null && isObject(store) || isFunction(store)) &&
isFunction(store.then)) {
return propify(store)
}
return gettersetter(store)
}
var roots = []
var components = []
var controllers = []
var lastRedrawId = null
var lastRedrawCallTime = 0
var computePreRedrawHook = null
var computePostRedrawHook = null
var topComponent
var FRAME_BUDGET = 16 // 60 frames per second = 1 call per 16 ms
function parameterize(component, args) {
function controller() {
/* eslint-disable no-invalid-this */
return (component.controller || noop).apply(this, args) || this
/* eslint-enable no-invalid-this */
}
if (component.controller) {
controller.prototype = component.controller.prototype
}
function view(ctrl) {
var currentArgs = [ctrl].concat(args)
for (var i = 1; i < arguments.length; i++) {
currentArgs.push(arguments[i])
}
return component.view.apply(component, currentArgs)
}
view.$original = component.view
var output = {controller: controller, view: view}
if (args[0] && args[0].key != null) output.attrs = {key: args[0].key}
return output
}
m.component = function (component) {
var args = [].slice.call(arguments, 1)
return parameterize(component, args)
}
function checkPrevented(component, root, index, isPrevented) {
if (!isPrevented) {
m.redraw.strategy("all")
m.startComputation()
roots[index] = root
var currentComponent
if (component) {
currentComponent = topComponent = component
} else {
currentComponent = topComponent = component = {controller: noop}
}
var controller = new (component.controller || noop)()
// controllers may call m.mount recursively (via m.route redirects,
// for example)
// this conditional ensures only the last recursive m.mount call is
// applied
if (currentComponent === topComponent) {
controllers[index] = controller
components[index] = component
}
endFirstComputation()
if (component === null) {
removeRootElement(root, index)
}
return controllers[index]
} else if (component == null) {
removeRootElement(root, index)
}
}
m.mount = m.module = function (root, component) {
if (!root) {
throw new Error("Please ensure the DOM element exists before " +
"rendering a template into it.")
}
var index = roots.indexOf(root)
if (index < 0) index = roots.length
var isPrevented = false
var event = {
preventDefault: function () {
isPrevented = true
computePreRedrawHook = computePostRedrawHook = null
}
}
forEach(unloaders, function (unloader) {
unloader.handler.call(unloader.controller, event)
unloader.controller.onunload = null
})
if (isPrevented) {
forEach(unloaders, function (unloader) {
unloader.controller.onunload = unloader.handler
})
} else {
unloaders = []
}
if (controllers[index] && isFunction(controllers[index].onunload)) {
controllers[index].onunload(event)
}
return checkPrevented(component, root, index, isPrevented)
}
function removeRootElement(root, index) {
roots.splice(index, 1)
controllers.splice(index, 1)
components.splice(index, 1)
reset(root)
nodeCache.splice(getCellCacheKey(root), 1)
}
var redrawing = false
m.redraw = function (force) {
if (redrawing) return
redrawing = true
if (force) forcing = true
try {
// lastRedrawId is a positive number if a second redraw is requested
// before the next animation frame
// lastRedrawID is null if it's the first redraw and not an event
// handler
if (lastRedrawId && !force) {
// when setTimeout: only reschedule redraw if time between now
// and previous redraw is bigger than a frame, otherwise keep
// currently scheduled timeout
// when rAF: always reschedule redraw
if ($requestAnimationFrame === global.requestAnimationFrame ||
new Date() - lastRedrawCallTime > FRAME_BUDGET) {
if (lastRedrawId > 0) $cancelAnimationFrame(lastRedrawId)
lastRedrawId = $requestAnimationFrame(redraw, FRAME_BUDGET)
}
} else {
redraw()
lastRedrawId = $requestAnimationFrame(function () {
lastRedrawId = null
}, FRAME_BUDGET)
}
} finally {
redrawing = forcing = false
}
}
m.redraw.strategy = m.prop()
function redraw() {
if (computePreRedrawHook) {
computePreRedrawHook()
computePreRedrawHook = null
}
forEach(roots, function (root, i) {
var component = components[i]
if (controllers[i]) {
var args = [controllers[i]]
m.render(root,
component.view ? component.view(controllers[i], args) : "")
}
})
// after rendering within a routed context, we need to scroll back to
// the top, and fetch the document title for history.pushState
if (computePostRedrawHook) {
computePostRedrawHook()
computePostRedrawHook = null
}
lastRedrawId = null
lastRedrawCallTime = new Date()
m.redraw.strategy("diff")
}
function endFirstComputation() {
if (m.redraw.strategy() === "none") {
pendingRequests--
m.redraw.strategy("diff")
} else {
m.endComputation()
}
}
m.withAttr = function (prop, withAttrCallback, callbackThis) {
return function (e) {
e = e || event
/* eslint-disable no-invalid-this */
var currentTarget = e.currentTarget || this
var _this = callbackThis || this
/* eslint-enable no-invalid-this */
var target = prop in currentTarget ?
currentTarget[prop] :
currentTarget.getAttribute(prop)
withAttrCallback.call(_this, target)
}
}
// routing
var modes = {pathname: "", hash: "#", search: "?"}
var redirect = noop
var isDefaultRoute = false
var routeParams, currentRoute
m.route = function (root, arg1, arg2, vdom) { // eslint-disable-line
// m.route()
if (arguments.length === 0) return currentRoute
// m.route(el, defaultRoute, routes)
if (arguments.length === 3 && isString(arg1)) {
redirect = function (source) {
var path = currentRoute = normalizeRoute(source)
if (!routeByValue(root, arg2, path)) {
if (isDefaultRoute) {
throw new Error("Ensure the default route matches " +
"one of the routes defined in m.route")
}
isDefaultRoute = true
m.route(arg1, true)
isDefaultRoute = false
}
}
var listener = m.route.mode === "hash" ?
"onhashchange" :
"onpopstate"
global[listener] = function () {
var path = $location[m.route.mode]
if (m.route.mode === "pathname") path += $location.search
if (currentRoute !== normalizeRoute(path)) redirect(path)
}
computePreRedrawHook = setScroll
global[listener]()
return
}
// config: m.route
if (root.addEventListener || root.attachEvent) {
var base = m.route.mode !== "pathname" ? $location.pathname : ""
root.href = base + modes[m.route.mode] + vdom.attrs.href
if (root.addEventListener) {
root.removeEventListener("click", routeUnobtrusive)
root.addEventListener("click", routeUnobtrusive)
} else {
root.detachEvent("onclick", routeUnobtrusive)
root.attachEvent("onclick", routeUnobtrusive)
}
return
}
// m.route(route, params, shouldReplaceHistoryEntry)
if (isString(root)) {
var oldRoute = currentRoute
currentRoute = root
var args = arg1 || {}
var queryIndex = currentRoute.indexOf("?")
var params
if (queryIndex > -1) {
params = parseQueryString(currentRoute.slice(queryIndex + 1))
} else {
params = {}
}
for (var i in args) if (hasOwn.call(args, i)) {
params[i] = args[i]
}
var querystring = buildQueryString(params)
var currentPath
if (queryIndex > -1) {
currentPath = currentRoute.slice(0, queryIndex)
} else {
currentPath = currentRoute
}
if (querystring) {
currentRoute = currentPath +
(currentPath.indexOf("?") === -1 ? "?" : "&") +
querystring
}
var replaceHistory =
(arguments.length === 3 ? arg2 : arg1) === true ||
oldRoute === root
if (global.history.pushState) {
var method = replaceHistory ? "replaceState" : "pushState"
computePreRedrawHook = setScroll
computePostRedrawHook = function () {
global.history[method](null, $document.title,
modes[m.route.mode] + currentRoute)
}
redirect(modes[m.route.mode] + currentRoute)
} else {
$location[m.route.mode] = currentRoute
redirect(modes[m.route.mode] + currentRoute)
}
}
}
m.route.param = function (key) {
if (!routeParams) {
throw new Error("You must call m.route(element, defaultRoute, " +
"routes) before calling m.route.param()")
}
if (!key) {
return routeParams
}
return routeParams[key]
}
m.route.mode = "search"
function normalizeRoute(route) {
return route.slice(modes[m.route.mode].length)
}
function routeByValue(root, router, path) {
routeParams = {}
var queryStart = path.indexOf("?")
if (queryStart !== -1) {
routeParams = parseQueryString(
path.substr(queryStart + 1, path.length))
path = path.substr(0, queryStart)
}
// Get all routes and check if there's
// an exact match for the current path
var keys = Object.keys(router)
var index = keys.indexOf(path)
if (index !== -1){
m.mount(root, router[keys [index]])
return true
}
for (var route in router) if (hasOwn.call(router, route)) {
if (route === path) {
m.mount(root, router[route])
return true
}
var matcher = new RegExp("^" + route
.replace(/:[^\/]+?\.{3}/g, "(.*?)")
.replace(/:[^\/]+/g, "([^\\/]+)") + "\/?$")
if (matcher.test(path)) {
/* eslint-disable no-loop-func */
path.replace(matcher, function () {
var keys = route.match(/:[^\/]+/g) || []
var values = [].slice.call(arguments, 1, -2)
forEach(keys, function (key, i) {
routeParams[key.replace(/:|\./g, "")] =
decodeURIComponent(values[i])
})
m.mount(root, router[route])
})
/* eslint-enable no-loop-func */
return true
}
}
}
function routeUnobtrusive(e) {
e = e || event
if (e.ctrlKey || e.metaKey || e.shiftKey || e.which === 2) return
if (e.preventDefault) {
e.preventDefault()
} else {
e.returnValue = false
}
var currentTarget = e.currentTarget || e.srcElement
var args
if (m.route.mode === "pathname" && currentTarget.search) {
args = parseQueryString(currentTarget.search.slice(1))
} else {
args = {}
}
while (currentTarget && !/a/i.test(currentTarget.nodeName)) {
currentTarget = currentTarget.parentNode
}
// clear pendingRequests because we want an immediate route change
pendingRequests = 0
m.route(currentTarget[m.route.mode]
.slice(modes[m.route.mode].length), args)
}
function setScroll() {
if (m.route.mode !== "hash" && $location.hash) {
$location.hash = $location.hash
} else {
global.scrollTo(0, 0)
}
}
function buildQueryString(object, prefix) {
var duplicates = {}
var str = []
for (var prop in object) if (hasOwn.call(object, prop)) {
var key = prefix ? prefix + "[" + prop + "]" : prop
var value = object[prop]
if (value === null) {
str.push(encodeURIComponent(key))
} else if (isObject(value)) {
str.push(buildQueryString(value, key))
} else if (isArray(value)) {
var keys = []
duplicates[key] = duplicates[key] || {}
/* eslint-disable no-loop-func */
forEach(value, function (item) {
/* eslint-enable no-loop-func */
if (!duplicates[key][item]) {
duplicates[key][item] = true
keys.push(encodeURIComponent(key) + "=" +
encodeURIComponent(item))
}
})
str.push(keys.join("&"))
} else if (value !== undefined) {
str.push(encodeURIComponent(key) + "=" +
encodeURIComponent(value))
}
}
return str.join("&")
}
function parseQueryString(str) {
if (str === "" || str == null) return {}
if (str.charAt(0) === "?") str = str.slice(1)
var pairs = str.split("&")
var params = {}
forEach(pairs, function (string) {
var pair = string.split("=")
var key = decodeURIComponent(pair[0])
var value = pair.length === 2 ? decodeURIComponent(pair[1]) : null
if (params[key] != null) {
if (!isArray(params[key])) params[key] = [params[key]]
params[key].push(value)
}
else params[key] = value
})
return params
}
m.route.buildQueryString = buildQueryString
m.route.parseQueryString = parseQueryString
function reset(root) {
var cacheKey = getCellCacheKey(root)
clear(root.childNodes, cellCache[cacheKey])
cellCache[cacheKey] = undefined
}
m.deferred = function () {
var deferred = new Deferred()
deferred.promise = propify(deferred.promise)
return deferred
}
function propify(promise, initialValue) {
var prop = m.prop(initialValue)
promise.then(prop)
prop.then = function (resolve, reject) {
return propify(promise.then(resolve, reject), initialValue)
}
prop.catch = prop.then.bind(null, null)
return prop
}
// Promiz.mithril.js | Zolmeister | MIT
// a modified version of Promiz.js, which does not conform to Promises/A+
// for two reasons:
//
// 1) `then` callbacks are called synchronously (because setTimeout is too
// slow, and the setImmediate polyfill is too big
//
// 2) throwing subclasses of Error cause the error to be bubbled up instead
// of triggering rejection (because the spec does not account for the
// important use case of default browser error handling, i.e. message w/
// line number)
var RESOLVING = 1
var REJECTING = 2
var RESOLVED = 3
var REJECTED = 4
function Deferred(onSuccess, onFailure) {
var self = this
var state = 0
var promiseValue = 0
var next = []
self.promise = {}
self.resolve = function (value) {
if (!state) {
promiseValue = value
state = RESOLVING
fire()
}
return self
}
self.reject = function (value) {
if (!state) {
promiseValue = value
state = REJECTING
fire()
}
return self
}
self.promise.then = function (onSuccess, onFailure) {
var deferred = new Deferred(onSuccess, onFailure)
if (state === RESOLVED) {
deferred.resolve(promiseValue)
} else if (state === REJECTED) {
deferred.reject(promiseValue)
} else {
next.push(deferred)
}
return deferred.promise
}
function finish(type) {
state = type || REJECTED
next.map(function (deferred) {
if (state === RESOLVED) {
deferred.resolve(promiseValue)
} else {
deferred.reject(promiseValue)
}
})
}
function thennable(then, success, failure, notThennable) {
if (((promiseValue != null && isObject(promiseValue)) ||
isFunction(promiseValue)) && isFunction(then)) {
try {
// count protects against abuse calls from spec checker
var count = 0
then.call(promiseValue, function (value) {
if (count++) return
promiseValue = value
success()
}, function (value) {
if (count++) return
promiseValue = value
failure()
})
} catch (e) {
m.deferred.onerror(e)
promiseValue = e
failure()
}
} else {
notThennable()
}
}
function fire() {
// check if it's a thenable
var then
try {
then = promiseValue && promiseValue.then
} catch (e) {
m.deferred.onerror(e)
promiseValue = e
state = REJECTING
return fire()
}
if (state === REJECTING) {
m.deferred.onerror(promiseValue)
}
thennable(then, function () {
state = RESOLVING
fire()
}, function () {
state = REJECTING
fire()
}, function () {
try {
if (state === RESOLVING && isFunction(onSuccess)) {
promiseValue = onSuccess(promiseValue)
} else if (state === REJECTING && isFunction(onFailure)) {
promiseValue = onFailure(promiseValue)
state = RESOLVING
}
} catch (e) {
m.deferred.onerror(e)
promiseValue = e
return finish()
}
if (promiseValue === self) {
promiseValue = TypeError()
finish()
} else {
thennable(then, function () {
finish(RESOLVED)
}, finish, function () {
finish(state === RESOLVING && RESOLVED)
})
}
})
}
}
m.deferred.onerror = function (e) {
if (type.call(e) === "[object Error]" &&
!/ Error/.test(e.constructor.toString())) {
pendingRequests = 0
throw e
}
}
m.sync = function (args) {
var deferred = m.deferred()
var outstanding = args.length
var results = new Array(outstanding)
var method = "resolve"
function synchronizer(pos, resolved) {
return function (value) {
results[pos] = value
if (!resolved) method = "reject"
if (--outstanding === 0) {
deferred.promise(results)
deferred[method](results)
}
return value
}
}
if (args.length > 0) {
forEach(args, function (arg, i) {
arg.then(synchronizer(i, true), synchronizer(i, false))
})
} else {
deferred.resolve([])
}
return deferred.promise
}
function identity(value) { return value }
function handleJsonp(options) {
var callbackKey = "mithril_callback_" +
new Date().getTime() + "_" +
(Math.round(Math.random() * 1e16)).toString(36)
var script = $document.createElement("script")
global[callbackKey] = function (resp) {
script.parentNode.removeChild(script)
options.onload({
type: "load",
target: {
responseText: resp
}
})
global[callbackKey] = undefined
}
script.onerror = function () {
script.parentNode.removeChild(script)
options.onerror({
type: "error",
target: {
status: 500,
responseText: JSON.stringify({
error: "Error making jsonp request"
})
}
})
global[callbackKey] = undefined
return false
}
script.onload = function () {
return false
}
script.src = options.url +
(options.url.indexOf("?") > 0 ? "&" : "?") +
(options.callbackKey ? options.callbackKey : "callback") +
"=" + callbackKey +
"&" + buildQueryString(options.data || {})
$document.body.appendChild(script)
}
function createXhr(options) {
var xhr = new global.XMLHttpRequest()
xhr.open(options.method, options.url, true, options.user,
options.password)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
options.onload({type: "load", target: xhr})
} else {
options.onerror({type: "error", target: xhr})
}
}
}
if (options.serialize === JSON.stringify &&
options.data &&
options.method !== "GET") {
xhr.setRequestHeader("Content-Type",
"application/json; charset=utf-8")
}
if (options.deserialize === JSON.parse) {
xhr.setRequestHeader("Accept", "application/json, text/*")
}
if (isFunction(options.config)) {
var maybeXhr = options.config(xhr, options)
if (maybeXhr != null) xhr = maybeXhr
}
var data = options.method === "GET" || !options.data ? "" : options.data
if (data && !isString(data) && data.constructor !== global.FormData) {
throw new Error("Request data should be either be a string or " +
"FormData. Check the `serialize` option in `m.request`")
}
xhr.send(data)
return xhr
}
function ajax(options) {
if (options.dataType && options.dataType.toLowerCase() === "jsonp") {
return handleJsonp(options)
} else {
return createXhr(options)
}
}
function bindData(options, data, serialize) {
if (options.method === "GET" && options.dataType !== "jsonp") {
var prefix = options.url.indexOf("?") < 0 ? "?" : "&"
var querystring = buildQueryString(data)
options.url += (querystring ? prefix + querystring : "")
} else {
options.data = serialize(data)
}
}
function parameterizeUrl(url, data) {
if (data) {
url = url.replace(/:[a-z]\w+/gi, function(token){
var key = token.slice(1)
var value = data[key]
delete data[key]
return value
})
}
return url
}
m.request = function (options) {
if (options.background !== true) m.startComputation()
var deferred = new Deferred()
var isJSONP = options.dataType &&
options.dataType.toLowerCase() === "jsonp"
var serialize, deserialize, extract
if (isJSONP) {
serialize = options.serialize =
deserialize = options.deserialize = identity
extract = function (jsonp) { return jsonp.responseText }
} else {
serialize = options.serialize = options.serialize || JSON.stringify
deserialize = options.deserialize =
options.deserialize || JSON.parse
extract = options.extract || function (xhr) {
if (xhr.responseText.length || deserialize !== JSON.parse) {
return xhr.responseText
} else {
return null
}
}
}
options.method = (options.method || "GET").toUpperCase()
options.url = parameterizeUrl(options.url, options.data)
bindData(options, options.data, serialize)
options.onload = options.onerror = function (ev) {
try {
ev = ev || event
var response = deserialize(extract(ev.target, options))
if (ev.type === "load") {
if (options.unwrapSuccess) {
response = options.unwrapSuccess(response, ev.target)
}
if (isArray(response) && options.type) {
forEach(response, function (res, i) {
response[i] = new options.type(res)
})
} else if (options.type) {
response = new options.type(response)
}
deferred.resolve(response)
} else {
if (options.unwrapError) {
response = options.unwrapError(response, ev.target)
}
deferred.reject(response)
}
} catch (e) {
deferred.reject(e)
} finally {
if (options.background !== true) m.endComputation()
}
}
ajax(options)
deferred.promise = propify(deferred.promise, options.initialValue)
return deferred.promise
}
return m
})
;
( function _package( factory ){
if( typeof define === 'function' && define.amd ){
define( [ 'mithril' ], factory )
}
else if( typeof exports === 'object' ){
module.exports = factory( require( 'mithril' ) )
}
else{
factory( m )
}
}( function define( m ){
function bidi( node, prop ){
var type = node.tag === 'select'
? node.attrs.multi
? 'multi'
: 'select'
: node.attrs.type
// Setup: bind listeners
if( type === 'multi' ){
node.attrs.onchange = function(){
prop( [].slice.call( this.selectedOptions, function( x ){
return x.value
} ) )
}
}
else if( type === 'select' ){
node.attrs.onchange = function( e ){
prop( this.selectedOptions[ 0 ].value )
}
}
else if( type === 'checkbox' ){
node.attrs.onchange = function( e ){
prop( this.checked )
}
}
else {
node.attrs.onchange = node.attrs.oninput = function( e ){
prop( this.value )
}
}
if( node.tag === 'select' ){
node.children.forEach( function( option ){
if( option.attrs.value === prop() || option.children[ 0 ] === prop() ){
option.attrs.selected = true
}
} )
}
else if( type === 'checkbox' ){
node.attrs.checked = prop()
}
else if( type === 'radio' ){
node.attrs.checked = prop() === node.attrs.value
}
else {
node.attrs.value = prop()
}
return node
}
bidi.view = function( ctrl, node, prop ){
return bidi( node, node.attrs.bidi )
}
if( m.attrs ) m.attrs.bidi = bidi
m.bidi = bidi
return bidi
} ) )
;
/*!
* jQuery JavaScript Library v2.1.4
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-04-28T16:01Z
*/
(function( global, factory ) {
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 ) {
// Support: Firefox 18+
// Can't be in strict mode, several libs including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
//
var arr = [];
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 support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.4",
// 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.1
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// 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,
// Start with an empty selector
selector: "",
// 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 num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// 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;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
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(null);
},
// 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 = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.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";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android<4.0, iOS<6 (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 ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Support: IE9-11+
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1
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 );
},
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 value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
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
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
// Support: iOS 8.2 (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 = "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.2.0-pre
* http://sizzlejs.com/
*
* Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-16
*/
(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;
},
// General-purpose constants
MAX_NEGATIVE = 1 << 31,
// 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
// http://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
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// 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( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"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 = /[+~]/,
rescape = /'|\\/g,
// 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 );
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
};
// 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 match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
nodeType = context.nodeType;
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
if ( !seed && documentIsHTML ) {
// Try to shortcut find operations when possible (e.g., not under DocumentFragment)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType !== 1 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
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 div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = 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 = attrs.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 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// 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 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, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
parent = doc.defaultView;
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* Support tests
---------------------------------------------------------------------- */
documentIsHTML = !isXML( doc );
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( doc.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
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;
};
};
}
// 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 ( 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 http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// 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
// http://bugs.jquery.com/ticket/12359
docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\f]' 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
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
if ( !div.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 ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibing-combinator selector` fails
if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.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 ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[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 does not implement inclusive descendent
// 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 === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || 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 === doc ? -1 :
b === doc ? 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 doc;
};
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 &&
( !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.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, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
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
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && 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 ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// 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 ) {
(node[ expando ] || (node[ expando ] = {}))[ 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": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === 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,
checkNonElements = base && dir === "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 );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir 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 ] = {});
if ( (oldCache = outerCache[ dir ]) &&
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
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
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;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// 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;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, 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 );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
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 no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && 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,
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( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.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( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.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( div ) {
return div.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;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
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 ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
len = this.length,
ret = [],
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;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return 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 <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// 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] );
// Support: Blackberry 4.6
// gEBID returns nodes no longer in the document (#6963)
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).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.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
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.extend({
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;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
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 = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.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.unique( 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.unique(
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 jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || 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.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], 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" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
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 && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
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;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).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 = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
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( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// Add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// If we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
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,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// 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 ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// We once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.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 ) {
jQuery.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 ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[0], key ) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android<4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android<4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// 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) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(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, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
var data_priv = new Data();
var data_user = 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 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, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.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 = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// 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 ] );
}
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// 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
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.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 data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.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 = data_priv.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 cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Safari<=5.1
// 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: Safari<=5.1, Android<4.2
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<=11+
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* 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 = data_priv.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;
}
// 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 !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
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, false );
}
}
}
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 = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
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 the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
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(".") >= 0 ) {
// 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.namespace_re = 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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.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) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name 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;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( data_priv.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;
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.namespace_re || event.namespace_re.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, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome<28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
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 && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.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;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
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<4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// 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
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
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 mousenter/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;
}
};
});
// Support: Firefox, Chrome, Safari
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
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 ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
data_priv.remove( doc, fix );
} else {
data_priv.access( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ 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 ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
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 this;
}
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 this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( 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 );
});
},
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 );
}
}
});
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
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: IE9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
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;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
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 ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.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 ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// 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;
}
}
jQuery.extend({
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: http://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;
},
buildFragment: function( elems, context, scripts, selection ) {
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: QtWebKit, PhantomJS
// 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 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: QtWebKit, PhantomJS
// 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++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
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;
},
cleanData: function( elems ) {
var data, elem, type, key,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( jQuery.acceptData( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
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 );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
}
});
jQuery.fn.extend({
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 this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( 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 this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
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 = value.replace( rxhtmlTag, "<$1></$2>" );
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 arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
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 this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
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: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ 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 || "" ) &&
!data_priv.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 {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
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: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optimization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = iframe[ 0 ].contentDocument;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
if ( elem.ownerDocument.defaultView.opener ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
}
return window.getComputedStyle( elem, null );
};
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE9
// getPropertyValue is only needed for .css('filter') (#12537)
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
}
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: iOS < 6
// A tribute to the "awesome hack by Dean Edwards"
// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( 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
// 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 );
}
};
}
(function() {
var pixelPositionVal, boxSizingReliableVal,
docElem = document.documentElement,
container = document.createElement( "div" ),
div = document.createElement( "div" );
if ( !div.style ) {
return;
}
// Support: IE9-11+
// 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:0;height:0;top:0;left:-9999px;margin-top:1px;" +
"position:absolute";
container.appendChild( div );
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
div.innerHTML = "";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
// Support: node.js jsdom
// Don't assume that getComputedStyle is a property of the global object
if ( window.getComputedStyle ) {
jQuery.extend( support, {
pixelPosition: function() {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
marginDiv.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
docElem.removeChild( container );
div.removeChild( marginDiv );
return ret;
}
});
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.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;
};
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]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// Shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// Check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 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 offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// Some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// 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 ] );
// 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";
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = data_priv.get( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
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: {
"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 ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, 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 = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// 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, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Support: IE9-11+
// 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 ) {
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 );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, 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 || jQuery.isNumeric( 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" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// 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 ( jQuery.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 );
},
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 ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
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 || "swing";
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;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || 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.style && ( 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: IE9
// 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;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 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
start = start / scale;
jQuery.style( tween.elem, prop, start + 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 = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
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 = ( tweeners[ prop ] || [] ).concat( 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 ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = data_priv.get( elem, "fxshow" );
// Handle queue: false promises
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();
}
});
});
}
// Height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE9-10 do not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
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 ];
});
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = data_priv.access( elem, "fxshow", {} );
}
// Store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
data_priv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
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 ( jQuery.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 = animationPrefilters.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
// 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 ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, 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.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 = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.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
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ 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( isHidden ).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 || data_priv.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 = data_priv.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 = data_priv.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 ];
// Checks the timer has not already been removed
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 );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// 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 = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: iOS<=5.1, Android<=4.2+
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE<=11+
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: Android<=2.3
// Options inside disabled selects are incorrectly marked as disabled
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<=11+
// 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 nodeHook, 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 hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// 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;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/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({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = 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, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// Toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
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 ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.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.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
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;
return typeof ret === "string" ?
// Handle most common string cases
ret.replace(rreturn, "") :
// Handle cases where value is null/undef or number
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 ( jQuery.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: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-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
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled || !jQuery.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 ];
if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) {
optionSet = true;
}
}
// 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 ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error 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 );
},
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 );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* 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( "*" ),
// Document location
ajaxLocation = window.location.href,
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// 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( rnotwhite ) || [];
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: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
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: /xml/,
html: /html/,
json: /json/
},
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": jQuery.parseJSON,
// 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,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// 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 = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
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 state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
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 ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// 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 || ajaxLocation ) + "" ).replace( rhash, "" )
.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// 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 ( state === 2 ) {
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
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// 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 || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// Aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// 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 ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
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;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( 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() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
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 ( jQuery.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" ? 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, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.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( "&" ).replace( r20, "+" );
};
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();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrId = 0,
xhrCallbacks = {},
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE9
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
window.attachEvent( "onunload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
});
}
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
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 ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// Accessing binary-data responseText throws an exception
// (#11426)
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[ id ] = 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();
}
}
};
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
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({
async: true,
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 );
}
}
);
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") && 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() {
// Restore preexisting value
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";
}
});
// data: 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 ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( 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
type: type,
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 );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, 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.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
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 ) ) {
options = options.call( elem, i, 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 ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// Support: BlackBerry 5, iOS 3 (original iPhone)
// If we don't have gBCR, just use 0,0 rather than error
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.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 ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
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 )
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// 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 ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Support: Safari<7+, Chrome<37+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// 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 ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return 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, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// 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 ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
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 ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
;
//! moment.js
//! version : 2.8.4
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
(function (undefined) {
/************************************
Constants
************************************/
var moment,
VERSION = '2.8.4',
// the global-scope this is NOT the global object in Node.js
globalScope = typeof global !== 'undefined' ? global : this,
oldGlobalMoment,
round = Math.round,
hasOwnProperty = Object.prototype.hasOwnProperty,
i,
YEAR = 0,
MONTH = 1,
DATE = 2,
HOUR = 3,
MINUTE = 4,
SECOND = 5,
MILLISECOND = 6,
// internal storage for locale config files
locales = {},
// extra moment internal properties (plugins register props here)
momentProperties = [],
// check for nodeJS
hasModule = (typeof module !== 'undefined' && module && module.exports),
// ASP.NET json date format regex
aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
// format tokens
formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,
localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
// parsing token regexes
parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
parseTokenDigits = /\d+/, // nonzero number of digits
parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic.
parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
parseTokenT = /T/i, // T (ISO separator)
parseTokenOffsetMs = /[\+\-]?\d+/, // 1234567890123
parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
//strict parsing regexes
parseTokenOneDigit = /\d/, // 0 - 9
parseTokenTwoDigits = /\d\d/, // 00 - 99
parseTokenThreeDigits = /\d{3}/, // 000 - 999
parseTokenFourDigits = /\d{4}/, // 0000 - 9999
parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
isoDates = [
['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
['GGGG-[W]WW', /\d{4}-W\d{2}/],
['YYYY-DDD', /\d{4}-\d{3}/]
],
// iso time formats and regexes
isoTimes = [
['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
['HH:mm', /(T| )\d\d:\d\d/],
['HH', /(T| )\d\d/]
],
// timezone chunker '+10:00' > ['10', '00'] or '-1530' > ['-15', '30']
parseTimezoneChunker = /([\+\-]|\d\d)/gi,
// getter and setter names
proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
unitMillisecondFactors = {
'Milliseconds' : 1,
'Seconds' : 1e3,
'Minutes' : 6e4,
'Hours' : 36e5,
'Days' : 864e5,
'Months' : 2592e6,
'Years' : 31536e6
},
unitAliases = {
ms : 'millisecond',
s : 'second',
m : 'minute',
h : 'hour',
d : 'day',
D : 'date',
w : 'week',
W : 'isoWeek',
M : 'month',
Q : 'quarter',
y : 'year',
DDD : 'dayOfYear',
e : 'weekday',
E : 'isoWeekday',
gg: 'weekYear',
GG: 'isoWeekYear'
},
camelFunctions = {
dayofyear : 'dayOfYear',
isoweekday : 'isoWeekday',
isoweek : 'isoWeek',
weekyear : 'weekYear',
isoweekyear : 'isoWeekYear'
},
// format function strings
formatFunctions = {},
// default relative time thresholds
relativeTimeThresholds = {
s: 45, // seconds to minute
m: 45, // minutes to hour
h: 22, // hours to day
d: 26, // days to month
M: 11 // months to year
},
// tokens to ordinalize and pad
ordinalizeTokens = 'DDD w W M D d'.split(' '),
paddedTokens = 'M D H h m s w W'.split(' '),
formatTokenFunctions = {
M : function () {
return this.month() + 1;
},
MMM : function (format) {
return this.localeData().monthsShort(this, format);
},
MMMM : function (format) {
return this.localeData().months(this, format);
},
D : function () {
return this.date();
},
DDD : function () {
return this.dayOfYear();
},
d : function () {
return this.day();
},
dd : function (format) {
return this.localeData().weekdaysMin(this, format);
},
ddd : function (format) {
return this.localeData().weekdaysShort(this, format);
},
dddd : function (format) {
return this.localeData().weekdays(this, format);
},
w : function () {
return this.week();
},
W : function () {
return this.isoWeek();
},
YY : function () {
return leftZeroFill(this.year() % 100, 2);
},
YYYY : function () {
return leftZeroFill(this.year(), 4);
},
YYYYY : function () {
return leftZeroFill(this.year(), 5);
},
YYYYYY : function () {
var y = this.year(), sign = y >= 0 ? '+' : '-';
return sign + leftZeroFill(Math.abs(y), 6);
},
gg : function () {
return leftZeroFill(this.weekYear() % 100, 2);
},
gggg : function () {
return leftZeroFill(this.weekYear(), 4);
},
ggggg : function () {
return leftZeroFill(this.weekYear(), 5);
},
GG : function () {
return leftZeroFill(this.isoWeekYear() % 100, 2);
},
GGGG : function () {
return leftZeroFill(this.isoWeekYear(), 4);
},
GGGGG : function () {
return leftZeroFill(this.isoWeekYear(), 5);
},
e : function () {
return this.weekday();
},
E : function () {
return this.isoWeekday();
},
a : function () {
return this.localeData().meridiem(this.hours(), this.minutes(), true);
},
A : function () {
return this.localeData().meridiem(this.hours(), this.minutes(), false);
},
H : function () {
return this.hours();
},
h : function () {
return this.hours() % 12 || 12;
},
m : function () {
return this.minutes();
},
s : function () {
return this.seconds();
},
S : function () {
return toInt(this.milliseconds() / 100);
},
SS : function () {
return leftZeroFill(toInt(this.milliseconds() / 10), 2);
},
SSS : function () {
return leftZeroFill(this.milliseconds(), 3);
},
SSSS : function () {
return leftZeroFill(this.milliseconds(), 3);
},
Z : function () {
var a = -this.zone(),
b = '+';
if (a < 0) {
a = -a;
b = '-';
}
return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2);
},
ZZ : function () {
var a = -this.zone(),
b = '+';
if (a < 0) {
a = -a;
b = '-';
}
return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
},
z : function () {
return this.zoneAbbr();
},
zz : function () {
return this.zoneName();
},
x : function () {
return this.valueOf();
},
X : function () {
return this.unix();
},
Q : function () {
return this.quarter();
}
},
deprecations = {},
lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
// Pick the first defined of two or three arguments. dfl comes from
// default.
function dfl(a, b, c) {
switch (arguments.length) {
case 2: return a != null ? a : b;
case 3: return a != null ? a : b != null ? b : c;
default: throw new Error('Implement me');
}
}
function hasOwnProp(a, b) {
return hasOwnProperty.call(a, b);
}
function defaultParsingFlags() {
// We need to deep clone this object, and es5 standard is not very
// helpful.
return {
empty : false,
unusedTokens : [],
unusedInput : [],
overflow : -2,
charsLeftOver : 0,
nullInput : false,
invalidMonth : null,
invalidFormat : false,
userInvalidated : false,
iso: false
};
}
function printMsg(msg) {
if (moment.suppressDeprecationWarnings === false &&
typeof console !== 'undefined' && console.warn) {
console.warn('Deprecation warning: ' + msg);
}
}
function deprecate(msg, fn) {
var firstTime = true;
return extend(function () {
if (firstTime) {
printMsg(msg);
firstTime = false;
}
return fn.apply(this, arguments);
}, fn);
}
function deprecateSimple(name, msg) {
if (!deprecations[name]) {
printMsg(msg);
deprecations[name] = true;
}
}
function padToken(func, count) {
return function (a) {
return leftZeroFill(func.call(this, a), count);
};
}
function ordinalizeToken(func, period) {
return function (a) {
return this.localeData().ordinal(func.call(this, a), period);
};
}
while (ordinalizeTokens.length) {
i = ordinalizeTokens.pop();
formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
}
while (paddedTokens.length) {
i = paddedTokens.pop();
formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
}
formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
/************************************
Constructors
************************************/
function Locale() {
}
// Moment prototype object
function Moment(config, skipOverflow) {
if (skipOverflow !== false) {
checkOverflow(config);
}
copyConfig(this, config);
this._d = new Date(+config._d);
}
// Duration Constructor
function Duration(duration) {
var normalizedInput = normalizeObjectUnits(duration),
years = normalizedInput.year || 0,
quarters = normalizedInput.quarter || 0,
months = normalizedInput.month || 0,
weeks = normalizedInput.week || 0,
days = normalizedInput.day || 0,
hours = normalizedInput.hour || 0,
minutes = normalizedInput.minute || 0,
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;
// representation for dateAddRemove
this._milliseconds = +milliseconds +
seconds * 1e3 + // 1000
minutes * 6e4 + // 1000 * 60
hours * 36e5; // 1000 * 60 * 60
// Because of dateAddRemove treats 24 hours as different from a
// day when working around DST, we need to store them separately
this._days = +days +
weeks * 7;
// It is impossible translate months into days without knowing
// which months you are are talking about, so we have to store
// it separately.
this._months = +months +
quarters * 3 +
years * 12;
this._data = {};
this._locale = moment.localeData();
this._bubble();
}
/************************************
Helpers
************************************/
function extend(a, b) {
for (var i in b) {
if (hasOwnProp(b, i)) {
a[i] = b[i];
}
}
if (hasOwnProp(b, 'toString')) {
a.toString = b.toString;
}
if (hasOwnProp(b, 'valueOf')) {
a.valueOf = b.valueOf;
}
return a;
}
function copyConfig(to, from) {
var i, prop, val;
if (typeof from._isAMomentObject !== 'undefined') {
to._isAMomentObject = from._isAMomentObject;
}
if (typeof from._i !== 'undefined') {
to._i = from._i;
}
if (typeof from._f !== 'undefined') {
to._f = from._f;
}
if (typeof from._l !== 'undefined') {
to._l = from._l;
}
if (typeof from._strict !== 'undefined') {
to._strict = from._strict;
}
if (typeof from._tzm !== 'undefined') {
to._tzm = from._tzm;
}
if (typeof from._isUTC !== 'undefined') {
to._isUTC = from._isUTC;
}
if (typeof from._offset !== 'undefined') {
to._offset = from._offset;
}
if (typeof from._pf !== 'undefined') {
to._pf = from._pf;
}
if (typeof from._locale !== 'undefined') {
to._locale = from._locale;
}
if (momentProperties.length > 0) {
for (i in momentProperties) {
prop = momentProperties[i];
val = from[prop];
if (typeof val !== 'undefined') {
to[prop] = val;
}
}
}
return to;
}
function absRound(number) {
if (number < 0) {
return Math.ceil(number);
} else {
return Math.floor(number);
}
}
// left zero fill a number
// see http://jsperf.com/left-zero-filling for performance comparison
function leftZeroFill(number, targetLength, forceSign) {
var output = '' + Math.abs(number),
sign = number >= 0;
while (output.length < targetLength) {
output = '0' + output;
}
return (sign ? (forceSign ? '+' : '') : '-') + output;
}
function positiveMomentsDifference(base, other) {
var res = {milliseconds: 0, months: 0};
res.months = other.month() - base.month() +
(other.year() - base.year()) * 12;
if (base.clone().add(res.months, 'M').isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
return res;
}
function momentsDifference(base, other) {
var res;
other = makeAs(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
return function (val, period) {
var dur, tmp;
//invert the arguments, but complain about it
if (period !== null && !isNaN(+period)) {
deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
tmp = val; val = period; period = tmp;
}
val = typeof val === 'string' ? +val : val;
dur = moment.duration(val, period);
addOrSubtractDurationFromMoment(this, dur, direction);
return this;
};
}
function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds,
days = duration._days,
months = duration._months;
updateOffset = updateOffset == null ? true : updateOffset;
if (milliseconds) {
mom._d.setTime(+mom._d + milliseconds * isAdding);
}
if (days) {
rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
}
if (months) {
rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
}
if (updateOffset) {
moment.updateOffset(mom, days || months);
}
}
// check if is an array
function isArray(input) {
return Object.prototype.toString.call(input) === '[object Array]';
}
function isDate(input) {
return Object.prototype.toString.call(input) === '[object Date]' ||
input instanceof Date;
}
// compare two arrays, return the number of differences
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if ((dontConvert && array1[i] !== array2[i]) ||
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
diffs++;
}
}
return diffs + lengthDiff;
}
function normalizeUnits(units) {
if (units) {
var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
units = unitAliases[units] || camelFunctions[lowered] || lowered;
}
return units;
}
function normalizeObjectUnits(inputObject) {
var normalizedInput = {},
normalizedProp,
prop;
for (prop in inputObject) {
if (hasOwnProp(inputObject, prop)) {
normalizedProp = normalizeUnits(prop);
if (normalizedProp) {
normalizedInput[normalizedProp] = inputObject[prop];
}
}
}
return normalizedInput;
}
function makeList(field) {
var count, setter;
if (field.indexOf('week') === 0) {
count = 7;
setter = 'day';
}
else if (field.indexOf('month') === 0) {
count = 12;
setter = 'month';
}
else {
return;
}
moment[field] = function (format, index) {
var i, getter,
method = moment._locale[field],
results = [];
if (typeof format === 'number') {
index = format;
format = undefined;
}
getter = function (i) {
var m = moment().utc().set(setter, i);
return method.call(moment._locale, m, format || '');
};
if (index != null) {
return getter(index);
}
else {
for (i = 0; i < count; i++) {
results.push(getter(i));
}
return results;
}
};
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
if (coercedNumber >= 0) {
value = Math.floor(coercedNumber);
} else {
value = Math.ceil(coercedNumber);
}
}
return value;
}
function daysInMonth(year, month) {
return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
}
function weeksInYear(year, dow, doy) {
return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
}
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function checkOverflow(m) {
var overflow;
if (m._a && m._pf.overflow === -2) {
overflow =
m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
m._a[HOUR] < 0 || m._a[HOUR] > 24 ||
(m._a[HOUR] === 24 && (m._a[MINUTE] !== 0 ||
m._a[SECOND] !== 0 ||
m._a[MILLISECOND] !== 0)) ? HOUR :
m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
-1;
if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
overflow = DATE;
}
m._pf.overflow = overflow;
}
}
function isValid(m) {
if (m._isValid == null) {
m._isValid = !isNaN(m._d.getTime()) &&
m._pf.overflow < 0 &&
!m._pf.empty &&
!m._pf.invalidMonth &&
!m._pf.nullInput &&
!m._pf.invalidFormat &&
!m._pf.userInvalidated;
if (m._strict) {
m._isValid = m._isValid &&
m._pf.charsLeftOver === 0 &&
m._pf.unusedTokens.length === 0 &&
m._pf.bigHour === undefined;
}
}
return m._isValid;
}
function normalizeLocale(key) {
return key ? key.toLowerCase().replace('_', '-') : key;
}
// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function chooseLocale(names) {
var i = 0, j, next, locale, split;
while (i < names.length) {
split = normalizeLocale(names[i]).split('-');
j = split.length;
next = normalizeLocale(names[i + 1]);
next = next ? next.split('-') : null;
while (j > 0) {
locale = loadLocale(split.slice(0, j).join('-'));
if (locale) {
return locale;
}
if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return null;
}
function loadLocale(name) {
var oldLocale = null;
if (!locales[name] && hasModule) {
try {
oldLocale = moment.locale();
require('./locale/' + name);
// because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales
moment.locale(oldLocale);
} catch (e) { }
}
return locales[name];
}
// Return a moment from input, that is local/utc/zone equivalent to model.
function makeAs(input, model) {
var res, diff;
if (model._isUTC) {
res = model.clone();
diff = (moment.isMoment(input) || isDate(input) ?
+input : +moment(input)) - (+res);
// Use low-level api, because this fn is low-level api.
res._d.setTime(+res._d + diff);
moment.updateOffset(res, false);
return res;
} else {
return moment(input).local();
}
}
/************************************
Locale
************************************/
extend(Locale.prototype, {
set : function (config) {
var prop, i;
for (i in config) {
prop = config[i];
if (typeof prop === 'function') {
this[i] = prop;
} else {
this['_' + i] = prop;
}
}
// Lenient ordinal parsing accepts just a number in addition to
// number + (possibly) stuff coming from _ordinalParseLenient.
this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source);
},
_months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
months : function (m) {
return this._months[m.month()];
},
_monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
monthsShort : function (m) {
return this._monthsShort[m.month()];
},
monthsParse : function (monthName, format, strict) {
var i, mom, regex;
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = moment.utc([2000, i]);
if (strict && !this._longMonthsParse[i]) {
this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
}
if (!strict && !this._monthsParse[i]) {
regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
return i;
} else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
return i;
} else if (!strict && this._monthsParse[i].test(monthName)) {
return i;
}
}
},
_weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
weekdays : function (m) {
return this._weekdays[m.day()];
},
_weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
weekdaysShort : function (m) {
return this._weekdaysShort[m.day()];
},
_weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
weekdaysMin : function (m) {
return this._weekdaysMin[m.day()];
},
weekdaysParse : function (weekdayName) {
var i, mom, regex;
if (!this._weekdaysParse) {
this._weekdaysParse = [];
}
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
if (!this._weekdaysParse[i]) {
mom = moment([2000, 1]).day(i);
regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (this._weekdaysParse[i].test(weekdayName)) {
return i;
}
}
},
_longDateFormat : {
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY LT',
LLLL : 'dddd, MMMM D, YYYY LT'
},
longDateFormat : function (key) {
var output = this._longDateFormat[key];
if (!output && this._longDateFormat[key.toUpperCase()]) {
output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
return val.slice(1);
});
this._longDateFormat[key] = output;
}
return output;
},
isPM : function (input) {
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
// Using charAt should be more compatible.
return ((input + '').toLowerCase().charAt(0) === 'p');
},
_meridiemParse : /[ap]\.?m?\.?/i,
meridiem : function (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'pm' : 'PM';
} else {
return isLower ? 'am' : 'AM';
}
},
_calendar : {
sameDay : '[Today at] LT',
nextDay : '[Tomorrow at] LT',
nextWeek : 'dddd [at] LT',
lastDay : '[Yesterday at] LT',
lastWeek : '[Last] dddd [at] LT',
sameElse : 'L'
},
calendar : function (key, mom, now) {
var output = this._calendar[key];
return typeof output === 'function' ? output.apply(mom, [now]) : output;
},
_relativeTime : {
future : 'in %s',
past : '%s ago',
s : 'a few seconds',
m : 'a minute',
mm : '%d minutes',
h : 'an hour',
hh : '%d hours',
d : 'a day',
dd : '%d days',
M : 'a month',
MM : '%d months',
y : 'a year',
yy : '%d years'
},
relativeTime : function (number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return (typeof output === 'function') ?
output(number, withoutSuffix, string, isFuture) :
output.replace(/%d/i, number);
},
pastFuture : function (diff, output) {
var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
},
ordinal : function (number) {
return this._ordinal.replace('%d', number);
},
_ordinal : '%d',
_ordinalParse : /\d{1,2}/,
preparse : function (string) {
return string;
},
postformat : function (string) {
return string;
},
week : function (mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
},
_week : {
dow : 0, // Sunday is the first day of the week.
doy : 6 // The week that contains Jan 1st is the first week of the year.
},
_invalidDate: 'Invalid date',
invalidDate: function () {
return this._invalidDate;
}
});
/************************************
Formatting
************************************/
function removeFormattingTokens(input) {
if (input.match(/\[[\s\S]/)) {
return input.replace(/^\[|\]$/g, '');
}
return input.replace(/\\/g, '');
}
function makeFormatFunction(format) {
var array = format.match(formattingTokens), i, length;
for (i = 0, length = array.length; i < length; i++) {
if (formatTokenFunctions[array[i]]) {
array[i] = formatTokenFunctions[array[i]];
} else {
array[i] = removeFormattingTokens(array[i]);
}
}
return function (mom) {
var output = '';
for (i = 0; i < length; i++) {
output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
}
return output;
};
}
// format date using native date object
function formatMoment(m, format) {
if (!m.isValid()) {
return m.localeData().invalidDate();
}
format = expandFormat(format, m.localeData());
if (!formatFunctions[format]) {
formatFunctions[format] = makeFormatFunction(format);
}
return formatFunctions[format](m);
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
localFormattingTokens.lastIndex = 0;
while (i >= 0 && localFormattingTokens.test(format)) {
format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
localFormattingTokens.lastIndex = 0;
i -= 1;
}
return format;
}
/************************************
Parsing
************************************/
// get the regex to find the next token
function getParseRegexForToken(token, config) {
var a, strict = config._strict;
switch (token) {
case 'Q':
return parseTokenOneDigit;
case 'DDDD':
return parseTokenThreeDigits;
case 'YYYY':
case 'GGGG':
case 'gggg':
return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
case 'Y':
case 'G':
case 'g':
return parseTokenSignedNumber;
case 'YYYYYY':
case 'YYYYY':
case 'GGGGG':
case 'ggggg':
return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
case 'S':
if (strict) {
return parseTokenOneDigit;
}
/* falls through */
case 'SS':
if (strict) {
return parseTokenTwoDigits;
}
/* falls through */
case 'SSS':
if (strict) {
return parseTokenThreeDigits;
}
/* falls through */
case 'DDD':
return parseTokenOneToThreeDigits;
case 'MMM':
case 'MMMM':
case 'dd':
case 'ddd':
case 'dddd':
return parseTokenWord;
case 'a':
case 'A':
return config._locale._meridiemParse;
case 'x':
return parseTokenOffsetMs;
case 'X':
return parseTokenTimestampMs;
case 'Z':
case 'ZZ':
return parseTokenTimezone;
case 'T':
return parseTokenT;
case 'SSSS':
return parseTokenDigits;
case 'MM':
case 'DD':
case 'YY':
case 'GG':
case 'gg':
case 'HH':
case 'hh':
case 'mm':
case 'ss':
case 'ww':
case 'WW':
return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
case 'M':
case 'D':
case 'd':
case 'H':
case 'h':
case 'm':
case 's':
case 'w':
case 'W':
case 'e':
case 'E':
return parseTokenOneOrTwoDigits;
case 'Do':
return strict ? config._locale._ordinalParse : config._locale._ordinalParseLenient;
default :
a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i'));
return a;
}
}
function timezoneMinutesFromString(string) {
string = string || '';
var possibleTzMatches = (string.match(parseTokenTimezone) || []),
tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
minutes = +(parts[1] * 60) + toInt(parts[2]);
return parts[0] === '+' ? -minutes : minutes;
}
// function to convert string input to date
function addTimeToArrayFromToken(token, input, config) {
var a, datePartArray = config._a;
switch (token) {
// QUARTER
case 'Q':
if (input != null) {
datePartArray[MONTH] = (toInt(input) - 1) * 3;
}
break;
// MONTH
case 'M' : // fall through to MM
case 'MM' :
if (input != null) {
datePartArray[MONTH] = toInt(input) - 1;
}
break;
case 'MMM' : // fall through to MMMM
case 'MMMM' :
a = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
if (a != null) {
datePartArray[MONTH] = a;
} else {
config._pf.invalidMonth = input;
}
break;
// DAY OF MONTH
case 'D' : // fall through to DD
case 'DD' :
if (input != null) {
datePartArray[DATE] = toInt(input);
}
break;
case 'Do' :
if (input != null) {
datePartArray[DATE] = toInt(parseInt(
input.match(/\d{1,2}/)[0], 10));
}
break;
// DAY OF YEAR
case 'DDD' : // fall through to DDDD
case 'DDDD' :
if (input != null) {
config._dayOfYear = toInt(input);
}
break;
// YEAR
case 'YY' :
datePartArray[YEAR] = moment.parseTwoDigitYear(input);
break;
case 'YYYY' :
case 'YYYYY' :
case 'YYYYYY' :
datePartArray[YEAR] = toInt(input);
break;
// AM / PM
case 'a' : // fall through to A
case 'A' :
config._isPm = config._locale.isPM(input);
break;
// HOUR
case 'h' : // fall through to hh
case 'hh' :
config._pf.bigHour = true;
/* falls through */
case 'H' : // fall through to HH
case 'HH' :
datePartArray[HOUR] = toInt(input);
break;
// MINUTE
case 'm' : // fall through to mm
case 'mm' :
datePartArray[MINUTE] = toInt(input);
break;
// SECOND
case 's' : // fall through to ss
case 'ss' :
datePartArray[SECOND] = toInt(input);
break;
// MILLISECOND
case 'S' :
case 'SS' :
case 'SSS' :
case 'SSSS' :
datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
break;
// UNIX OFFSET (MILLISECONDS)
case 'x':
config._d = new Date(toInt(input));
break;
// UNIX TIMESTAMP WITH MS
case 'X':
config._d = new Date(parseFloat(input) * 1000);
break;
// TIMEZONE
case 'Z' : // fall through to ZZ
case 'ZZ' :
config._useUTC = true;
config._tzm = timezoneMinutesFromString(input);
break;
// WEEKDAY - human
case 'dd':
case 'ddd':
case 'dddd':
a = config._locale.weekdaysParse(input);
// if we didn't get a weekday name, mark the date as invalid
if (a != null) {
config._w = config._w || {};
config._w['d'] = a;
} else {
config._pf.invalidWeekday = input;
}
break;
// WEEK, WEEK DAY - numeric
case 'w':
case 'ww':
case 'W':
case 'WW':
case 'd':
case 'e':
case 'E':
token = token.substr(0, 1);
/* falls through */
case 'gggg':
case 'GGGG':
case 'GGGGG':
token = token.substr(0, 2);
if (input) {
config._w = config._w || {};
config._w[token] = toInt(input);
}
break;
case 'gg':
case 'GG':
config._w = config._w || {};
config._w[token] = moment.parseTwoDigitYear(input);
}
}
function dayOfYearFromWeekInfo(config) {
var w, weekYear, week, weekday, dow, doy, temp;
w = config._w;
if (w.GG != null || w.W != null || w.E != null) {
dow = 1;
doy = 4;
// TODO: We need to take the current isoWeekYear, but that depends on
// how we interpret now (local, utc, fixed offset). So create
// a now version of current config (take local/utc/offset flags, and
// create now).
weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year);
week = dfl(w.W, 1);
weekday = dfl(w.E, 1);
} else {
dow = config._locale._week.dow;
doy = config._locale._week.doy;
weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year);
week = dfl(w.w, 1);
if (w.d != null) {
// weekday -- low day numbers are considered next week
weekday = w.d;
if (weekday < dow) {
++week;
}
} else if (w.e != null) {
// local weekday -- counting starts from begining of week
weekday = w.e + dow;
} else {
// default to begining of week
weekday = dow;
}
}
temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow);
config._a[YEAR] = temp.year;
config._dayOfYear = temp.dayOfYear;
}
// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function dateFromConfig(config) {
var i, date, input = [], currentDate, yearToUse;
if (config._d) {
return;
}
currentDate = currentDateArray(config);
//compute day of the year from weeks and weekdays
if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
dayOfYearFromWeekInfo(config);
}
//if the day of the year is set, figure out what it is
if (config._dayOfYear) {
yearToUse = dfl(config._a[YEAR], currentDate[YEAR]);
if (config._dayOfYear > daysInYear(yearToUse)) {
config._pf._overflowDayOfYear = true;
}
date = makeUTCDate(yearToUse, 0, config._dayOfYear);
config._a[MONTH] = date.getUTCMonth();
config._a[DATE] = date.getUTCDate();
}
// Default to current date.
// * if no year, month, day of month are given, default to today
// * if day of month is given, default month and year
// * if month is given, default only year
// * if year is given, don't default anything
for (i = 0; i < 3 && config._a[i] == null; ++i) {
config._a[i] = input[i] = currentDate[i];
}
// Zero out whatever was not defaulted, including time
for (; i < 7; i++) {
config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
}
// Check for 24:00:00.000
if (config._a[HOUR] === 24 &&
config._a[MINUTE] === 0 &&
config._a[SECOND] === 0 &&
config._a[MILLISECOND] === 0) {
config._nextDay = true;
config._a[HOUR] = 0;
}
config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
// Apply timezone offset from input. The actual zone can be changed
// with parseZone.
if (config._tzm != null) {
config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm);
}
if (config._nextDay) {
config._a[HOUR] = 24;
}
}
function dateFromObject(config) {
var normalizedInput;
if (config._d) {
return;
}
normalizedInput = normalizeObjectUnits(config._i);
config._a = [
normalizedInput.year,
normalizedInput.month,
normalizedInput.day || normalizedInput.date,
normalizedInput.hour,
normalizedInput.minute,
normalizedInput.second,
normalizedInput.millisecond
];
dateFromConfig(config);
}
function currentDateArray(config) {
var now = new Date();
if (config._useUTC) {
return [
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate()
];
} else {
return [now.getFullYear(), now.getMonth(), now.getDate()];
}
}
// date from string and format string
function makeDateFromStringAndFormat(config) {
if (config._f === moment.ISO_8601) {
parseISO(config);
return;
}
config._a = [];
config._pf.empty = true;
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var string = '' + config._i,
i, parsedInput, tokens, token, skipped,
stringLength = string.length,
totalParsedInputLength = 0;
tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
if (parsedInput) {
skipped = string.substr(0, string.indexOf(parsedInput));
if (skipped.length > 0) {
config._pf.unusedInput.push(skipped);
}
string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
totalParsedInputLength += parsedInput.length;
}
// don't parse if it's not a known token
if (formatTokenFunctions[token]) {
if (parsedInput) {
config._pf.empty = false;
}
else {
config._pf.unusedTokens.push(token);
}
addTimeToArrayFromToken(token, parsedInput, config);
}
else if (config._strict && !parsedInput) {
config._pf.unusedTokens.push(token);
}
}
// add remaining unparsed input length to the string
config._pf.charsLeftOver = stringLength - totalParsedInputLength;
if (string.length > 0) {
config._pf.unusedInput.push(string);
}
// clear _12h flag if hour is <= 12
if (config._pf.bigHour === true && config._a[HOUR] <= 12) {
config._pf.bigHour = undefined;
}
// handle am pm
if (config._isPm && config._a[HOUR] < 12) {
config._a[HOUR] += 12;
}
// if is 12 am, change hours to 0
if (config._isPm === false && config._a[HOUR] === 12) {
config._a[HOUR] = 0;
}
dateFromConfig(config);
checkOverflow(config);
}
function unescapeFormat(s) {
return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
});
}
// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
function regexpEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
// date from string and array of format strings
function makeDateFromStringAndArray(config) {
var tempConfig,
bestMoment,
scoreToBeat,
i,
currentScore;
if (config._f.length === 0) {
config._pf.invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i = 0; i < config._f.length; i++) {
currentScore = 0;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._pf = defaultParsingFlags();
tempConfig._f = config._f[i];
makeDateFromStringAndFormat(tempConfig);
if (!isValid(tempConfig)) {
continue;
}
// if there is any input that was not parsed add a penalty for that format
currentScore += tempConfig._pf.charsLeftOver;
//or tokens
currentScore += tempConfig._pf.unusedTokens.length * 10;
tempConfig._pf.score = currentScore;
if (scoreToBeat == null || currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
extend(config, bestMoment || tempConfig);
}
// date from iso format
function parseISO(config) {
var i, l,
string = config._i,
match = isoRegex.exec(string);
if (match) {
config._pf.iso = true;
for (i = 0, l = isoDates.length; i < l; i++) {
if (isoDates[i][1].exec(string)) {
// match[5] should be 'T' or undefined
config._f = isoDates[i][0] + (match[6] || ' ');
break;
}
}
for (i = 0, l = isoTimes.length; i < l; i++) {
if (isoTimes[i][1].exec(string)) {
config._f += isoTimes[i][0];
break;
}
}
if (string.match(parseTokenTimezone)) {
config._f += 'Z';
}
makeDateFromStringAndFormat(config);
} else {
config._isValid = false;
}
}
// date from iso format or fallback
function makeDateFromString(config) {
parseISO(config);
if (config._isValid === false) {
delete config._isValid;
moment.createFromInputFallback(config);
}
}
function map(arr, fn) {
var res = [], i;
for (i = 0; i < arr.length; ++i) {
res.push(fn(arr[i], i));
}
return res;
}
function makeDateFromInput(config) {
var input = config._i, matched;
if (input === undefined) {
config._d = new Date();
} else if (isDate(input)) {
config._d = new Date(+input);
} else if ((matched = aspNetJsonRegex.exec(input)) !== null) {
config._d = new Date(+matched[1]);
} else if (typeof input === 'string') {
makeDateFromString(config);
} else if (isArray(input)) {
config._a = map(input.slice(0), function (obj) {
return parseInt(obj, 10);
});
dateFromConfig(config);
} else if (typeof(input) === 'object') {
dateFromObject(config);
} else if (typeof(input) === 'number') {
// from milliseconds
config._d = new Date(input);
} else {
moment.createFromInputFallback(config);
}
}
function makeDate(y, m, d, h, M, s, ms) {
//can't just apply() to create a date:
//http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
var date = new Date(y, m, d, h, M, s, ms);
//the date constructor doesn't accept years < 1970
if (y < 1970) {
date.setFullYear(y);
}
return date;
}
function makeUTCDate(y) {
var date = new Date(Date.UTC.apply(null, arguments));
if (y < 1970) {
date.setUTCFullYear(y);
}
return date;
}
function parseWeekday(input, locale) {
if (typeof input === 'string') {
if (!isNaN(input)) {
input = parseInt(input, 10);
}
else {
input = locale.weekdaysParse(input);
if (typeof input !== 'number') {
return null;
}
}
}
return input;
}
/************************************
Relative Time
************************************/
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}
function relativeTime(posNegDuration, withoutSuffix, locale) {
var duration = moment.duration(posNegDuration).abs(),
seconds = round(duration.as('s')),
minutes = round(duration.as('m')),
hours = round(duration.as('h')),
days = round(duration.as('d')),
months = round(duration.as('M')),
years = round(duration.as('y')),
args = seconds < relativeTimeThresholds.s && ['s', seconds] ||
minutes === 1 && ['m'] ||
minutes < relativeTimeThresholds.m && ['mm', minutes] ||
hours === 1 && ['h'] ||
hours < relativeTimeThresholds.h && ['hh', hours] ||
days === 1 && ['d'] ||
days < relativeTimeThresholds.d && ['dd', days] ||
months === 1 && ['M'] ||
months < relativeTimeThresholds.M && ['MM', months] ||
years === 1 && ['y'] || ['yy', years];
args[2] = withoutSuffix;
args[3] = +posNegDuration > 0;
args[4] = locale;
return substituteTimeAgo.apply({}, args);
}
/************************************
Week of Year
************************************/
// firstDayOfWeek 0 = sun, 6 = sat
// the day of the week that starts the week
// (usually sunday or monday)
// firstDayOfWeekOfYear 0 = sun, 6 = sat
// the first week is the week that contains the first
// of this day of the week
// (eg. ISO weeks use thursday (4))
function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
var end = firstDayOfWeekOfYear - firstDayOfWeek,
daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
adjustedMoment;
if (daysToDayOfWeek > end) {
daysToDayOfWeek -= 7;
}
if (daysToDayOfWeek < end - 7) {
daysToDayOfWeek += 7;
}
adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd');
return {
week: Math.ceil(adjustedMoment.dayOfYear() / 7),
year: adjustedMoment.year()
};
}
//http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
d = d === 0 ? 7 : d;
weekday = weekday != null ? weekday : firstDayOfWeek;
daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
return {
year: dayOfYear > 0 ? year : year - 1,
dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
};
}
/************************************
Top Level Functions
************************************/
function makeMoment(config) {
var input = config._i,
format = config._f,
res;
config._locale = config._locale || moment.localeData(config._l);
if (input === null || (format === undefined && input === '')) {
return moment.invalid({nullInput: true});
}
if (typeof input === 'string') {
config._i = input = config._locale.preparse(input);
}
if (moment.isMoment(input)) {
return new Moment(input, true);
} else if (format) {
if (isArray(format)) {
makeDateFromStringAndArray(config);
} else {
makeDateFromStringAndFormat(config);
}
} else {
makeDateFromInput(config);
}
res = new Moment(config);
if (res._nextDay) {
// Adding is smart enough around DST
res.add(1, 'd');
res._nextDay = undefined;
}
return res;
}
moment = function (input, format, locale, strict) {
var c;
if (typeof(locale) === 'boolean') {
strict = locale;
locale = undefined;
}
// object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c = {};
c._isAMomentObject = true;
c._i = input;
c._f = format;
c._l = locale;
c._strict = strict;
c._isUTC = false;
c._pf = defaultParsingFlags();
return makeMoment(c);
};
moment.suppressDeprecationWarnings = false;
moment.createFromInputFallback = deprecate(
'moment construction falls back to js Date. This is ' +
'discouraged and will be removed in upcoming major ' +
'release. Please refer to ' +
'https://github.com/moment/moment/issues/1407 for more info.',
function (config) {
config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
}
);
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return moment();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
moment.min = function () {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
};
moment.max = function () {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
};
// creating with utc
moment.utc = function (input, format, locale, strict) {
var c;
if (typeof(locale) === 'boolean') {
strict = locale;
locale = undefined;
}
// object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c = {};
c._isAMomentObject = true;
c._useUTC = true;
c._isUTC = true;
c._l = locale;
c._i = input;
c._f = format;
c._strict = strict;
c._pf = defaultParsingFlags();
return makeMoment(c).utc();
};
// creating with unix timestamp (in seconds)
moment.unix = function (input) {
return moment(input * 1000);
};
// duration
moment.duration = function (input, key) {
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
ret,
parseIso,
diffRes;
if (moment.isDuration(input)) {
duration = {
ms: input._milliseconds,
d: input._days,
M: input._months
};
} else if (typeof input === 'number') {
duration = {};
if (key) {
duration[key] = input;
} else {
duration.milliseconds = input;
}
} else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y: 0,
d: toInt(match[DATE]) * sign,
h: toInt(match[HOUR]) * sign,
m: toInt(match[MINUTE]) * sign,
s: toInt(match[SECOND]) * sign,
ms: toInt(match[MILLISECOND]) * sign
};
} else if (!!(match = isoDurationRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
parseIso = function (inp) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(',', '.'));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
};
duration = {
y: parseIso(match[2]),
M: parseIso(match[3]),
d: parseIso(match[4]),
h: parseIso(match[5]),
m: parseIso(match[6]),
s: parseIso(match[7]),
w: parseIso(match[8])
};
} else if (typeof duration === 'object' &&
('from' in duration || 'to' in duration)) {
diffRes = momentsDifference(moment(duration.from), moment(duration.to));
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (moment.isDuration(input) && hasOwnProp(input, '_locale')) {
ret._locale = input._locale;
}
return ret;
};
// version number
moment.version = VERSION;
// default format
moment.defaultFormat = isoFormat;
// constant that refers to the ISO standard
moment.ISO_8601 = function () {};
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
moment.momentProperties = momentProperties;
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
moment.updateOffset = function () {};
// This function allows you to set a threshold for relative time strings
moment.relativeTimeThreshold = function (threshold, limit) {
if (relativeTimeThresholds[threshold] === undefined) {
return false;
}
if (limit === undefined) {
return relativeTimeThresholds[threshold];
}
relativeTimeThresholds[threshold] = limit;
return true;
};
moment.lang = deprecate(
'moment.lang is deprecated. Use moment.locale instead.',
function (key, value) {
return moment.locale(key, value);
}
);
// This function will load locale and then set the global locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
moment.locale = function (key, values) {
var data;
if (key) {
if (typeof(values) !== 'undefined') {
data = moment.defineLocale(key, values);
}
else {
data = moment.localeData(key);
}
if (data) {
moment.duration._locale = moment._locale = data;
}
}
return moment._locale._abbr;
};
moment.defineLocale = function (name, values) {
if (values !== null) {
values.abbr = name;
if (!locales[name]) {
locales[name] = new Locale();
}
locales[name].set(values);
// backwards compat for now: also set the locale
moment.locale(name);
return locales[name];
} else {
// useful for testing
delete locales[name];
return null;
}
};
moment.langData = deprecate(
'moment.langData is deprecated. Use moment.localeData instead.',
function (key) {
return moment.localeData(key);
}
);
// returns locale data
moment.localeData = function (key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return moment._locale;
}
if (!isArray(key)) {
//short-circuit everything else
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
};
// compare moment object
moment.isMoment = function (obj) {
return obj instanceof Moment ||
(obj != null && hasOwnProp(obj, '_isAMomentObject'));
};
// for typechecking Duration objects
moment.isDuration = function (obj) {
return obj instanceof Duration;
};
for (i = lists.length - 1; i >= 0; --i) {
makeList(lists[i]);
}
moment.normalizeUnits = function (units) {
return normalizeUnits(units);
};
moment.invalid = function (flags) {
var m = moment.utc(NaN);
if (flags != null) {
extend(m._pf, flags);
}
else {
m._pf.userInvalidated = true;
}
return m;
};
moment.parseZone = function () {
return moment.apply(null, arguments).parseZone();
};
moment.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
/************************************
Moment Prototype
************************************/
extend(moment.fn = Moment.prototype, {
clone : function () {
return moment(this);
},
valueOf : function () {
return +this._d + ((this._offset || 0) * 60000);
},
unix : function () {
return Math.floor(+this / 1000);
},
toString : function () {
return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
},
toDate : function () {
return this._offset ? new Date(+this) : this._d;
},
toISOString : function () {
var m = moment(this).utc();
if (0 < m.year() && m.year() <= 9999) {
if ('function' === typeof Date.prototype.toISOString) {
// native implementation is ~50x faster, use it when we can
return this.toDate().toISOString();
} else {
return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
}
} else {
return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
}
},
toArray : function () {
var m = this;
return [
m.year(),
m.month(),
m.date(),
m.hours(),
m.minutes(),
m.seconds(),
m.milliseconds()
];
},
isValid : function () {
return isValid(this);
},
isDSTShifted : function () {
if (this._a) {
return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
}
return false;
},
parsingFlags : function () {
return extend({}, this._pf);
},
invalidAt: function () {
return this._pf.overflow;
},
utc : function (keepLocalTime) {
return this.zone(0, keepLocalTime);
},
local : function (keepLocalTime) {
if (this._isUTC) {
this.zone(0, keepLocalTime);
this._isUTC = false;
if (keepLocalTime) {
this.add(this._dateTzOffset(), 'm');
}
}
return this;
},
format : function (inputString) {
var output = formatMoment(this, inputString || moment.defaultFormat);
return this.localeData().postformat(output);
},
add : createAdder(1, 'add'),
subtract : createAdder(-1, 'subtract'),
diff : function (input, units, asFloat) {
var that = makeAs(input, this),
zoneDiff = (this.zone() - that.zone()) * 6e4,
diff, output, daysAdjust;
units = normalizeUnits(units);
if (units === 'year' || units === 'month') {
// average number of days in the months in the given dates
diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
// difference in months
output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
// adjust by taking difference in days, average number of days
// and dst in the given months.
daysAdjust = (this - moment(this).startOf('month')) -
(that - moment(that).startOf('month'));
// same as above but with zones, to negate all dst
daysAdjust -= ((this.zone() - moment(this).startOf('month').zone()) -
(that.zone() - moment(that).startOf('month').zone())) * 6e4;
output += daysAdjust / diff;
if (units === 'year') {
output = output / 12;
}
} else {
diff = (this - that);
output = units === 'second' ? diff / 1e3 : // 1000
units === 'minute' ? diff / 6e4 : // 1000 * 60
units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
diff;
}
return asFloat ? output : absRound(output);
},
from : function (time, withoutSuffix) {
return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
},
fromNow : function (withoutSuffix) {
return this.from(moment(), withoutSuffix);
},
calendar : function (time) {
// We want to compare the start of today, vs this.
// Getting start-of-today depends on whether we're zone'd or not.
var now = time || moment(),
sod = makeAs(now, this).startOf('day'),
diff = this.diff(sod, 'days', true),
format = diff < -6 ? 'sameElse' :
diff < -1 ? 'lastWeek' :
diff < 0 ? 'lastDay' :
diff < 1 ? 'sameDay' :
diff < 2 ? 'nextDay' :
diff < 7 ? 'nextWeek' : 'sameElse';
return this.format(this.localeData().calendar(format, this, moment(now)));
},
isLeapYear : function () {
return isLeapYear(this.year());
},
isDST : function () {
return (this.zone() < this.clone().month(0).zone() ||
this.zone() < this.clone().month(5).zone());
},
day : function (input) {
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, 'd');
} else {
return day;
}
},
month : makeAccessor('Month', true),
startOf : function (units) {
units = normalizeUnits(units);
// the following switch intentionally omits break keywords
// to utilize falling through the cases.
switch (units) {
case 'year':
this.month(0);
/* falls through */
case 'quarter':
case 'month':
this.date(1);
/* falls through */
case 'week':
case 'isoWeek':
case 'day':
this.hours(0);
/* falls through */
case 'hour':
this.minutes(0);
/* falls through */
case 'minute':
this.seconds(0);
/* falls through */
case 'second':
this.milliseconds(0);
/* falls through */
}
// weeks are a special case
if (units === 'week') {
this.weekday(0);
} else if (units === 'isoWeek') {
this.isoWeekday(1);
}
// quarters are also special
if (units === 'quarter') {
this.month(Math.floor(this.month() / 3) * 3);
}
return this;
},
endOf: function (units) {
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond') {
return this;
}
return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
},
isAfter: function (input, units) {
var inputMs;
units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
if (units === 'millisecond') {
input = moment.isMoment(input) ? input : moment(input);
return +this > +input;
} else {
inputMs = moment.isMoment(input) ? +input : +moment(input);
return inputMs < +this.clone().startOf(units);
}
},
isBefore: function (input, units) {
var inputMs;
units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
if (units === 'millisecond') {
input = moment.isMoment(input) ? input : moment(input);
return +this < +input;
} else {
inputMs = moment.isMoment(input) ? +input : +moment(input);
return +this.clone().endOf(units) < inputMs;
}
},
isSame: function (input, units) {
var inputMs;
units = normalizeUnits(units || 'millisecond');
if (units === 'millisecond') {
input = moment.isMoment(input) ? input : moment(input);
return +this === +input;
} else {
inputMs = +moment(input);
return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units));
}
},
min: deprecate(
'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
function (other) {
other = moment.apply(null, arguments);
return other < this ? this : other;
}
),
max: deprecate(
'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
function (other) {
other = moment.apply(null, arguments);
return other > this ? this : other;
}
),
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
zone : function (input, keepLocalTime) {
var offset = this._offset || 0,
localAdjust;
if (input != null) {
if (typeof input === 'string') {
input = timezoneMinutesFromString(input);
}
if (Math.abs(input) < 16) {
input = input * 60;
}
if (!this._isUTC && keepLocalTime) {
localAdjust = this._dateTzOffset();
}
this._offset = input;
this._isUTC = true;
if (localAdjust != null) {
this.subtract(localAdjust, 'm');
}
if (offset !== input) {
if (!keepLocalTime || this._changeInProgress) {
addOrSubtractDurationFromMoment(this,
moment.duration(offset - input, 'm'), 1, false);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
moment.updateOffset(this, true);
this._changeInProgress = null;
}
}
} else {
return this._isUTC ? offset : this._dateTzOffset();
}
return this;
},
zoneAbbr : function () {
return this._isUTC ? 'UTC' : '';
},
zoneName : function () {
return this._isUTC ? 'Coordinated Universal Time' : '';
},
parseZone : function () {
if (this._tzm) {
this.zone(this._tzm);
} else if (typeof this._i === 'string') {
this.zone(this._i);
}
return this;
},
hasAlignedHourOffset : function (input) {
if (!input) {
input = 0;
}
else {
input = moment(input).zone();
}
return (this.zone() - input) % 60 === 0;
},
daysInMonth : function () {
return daysInMonth(this.year(), this.month());
},
dayOfYear : function (input) {
var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
},
quarter : function (input) {
return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
},
weekYear : function (input) {
var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year;
return input == null ? year : this.add((input - year), 'y');
},
isoWeekYear : function (input) {
var year = weekOfYear(this, 1, 4).year;
return input == null ? year : this.add((input - year), 'y');
},
week : function (input) {
var week = this.localeData().week(this);
return input == null ? week : this.add((input - week) * 7, 'd');
},
isoWeek : function (input) {
var week = weekOfYear(this, 1, 4).week;
return input == null ? week : this.add((input - week) * 7, 'd');
},
weekday : function (input) {
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return input == null ? weekday : this.add(input - weekday, 'd');
},
isoWeekday : function (input) {
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
},
isoWeeksInYear : function () {
return weeksInYear(this.year(), 1, 4);
},
weeksInYear : function () {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
},
get : function (units) {
units = normalizeUnits(units);
return this[units]();
},
set : function (units, value) {
units = normalizeUnits(units);
if (typeof this[units] === 'function') {
this[units](value);
}
return this;
},
// If passed a locale key, it will set the locale for this
// instance. Otherwise, it will return the locale configuration
// variables for this instance.
locale : function (key) {
var newLocaleData;
if (key === undefined) {
return this._locale._abbr;
} else {
newLocaleData = moment.localeData(key);
if (newLocaleData != null) {
this._locale = newLocaleData;
}
return this;
}
},
lang : deprecate(
'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
function (key) {
if (key === undefined) {
return this.localeData();
} else {
return this.locale(key);
}
}
),
localeData : function () {
return this._locale;
},
_dateTzOffset : function () {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return Math.round(this._d.getTimezoneOffset() / 15) * 15;
}
});
function rawMonthSetter(mom, value) {
var dayOfMonth;
// TODO: Move this out of here!
if (typeof value === 'string') {
value = mom.localeData().monthsParse(value);
// TODO: Another silent failure?
if (typeof value !== 'number') {
return mom;
}
}
dayOfMonth = Math.min(mom.date(),
daysInMonth(mom.year(), value));
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
return mom;
}
function rawGetter(mom, unit) {
return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
}
function rawSetter(mom, unit, value) {
if (unit === 'Month') {
return rawMonthSetter(mom, value);
} else {
return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
}
}
function makeAccessor(unit, keepTime) {
return function (value) {
if (value != null) {
rawSetter(this, unit, value);
moment.updateOffset(this, keepTime);
return this;
} else {
return rawGetter(this, unit);
}
};
}
moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
// Setting the hour should keep the time, because the user explicitly
// specified which hour he wants. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
// moment.fn.month is defined separately
moment.fn.date = makeAccessor('Date', true);
moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true));
moment.fn.year = makeAccessor('FullYear', true);
moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true));
// add plural methods
moment.fn.days = moment.fn.day;
moment.fn.months = moment.fn.month;
moment.fn.weeks = moment.fn.week;
moment.fn.isoWeeks = moment.fn.isoWeek;
moment.fn.quarters = moment.fn.quarter;
// add aliased format methods
moment.fn.toJSON = moment.fn.toISOString;
/************************************
Duration Prototype
************************************/
function daysToYears (days) {
// 400 years have 146097 days (taking into account leap year rules)
return days * 400 / 146097;
}
function yearsToDays (years) {
// years * 365 + absRound(years / 4) -
// absRound(years / 100) + absRound(years / 400);
return years * 146097 / 400;
}
extend(moment.duration.fn = Duration.prototype, {
_bubble : function () {
var milliseconds = this._milliseconds,
days = this._days,
months = this._months,
data = this._data,
seconds, minutes, hours, years = 0;
// The following code bubbles up values, see the tests for
// examples of what that means.
data.milliseconds = milliseconds % 1000;
seconds = absRound(milliseconds / 1000);
data.seconds = seconds % 60;
minutes = absRound(seconds / 60);
data.minutes = minutes % 60;
hours = absRound(minutes / 60);
data.hours = hours % 24;
days += absRound(hours / 24);
// Accurately convert days to years, assume start from year 0.
years = absRound(daysToYears(days));
days -= absRound(yearsToDays(years));
// 30 days to a month
// TODO (iskren): Use anchor date (like 1st Jan) to compute this.
months += absRound(days / 30);
days %= 30;
// 12 months -> 1 year
years += absRound(months / 12);
months %= 12;
data.days = days;
data.months = months;
data.years = years;
},
abs : function () {
this._milliseconds = Math.abs(this._milliseconds);
this._days = Math.abs(this._days);
this._months = Math.abs(this._months);
this._data.milliseconds = Math.abs(this._data.milliseconds);
this._data.seconds = Math.abs(this._data.seconds);
this._data.minutes = Math.abs(this._data.minutes);
this._data.hours = Math.abs(this._data.hours);
this._data.months = Math.abs(this._data.months);
this._data.years = Math.abs(this._data.years);
return this;
},
weeks : function () {
return absRound(this.days() / 7);
},
valueOf : function () {
return this._milliseconds +
this._days * 864e5 +
(this._months % 12) * 2592e6 +
toInt(this._months / 12) * 31536e6;
},
humanize : function (withSuffix) {
var output = relativeTime(this, !withSuffix, this.localeData());
if (withSuffix) {
output = this.localeData().pastFuture(+this, output);
}
return this.localeData().postformat(output);
},
add : function (input, val) {
// supports only 2.0-style add(1, 's') or add(moment)
var dur = moment.duration(input, val);
this._milliseconds += dur._milliseconds;
this._days += dur._days;
this._months += dur._months;
this._bubble();
return this;
},
subtract : function (input, val) {
var dur = moment.duration(input, val);
this._milliseconds -= dur._milliseconds;
this._days -= dur._days;
this._months -= dur._months;
this._bubble();
return this;
},
get : function (units) {
units = normalizeUnits(units);
return this[units.toLowerCase() + 's']();
},
as : function (units) {
var days, months;
units = normalizeUnits(units);
if (units === 'month' || units === 'year') {
days = this._days + this._milliseconds / 864e5;
months = this._months + daysToYears(days) * 12;
return units === 'month' ? months : months / 12;
} else {
// handle milliseconds separately because of floating point math errors (issue #1867)
days = this._days + Math.round(yearsToDays(this._months / 12));
switch (units) {
case 'week': return days / 7 + this._milliseconds / 6048e5;
case 'day': return days + this._milliseconds / 864e5;
case 'hour': return days * 24 + this._milliseconds / 36e5;
case 'minute': return days * 24 * 60 + this._milliseconds / 6e4;
case 'second': return days * 24 * 60 * 60 + this._milliseconds / 1000;
// Math.floor prevents floating point math errors here
case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + this._milliseconds;
default: throw new Error('Unknown unit ' + units);
}
}
},
lang : moment.fn.lang,
locale : moment.fn.locale,
toIsoString : deprecate(
'toIsoString() is deprecated. Please use toISOString() instead ' +
'(notice the capitals)',
function () {
return this.toISOString();
}
),
toISOString : function () {
// inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
var years = Math.abs(this.years()),
months = Math.abs(this.months()),
days = Math.abs(this.days()),
hours = Math.abs(this.hours()),
minutes = Math.abs(this.minutes()),
seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
if (!this.asSeconds()) {
// this is the same as C#'s (Noda) and python (isodate)...
// but not other JS (goog.date)
return 'P0D';
}
return (this.asSeconds() < 0 ? '-' : '') +
'P' +
(years ? years + 'Y' : '') +
(months ? months + 'M' : '') +
(days ? days + 'D' : '') +
((hours || minutes || seconds) ? 'T' : '') +
(hours ? hours + 'H' : '') +
(minutes ? minutes + 'M' : '') +
(seconds ? seconds + 'S' : '');
},
localeData : function () {
return this._locale;
}
});
moment.duration.fn.toString = moment.duration.fn.toISOString;
function makeDurationGetter(name) {
moment.duration.fn[name] = function () {
return this._data[name];
};
}
for (i in unitMillisecondFactors) {
if (hasOwnProp(unitMillisecondFactors, i)) {
makeDurationGetter(i.toLowerCase());
}
}
moment.duration.fn.asMilliseconds = function () {
return this.as('ms');
};
moment.duration.fn.asSeconds = function () {
return this.as('s');
};
moment.duration.fn.asMinutes = function () {
return this.as('m');
};
moment.duration.fn.asHours = function () {
return this.as('h');
};
moment.duration.fn.asDays = function () {
return this.as('d');
};
moment.duration.fn.asWeeks = function () {
return this.as('weeks');
};
moment.duration.fn.asMonths = function () {
return this.as('M');
};
moment.duration.fn.asYears = function () {
return this.as('y');
};
/************************************
Default Locale
************************************/
// Set default locale, other locale will inherit from English.
moment.locale('en', {
ordinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal : function (number) {
var b = number % 10,
output = (toInt(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
return number + output;
}
});
/* EMBED_LOCALES */
/************************************
Exposing Moment
************************************/
function makeGlobal(shouldDeprecate) {
/*global ender:false */
if (typeof ender !== 'undefined') {
return;
}
oldGlobalMoment = globalScope.moment;
if (shouldDeprecate) {
globalScope.moment = deprecate(
'Accessing Moment through the global scope is ' +
'deprecated, and will be removed in an upcoming ' +
'release.',
moment);
} else {
globalScope.moment = moment;
}
}
// CommonJS module is defined
if (hasModule) {
module.exports = moment;
} else if (typeof define === 'function' && define.amd) {
define('moment', function (require, exports, module) {
if (module.config && module.config() && module.config().noGlobal === true) {
// release the global variable
globalScope.moment = oldGlobalMoment;
}
return moment;
});
makeGlobal(true);
} else {
makeGlobal();
}
}).call(this);
;
/* ========================================================================
* Bootstrap: affix.js v3.3.6
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.6'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
;
/* ========================================================================
* Bootstrap: dropdown.js v3.3.6
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.6'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
})
}
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div'))
.addClass('dropdown-backdrop')
.insertAfter($(this))
.on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger($.Event('shown.bs.dropdown', relatedTarget))
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
;
/* ========================================================================
* Bootstrap: modal.js v3.3.6
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.6'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function () {
that.$element.one('mouseup.dismiss.bs.modal', function (e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus()
: this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
;
/* ========================================================================
* Bootstrap: tooltip.js v3.3.6
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.6'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = { click: false, hover: false, focus: false }
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function () {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
this.arrow()
.css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
;
/* ========================================================================
* Bootstrap: transition.js v3.3.6
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
;
/**
* Copyright (c) 2011-2014 Felix Gnass
* Licensed under the MIT license
*/
(function(root, factory) {
/* CommonJS */
if (typeof exports == 'object') module.exports = factory()
/* AMD module */
else if (typeof define == 'function' && define.amd) define(factory)
/* Browser global */
else root.Spinner = factory()
}
(this, function() {
"use strict";
var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */
, animations = {} /* Animation rules keyed by their name */
, useCssAnimations /* Whether to use CSS animations or setTimeout */
/**
* Utility function to create elements. If no tag name is given,
* a DIV is created. Optionally properties can be passed.
*/
function createEl(tag, prop) {
var el = document.createElement(tag || 'div')
, n
for(n in prop) el[n] = prop[n]
return el
}
/**
* Appends children and returns the parent.
*/
function ins(parent /* child1, child2, ...*/) {
for (var i=1, n=arguments.length; i<n; i++)
parent.appendChild(arguments[i])
return parent
}
/**
* Insert a new stylesheet to hold the @keyframe or VML rules.
*/
var sheet = (function() {
var el = createEl('style', {type : 'text/css'})
ins(document.getElementsByTagName('head')[0], el)
return el.sheet || el.styleSheet
}())
/**
* Creates an opacity keyframe animation rule and returns its name.
* Since most mobile Webkits have timing issues with animation-delay,
* we create separate rules for each line/segment.
*/
function addAnimation(alpha, trail, i, lines) {
var name = ['opacity', trail, ~~(alpha*100), i, lines].join('-')
, start = 0.01 + i/lines * 100
, z = Math.max(1 - (1-alpha) / trail * (100-start), alpha)
, prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase()
, pre = prefix && '-' + prefix + '-' || ''
if (!animations[name]) {
sheet.insertRule(
'@' + pre + 'keyframes ' + name + '{' +
'0%{opacity:' + z + '}' +
start + '%{opacity:' + alpha + '}' +
(start+0.01) + '%{opacity:1}' +
(start+trail) % 100 + '%{opacity:' + alpha + '}' +
'100%{opacity:' + z + '}' +
'}', sheet.cssRules.length)
animations[name] = 1
}
return name
}
/**
* Tries various vendor prefixes and returns the first supported property.
*/
function vendor(el, prop) {
var s = el.style
, pp
, i
prop = prop.charAt(0).toUpperCase() + prop.slice(1)
for(i=0; i<prefixes.length; i++) {
pp = prefixes[i]+prop
if(s[pp] !== undefined) return pp
}
if(s[prop] !== undefined) return prop
}
/**
* Sets multiple style properties at once.
*/
function css(el, prop) {
for (var n in prop)
el.style[vendor(el, n)||n] = prop[n]
return el
}
/**
* Fills in default values.
*/
function merge(obj) {
for (var i=1; i < arguments.length; i++) {
var def = arguments[i]
for (var n in def)
if (obj[n] === undefined) obj[n] = def[n]
}
return obj
}
/**
* Returns the line color from the given string or array.
*/
function getColor(color, idx) {
return typeof color == 'string' ? color : color[idx % color.length]
}
// Built-in defaults
var defaults = {
lines: 12, // The number of lines to draw
length: 7, // The length of each line
width: 5, // The line thickness
radius: 10, // The radius of the inner circle
rotate: 0, // Rotation offset
corners: 1, // Roundness (0..1)
color: '#000', // #rgb or #rrggbb
direction: 1, // 1: clockwise, -1: counterclockwise
speed: 1, // Rounds per second
trail: 100, // Afterglow percentage
opacity: 1/4, // Opacity of the lines
fps: 20, // Frames per second when using setTimeout()
zIndex: 2e9, // Use a high z-index by default
className: 'spinner', // CSS class to assign to the element
top: '50%', // center vertically
left: '50%', // center horizontally
position: 'absolute' // element position
}
/** The constructor */
function Spinner(o) {
this.opts = merge(o || {}, Spinner.defaults, defaults)
}
// Global defaults that override the built-ins:
Spinner.defaults = {}
merge(Spinner.prototype, {
/**
* Adds the spinner to the given target element. If this instance is already
* spinning, it is automatically removed from its previous target b calling
* stop() internally.
*/
spin: function(target) {
this.stop()
var self = this
, o = self.opts
, el = self.el = css(createEl(0, {className: o.className}), {position: o.position, width: 0, zIndex: o.zIndex})
css(el, {
left: o.left,
top: o.top
})
if (target) {
target.insertBefore(el, target.firstChild||null)
}
el.setAttribute('role', 'progressbar')
self.lines(el, self.opts)
if (!useCssAnimations) {
// No CSS animation support, use setTimeout() instead
var i = 0
, start = (o.lines - 1) * (1 - o.direction) / 2
, alpha
, fps = o.fps
, f = fps/o.speed
, ostep = (1-o.opacity) / (f*o.trail / 100)
, astep = f/o.lines
;(function anim() {
i++;
for (var j = 0; j < o.lines; j++) {
alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity)
self.opacity(el, j * o.direction + start, alpha, o)
}
self.timeout = self.el && setTimeout(anim, ~~(1000/fps))
})()
}
return self
},
/**
* Stops and removes the Spinner.
*/
stop: function() {
var el = this.el
if (el) {
clearTimeout(this.timeout)
if (el.parentNode) el.parentNode.removeChild(el)
this.el = undefined
}
return this
},
/**
* Internal method that draws the individual lines. Will be overwritten
* in VML fallback mode below.
*/
lines: function(el, o) {
var i = 0
, start = (o.lines - 1) * (1 - o.direction) / 2
, seg
function fill(color, shadow) {
return css(createEl(), {
position: 'absolute',
width: (o.length+o.width) + 'px',
height: o.width + 'px',
background: color,
boxShadow: shadow,
transformOrigin: 'left',
transform: 'rotate(' + ~~(360/o.lines*i+o.rotate) + 'deg) translate(' + o.radius+'px' +',0)',
borderRadius: (o.corners * o.width>>1) + 'px'
})
}
for (; i < o.lines; i++) {
seg = css(createEl(), {
position: 'absolute',
top: 1+~(o.width/2) + 'px',
transform: o.hwaccel ? 'translate3d(0,0,0)' : '',
opacity: o.opacity,
animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1/o.speed + 's linear infinite'
})
if (o.shadow) ins(seg, css(fill('#000', '0 0 4px ' + '#000'), {top: 2+'px'}))
ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)')))
}
return el
},
/**
* Internal method that adjusts the opacity of a single line.
* Will be overwritten in VML fallback mode below.
*/
opacity: function(el, i, val) {
if (i < el.childNodes.length) el.childNodes[i].style.opacity = val
}
})
function initVML() {
/* Utility function to create a VML tag */
function vml(tag, attr) {
return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr)
}
// No CSS transforms but VML support, add a CSS rule for VML elements:
sheet.addRule('.spin-vml', 'behavior:url(#default#VML)')
Spinner.prototype.lines = function(el, o) {
var r = o.length+o.width
, s = 2*r
function grp() {
return css(
vml('group', {
coordsize: s + ' ' + s,
coordorigin: -r + ' ' + -r
}),
{ width: s, height: s }
)
}
var margin = -(o.width+o.length)*2 + 'px'
, g = css(grp(), {position: 'absolute', top: margin, left: margin})
, i
function seg(i, dx, filter) {
ins(g,
ins(css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}),
ins(css(vml('roundrect', {arcsize: o.corners}), {
width: r,
height: o.width,
left: o.radius,
top: -o.width>>1,
filter: filter
}),
vml('fill', {color: getColor(o.color, i), opacity: o.opacity}),
vml('stroke', {opacity: 0}) // transparent stroke to fix color bleeding upon opacity change
)
)
)
}
if (o.shadow)
for (i = 1; i <= o.lines; i++)
seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)')
for (i = 1; i <= o.lines; i++) seg(i)
return ins(el, g)
}
Spinner.prototype.opacity = function(el, i, val, o) {
var c = el.firstChild
o = o.shadow && o.lines || 0
if (c && i+o < c.childNodes.length) {
c = c.childNodes[i+o]; c = c && c.firstChild; c = c && c.firstChild
if (c) c.opacity = val
}
}
}
var probe = css(createEl('group'), {behavior: 'url(#default#VML)'})
if (!vendor(probe, 'transform') && probe.adj) initVML()
else useCssAnimations = vendor(probe, 'animation')
return Spinner
}));
;
/**
* Copyright (c) 2011-2014 Felix Gnass
* Licensed under the MIT license
*/
/*
Basic Usage:
============
$('#el').spin(); // Creates a default Spinner using the text color of #el.
$('#el').spin({ ... }); // Creates a Spinner using the provided options.
$('#el').spin(false); // Stops and removes the spinner.
Using Presets:
==============
$('#el').spin('small'); // Creates a 'small' Spinner using the text color of #el.
$('#el').spin('large', '#fff'); // Creates a 'large' white Spinner.
Adding a custom preset:
=======================
$.fn.spin.presets.flower = {
lines: 9,
length: 10,
width: 20,
radius: 0
}
$('#el').spin('flower', 'red');
*/
(function(factory) {
if (typeof exports == 'object') {
// CommonJS
factory(require('jquery'), require('spin.js'))
}
else if (typeof define == 'function' && define.amd) {
// AMD, register as anonymous module
define(['jquery', 'spin'], factory)
}
else {
// Browser globals
if (!window.Spinner) throw new Error('Spin.js not present')
factory(window.jQuery, window.Spinner)
}
}(function($, Spinner) {
$.fn.spin = function(opts, color) {
return this.each(function() {
var $this = $(this),
data = $this.data();
if (data.spinner) {
data.spinner.stop();
delete data.spinner;
}
if (opts !== false) {
opts = $.extend(
{ color: color || $this.css('color') },
$.fn.spin.presets[opts] || opts
)
data.spinner = new Spinner(opts).spin(this)
}
})
}
$.fn.spin.presets = {
tiny: { lines: 8, length: 2, width: 2, radius: 3 },
small: { lines: 8, length: 4, width: 3, radius: 5 },
large: { lines: 10, length: 8, width: 4, radius: 8 }
}
}));
;
'use strict';
System.register('flarum/app', ['flarum/App', 'flarum/initializers/store', 'flarum/initializers/preload', 'flarum/initializers/routes', 'flarum/initializers/boot'], function (_export, _context) {
"use strict";
var App, store, preload, routes, boot, app;
return {
setters: [function (_flarumApp) {
App = _flarumApp.default;
}, function (_flarumInitializersStore) {
store = _flarumInitializersStore.default;
}, function (_flarumInitializersPreload) {
preload = _flarumInitializersPreload.default;
}, function (_flarumInitializersRoutes) {
routes = _flarumInitializersRoutes.default;
}, function (_flarumInitializersBoot) {
boot = _flarumInitializersBoot.default;
}],
execute: function () {
app = new App();
app.initializers.add('store', store);
app.initializers.add('routes', routes);
app.initializers.add('preload', preload, -100);
app.initializers.add('boot', boot, -100);
app.extensionSettings = {};
_export('default', app);
}
};
});;
'use strict';
System.register('flarum/App', ['flarum/utils/ItemList', 'flarum/components/Alert', 'flarum/components/Button', 'flarum/components/RequestErrorModal', 'flarum/components/ConfirmPasswordModal', 'flarum/Translator', 'flarum/utils/extract', 'flarum/utils/patchMithril', 'flarum/utils/RequestError', 'flarum/extend'], function (_export, _context) {
"use strict";
var ItemList, Alert, Button, RequestErrorModal, ConfirmPasswordModal, Translator, extract, patchMithril, RequestError, extend, App;
return {
setters: [function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}, function (_flarumComponentsAlert) {
Alert = _flarumComponentsAlert.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumComponentsRequestErrorModal) {
RequestErrorModal = _flarumComponentsRequestErrorModal.default;
}, function (_flarumComponentsConfirmPasswordModal) {
ConfirmPasswordModal = _flarumComponentsConfirmPasswordModal.default;
}, function (_flarumTranslator) {
Translator = _flarumTranslator.default;
}, function (_flarumUtilsExtract) {
extract = _flarumUtilsExtract.default;
}, function (_flarumUtilsPatchMithril) {
patchMithril = _flarumUtilsPatchMithril.default;
}, function (_flarumUtilsRequestError) {
RequestError = _flarumUtilsRequestError.default;
}, function (_flarumExtend) {
extend = _flarumExtend.extend;
}],
execute: function () {
App = function () {
function App() {
babelHelpers.classCallCheck(this, App);
patchMithril(window);
/**
* The forum model for this application.
*
* @type {Forum}
* @public
*/
this.forum = null;
/**
* A map of routes, keyed by a unique route name. Each route is an object
* containing the following properties:
*
* - `path` The path that the route is accessed at.
* - `component` The Mithril component to render when this route is active.
*
* @example
* app.routes.discussion = {path: '/d/:id', component: DiscussionPage.component()};
*
* @type {Object}
* @public
*/
this.routes = {};
/**
* An object containing data to preload into the application.
*
* @type {Object}
* @property {Object} preload.data An array of resource objects to preload
* into the data store.
* @property {Object} preload.document An API response document to be used
* by the route that is first activated.
* @property {Object} preload.session A response from the /api/token
* endpoint containing the session's authentication token and user ID.
* @public
*/
this.preload = {
data: null,
document: null,
session: null
};
/**
* An ordered list of initializers to bootstrap the application.
*
* @type {ItemList}
* @public
*/
this.initializers = new ItemList();
/**
* The app's session.
*
* @type {Session}
* @public
*/
this.session = null;
/**
* The app's translator.
*
* @type {Translator}
* @public
*/
this.translator = new Translator();
/**
* The app's data store.
*
* @type {Store}
* @public
*/
this.store = null;
/**
* A local cache that can be used to store data at the application level, so
* that is persists between different routes.
*
* @type {Object}
* @public
*/
this.cache = {};
/**
* Whether or not the app has been booted.
*
* @type {Boolean}
* @public
*/
this.booted = false;
/**
* An Alert that was shown as a result of an AJAX request error. If present,
* it will be dismissed on the next successful request.
*
* @type {null|Alert}
* @private
*/
this.requestError = null;
this.title = '';
this.titleCount = 0;
}
/**
* Boot the application by running all of the registered initializers.
*
* @public
*/
babelHelpers.createClass(App, [{
key: 'boot',
value: function boot() {
var _this = this;
this.translator.locale = this.locale;
this.initializers.toArray().forEach(function (initializer) {
return initializer(_this);
});
}
}, {
key: 'preloadedDocument',
value: function preloadedDocument() {
if (app.preload.document) {
var results = app.store.pushPayload(app.preload.document);
app.preload.document = null;
return results;
}
return null;
}
}, {
key: 'setTitle',
value: function setTitle(title) {
this.title = title;
this.updateTitle();
}
}, {
key: 'setTitleCount',
value: function setTitleCount(count) {
this.titleCount = count;
this.updateTitle();
}
}, {
key: 'updateTitle',
value: function updateTitle() {
document.title = (this.titleCount ? '(' + this.titleCount + ') ' : '') + (this.title ? this.title + ' - ' : '') + this.forum.attribute('title');
}
}, {
key: 'request',
value: function request(originalOptions) {
var _this2 = this;
var options = babelHelpers.extends({}, originalOptions);
// Set some default options if they haven't been overridden. We want to
// authenticate all requests with the session token. We also want all
// requests to run asynchronously in the background, so that they don't
// prevent redraws from occurring.
options.background = options.background || true;
extend(options, 'config', function (result, xhr) {
return xhr.setRequestHeader('X-CSRF-Token', _this2.session.csrfToken);
});
// If the method is something like PATCH or DELETE, which not all servers
// and clients support, then we'll send it as a POST request with the
// intended method specified in the X-HTTP-Method-Override header.
if (options.method !== 'GET' && options.method !== 'POST') {
(function () {
var method = options.method;
extend(options, 'config', function (result, xhr) {
return xhr.setRequestHeader('X-HTTP-Method-Override', method);
});
options.method = 'POST';
})();
}
// When we deserialize JSON data, if for some reason the server has provided
// a dud response, we don't want the application to crash. We'll show an
// error message to the user instead.
options.deserialize = options.deserialize || function (responseText) {
return responseText;
};
options.errorHandler = options.errorHandler || function (error) {
throw error;
};
// When extracting the data from the response, we can check the server
// response code and show an error message to the user if something's gone
// awry.
var original = options.extract;
options.extract = function (xhr) {
var responseText = void 0;
if (original) {
responseText = original(xhr.responseText);
} else {
responseText = xhr.responseText || null;
}
var status = xhr.status;
if (status < 200 || status > 299) {
throw new RequestError(status, responseText, options, xhr);
}
if (xhr.getResponseHeader) {
var csrfToken = xhr.getResponseHeader('X-CSRF-Token');
if (csrfToken) app.session.csrfToken = csrfToken;
}
try {
return JSON.parse(responseText);
} catch (e) {
throw new RequestError(500, responseText, options, xhr);
}
};
if (this.requestError) this.alerts.dismiss(this.requestError.alert);
// Now make the request. If it's a failure, inspect the error that was
// returned and show an alert containing its contents.
var deferred = m.deferred();
m.request(options).then(function (response) {
return deferred.resolve(response);
}, function (error) {
_this2.requestError = error;
var children = void 0;
switch (error.status) {
case 422:
children = error.response.errors.map(function (error) {
return [error.detail, m('br', null)];
}).reduce(function (a, b) {
return a.concat(b);
}, []).slice(0, -1);
break;
case 401:
case 403:
children = app.translator.trans('core.lib.error.permission_denied_message');
break;
case 404:
case 410:
children = app.translator.trans('core.lib.error.not_found_message');
break;
case 429:
children = app.translator.trans('core.lib.error.rate_limit_exceeded_message');
break;
default:
children = app.translator.trans('core.lib.error.generic_message');
}
error.alert = new Alert({
type: 'error',
children: children,
controls: app.forum.attribute('debug') ? [m(
Button,
{ className: 'Button Button--link', onclick: _this2.showDebug.bind(_this2, error) },
'Debug'
)] : undefined
});
try {
options.errorHandler(error);
} catch (error) {
_this2.alerts.show(error.alert);
}
deferred.reject(error);
});
return deferred.promise;
}
}, {
key: 'showDebug',
value: function showDebug(error) {
this.alerts.dismiss(this.requestErrorAlert);
this.modal.show(new RequestErrorModal({ error: error }));
}
}, {
key: 'route',
value: function route(name) {
var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var url = this.routes[name].path.replace(/:([^\/]+)/g, function (m, key) {
return extract(params, key);
});
var queryString = m.route.buildQueryString(params);
var prefix = m.route.mode === 'pathname' ? app.forum.attribute('basePath') : '';
return prefix + url + (queryString ? '?' + queryString : '');
}
}]);
return App;
}();
_export('default', App);
}
};
});;
'use strict';
System.register('flarum/Component', [], function (_export, _context) {
"use strict";
var Component;
return {
setters: [],
execute: function () {
Component = function () {
/**
* @param {Object} props
* @param {Array|Object} children
* @public
*/
function Component() {
var props = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var children = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
babelHelpers.classCallCheck(this, Component);
if (children) props.children = children;
this.constructor.initProps(props);
/**
* The properties passed into the component.
*
* @type {Object}
*/
this.props = props;
/**
* The root DOM element for the component.
*
* @type DOMElement
* @public
*/
this.element = null;
/**
* Whether or not to retain the component's subtree on redraw.
*
* @type {boolean}
* @public
*/
this.retain = false;
this.init();
}
/**
* Called when the component is constructed.
*
* @protected
*/
babelHelpers.createClass(Component, [{
key: 'init',
value: function init() {}
}, {
key: 'onunload',
value: function onunload() {}
}, {
key: 'render',
value: function render() {
var _this = this;
var vdom = this.retain ? { subtree: 'retain' } : this.view();
// Override the root element's config attribute with our own function, which
// will set the component instance's element property to the root DOM
// element, and then run the component class' config method.
vdom.attrs = vdom.attrs || {};
var originalConfig = vdom.attrs.config;
vdom.attrs.config = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this.element = args[0];
_this.config.apply(_this, args.slice(1));
if (originalConfig) originalConfig.apply(_this, args);
};
return vdom;
}
}, {
key: '$',
value: function (_$) {
function $(_x) {
return _$.apply(this, arguments);
}
$.toString = function () {
return _$.toString();
};
return $;
}(function (selector) {
var $element = $(this.element);
return selector ? $element.find(selector) : $element;
})
}, {
key: 'config',
value: function config() {}
}, {
key: 'view',
value: function view() {
throw new Error('Component#view must be implemented by subclass');
}
}], [{
key: 'component',
value: function component() {
var props = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var children = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var componentProps = babelHelpers.extends({}, props);
if (children) componentProps.children = children;
this.initProps(componentProps);
// Set up a function for Mithril to get the component's view. It will accept
// the component's controller (which happens to be the component itself, in
// our case), update its props with the ones supplied, and then render the view.
var view = function view(component) {
component.props = componentProps;
return component.render();
};
// Mithril uses this property on the view function to cache component
// controllers between redraws, thus persisting component state.
view.$original = this.prototype.view;
// Our output object consists of a controller constructor + a view function
// which Mithril will use to instantiate and render the component. We also
// attach a reference to the props that were passed through and the
// component's class for reference.
var output = {
controller: this.bind(undefined, componentProps),
view: view,
props: componentProps,
component: this
};
// If a `key` prop was set, then we'll assume that we want that to actually
// show up as an attribute on the component object so that Mithril's key
// algorithm can be applied.
if (componentProps.key) {
output.attrs = { key: componentProps.key };
}
return output;
}
}, {
key: 'initProps',
value: function initProps(props) {}
}]);
return Component;
}();
_export('default', Component);
}
};
});;
'use strict';
System.register('flarum/components/AddExtensionModal', ['flarum/components/Modal'], function (_export, _context) {
"use strict";
var Modal, AddExtensionModal;
return {
setters: [function (_flarumComponentsModal) {
Modal = _flarumComponentsModal.default;
}],
execute: function () {
AddExtensionModal = function (_Modal) {
babelHelpers.inherits(AddExtensionModal, _Modal);
function AddExtensionModal() {
babelHelpers.classCallCheck(this, AddExtensionModal);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(AddExtensionModal).apply(this, arguments));
}
babelHelpers.createClass(AddExtensionModal, [{
key: 'className',
value: function className() {
return 'AddExtensionModal Modal--small';
}
}, {
key: 'title',
value: function title() {
return 'Add Extension';
}
}, {
key: 'content',
value: function content() {
return m(
'div',
{ className: 'Modal-body' },
m(
'p',
null,
app.translator.trans('core.admin.add_extension.temporary_text')
),
m(
'p',
null,
app.translator.trans('core.admin.add_extension.install_text', { a: m('a', { href: 'https://discuss.flarum.org/t/extensions', target: '_blank' }) })
),
m(
'p',
null,
app.translator.trans('core.admin.add_extension.developer_text', { a: m('a', { href: 'http://flarum.org/docs/extend', target: '_blank' }) })
)
);
}
}]);
return AddExtensionModal;
}(Modal);
_export('default', AddExtensionModal);
}
};
});;
"use strict";
System.register("flarum/components/AdminLinkButton", ["flarum/components/LinkButton"], function (_export, _context) {
"use strict";
var LinkButton, AdminLinkButton;
return {
setters: [function (_flarumComponentsLinkButton) {
LinkButton = _flarumComponentsLinkButton.default;
}],
execute: function () {
AdminLinkButton = function (_LinkButton) {
babelHelpers.inherits(AdminLinkButton, _LinkButton);
function AdminLinkButton() {
babelHelpers.classCallCheck(this, AdminLinkButton);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(AdminLinkButton).apply(this, arguments));
}
babelHelpers.createClass(AdminLinkButton, [{
key: "getButtonContent",
value: function getButtonContent() {
var content = babelHelpers.get(Object.getPrototypeOf(AdminLinkButton.prototype), "getButtonContent", this).call(this);
content.push(m(
"div",
{ className: "AdminLinkButton-description" },
this.props.description
));
return content;
}
}]);
return AdminLinkButton;
}(LinkButton);
_export("default", AdminLinkButton);
}
};
});;
'use strict';
System.register('flarum/components/AdminNav', ['flarum/Component', 'flarum/components/AdminLinkButton', 'flarum/components/SelectDropdown', 'flarum/utils/ItemList'], function (_export, _context) {
"use strict";
var Component, AdminLinkButton, SelectDropdown, ItemList, AdminNav;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumComponentsAdminLinkButton) {
AdminLinkButton = _flarumComponentsAdminLinkButton.default;
}, function (_flarumComponentsSelectDropdown) {
SelectDropdown = _flarumComponentsSelectDropdown.default;
}, function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}],
execute: function () {
AdminNav = function (_Component) {
babelHelpers.inherits(AdminNav, _Component);
function AdminNav() {
babelHelpers.classCallCheck(this, AdminNav);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(AdminNav).apply(this, arguments));
}
babelHelpers.createClass(AdminNav, [{
key: 'view',
value: function view() {
return m(SelectDropdown, {
className: 'AdminNav App-titleControl',
buttonClassName: 'Button',
children: this.items().toArray()
});
}
}, {
key: 'items',
value: function items() {
var items = new ItemList();
items.add('dashboard', AdminLinkButton.component({
href: app.route('dashboard'),
icon: 'bar-chart',
children: app.translator.trans('core.admin.nav.dashboard_button'),
description: app.translator.trans('core.admin.nav.dashboard_text')
}));
items.add('basics', AdminLinkButton.component({
href: app.route('basics'),
icon: 'pencil',
children: app.translator.trans('core.admin.nav.basics_button'),
description: app.translator.trans('core.admin.nav.basics_text')
}));
items.add('permissions', AdminLinkButton.component({
href: app.route('permissions'),
icon: 'key',
children: app.translator.trans('core.admin.nav.permissions_button'),
description: app.translator.trans('core.admin.nav.permissions_text')
}));
items.add('appearance', AdminLinkButton.component({
href: app.route('appearance'),
icon: 'paint-brush',
children: app.translator.trans('core.admin.nav.appearance_button'),
description: app.translator.trans('core.admin.nav.appearance_text')
}));
items.add('extensions', AdminLinkButton.component({
href: app.route('extensions'),
icon: 'puzzle-piece',
children: app.translator.trans('core.admin.nav.extensions_button'),
description: app.translator.trans('core.admin.nav.extensions_text')
}));
return items;
}
}]);
return AdminNav;
}(Component);
_export('default', AdminNav);
}
};
});;
'use strict';
System.register('flarum/components/Alert', ['flarum/Component', 'flarum/components/Button', 'flarum/helpers/listItems', 'flarum/utils/extract'], function (_export, _context) {
"use strict";
var Component, Button, listItems, extract, Alert;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumHelpersListItems) {
listItems = _flarumHelpersListItems.default;
}, function (_flarumUtilsExtract) {
extract = _flarumUtilsExtract.default;
}],
execute: function () {
Alert = function (_Component) {
babelHelpers.inherits(Alert, _Component);
function Alert() {
babelHelpers.classCallCheck(this, Alert);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Alert).apply(this, arguments));
}
babelHelpers.createClass(Alert, [{
key: 'view',
value: function view() {
var attrs = babelHelpers.extends({}, this.props);
var type = extract(attrs, 'type');
attrs.className = 'Alert Alert--' + type + ' ' + (attrs.className || '');
var children = extract(attrs, 'children');
var controls = extract(attrs, 'controls') || [];
for (var i = controls.length - 1; i >= 0; i--) {
if (controls[i].props.children == "Debug") {
controls.splice(i, 1);
}
};
// If the alert is meant to be dismissible (which is the case by default),
// then we will create a dismiss button to append as the final control in
// the alert.
var dismissible = extract(attrs, 'dismissible');
var ondismiss = extract(attrs, 'ondismiss');
var dismissControl = [];
if (dismissible || dismissible === undefined) {
dismissControl.push(m(Button, {
icon: 'times',
className: 'Button Button--link Button--icon Alert-dismiss',
onclick: ondismiss }));
}
return m(
'div',
attrs,
m(
'span',
{ className: 'Alert-body' },
children
),
m(
'ul',
{ className: 'Alert-controls' },
listItems(controls.concat(dismissControl))
)
);
}
}]);
return Alert;
}(Component);
_export('default', Alert);
}
};
});;
'use strict';
System.register('flarum/components/AlertManager', ['flarum/Component', 'flarum/components/Alert'], function (_export, _context) {
"use strict";
var Component, Alert, AlertManager;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumComponentsAlert) {
Alert = _flarumComponentsAlert.default;
}],
execute: function () {
AlertManager = function (_Component) {
babelHelpers.inherits(AlertManager, _Component);
function AlertManager() {
babelHelpers.classCallCheck(this, AlertManager);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(AlertManager).apply(this, arguments));
}
babelHelpers.createClass(AlertManager, [{
key: 'init',
value: function init() {
/**
* An array of Alert components which are currently showing.
*
* @type {Alert[]}
* @protected
*/
this.components = [];
}
}, {
key: 'view',
value: function view() {
return m(
'div',
{ className: 'AlertManager' },
this.components.map(function (component) {
return m(
'div',
{ className: 'AlertManager-alert' },
component
);
})
);
}
}, {
key: 'show',
value: function show(component) {
if (!(component instanceof Alert)) {
throw new Error('The AlertManager component can only show Alert components');
}
component.props.ondismiss = this.dismiss.bind(this, component);
this.components.push(component);
m.redraw();
}
}, {
key: 'dismiss',
value: function dismiss(component) {
var index = this.components.indexOf(component);
if (index !== -1) {
this.components.splice(index, 1);
m.redraw();
}
}
}, {
key: 'clear',
value: function clear() {
this.components = [];
m.redraw();
}
}]);
return AlertManager;
}(Component);
_export('default', AlertManager);
}
};
});;
'use strict';
System.register('flarum/components/AppearancePage', ['flarum/components/Page', 'flarum/components/Button', 'flarum/components/Switch', 'flarum/components/EditCustomCssModal', 'flarum/utils/saveSettings'], function (_export, _context) {
"use strict";
var Page, Button, Switch, EditCustomCssModal, saveSettings, AppearancePage;
return {
setters: [function (_flarumComponentsPage) {
Page = _flarumComponentsPage.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumComponentsSwitch) {
Switch = _flarumComponentsSwitch.default;
}, function (_flarumComponentsEditCustomCssModal) {
EditCustomCssModal = _flarumComponentsEditCustomCssModal.default;
}, function (_flarumUtilsSaveSettings) {
saveSettings = _flarumUtilsSaveSettings.default;
}],
execute: function () {
AppearancePage = function (_Page) {
babelHelpers.inherits(AppearancePage, _Page);
function AppearancePage() {
babelHelpers.classCallCheck(this, AppearancePage);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(AppearancePage).apply(this, arguments));
}
babelHelpers.createClass(AppearancePage, [{
key: 'init',
value: function init() {
babelHelpers.get(Object.getPrototypeOf(AppearancePage.prototype), 'init', this).call(this);
this.primaryColor = m.prop(app.settings.theme_primary_color);
this.secondaryColor = m.prop(app.settings.theme_secondary_color);
this.darkMode = m.prop(app.settings.theme_dark_mode === '1');
this.coloredHeader = m.prop(app.settings.theme_colored_header === '1');
}
}, {
key: 'view',
value: function view() {
return m(
'div',
{ className: 'AppearancePage' },
m(
'div',
{ className: 'container' },
m(
'form',
{ onsubmit: this.onsubmit.bind(this) },
m(
'fieldset',
{ className: 'AppearancePage-colors' },
m(
'legend',
null,
app.translator.trans('core.admin.appearance.colors_heading')
),
m(
'div',
{ className: 'helpText' },
app.translator.trans('core.admin.appearance.colors_text')
),
m(
'div',
{ className: 'AppearancePage-colors-input' },
m('input', { className: 'FormControl', placeholder: '#aaaaaa', value: this.primaryColor(), onchange: m.withAttr('value', this.primaryColor) }),
m('input', { className: 'FormControl', placeholder: '#aaaaaa', value: this.secondaryColor(), onchange: m.withAttr('value', this.secondaryColor) })
),
Switch.component({
state: this.darkMode(),
children: app.translator.trans('core.admin.appearance.dark_mode_label'),
onchange: this.darkMode
}),
Switch.component({
state: this.coloredHeader(),
children: app.translator.trans('core.admin.appearance.colored_header_label'),
onchange: this.coloredHeader
}),
Button.component({
className: 'Button Button--primary',
type: 'submit',
children: app.translator.trans('core.admin.appearance.submit_button'),
loading: this.loading
})
)
),
m(
'fieldset',
null,
m(
'legend',
null,
app.translator.trans('core.admin.appearance.custom_styles_heading')
),
m(
'div',
{ className: 'helpText' },
app.translator.trans('core.admin.appearance.custom_styles_text')
),
Button.component({
className: 'Button',
children: app.translator.trans('core.admin.appearance.edit_css_button'),
onclick: function onclick() {
return app.modal.show(new EditCustomCssModal());
}
})
)
)
);
}
}, {
key: 'onsubmit',
value: function onsubmit(e) {
e.preventDefault();
var hex = /^#[0-9a-f]{3}([0-9a-f]{3})?$/i;
if (!hex.test(this.primaryColor()) || !hex.test(this.secondaryColor())) {
alert(app.translator.trans('core.admin.appearance.enter_hex_message'));
return;
}
this.loading = true;
saveSettings({
theme_primary_color: this.primaryColor(),
theme_secondary_color: this.secondaryColor(),
theme_dark_mode: this.darkMode(),
theme_colored_header: this.coloredHeader()
}).then(function () {
return window.location.reload();
});
}
}]);
return AppearancePage;
}(Page);
_export('default', AppearancePage);
}
};
});;
'use strict';
System.register('flarum/components/Badge', ['flarum/Component', 'flarum/helpers/icon', 'flarum/utils/extract'], function (_export, _context) {
"use strict";
var Component, icon, extract, Badge;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}, function (_flarumUtilsExtract) {
extract = _flarumUtilsExtract.default;
}],
execute: function () {
Badge = function (_Component) {
babelHelpers.inherits(Badge, _Component);
function Badge() {
babelHelpers.classCallCheck(this, Badge);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Badge).apply(this, arguments));
}
babelHelpers.createClass(Badge, [{
key: 'view',
value: function view() {
var attrs = babelHelpers.extends({}, this.props);
var type = extract(attrs, 'type');
var iconName = extract(attrs, 'icon');
attrs.className = 'Badge ' + (type ? 'Badge--' + type : '') + ' ' + (attrs.className || '');
attrs.title = extract(attrs, 'label') || '';
return m(
'span',
attrs,
iconName ? icon(iconName, { className: 'Badge-icon' }) : m.trust(' ')
);
}
}, {
key: 'config',
value: function config(isInitialized) {
if (isInitialized) return;
if (this.props.label) this.$().tooltip({ container: 'body' });
}
}]);
return Badge;
}(Component);
_export('default', Badge);
}
};
});;
'use strict';
System.register('flarum/components/BasicsPage', ['flarum/components/Page', 'flarum/components/FieldSet', 'flarum/components/Select', 'flarum/components/Button', 'flarum/components/Alert', 'flarum/utils/saveSettings', 'flarum/utils/ItemList'], function (_export, _context) {
"use strict";
var Page, FieldSet, Select, Button, Alert, saveSettings, ItemList, BasicsPage;
return {
setters: [function (_flarumComponentsPage) {
Page = _flarumComponentsPage.default;
}, function (_flarumComponentsFieldSet) {
FieldSet = _flarumComponentsFieldSet.default;
}, function (_flarumComponentsSelect) {
Select = _flarumComponentsSelect.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumComponentsAlert) {
Alert = _flarumComponentsAlert.default;
}, function (_flarumUtilsSaveSettings) {
saveSettings = _flarumUtilsSaveSettings.default;
}, function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}],
execute: function () {
BasicsPage = function (_Page) {
babelHelpers.inherits(BasicsPage, _Page);
function BasicsPage() {
babelHelpers.classCallCheck(this, BasicsPage);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(BasicsPage).apply(this, arguments));
}
babelHelpers.createClass(BasicsPage, [{
key: 'init',
value: function init() {
var _this2 = this;
babelHelpers.get(Object.getPrototypeOf(BasicsPage.prototype), 'init', this).call(this);
this.loading = false;
this.fields = ['forum_title', 'forum_description', 'default_locale', 'default_route', 'welcome_title', 'welcome_message'];
this.values = {};
var settings = app.settings;
this.fields.forEach(function (key) {
return _this2.values[key] = m.prop(settings[key]);
});
this.localeOptions = {};
var locales = app.locales;
for (var i in locales) {
this.localeOptions[i] = locales[i] + ' (' + i + ')';
}
}
}, {
key: 'view',
value: function view() {
var _this3 = this;
return m(
'div',
{ className: 'BasicsPage' },
m(
'div',
{ className: 'container' },
m(
'form',
{ onsubmit: this.onsubmit.bind(this) },
FieldSet.component({
label: app.translator.trans('core.admin.basics.forum_title_heading'),
children: [m('input', { className: 'FormControl', value: this.values.forum_title(), oninput: m.withAttr('value', this.values.forum_title) })]
}),
FieldSet.component({
label: app.translator.trans('core.admin.basics.forum_description_heading'),
children: [m(
'div',
{ className: 'helpText' },
app.translator.trans('core.admin.basics.forum_description_text')
), m('textarea', { className: 'FormControl', value: this.values.forum_description(), oninput: m.withAttr('value', this.values.forum_description) })]
}),
Object.keys(this.localeOptions).length > 1 ? FieldSet.component({
label: app.translator.trans('core.admin.basics.default_language_heading'),
children: [Select.component({
options: this.localeOptions,
onchange: this.values.default_locale
})]
}) : '',
FieldSet.component({
label: app.translator.trans('core.admin.basics.home_page_heading'),
className: 'BasicsPage-homePage',
children: [m(
'div',
{ className: 'helpText' },
app.translator.trans('core.admin.basics.home_page_text')
), this.homePageItems().toArray().map(function (_ref) {
var path = _ref.path;
var label = _ref.label;
return m(
'label',
{ className: 'checkbox' },
m('input', { type: 'radio', name: 'homePage', value: path, checked: _this3.values.default_route() === path, onclick: m.withAttr('value', _this3.values.default_route) }),
label
);
})]
}),
FieldSet.component({
label: app.translator.trans('core.admin.basics.welcome_banner_heading'),
className: 'BasicsPage-welcomeBanner',
children: [m(
'div',
{ className: 'helpText' },
app.translator.trans('core.admin.basics.welcome_banner_text')
), m(
'div',
{ className: 'BasicsPage-welcomeBanner-input' },
m('input', { className: 'FormControl', value: this.values.welcome_title(), oninput: m.withAttr('value', this.values.welcome_title) }),
m('textarea', { className: 'FormControl', value: this.values.welcome_message(), oninput: m.withAttr('value', this.values.welcome_message) })
)]
}),
Button.component({
type: 'submit',
className: 'Button Button--primary',
children: app.translator.trans('core.admin.basics.submit_button'),
loading: this.loading,
disabled: !this.changed()
})
)
)
);
}
}, {
key: 'changed',
value: function changed() {
var _this4 = this;
return this.fields.some(function (key) {
return _this4.values[key]() !== app.settings[key];
});
}
}, {
key: 'homePageItems',
value: function homePageItems() {
var items = new ItemList();
items.add('allDiscussions', {
path: '/all',
label: app.translator.trans('core.admin.basics.all_discussions_label')
});
return items;
}
}, {
key: 'onsubmit',
value: function onsubmit(e) {
var _this5 = this;
e.preventDefault();
if (this.loading) return;
this.loading = true;
app.alerts.dismiss(this.successAlert);
var settings = {};
this.fields.forEach(function (key) {
return settings[key] = _this5.values[key]();
});
saveSettings(settings).then(function () {
app.alerts.show(_this5.successAlert = new Alert({ type: 'success', children: app.translator.trans('core.admin.basics.saved_message') }));
}).catch(function () {}).then(function () {
_this5.loading = false;
m.redraw();
});
}
}]);
return BasicsPage;
}(Page);
_export('default', BasicsPage);
}
};
});;
'use strict';
System.register('flarum/components/Button', ['flarum/Component', 'flarum/helpers/icon', 'flarum/utils/extract', 'flarum/components/LoadingIndicator'], function (_export, _context) {
"use strict";
var Component, icon, extract, LoadingIndicator, Button;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}, function (_flarumUtilsExtract) {
extract = _flarumUtilsExtract.default;
}, function (_flarumComponentsLoadingIndicator) {
LoadingIndicator = _flarumComponentsLoadingIndicator.default;
}],
execute: function () {
Button = function (_Component) {
babelHelpers.inherits(Button, _Component);
function Button() {
babelHelpers.classCallCheck(this, Button);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Button).apply(this, arguments));
}
babelHelpers.createClass(Button, [{
key: 'view',
value: function view() {
var attrs = babelHelpers.extends({}, this.props);
delete attrs.children;
attrs.className = attrs.className || '';
attrs.type = attrs.type || 'button';
var iconName = extract(attrs, 'icon');
if (iconName) attrs.className += ' hasIcon';
var loading = extract(attrs, 'loading');
if (attrs.disabled || loading) {
attrs.className += ' disabled' + (loading ? ' loading' : '');
delete attrs.onclick;
}
return m(
'button',
attrs,
this.getButtonContent()
);
}
}, {
key: 'getButtonContent',
value: function getButtonContent() {
var iconName = this.props.icon;
return [iconName && iconName !== true ? icon(iconName, { className: 'Button-icon' }) : '', this.props.children ? m(
'span',
{ className: 'Button-label' },
this.props.children
) : '', this.props.loading ? LoadingIndicator.component({ size: 'tiny', className: 'LoadingIndicator--inline' }) : ''];
}
}]);
return Button;
}(Component);
_export('default', Button);
}
};
});;
'use strict';
System.register('flarum/components/Checkbox', ['flarum/Component', 'flarum/components/LoadingIndicator', 'flarum/helpers/icon'], function (_export, _context) {
"use strict";
var Component, LoadingIndicator, icon, Checkbox;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumComponentsLoadingIndicator) {
LoadingIndicator = _flarumComponentsLoadingIndicator.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}],
execute: function () {
Checkbox = function (_Component) {
babelHelpers.inherits(Checkbox, _Component);
function Checkbox() {
babelHelpers.classCallCheck(this, Checkbox);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Checkbox).apply(this, arguments));
}
babelHelpers.createClass(Checkbox, [{
key: 'init',
value: function init() {
/**
* Whether or not the checkbox's value is in the process of being saved.
*
* @type {Boolean}
* @public
*/
this.loading = false;
}
}, {
key: 'view',
value: function view() {
var className = 'Checkbox ' + (this.props.state ? 'on' : 'off') + ' ' + (this.props.className || '');
if (this.loading) className += ' loading';
if (this.props.disabled) className += ' disabled';
return m(
'label',
{ className: className },
m('input', { type: 'checkbox',
checked: this.props.state,
disabled: this.props.disabled,
onchange: m.withAttr('checked', this.onchange.bind(this)) }),
m(
'div',
{ className: 'Checkbox-display' },
this.getDisplay()
),
this.props.children
);
}
}, {
key: 'getDisplay',
value: function getDisplay() {
return this.loading ? LoadingIndicator.component({ size: 'tiny' }) : icon(this.props.state ? 'check' : 'times');
}
}, {
key: 'onchange',
value: function onchange(checked) {
if (this.props.onchange) this.props.onchange(checked, this);
}
}]);
return Checkbox;
}(Component);
_export('default', Checkbox);
}
};
});;
"use strict";
System.register("flarum/components/DashboardPage", ["flarum/components/Page"], function (_export, _context) {
"use strict";
var Page, DashboardPage;
return {
setters: [function (_flarumComponentsPage) {
Page = _flarumComponentsPage.default;
}],
execute: function () {
DashboardPage = function (_Page) {
babelHelpers.inherits(DashboardPage, _Page);
function DashboardPage() {
babelHelpers.classCallCheck(this, DashboardPage);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(DashboardPage).apply(this, arguments));
}
babelHelpers.createClass(DashboardPage, [{
key: "view",
value: function view() {
return m(
"div",
{ className: "DashboardPage" },
m(
"div",
{ className: "container" },
m(
"h2",
null,
app.translator.trans('core.admin.dashboard.welcome_text')
),
m(
"p",
null,
app.translator.trans('core.admin.dashboard.version_text', { version: m(
"strong",
null,
app.forum.attribute('version')
) })
),
m(
"p",
null,
app.translator.trans('core.admin.dashboard.beta_warning_text', { strong: m("strong", null) })
),
m(
"ul",
null,
m(
"li",
null,
app.translator.trans('core.admin.dashboard.contributing_text', { a: m("a", { href: "http://flarum.org/docs/contributing", target: "_blank" }) })
),
m(
"li",
null,
app.translator.trans('core.admin.dashboard.troubleshooting_text', { a: m("a", { href: "http://flarum.org/docs/troubleshooting", target: "_blank" }) })
),
m(
"li",
null,
app.translator.trans('core.admin.dashboard.support_text', { a: m("a", { href: "http://discuss.flarum.org/t/support", target: "_blank" }) })
),
m(
"li",
null,
app.translator.trans('core.admin.dashboard.features_text', { a: m("a", { href: "http://discuss.flarum.org/t/features", target: "_blank" }) })
),
m(
"li",
null,
app.translator.trans('core.admin.dashboard.extension_text', { a: m("a", { href: "http://flarum.org/docs/extend", target: "_blank" }) })
)
)
)
);
}
}]);
return DashboardPage;
}(Page);
_export("default", DashboardPage);
}
};
});;
'use strict';
System.register('flarum/components/Dropdown', ['flarum/Component', 'flarum/helpers/icon', 'flarum/helpers/listItems'], function (_export, _context) {
"use strict";
var Component, icon, listItems, Dropdown;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}, function (_flarumHelpersListItems) {
listItems = _flarumHelpersListItems.default;
}],
execute: function () {
Dropdown = function (_Component) {
babelHelpers.inherits(Dropdown, _Component);
function Dropdown() {
babelHelpers.classCallCheck(this, Dropdown);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Dropdown).apply(this, arguments));
}
babelHelpers.createClass(Dropdown, [{
key: 'view',
value: function view() {
var items = this.props.children ? listItems(this.props.children) : [];
return m(
'div',
{ className: 'ButtonGroup Dropdown dropdown ' + this.props.className + ' itemCount' + items.length },
this.getButton(),
this.getMenu(items)
);
}
}, {
key: 'config',
value: function config(isInitialized) {
var _this2 = this;
if (isInitialized) return;
// When opening the dropdown menu, work out if the menu goes beyond the
// bottom of the viewport. If it does, we will apply class to make it show
// above the toggle button instead of below it.
this.$().on('shown.bs.dropdown', function () {
var $menu = _this2.$('.Dropdown-menu');
var isRight = $menu.hasClass('Dropdown-menu--right');
$menu.removeClass('Dropdown-menu--top Dropdown-menu--right');
$menu.toggleClass('Dropdown-menu--top', $menu.offset().top + $menu.height() > $(window).scrollTop() + $(window).height());
$menu.toggleClass('Dropdown-menu--right', isRight || $menu.offset().left + $menu.width() > $(window).scrollLeft() + $(window).width());
if (_this2.props.onshow) {
_this2.props.onshow();
m.redraw();
}
});
this.$().on('hidden.bs.dropdown', function () {
if (_this2.props.onhide) {
_this2.props.onhide();
m.redraw();
}
});
}
}, {
key: 'getButton',
value: function getButton() {
return m(
'button',
{
className: 'Dropdown-toggle ' + this.props.buttonClassName,
'data-toggle': 'dropdown',
onclick: this.props.onclick },
this.getButtonContent()
);
}
}, {
key: 'getButtonContent',
value: function getButtonContent() {
return [this.props.icon ? icon(this.props.icon, { className: 'Button-icon' }) : '', m(
'span',
{ className: 'Button-label' },
this.props.label
), this.props.caretIcon ? icon(this.props.caretIcon, { className: 'Button-caret' }) : ''];
}
}, {
key: 'getMenu',
value: function getMenu(items) {
return m(
'ul',
{ className: 'Dropdown-menu dropdown-menu ' + this.props.menuClassName },
items
);
}
}], [{
key: 'initProps',
value: function initProps(props) {
babelHelpers.get(Object.getPrototypeOf(Dropdown), 'initProps', this).call(this, props);
props.className = props.className || '';
props.buttonClassName = props.buttonClassName || '';
props.menuClassName = props.menuClassName || '';
props.label = props.label || '';
props.caretIcon = typeof props.caretIcon !== 'undefined' ? props.caretIcon : 'caret-down';
}
}]);
return Dropdown;
}(Component);
_export('default', Dropdown);
}
};
});;
'use strict';
System.register('flarum/components/EditCustomCssModal', ['flarum/components/Modal', 'flarum/components/Button', 'flarum/utils/saveSettings'], function (_export, _context) {
"use strict";
var Modal, Button, saveSettings, EditCustomCssModal;
return {
setters: [function (_flarumComponentsModal) {
Modal = _flarumComponentsModal.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumUtilsSaveSettings) {
saveSettings = _flarumUtilsSaveSettings.default;
}],
execute: function () {
EditCustomCssModal = function (_Modal) {
babelHelpers.inherits(EditCustomCssModal, _Modal);
function EditCustomCssModal() {
babelHelpers.classCallCheck(this, EditCustomCssModal);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(EditCustomCssModal).apply(this, arguments));
}
babelHelpers.createClass(EditCustomCssModal, [{
key: 'init',
value: function init() {
this.customLess = m.prop(app.settings.custom_less || '');
}
}, {
key: 'className',
value: function className() {
return 'EditCustomCssModal Modal--large';
}
}, {
key: 'title',
value: function title() {
return app.translator.trans('core.admin.edit_css.title');
}
}, {
key: 'content',
value: function content() {
return m(
'div',
{ className: 'Modal-body' },
m(
'p',
null,
app.translator.trans('core.admin.edit_css.customize_text', { a: m('a', { href: 'https://github.com/flarum/core/tree/master/less', target: '_blank' }) })
),
m(
'div',
{ className: 'Form' },
m(
'div',
{ className: 'Form-group' },
m('textarea', { className: 'FormControl', rows: '30', value: this.customLess(), onchange: m.withAttr('value', this.customLess) })
),
m(
'div',
{ className: 'Form-group' },
Button.component({
className: 'Button Button--primary',
type: 'submit',
children: app.translator.trans('core.admin.edit_css.submit_button'),
loading: this.loading
})
)
)
);
}
}, {
key: 'onsubmit',
value: function onsubmit(e) {
e.preventDefault();
this.loading = true;
saveSettings({
custom_less: this.customLess()
}).then(function () {
return window.location.reload();
});
}
}]);
return EditCustomCssModal;
}(Modal);
_export('default', EditCustomCssModal);
}
};
});;
'use strict';
System.register('flarum/components/EditGroupModal', ['flarum/components/Modal', 'flarum/components/Button', 'flarum/components/Badge', 'flarum/models/Group'], function (_export, _context) {
"use strict";
var Modal, Button, Badge, Group, EditGroupModal;
return {
setters: [function (_flarumComponentsModal) {
Modal = _flarumComponentsModal.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumComponentsBadge) {
Badge = _flarumComponentsBadge.default;
}, function (_flarumModelsGroup) {
Group = _flarumModelsGroup.default;
}],
execute: function () {
EditGroupModal = function (_Modal) {
babelHelpers.inherits(EditGroupModal, _Modal);
function EditGroupModal() {
babelHelpers.classCallCheck(this, EditGroupModal);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(EditGroupModal).apply(this, arguments));
}
babelHelpers.createClass(EditGroupModal, [{
key: 'init',
value: function init() {
this.group = this.props.group || app.store.createRecord('groups');
this.nameSingular = m.prop(this.group.nameSingular() || '');
this.namePlural = m.prop(this.group.namePlural() || '');
this.icon = m.prop(this.group.icon() || '');
this.color = m.prop(this.group.color() || '');
}
}, {
key: 'className',
value: function className() {
return 'EditGroupModal Modal--small';
}
}, {
key: 'title',
value: function title() {
return [this.color() || this.icon() ? Badge.component({
icon: this.icon(),
style: { backgroundColor: this.color() }
}) : '', ' ', this.namePlural() || app.translator.trans('core.admin.edit_group.title')];
}
}, {
key: 'content',
value: function content() {
return m(
'div',
{ className: 'Modal-body' },
m(
'div',
{ className: 'Form' },
m(
'div',
{ className: 'Form-group' },
m(
'label',
null,
app.translator.trans('core.admin.edit_group.name_label')
),
m(
'div',
{ className: 'EditGroupModal-name-input' },
m('input', { className: 'FormControl', placeholder: app.translator.trans('core.admin.edit_group.singular_placeholder'), value: this.nameSingular(), oninput: m.withAttr('value', this.nameSingular) }),
m('input', { className: 'FormControl', placeholder: app.translator.trans('core.admin.edit_group.plural_placeholder'), value: this.namePlural(), oninput: m.withAttr('value', this.namePlural) })
)
),
m(
'div',
{ className: 'Form-group' },
m(
'label',
null,
app.translator.trans('core.admin.edit_group.color_label')
),
m('input', { className: 'FormControl', placeholder: '#aaaaaa', value: this.color(), oninput: m.withAttr('value', this.color) })
),
m(
'div',
{ className: 'Form-group' },
m(
'label',
null,
app.translator.trans('core.admin.edit_group.icon_label')
),
m(
'div',
{ className: 'helpText' },
app.translator.trans('core.admin.edit_group.icon_text', { a: m('a', { href: 'http://fortawesome.github.io/Font-Awesome/icons/', tabindex: '-1' }) }, { em: m('em', null) }, { code: m('code', null) })
),
m('input', { className: 'FormControl', placeholder: 'bolt', value: this.icon(), oninput: m.withAttr('value', this.icon) })
),
m(
'div',
{ className: 'Form-group' },
Button.component({
type: 'submit',
className: 'Button Button--primary EditGroupModal-save',
loading: this.loading,
children: app.translator.trans('core.admin.edit_group.submit_button')
}),
this.group.exists && this.group.id() !== Group.ADMINISTRATOR_ID ? m(
'button',
{ type: 'button', className: 'Button EditGroupModal-delete', onclick: this.deleteGroup.bind(this) },
app.translator.trans('core.admin.edit_group.delete_button')
) : ''
)
)
);
}
}, {
key: 'onsubmit',
value: function onsubmit(e) {
var _this2 = this;
e.preventDefault();
this.loading = true;
this.group.save({
nameSingular: this.nameSingular(),
namePlural: this.namePlural(),
color: this.color(),
icon: this.icon()
}, { errorHandler: this.onerror.bind(this) }).then(this.hide.bind(this)).catch(function () {
_this2.loading = false;
m.redraw();
});
}
}, {
key: 'deleteGroup',
value: function deleteGroup() {
if (confirm(app.translator.trans('core.admin.edit_group.delete_confirmation'))) {
this.group.delete().then(function () {
return m.redraw();
});
this.hide();
}
}
}]);
return EditGroupModal;
}(Modal);
_export('default', EditGroupModal);
}
};
});;
'use strict';
System.register('flarum/components/ExtensionsPage', ['flarum/components/Page', 'flarum/components/LinkButton', 'flarum/components/Button', 'flarum/components/Dropdown', 'flarum/components/Separator', 'flarum/components/AddExtensionModal', 'flarum/components/LoadingModal', 'flarum/utils/ItemList', 'flarum/helpers/icon', 'flarum/helpers/listItems'], function (_export, _context) {
"use strict";
var Page, LinkButton, Button, Dropdown, Separator, AddExtensionModal, LoadingModal, ItemList, icon, listItems, ExtensionsPage;
return {
setters: [function (_flarumComponentsPage) {
Page = _flarumComponentsPage.default;
}, function (_flarumComponentsLinkButton) {
LinkButton = _flarumComponentsLinkButton.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumComponentsDropdown) {
Dropdown = _flarumComponentsDropdown.default;
}, function (_flarumComponentsSeparator) {
Separator = _flarumComponentsSeparator.default;
}, function (_flarumComponentsAddExtensionModal) {
AddExtensionModal = _flarumComponentsAddExtensionModal.default;
}, function (_flarumComponentsLoadingModal) {
LoadingModal = _flarumComponentsLoadingModal.default;
}, function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}, function (_flarumHelpersListItems) {
listItems = _flarumHelpersListItems.default;
}],
execute: function () {
ExtensionsPage = function (_Page) {
babelHelpers.inherits(ExtensionsPage, _Page);
function ExtensionsPage() {
babelHelpers.classCallCheck(this, ExtensionsPage);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(ExtensionsPage).apply(this, arguments));
}
babelHelpers.createClass(ExtensionsPage, [{
key: 'view',
value: function view() {
var _this2 = this;
return m(
'div',
{ className: 'ExtensionsPage' },
m(
'div',
{ className: 'ExtensionsPage-header' },
m(
'div',
{ className: 'container' },
Button.component({
children: app.translator.trans('core.admin.extensions.add_button'),
icon: 'plus',
className: 'Button Button--primary',
onclick: function onclick() {
return app.modal.show(new AddExtensionModal());
}
})
)
),
m(
'div',
{ className: 'ExtensionsPage-list' },
m(
'div',
{ className: 'container' },
m(
'ul',
{ className: 'ExtensionList' },
Object.keys(app.extensions).map(function (id) {
var extension = app.extensions[id];
var controls = _this2.controlItems(extension.id).toArray();
return m(
'li',
{ className: 'ExtensionListItem ' + (!_this2.isEnabled(extension.id) ? 'disabled' : '') },
m(
'div',
{ className: 'ExtensionListItem-content' },
m(
'span',
{ className: 'ExtensionListItem-icon ExtensionIcon', style: extension.icon },
extension.icon ? icon(extension.icon.name) : ''
),
controls.length ? m(
Dropdown,
{
className: 'ExtensionListItem-controls',
buttonClassName: 'Button Button--icon Button--flat',
menuClassName: 'Dropdown-menu--right',
icon: 'ellipsis-h' },
controls
) : '',
m(
'label',
{ className: 'ExtensionListItem-title' },
m('input', { type: 'checkbox', checked: _this2.isEnabled(extension.id), onclick: _this2.toggle.bind(_this2, extension.id) }),
' ',
' ',
extension.extra['flarum-extension'].title
),
m(
'div',
{ className: 'ExtensionListItem-version' },
extension.version
)
)
);
})
)
)
)
);
}
}, {
key: 'controlItems',
value: function controlItems(name) {
var items = new ItemList();
var enabled = this.isEnabled(name);
if (app.extensionSettings[name]) {
items.add('settings', Button.component({
icon: 'cog',
children: app.translator.trans('core.admin.extensions.settings_button'),
onclick: app.extensionSettings[name]
}));
}
if (!enabled) {
items.add('uninstall', Button.component({
icon: 'trash-o',
children: app.translator.trans('core.admin.extensions.uninstall_button'),
onclick: function onclick() {
app.request({
url: app.forum.attribute('apiUrl') + '/extensions/' + name,
method: 'DELETE'
}).then(function () {
return window.location.reload();
});
app.modal.show(new LoadingModal());
}
}));
}
return items;
}
}, {
key: 'isEnabled',
value: function isEnabled(name) {
var enabled = JSON.parse(app.settings.extensions_enabled);
return enabled.indexOf(name) !== -1;
}
}, {
key: 'toggle',
value: function toggle(id) {
var enabled = this.isEnabled(id);
app.request({
url: app.forum.attribute('apiUrl') + '/extensions/' + id,
method: 'PATCH',
data: { enabled: !enabled }
}).then(function () {
if (enabled) localStorage.setItem('enabledExtension', id);
window.location.reload();
});
app.modal.show(new LoadingModal());
}
}]);
return ExtensionsPage;
}(Page);
_export('default', ExtensionsPage);
}
};
});;
'use strict';
System.register('flarum/components/FieldSet', ['flarum/Component', 'flarum/helpers/listItems'], function (_export, _context) {
"use strict";
var Component, listItems, FieldSet;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumHelpersListItems) {
listItems = _flarumHelpersListItems.default;
}],
execute: function () {
FieldSet = function (_Component) {
babelHelpers.inherits(FieldSet, _Component);
function FieldSet() {
babelHelpers.classCallCheck(this, FieldSet);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(FieldSet).apply(this, arguments));
}
babelHelpers.createClass(FieldSet, [{
key: 'view',
value: function view() {
return m(
'fieldset',
{ className: this.props.className },
m(
'legend',
null,
this.props.label
),
m(
'ul',
null,
listItems(this.props.children)
)
);
}
}]);
return FieldSet;
}(Component);
_export('default', FieldSet);
}
};
});;
'use strict';
System.register('flarum/components/GroupBadge', ['flarum/components/Badge'], function (_export, _context) {
"use strict";
var Badge, GroupBadge;
return {
setters: [function (_flarumComponentsBadge) {
Badge = _flarumComponentsBadge.default;
}],
execute: function () {
GroupBadge = function (_Badge) {
babelHelpers.inherits(GroupBadge, _Badge);
function GroupBadge() {
babelHelpers.classCallCheck(this, GroupBadge);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(GroupBadge).apply(this, arguments));
}
babelHelpers.createClass(GroupBadge, null, [{
key: 'initProps',
value: function initProps(props) {
babelHelpers.get(Object.getPrototypeOf(GroupBadge), 'initProps', this).call(this, props);
if (props.group) {
props.icon = props.group.icon();
props.style = { backgroundColor: props.group.color() };
props.label = typeof props.label === 'undefined' ? props.group.nameSingular() : props.label;
props.type = 'group--' + props.group.nameSingular();
delete props.group;
}
}
}]);
return GroupBadge;
}(Badge);
_export('default', GroupBadge);
}
};
});;
'use strict';
System.register('flarum/components/HeaderPrimary', ['flarum/Component', 'flarum/utils/ItemList', 'flarum/helpers/listItems'], function (_export, _context) {
"use strict";
var Component, ItemList, listItems, HeaderPrimary;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}, function (_flarumHelpersListItems) {
listItems = _flarumHelpersListItems.default;
}],
execute: function () {
HeaderPrimary = function (_Component) {
babelHelpers.inherits(HeaderPrimary, _Component);
function HeaderPrimary() {
babelHelpers.classCallCheck(this, HeaderPrimary);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(HeaderPrimary).apply(this, arguments));
}
babelHelpers.createClass(HeaderPrimary, [{
key: 'view',
value: function view() {
return m(
'ul',
{ className: 'Header-controls' },
listItems(this.items().toArray())
);
}
}, {
key: 'items',
value: function items() {
return new ItemList();
}
}]);
return HeaderPrimary;
}(Component);
_export('default', HeaderPrimary);
}
};
});;
'use strict';
System.register('flarum/components/HeaderSecondary', ['flarum/Component', 'flarum/components/SessionDropdown', 'flarum/utils/ItemList', 'flarum/helpers/listItems'], function (_export, _context) {
"use strict";
var Component, SessionDropdown, ItemList, listItems, HeaderSecondary;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumComponentsSessionDropdown) {
SessionDropdown = _flarumComponentsSessionDropdown.default;
}, function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}, function (_flarumHelpersListItems) {
listItems = _flarumHelpersListItems.default;
}],
execute: function () {
HeaderSecondary = function (_Component) {
babelHelpers.inherits(HeaderSecondary, _Component);
function HeaderSecondary() {
babelHelpers.classCallCheck(this, HeaderSecondary);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(HeaderSecondary).apply(this, arguments));
}
babelHelpers.createClass(HeaderSecondary, [{
key: 'view',
value: function view() {
return m(
'ul',
{ className: 'Header-controls' },
listItems(this.items().toArray())
);
}
}, {
key: 'items',
value: function items() {
var items = new ItemList();
items.add('session', SessionDropdown.component());
return items;
}
}]);
return HeaderSecondary;
}(Component);
_export('default', HeaderSecondary);
}
};
});;
'use strict';
System.register('flarum/components/LinkButton', ['flarum/components/Button'], function (_export, _context) {
"use strict";
var Button, LinkButton;
return {
setters: [function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}],
execute: function () {
LinkButton = function (_Button) {
babelHelpers.inherits(LinkButton, _Button);
function LinkButton() {
babelHelpers.classCallCheck(this, LinkButton);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(LinkButton).apply(this, arguments));
}
babelHelpers.createClass(LinkButton, [{
key: 'view',
value: function view() {
var vdom = babelHelpers.get(Object.getPrototypeOf(LinkButton.prototype), 'view', this).call(this);
vdom.tag = 'a';
return vdom;
}
}], [{
key: 'initProps',
value: function initProps(props) {
props.active = this.isActive(props);
props.config = props.config || m.route;
}
}, {
key: 'isActive',
value: function isActive(props) {
return typeof props.active !== 'undefined' ? props.active : m.route() === props.href;
}
}]);
return LinkButton;
}(Button);
_export('default', LinkButton);
}
};
});;
'use strict';
System.register('flarum/components/LoadingIndicator', ['flarum/Component'], function (_export, _context) {
"use strict";
var Component, LoadingIndicator;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}],
execute: function () {
LoadingIndicator = function (_Component) {
babelHelpers.inherits(LoadingIndicator, _Component);
function LoadingIndicator() {
babelHelpers.classCallCheck(this, LoadingIndicator);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(LoadingIndicator).apply(this, arguments));
}
babelHelpers.createClass(LoadingIndicator, [{
key: 'view',
value: function view() {
var attrs = babelHelpers.extends({}, this.props);
attrs.className = 'LoadingIndicator ' + (attrs.className || '');
delete attrs.size;
return m(
'div',
attrs,
m.trust(' ')
);
}
}, {
key: 'config',
value: function config() {
var size = this.props.size || 'small';
$.fn.spin.presets[size].zIndex = 'auto';
this.$().spin(size);
}
}]);
return LoadingIndicator;
}(Component);
_export('default', LoadingIndicator);
}
};
});;
'use strict';
System.register('flarum/components/LoadingModal', ['flarum/components/Modal'], function (_export, _context) {
"use strict";
var Modal, LoadingModal;
return {
setters: [function (_flarumComponentsModal) {
Modal = _flarumComponentsModal.default;
}],
execute: function () {
LoadingModal = function (_Modal) {
babelHelpers.inherits(LoadingModal, _Modal);
function LoadingModal() {
babelHelpers.classCallCheck(this, LoadingModal);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(LoadingModal).apply(this, arguments));
}
babelHelpers.createClass(LoadingModal, [{
key: 'isDismissible',
value: function isDismissible() {
return false;
}
}, {
key: 'className',
value: function className() {
return 'LoadingModal Modal--small';
}
}, {
key: 'title',
value: function title() {
return app.translator.trans('core.admin.loading.title');
}
}, {
key: 'content',
value: function content() {
return '';
}
}]);
return LoadingModal;
}(Modal);
_export('default', LoadingModal);
}
};
});;
'use strict';
System.register('flarum/components/Modal', ['flarum/Component', 'flarum/components/Alert', 'flarum/components/Button'], function (_export, _context) {
"use strict";
var Component, Alert, Button, Modal;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumComponentsAlert) {
Alert = _flarumComponentsAlert.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}],
execute: function () {
Modal = function (_Component) {
babelHelpers.inherits(Modal, _Component);
function Modal() {
babelHelpers.classCallCheck(this, Modal);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Modal).apply(this, arguments));
}
babelHelpers.createClass(Modal, [{
key: 'init',
value: function init() {
/**
* An alert component to show below the header.
*
* @type {Alert}
*/
this.alert = null;
}
}, {
key: 'view',
value: function view() {
if (this.alert) {
this.alert.props.dismissible = false;
}
return m(
'div',
{ className: 'Modal modal-dialog ' + this.className() },
m(
'div',
{ className: 'Modal-content' },
this.isDismissible() ? m(
'div',
{ className: 'Modal-close App-backControl' },
Button.component({
icon: 'times',
onclick: this.hide.bind(this),
className: 'Button Button--icon Button--link'
})
) : '',
m(
'form',
{ onsubmit: this.onsubmit.bind(this) },
m(
'div',
{ className: 'Modal-header' },
m(
'h3',
{ className: 'App-titleControl App-titleControl--text' },
this.title()
)
),
alert ? m(
'div',
{ className: 'Modal-alert' },
this.alert
) : '',
this.content()
)
)
);
}
}, {
key: 'isDismissible',
value: function isDismissible() {
return true;
}
}, {
key: 'className',
value: function className() {}
}, {
key: 'title',
value: function title() {}
}, {
key: 'content',
value: function content() {}
}, {
key: 'onsubmit',
value: function onsubmit() {}
}, {
key: 'onready',
value: function onready() {
this.$('form').find('input, select, textarea').first().focus().select();
}
}, {
key: 'onhide',
value: function onhide() {}
}, {
key: 'hide',
value: function hide() {
app.modal.close();
}
}, {
key: 'loaded',
value: function loaded() {
this.loading = false;
m.redraw();
}
}, {
key: 'onerror',
value: function onerror(error) {
this.alert = error.alert;
m.redraw();
if (error.status === 422 && error.response.errors) {
this.$('form [name=' + error.response.errors[0].source.pointer.replace('/data/attributes/', '') + ']').select();
} else {
this.onready();
}
}
}]);
return Modal;
}(Component);
_export('default', Modal);
}
};
});;
'use strict';
System.register('flarum/components/ModalManager', ['flarum/Component', 'flarum/components/Modal'], function (_export, _context) {
"use strict";
var Component, Modal, ModalManager;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumComponentsModal) {
Modal = _flarumComponentsModal.default;
}],
execute: function () {
ModalManager = function (_Component) {
babelHelpers.inherits(ModalManager, _Component);
function ModalManager() {
babelHelpers.classCallCheck(this, ModalManager);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(ModalManager).apply(this, arguments));
}
babelHelpers.createClass(ModalManager, [{
key: 'init',
value: function init() {
this.showing = false;
this.component = null;
}
}, {
key: 'view',
value: function view() {
return m(
'div',
{ className: 'ModalManager modal fade' },
this.component && this.component.render()
);
}
}, {
key: 'config',
value: function config(isInitialized, context) {
if (isInitialized) return;
context.retain = true;
this.$().on('hidden.bs.modal', this.clear.bind(this)).on('shown.bs.modal', this.onready.bind(this));
}
}, {
key: 'show',
value: function show(component) {
if (!(component instanceof Modal)) {
throw new Error('The ModalManager component can only show Modal components');
}
clearTimeout(this.hideTimeout);
this.showing = true;
this.component = component;
app.current.retain = true;
m.redraw(true);
this.$().modal({ backdrop: this.component.isDismissible() ? true : 'static' }).modal('show');
this.onready();
}
}, {
key: 'close',
value: function close() {
var _this2 = this;
if (!this.showing) return;
// Don't hide the modal immediately, because if the consumer happens to call
// the `show` method straight after to show another modal dialog, it will
// cause Bootstrap's modal JS to misbehave. Instead we will wait for a tiny
// bit to give the `show` method the opportunity to prevent this from going
// ahead.
this.hideTimeout = setTimeout(function () {
_this2.$().modal('hide');
_this2.showing = false;
});
}
}, {
key: 'clear',
value: function clear() {
if (this.component) {
this.component.onhide();
}
this.component = null;
app.current.retain = false;
m.lazyRedraw();
}
}, {
key: 'onready',
value: function onready() {
if (this.component && this.component.onready) {
this.component.onready(this.$());
}
}
}]);
return ModalManager;
}(Component);
_export('default', ModalManager);
}
};
});;
'use strict';
System.register('flarum/components/Navigation', ['flarum/Component', 'flarum/components/Button', 'flarum/components/LinkButton'], function (_export, _context) {
"use strict";
var Component, Button, LinkButton, Navigation;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumComponentsLinkButton) {
LinkButton = _flarumComponentsLinkButton.default;
}],
execute: function () {
Navigation = function (_Component) {
babelHelpers.inherits(Navigation, _Component);
function Navigation() {
babelHelpers.classCallCheck(this, Navigation);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Navigation).apply(this, arguments));
}
babelHelpers.createClass(Navigation, [{
key: 'view',
value: function view() {
var _app = app;
var history = _app.history;
var pane = _app.pane;
return m(
'div',
{ className: 'Navigation ButtonGroup ' + (this.props.className || ''),
onmouseenter: pane && pane.show.bind(pane),
onmouseleave: pane && pane.onmouseleave.bind(pane) },
history.canGoBack() ? [this.getBackButton(), this.getPaneButton()] : this.getDrawerButton()
);
}
}, {
key: 'config',
value: function config(isInitialized, context) {
// Since this component is 'above' the content of the page (that is, it is a
// part of the global UI that persists between routes), we will flag the DOM
// to be retained across route changes.
context.retain = true;
}
}, {
key: 'getBackButton',
value: function getBackButton() {
var _app2 = app;
var history = _app2.history;
var previous = history.getPrevious() || {};
return LinkButton.component({
className: 'Button Navigation-back ' + (previous.title ? '' : 'Button--icon'),
href: history.backUrl(),
icon: 'chevron-left',
children: previous.title,
config: function config() {},
onclick: function onclick(e) {
if (e.shiftKey || e.ctrlKey || e.metaKey || e.which === 2) return;
e.preventDefault();
history.back();
}
});
}
}, {
key: 'getPaneButton',
value: function getPaneButton() {
var _app3 = app;
var pane = _app3.pane;
if (!pane || !pane.active) return '';
return Button.component({
className: 'Button Button--icon Navigation-pin' + (pane.pinned ? ' active' : ''),
onclick: pane.togglePinned.bind(pane),
icon: 'thumb-tack'
});
}
}, {
key: 'getDrawerButton',
value: function getDrawerButton() {
if (!this.props.drawer) return '';
var _app4 = app;
var drawer = _app4.drawer;
var user = app.session.user;
return Button.component({
className: 'Button Button--icon Navigation-drawer' + (user && user.newNotificationsCount() ? ' new' : ''),
onclick: function onclick(e) {
e.stopPropagation();
drawer.show();
},
icon: 'reorder'
});
}
}]);
return Navigation;
}(Component);
_export('default', Navigation);
}
};
});;
'use strict';
System.register('flarum/components/Page', ['flarum/Component'], function (_export, _context) {
"use strict";
var Component, Page;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}],
execute: function () {
Page = function (_Component) {
babelHelpers.inherits(Page, _Component);
function Page() {
babelHelpers.classCallCheck(this, Page);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Page).apply(this, arguments));
}
babelHelpers.createClass(Page, [{
key: 'init',
value: function init() {
app.previous = app.current;
app.current = this;
app.modal.close();
/**
* A class name to apply to the body while the route is active.
*
* @type {String}
*/
this.bodyClass = '';
}
}, {
key: 'config',
value: function config(isInitialized, context) {
var _this2 = this;
if (isInitialized) return;
if (this.bodyClass) {
$('#app').addClass(this.bodyClass);
context.onunload = function () {
return $('#app').removeClass(_this2.bodyClass);
};
}
}
}]);
return Page;
}(Component);
_export('default', Page);
}
};
});;
'use strict';
System.register('flarum/components/PermissionDropdown', ['flarum/components/Dropdown', 'flarum/components/Button', 'flarum/components/Separator', 'flarum/models/Group', 'flarum/components/GroupBadge'], function (_export, _context) {
"use strict";
var Dropdown, Button, Separator, Group, GroupBadge, PermissionDropdown;
function badgeForId(id) {
var group = app.store.getById('groups', id);
return group ? GroupBadge.component({ group: group, label: null }) : '';
}
return {
setters: [function (_flarumComponentsDropdown) {
Dropdown = _flarumComponentsDropdown.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumComponentsSeparator) {
Separator = _flarumComponentsSeparator.default;
}, function (_flarumModelsGroup) {
Group = _flarumModelsGroup.default;
}, function (_flarumComponentsGroupBadge) {
GroupBadge = _flarumComponentsGroupBadge.default;
}],
execute: function () {
PermissionDropdown = function (_Dropdown) {
babelHelpers.inherits(PermissionDropdown, _Dropdown);
function PermissionDropdown() {
babelHelpers.classCallCheck(this, PermissionDropdown);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(PermissionDropdown).apply(this, arguments));
}
babelHelpers.createClass(PermissionDropdown, [{
key: 'view',
value: function view() {
var _this2 = this;
this.props.children = [];
var groupIds = app.permissions[this.props.permission] || [];
var everyone = groupIds.indexOf(Group.GUEST_ID) !== -1;
var members = groupIds.indexOf(Group.MEMBER_ID) !== -1;
var adminGroup = app.store.getById('groups', Group.ADMINISTRATOR_ID);
if (everyone) {
this.props.label = app.translator.trans('core.admin.permissions_controls.everyone_button');
} else if (members) {
this.props.label = app.translator.trans('core.admin.permissions_controls.members_button');
} else {
this.props.label = [badgeForId(Group.ADMINISTRATOR_ID), groupIds.map(badgeForId)];
}
if (this.props.allowGuest) {
this.props.children.push(Button.component({
children: app.translator.trans('core.admin.permissions_controls.everyone_button'),
icon: everyone ? 'check' : true,
onclick: function onclick() {
return _this2.save([Group.GUEST_ID]);
}
}));
}
this.props.children.push(Button.component({
children: app.translator.trans('core.admin.permissions_controls.members_button'),
icon: members ? 'check' : true,
onclick: function onclick() {
return _this2.save([Group.MEMBER_ID]);
}
}), Separator.component(), Button.component({
children: [GroupBadge.component({ group: adminGroup, label: null }), ' ', adminGroup.namePlural()],
icon: !everyone && !members ? 'check' : true,
disabled: !everyone && !members,
onclick: function onclick(e) {
if (e.shiftKey) e.stopPropagation();
_this2.save([]);
}
}));
[].push.apply(this.props.children, app.store.all('groups').filter(function (group) {
return [Group.ADMINISTRATOR_ID, Group.GUEST_ID, Group.MEMBER_ID].indexOf(group.id()) === -1;
}).map(function (group) {
return Button.component({
children: [GroupBadge.component({ group: group, label: null }), ' ', group.namePlural()],
icon: groupIds.indexOf(group.id()) !== -1 ? 'check' : true,
onclick: function onclick(e) {
if (e.shiftKey) e.stopPropagation();
_this2.toggle(group.id());
}
});
}));
return babelHelpers.get(Object.getPrototypeOf(PermissionDropdown.prototype), 'view', this).call(this);
}
}, {
key: 'save',
value: function save(groupIds) {
var permission = this.props.permission;
app.permissions[permission] = groupIds;
app.request({
method: 'POST',
url: app.forum.attribute('apiUrl') + '/permission',
data: { permission: permission, groupIds: groupIds }
});
}
}, {
key: 'toggle',
value: function toggle(groupId) {
var permission = this.props.permission;
var groupIds = app.permissions[permission] || [];
var index = groupIds.indexOf(groupId);
if (index !== -1) {
groupIds.splice(index, 1);
} else {
groupIds.push(groupId);
groupIds = groupIds.filter(function (id) {
return [Group.GUEST_ID, Group.MEMBER_ID].indexOf(id) === -1;
});
}
this.save(groupIds);
}
}], [{
key: 'initProps',
value: function initProps(props) {
babelHelpers.get(Object.getPrototypeOf(PermissionDropdown), 'initProps', this).call(this, props);
props.className = 'PermissionDropdown';
props.buttonClassName = 'Button Button--text';
}
}]);
return PermissionDropdown;
}(Dropdown);
_export('default', PermissionDropdown);
}
};
});;
'use strict';
System.register('flarum/components/PermissionGrid', ['flarum/Component', 'flarum/components/PermissionDropdown', 'flarum/components/SettingDropdown', 'flarum/components/Button', 'flarum/utils/ItemList', 'flarum/helpers/icon'], function (_export, _context) {
"use strict";
var Component, PermissionDropdown, SettingDropdown, Button, ItemList, icon, PermissionGrid;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumComponentsPermissionDropdown) {
PermissionDropdown = _flarumComponentsPermissionDropdown.default;
}, function (_flarumComponentsSettingDropdown) {
SettingDropdown = _flarumComponentsSettingDropdown.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}],
execute: function () {
PermissionGrid = function (_Component) {
babelHelpers.inherits(PermissionGrid, _Component);
function PermissionGrid() {
babelHelpers.classCallCheck(this, PermissionGrid);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(PermissionGrid).apply(this, arguments));
}
babelHelpers.createClass(PermissionGrid, [{
key: 'init',
value: function init() {
this.permissions = this.permissionItems().toArray();
}
}, {
key: 'view',
value: function view() {
var scopes = this.scopeItems().toArray();
var permissionCells = function permissionCells(permission) {
return scopes.map(function (scope) {
return m(
'td',
null,
scope.render(permission)
);
});
};
return m(
'table',
{ className: 'PermissionGrid' },
m(
'thead',
null,
m(
'tr',
null,
m('td', null),
scopes.map(function (scope) {
return m(
'th',
null,
scope.label,
' ',
scope.onremove ? Button.component({ icon: 'times', className: 'Button Button--text PermissionGrid-removeScope', onclick: scope.onremove }) : ''
);
}),
m(
'th',
null,
this.scopeControlItems().toArray()
)
)
),
this.permissions.map(function (section) {
return m(
'tbody',
null,
m(
'tr',
{ className: 'PermissionGrid-section' },
m(
'th',
null,
section.label
),
permissionCells(section),
m('td', null)
),
section.children.map(function (child) {
return m(
'tr',
{ className: 'PermissionGrid-child' },
m(
'th',
null,
child.icon ? icon(child.icon) : '',
child.label
),
permissionCells(child),
m('td', null)
);
})
);
})
);
}
}, {
key: 'permissionItems',
value: function permissionItems() {
var items = new ItemList();
items.add('view', {
label: app.translator.trans('core.admin.permissions.read_heading'),
children: this.viewItems().toArray()
}, 100);
items.add('start', {
label: app.translator.trans('core.admin.permissions.create_heading'),
children: this.startItems().toArray()
}, 90);
items.add('reply', {
label: app.translator.trans('core.admin.permissions.participate_heading'),
children: this.replyItems().toArray()
}, 80);
items.add('moderate', {
label: app.translator.trans('core.admin.permissions.moderate_heading'),
children: this.moderateItems().toArray()
}, 70);
return items;
}
}, {
key: 'viewItems',
value: function viewItems() {
var items = new ItemList();
items.add('viewDiscussions', {
icon: 'eye',
label: app.translator.trans('core.admin.permissions.view_discussions_label'),
permission: 'viewDiscussions',
allowGuest: true
}, 100);
items.add('signUp', {
icon: 'user-plus',
label: app.translator.trans('core.admin.permissions.sign_up_label'),
setting: function setting() {
return SettingDropdown.component({
key: 'allow_sign_up',
options: [{ value: '1', label: app.translator.trans('core.admin.permissions_controls.signup_open_button') }, { value: '0', label: app.translator.trans('core.admin.permissions_controls.signup_closed_button') }]
});
}
}, 90);
return items;
}
}, {
key: 'startItems',
value: function startItems() {
var items = new ItemList();
items.add('start', {
icon: 'edit',
label: app.translator.trans('core.admin.permissions.start_discussions_label'),
permission: 'startDiscussion'
}, 100);
items.add('allowRenaming', {
icon: 'i-cursor',
label: app.translator.trans('core.admin.permissions.allow_renaming_label'),
setting: function setting() {
var minutes = parseInt(app.settings.allow_renaming, 10);
return SettingDropdown.component({
defaultLabel: minutes ? app.translator.transChoice('core.admin.permissions_controls.allow_some_minutes_button', minutes, { count: minutes }) : app.translator.trans('core.admin.permissions_controls.allow_indefinitely_button'),
key: 'allow_renaming',
options: [{ value: '-1', label: app.translator.trans('core.admin.permissions_controls.allow_indefinitely_button') }, { value: '10', label: app.translator.trans('core.admin.permissions_controls.allow_ten_minutes_button') }, { value: 'reply', label: app.translator.trans('core.admin.permissions_controls.allow_until_reply_button') }]
});
}
}, 90);
return items;
}
}, {
key: 'replyItems',
value: function replyItems() {
var items = new ItemList();
items.add('reply', {
icon: 'reply',
label: app.translator.trans('core.admin.permissions.reply_to_discussions_label'),
permission: 'discussion.reply'
}, 100);
items.add('allowPostEditing', {
icon: 'pencil',
label: app.translator.trans('core.admin.permissions.allow_post_editing_label'),
setting: function setting() {
var minutes = parseInt(app.settings.allow_post_editing, 10);
return SettingDropdown.component({
defaultLabel: minutes ? app.translator.transChoice('core.admin.permissions_controls.allow_some_minutes_button', minutes, { count: minutes }) : app.translator.trans('core.admin.permissions_controls.allow_indefinitely_button'),
key: 'allow_post_editing',
options: [{ value: '-1', label: app.translator.trans('core.admin.permissions_controls.allow_indefinitely_button') }, { value: '10', label: app.translator.trans('core.admin.permissions_controls.allow_ten_minutes_button') }, { value: 'reply', label: app.translator.trans('core.admin.permissions_controls.allow_until_reply_button') }]
});
}
}, 90);
return items;
}
}, {
key: 'moderateItems',
value: function moderateItems() {
var items = new ItemList();
items.add('renameDiscussions', {
icon: 'i-cursor',
label: app.translator.trans('core.admin.permissions.rename_discussions_label'),
permission: 'discussion.rename'
}, 100);
items.add('hideDiscussions', {
icon: 'trash-o',
label: app.translator.trans('core.admin.permissions.delete_discussions_label'),
permission: 'discussion.hide'
}, 90);
items.add('deleteDiscussions', {
icon: 'times',
label: app.translator.trans('core.admin.permissions.delete_discussions_forever_label'),
permission: 'discussion.delete'
}, 80);
items.add('editPosts', {
icon: 'pencil',
label: app.translator.trans('core.admin.permissions.edit_and_delete_posts_label'),
permission: 'discussion.editPosts'
}, 70);
items.add('deletePosts', {
icon: 'times',
label: app.translator.trans('core.admin.permissions.delete_posts_forever_label'),
permission: 'discussion.deletePosts'
}, 60);
return items;
}
}, {
key: 'scopeItems',
value: function scopeItems() {
var items = new ItemList();
items.add('global', {
label: app.translator.trans('core.admin.permissions.global_heading'),
render: function render(item) {
if (item.setting) {
return item.setting();
} else if (item.permission) {
return PermissionDropdown.component({
permission: item.permission,
allowGuest: item.allowGuest
});
}
return '';
}
}, 100);
return items;
}
}, {
key: 'scopeControlItems',
value: function scopeControlItems() {
return new ItemList();
}
}]);
return PermissionGrid;
}(Component);
_export('default', PermissionGrid);
}
};
});;
'use strict';
System.register('flarum/components/PermissionsPage', ['flarum/components/Page', 'flarum/components/GroupBadge', 'flarum/components/EditGroupModal', 'flarum/models/Group', 'flarum/helpers/icon', 'flarum/components/PermissionGrid'], function (_export, _context) {
"use strict";
var Page, GroupBadge, EditGroupModal, Group, icon, PermissionGrid, PermissionsPage;
return {
setters: [function (_flarumComponentsPage) {
Page = _flarumComponentsPage.default;
}, function (_flarumComponentsGroupBadge) {
GroupBadge = _flarumComponentsGroupBadge.default;
}, function (_flarumComponentsEditGroupModal) {
EditGroupModal = _flarumComponentsEditGroupModal.default;
}, function (_flarumModelsGroup) {
Group = _flarumModelsGroup.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}, function (_flarumComponentsPermissionGrid) {
PermissionGrid = _flarumComponentsPermissionGrid.default;
}],
execute: function () {
PermissionsPage = function (_Page) {
babelHelpers.inherits(PermissionsPage, _Page);
function PermissionsPage() {
babelHelpers.classCallCheck(this, PermissionsPage);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(PermissionsPage).apply(this, arguments));
}
babelHelpers.createClass(PermissionsPage, [{
key: 'view',
value: function view() {
return m(
'div',
{ className: 'PermissionsPage' },
m(
'div',
{ className: 'PermissionsPage-groups' },
m(
'div',
{ className: 'container' },
app.store.all('groups').filter(function (group) {
return [Group.GUEST_ID, Group.MEMBER_ID].indexOf(group.id()) === -1;
}).map(function (group) {
return m(
'button',
{ className: 'Button Group', onclick: function onclick() {
return app.modal.show(new EditGroupModal({ group: group }));
} },
GroupBadge.component({
group: group,
className: 'Group-icon',
label: null
}),
m(
'span',
{ className: 'Group-name' },
group.namePlural()
)
);
}),
m(
'button',
{ className: 'Button Group Group--add', onclick: function onclick() {
return app.modal.show(new EditGroupModal());
} },
icon('plus', { className: 'Group-icon' }),
m(
'span',
{ className: 'Group-name' },
app.translator.trans('core.admin.permissions.new_group_button')
)
)
)
),
m(
'div',
{ className: 'PermissionsPage-permissions' },
m(
'div',
{ className: 'container' },
PermissionGrid.component()
)
)
);
}
}]);
return PermissionsPage;
}(Page);
_export('default', PermissionsPage);
}
};
});;
"use strict";
System.register("flarum/components/Placeholder", ["flarum/Component"], function (_export, _context) {
"use strict";
var Component, Placeholder;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}],
execute: function () {
Placeholder = function (_Component) {
babelHelpers.inherits(Placeholder, _Component);
function Placeholder() {
babelHelpers.classCallCheck(this, Placeholder);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Placeholder).apply(this, arguments));
}
babelHelpers.createClass(Placeholder, [{
key: "view",
value: function view() {
return m(
"div",
{ className: "Placeholder" },
m(
"p",
null,
this.props.text
)
);
}
}]);
return Placeholder;
}(Component);
_export("default", Placeholder);
}
};
});;
'use strict';
System.register('flarum/components/RequestErrorModal', ['flarum/components/Modal'], function (_export, _context) {
"use strict";
var Modal, RequestErrorModal;
return {
setters: [function (_flarumComponentsModal) {
Modal = _flarumComponentsModal.default;
}],
execute: function () {
RequestErrorModal = function (_Modal) {
babelHelpers.inherits(RequestErrorModal, _Modal);
function RequestErrorModal() {
babelHelpers.classCallCheck(this, RequestErrorModal);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(RequestErrorModal).apply(this, arguments));
}
babelHelpers.createClass(RequestErrorModal, [{
key: 'className',
value: function className() {
return 'RequestErrorModal Modal--large';
}
}, {
key: 'title',
value: function title() {
return this.props.error.xhr ? this.props.error.xhr.status + ' ' + this.props.error.xhr.statusText : '';
}
}, {
key: 'content',
value: function content() {
var responseText = void 0;
try {
responseText = JSON.stringify(JSON.parse(this.props.error.responseText), null, 2);
} catch (e) {
responseText = this.props.error.responseText;
}
return m(
'div',
{ className: 'Modal-body' },
m(
'pre',
null,
this.props.error.options.method,
' ',
this.props.error.options.url,
m('br', null),
m('br', null),
responseText
)
);
}
}]);
return RequestErrorModal;
}(Modal);
_export('default', RequestErrorModal);
}
};
});;
'use strict';
System.register('flarum/components/Select', ['flarum/Component', 'flarum/helpers/icon'], function (_export, _context) {
"use strict";
var Component, icon, Select;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}],
execute: function () {
Select = function (_Component) {
babelHelpers.inherits(Select, _Component);
function Select() {
babelHelpers.classCallCheck(this, Select);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Select).apply(this, arguments));
}
babelHelpers.createClass(Select, [{
key: 'view',
value: function view() {
var _props = this.props;
var options = _props.options;
var onchange = _props.onchange;
var value = _props.value;
return m(
'span',
{ className: 'Select' },
m(
'select',
{ className: 'Select-input FormControl', onchange: onchange ? m.withAttr('value', onchange.bind(this)) : undefined, value: value },
Object.keys(options).map(function (key) {
return m(
'option',
{ value: key },
options[key]
);
})
),
icon('sort', { className: 'Select-caret' })
);
}
}]);
return Select;
}(Component);
_export('default', Select);
}
};
});;
'use strict';
System.register('flarum/components/SelectDropdown', ['flarum/components/Dropdown', 'flarum/helpers/icon'], function (_export, _context) {
"use strict";
var Dropdown, icon, SelectDropdown;
return {
setters: [function (_flarumComponentsDropdown) {
Dropdown = _flarumComponentsDropdown.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}],
execute: function () {
SelectDropdown = function (_Dropdown) {
babelHelpers.inherits(SelectDropdown, _Dropdown);
function SelectDropdown() {
babelHelpers.classCallCheck(this, SelectDropdown);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(SelectDropdown).apply(this, arguments));
}
babelHelpers.createClass(SelectDropdown, [{
key: 'getButtonContent',
value: function getButtonContent() {
var activeChild = this.props.children.filter(function (child) {
return child.props.active;
})[0];
var label = activeChild && activeChild.props.children || this.props.defaultLabel;
if (label instanceof Array) label = label[0];
return [m(
'span',
{ className: 'Button-label' },
label
), icon(this.props.caretIcon, { className: 'Button-caret' })];
}
}], [{
key: 'initProps',
value: function initProps(props) {
props.caretIcon = typeof props.caretIcon !== 'undefined' ? props.caretIcon : 'sort';
babelHelpers.get(Object.getPrototypeOf(SelectDropdown), 'initProps', this).call(this, props);
props.className += ' Dropdown--select';
}
}]);
return SelectDropdown;
}(Dropdown);
_export('default', SelectDropdown);
}
};
});;
"use strict";
System.register("flarum/components/Separator", ["flarum/Component"], function (_export, _context) {
"use strict";
var Component, Separator;
return {
setters: [function (_flarumComponent) {
Component = _flarumComponent.default;
}],
execute: function () {
Separator = function (_Component) {
babelHelpers.inherits(Separator, _Component);
function Separator() {
babelHelpers.classCallCheck(this, Separator);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Separator).apply(this, arguments));
}
babelHelpers.createClass(Separator, [{
key: "view",
value: function view() {
return m("li", { className: "Dropdown-separator" });
}
}]);
return Separator;
}(Component);
Separator.isListItem = true;
_export("default", Separator);
}
};
});;
'use strict';
System.register('flarum/components/SessionDropdown', ['flarum/helpers/avatar', 'flarum/helpers/username', 'flarum/components/Dropdown', 'flarum/components/Button', 'flarum/utils/ItemList'], function (_export, _context) {
"use strict";
var avatar, username, Dropdown, Button, ItemList, SessionDropdown;
return {
setters: [function (_flarumHelpersAvatar) {
avatar = _flarumHelpersAvatar.default;
}, function (_flarumHelpersUsername) {
username = _flarumHelpersUsername.default;
}, function (_flarumComponentsDropdown) {
Dropdown = _flarumComponentsDropdown.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}],
execute: function () {
SessionDropdown = function (_Dropdown) {
babelHelpers.inherits(SessionDropdown, _Dropdown);
function SessionDropdown() {
babelHelpers.classCallCheck(this, SessionDropdown);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(SessionDropdown).apply(this, arguments));
}
babelHelpers.createClass(SessionDropdown, [{
key: 'view',
value: function view() {
this.props.children = this.items().toArray();
return babelHelpers.get(Object.getPrototypeOf(SessionDropdown.prototype), 'view', this).call(this);
}
}, {
key: 'getButtonContent',
value: function getButtonContent() {
var user = app.session.user;
return [avatar(user), ' ', m(
'span',
{ className: 'Button-label' },
username(user)
)];
}
}, {
key: 'items',
value: function items() {
var items = new ItemList();
items.add('logOut', Button.component({
icon: 'sign-out',
children: app.translator.trans('core.admin.header.log_out_button'),
onclick: app.session.logout.bind(app.session)
}), -100);
return items;
}
}], [{
key: 'initProps',
value: function initProps(props) {
babelHelpers.get(Object.getPrototypeOf(SessionDropdown), 'initProps', this).call(this, props);
props.className = 'SessionDropdown';
props.buttonClassName = 'Button Button--user Button--flat';
props.menuClassName = 'Dropdown-menu--right';
}
}]);
return SessionDropdown;
}(Dropdown);
_export('default', SessionDropdown);
}
};
});;
'use strict';
System.register('flarum/components/SettingDropdown', ['flarum/components/SelectDropdown', 'flarum/components/Button', 'flarum/utils/saveSettings'], function (_export, _context) {
"use strict";
var SelectDropdown, Button, saveSettings, SettingDropdown;
return {
setters: [function (_flarumComponentsSelectDropdown) {
SelectDropdown = _flarumComponentsSelectDropdown.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumUtilsSaveSettings) {
saveSettings = _flarumUtilsSaveSettings.default;
}],
execute: function () {
SettingDropdown = function (_SelectDropdown) {
babelHelpers.inherits(SettingDropdown, _SelectDropdown);
function SettingDropdown() {
babelHelpers.classCallCheck(this, SettingDropdown);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(SettingDropdown).apply(this, arguments));
}
babelHelpers.createClass(SettingDropdown, null, [{
key: 'initProps',
value: function initProps(props) {
var _this2 = this;
babelHelpers.get(Object.getPrototypeOf(SettingDropdown), 'initProps', this).call(this, props);
props.className = 'SettingDropdown';
props.buttonClassName = 'Button Button--text';
props.caretIcon = 'caret-down';
props.defaultLabel = 'Custom';
props.children = props.options.map(function (_ref) {
var value = _ref.value;
var label = _ref.label;
var active = app.settings[props.key] === value;
return Button.component({
children: label,
icon: active ? 'check' : true,
onclick: saveSettings.bind(_this2, babelHelpers.defineProperty({}, props.key, value)),
active: active
});
});
}
}]);
return SettingDropdown;
}(SelectDropdown);
_export('default', SettingDropdown);
}
};
});;
'use strict';
System.register('flarum/components/SettingsModal', ['flarum/components/Modal', 'flarum/components/Button', 'flarum/utils/saveSettings'], function (_export, _context) {
"use strict";
var Modal, Button, saveSettings, SettingsModal;
return {
setters: [function (_flarumComponentsModal) {
Modal = _flarumComponentsModal.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumUtilsSaveSettings) {
saveSettings = _flarumUtilsSaveSettings.default;
}],
execute: function () {
SettingsModal = function (_Modal) {
babelHelpers.inherits(SettingsModal, _Modal);
function SettingsModal() {
babelHelpers.classCallCheck(this, SettingsModal);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(SettingsModal).apply(this, arguments));
}
babelHelpers.createClass(SettingsModal, [{
key: 'init',
value: function init() {
this.settings = {};
this.loading = false;
}
}, {
key: 'form',
value: function form() {
return '';
}
}, {
key: 'content',
value: function content() {
return m(
'div',
{ className: 'Modal-body' },
m(
'div',
{ className: 'Form' },
this.form(),
m(
'div',
{ className: 'Form-group' },
this.submitButton()
)
)
);
}
}, {
key: 'submitButton',
value: function submitButton() {
return m(
Button,
{
type: 'submit',
className: 'Button Button--primary',
loading: this.loading,
disabled: !this.changed() },
app.translator.trans('core.admin.settings.submit_button')
);
}
}, {
key: 'setting',
value: function setting(key) {
var fallback = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
this.settings[key] = this.settings[key] || m.prop(app.settings[key] || fallback);
return this.settings[key];
}
}, {
key: 'dirty',
value: function dirty() {
var _this2 = this;
var dirty = {};
Object.keys(this.settings).forEach(function (key) {
var value = _this2.settings[key]();
if (value !== app.settings[key]) {
dirty[key] = value;
}
});
return dirty;
}
}, {
key: 'changed',
value: function changed() {
return Object.keys(this.dirty()).length;
}
}, {
key: 'onsubmit',
value: function onsubmit(e) {
e.preventDefault();
this.loading = true;
saveSettings(this.dirty()).then(this.hide.bind(this), this.loaded.bind(this));
}
}]);
return SettingsModal;
}(Modal);
_export('default', SettingsModal);
}
};
});;
'use strict';
System.register('flarum/components/SplitDropdown', ['flarum/components/Dropdown', 'flarum/components/Button', 'flarum/helpers/icon'], function (_export, _context) {
"use strict";
var Dropdown, Button, icon, SplitDropdown;
return {
setters: [function (_flarumComponentsDropdown) {
Dropdown = _flarumComponentsDropdown.default;
}, function (_flarumComponentsButton) {
Button = _flarumComponentsButton.default;
}, function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}],
execute: function () {
SplitDropdown = function (_Dropdown) {
babelHelpers.inherits(SplitDropdown, _Dropdown);
function SplitDropdown() {
babelHelpers.classCallCheck(this, SplitDropdown);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(SplitDropdown).apply(this, arguments));
}
babelHelpers.createClass(SplitDropdown, [{
key: 'getButton',
value: function getButton() {
// Make a copy of the props of the first child component. We will assign
// these props to a new button, so that it has exactly the same behaviour as
// the first child.
var firstChild = this.getFirstChild();
var buttonProps = babelHelpers.extends({}, firstChild.props);
buttonProps.className = (buttonProps.className || '') + ' SplitDropdown-button Button ' + this.props.buttonClassName;
return [Button.component(buttonProps), m(
'button',
{
className: 'Dropdown-toggle Button Button--icon ' + this.props.buttonClassName,
'data-toggle': 'dropdown' },
icon(this.props.icon, { className: 'Button-icon' }),
icon('caret-down', { className: 'Button-caret' })
)];
}
}, {
key: 'getFirstChild',
value: function getFirstChild() {
var firstChild = this.props.children;
while (firstChild instanceof Array) {
firstChild = firstChild[0];
}return firstChild;
}
}], [{
key: 'initProps',
value: function initProps(props) {
babelHelpers.get(Object.getPrototypeOf(SplitDropdown), 'initProps', this).call(this, props);
props.className += ' Dropdown--split';
props.menuClassName += ' Dropdown-menu--right';
}
}]);
return SplitDropdown;
}(Dropdown);
_export('default', SplitDropdown);
}
};
});;
'use strict';
System.register('flarum/components/Switch', ['flarum/components/Checkbox'], function (_export, _context) {
"use strict";
var Checkbox, Switch;
return {
setters: [function (_flarumComponentsCheckbox) {
Checkbox = _flarumComponentsCheckbox.default;
}],
execute: function () {
Switch = function (_Checkbox) {
babelHelpers.inherits(Switch, _Checkbox);
function Switch() {
babelHelpers.classCallCheck(this, Switch);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Switch).apply(this, arguments));
}
babelHelpers.createClass(Switch, [{
key: 'getDisplay',
value: function getDisplay() {
return this.loading ? babelHelpers.get(Object.getPrototypeOf(Switch.prototype), 'getDisplay', this).call(this) : '';
}
}], [{
key: 'initProps',
value: function initProps(props) {
babelHelpers.get(Object.getPrototypeOf(Switch), 'initProps', this).call(this, props);
props.className = (props.className || '') + ' Checkbox--switch';
}
}]);
return Switch;
}(Checkbox);
_export('default', Switch);
}
};
});;
"use strict";
System.register("flarum/extend", [], function (_export, _context) {
"use strict";
return {
setters: [],
execute: function () {
/**
* Extend an object's method by running its output through a mutating callback
* every time it is called.
*
* The callback accepts the method's return value and should perform any
* mutations directly on this value. For this reason, this function will not be
* effective on methods which return scalar values (numbers, strings, booleans).
*
* Care should be taken to extend the correct object – in most cases, a class'
* prototype will be the desired target of extension, not the class itself.
*
* @example
* extend(Discussion.prototype, 'badges', function(badges) {
* // do something with `badges`
* });
*
* @param {Object} object The object that owns the method
* @param {String} method The name of the method to extend
* @param {function} callback A callback which mutates the method's output
*/
function extend(object, method, callback) {
var original = object[method];
object[method] = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var value = original ? original.apply(this, args) : undefined;
callback.apply(this, [value].concat(args));
return value;
};
babelHelpers.extends(object[method], original);
}
/**
* Override an object's method by replacing it with a new function, so that the
* new function will be run every time the object's method is called.
*
* The replacement function accepts the original method as its first argument,
* which is like a call to 'super'. Any arguments passed to the original method
* are also passed to the replacement.
*
* Care should be taken to extend the correct object – in most cases, a class'
* prototype will be the desired target of extension, not the class itself.
*
* @example
* override(Discussion.prototype, 'badges', function(original) {
* const badges = original();
* // do something with badges
* return badges;
* });
*
* @param {Object} object The object that owns the method
* @param {String} method The name of the method to override
* @param {function} newMethod The method to replace it with
*/
_export("extend", extend);
function override(object, method, newMethod) {
var original = object[method];
object[method] = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return newMethod.apply(this, [original.bind(this)].concat(args));
};
babelHelpers.extends(object[method], original);
}
_export("override", override);
}
};
});;
'use strict';
System.register('flarum/helpers/avatar', [], function (_export, _context) {
"use strict";
function avatar(user) {
var attrs = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
attrs.className = 'Avatar ' + (attrs.className || '');
var content = '';
// If the `title` attribute is set to null or false, we don't want to give the
// avatar a title. On the other hand, if it hasn't been given at all, we can
// safely default it to the user's username.
var hasTitle = attrs.title === 'undefined' || attrs.title;
if (!hasTitle) delete attrs.title;
// If a user has been passed, then we will set up an avatar using their
// uploaded image, or the first letter of their username if they haven't
// uploaded one.
if (user) {
var username = user.username() || '?';
var avatarUrl = user.avatarUrl();
if (hasTitle) attrs.title = attrs.title || username;
if (avatarUrl) {
return m('img', babelHelpers.extends({}, attrs, { src: avatarUrl }));
}
content = username.charAt(0).toUpperCase();
attrs.style = { background: user.color() };
}
return m(
'span',
attrs,
content
);
}
_export('default', avatar);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/helpers/fullTime', [], function (_export, _context) {
"use strict";
function fullTime(time) {
var mo = moment(time);
var datetime = mo.format();
var full = mo.format('LLLL');
return m(
'time',
{ pubdate: true, datetime: datetime },
full
);
}
_export('default', fullTime);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/helpers/highlight', ['flarum/utils/string'], function (_export, _context) {
"use strict";
var truncate;
function highlight(string, phrase, length) {
if (!phrase && !length) return string;
var replaceStr = function replaceStr(str) {
return str.replace(/\\/g, '\\\\').replace(/\+/g, '\\+').replace(/\*/g, '\\*').replace(/\./g, '\\.').replace(/\[/g, '\\[').replace(/\]/g, '\\]').replace(/\./g, '\\.').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
};
phrase = replaceStr(phrase);
// Convert the word phrase into a global regular expression (if it isn't
// already) so we can search the string for matched.
var regexp = phrase instanceof RegExp ? phrase : new RegExp(phrase, 'gi');
var highlighted = string;
var start = 0;
// If a length was given, the truncate the string surrounding the first match.
if (length) {
if (phrase) start = Math.max(0, string.search(regexp) - length / 2);
highlighted = truncate(highlighted, length, start);
}
// Convert the string into HTML entities, then highlight all matches with
// <mark> tags. Then we will return the result as a trusted HTML string.
highlighted = $('<div/>').text(highlighted).html();
if (phrase) highlighted = highlighted.replace(regexp, '<mark>$&</mark>');
return m.trust(highlighted);
}
_export('default', highlight);
return {
setters: [function (_flarumUtilsString) {
truncate = _flarumUtilsString.truncate;
}],
execute: function () {}
};
});;
'use strict';
System.register('flarum/helpers/humanTime', ['flarum/utils/humanTime'], function (_export, _context) {
"use strict";
var humanTimeUtil;
function humanTime(time) {
var mo = moment(time);
var datetime = mo.format();
var full = mo.format('LLLL');
var ago = humanTimeUtil(time);
return m(
'time',
{ pubdate: true, datetime: datetime, title: full, 'data-humantime': true },
ago
);
}
_export('default', humanTime);
return {
setters: [function (_flarumUtilsHumanTime) {
humanTimeUtil = _flarumUtilsHumanTime.default;
}],
execute: function () {}
};
});;
'use strict';
System.register('flarum/helpers/icon', [], function (_export, _context) {
"use strict";
function icon(name) {
var attrs = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
attrs.className = 'icon fa fa-fw fa-' + name + ' ' + (attrs.className || '');
return m('i', attrs);
}
_export('default', icon);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/helpers/listItems', ['flarum/components/Separator', 'flarum/utils/classList'], function (_export, _context) {
"use strict";
var Separator, classList;
function isSeparator(item) {
return item && item.component === Separator;
}
function withoutUnnecessarySeparators(items) {
var newItems = [];
var prevItem = void 0;
items.forEach(function (item, i) {
if (!isSeparator(item) || prevItem && !isSeparator(prevItem) && i !== items.length - 1) {
prevItem = item;
newItems.push(item);
}
});
return newItems;
}
/**
* The `listItems` helper wraps a collection of components in <li> tags,
* stripping out any unnecessary `Separator` components.
*
* @param {*} items
* @return {Array}
*/
function listItems(items) {
if (!(items instanceof Array)) items = [items];
return withoutUnnecessarySeparators(items).map(function (item) {
var isListItem = item.component && item.component.isListItem;
var active = item.component && item.component.isActive && item.component.isActive(item.props);
var className = item.props ? item.props.itemClassName : item.itemClassName;
if (isListItem) {
item.attrs = item.attrs || {};
item.attrs.key = item.attrs.key || item.itemName;
}
var space = new String(' ');
space.attrs = { key: '_space_' + item.itemName };
return [isListItem ? item : m(
'li',
{ className: classList([item.itemName ? 'item-' + item.itemName : '', className, active ? 'active' : '']),
key: item.itemName },
item
), space];
});
}
_export('default', listItems);
return {
setters: [function (_flarumComponentsSeparator) {
Separator = _flarumComponentsSeparator.default;
}, function (_flarumUtilsClassList) {
classList = _flarumUtilsClassList.default;
}],
execute: function () {}
};
});;
'use strict';
System.register('flarum/helpers/punctuateSeries', [], function (_export, _context) {
"use strict";
function punctuateSeries(items) {
if (items.length === 2) {
return app.translator.trans('core.lib.series.two_text', {
first: items[0],
second: items[1]
});
} else if (items.length >= 3) {
// If there are three or more items, we will join all but the first and
// last items with the equivalent of a comma, and then we will feed that
// into the translator along with the first and last item.
var second = items.slice(1, items.length - 1).reduce(function (list, item) {
return list.concat([item, app.translator.trans('core.lib.series.glue_text')]);
}, []).slice(0, -1);
return app.translator.trans('core.lib.series.three_text', {
first: items[0],
second: second,
third: items[items.length - 1]
});
}
return items;
}
_export('default', punctuateSeries);
return {
setters: [],
execute: function () {}
};
});;
"use strict";
System.register("flarum/helpers/username", [], function (_export, _context) {
"use strict";
function username(user) {
var name = user && user.username() || app.translator.trans('core.lib.username.deleted_text');
return m(
"span",
{ className: "username" },
name
);
}
_export("default", username);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/helpers/userOnline', ['flarum/helpers/icon'], function (_export, _context) {
"use strict";
var icon;
function userOnline(user) {
if (user.lastSeenTime() && user.isOnline()) {
return m(
'span',
{ className: 'UserOnline' },
icon('circle')
);
}
}
_export('default', userOnline);
return {
setters: [function (_flarumHelpersIcon) {
icon = _flarumHelpersIcon.default;
}],
execute: function () {}
};
});;
'use strict';
System.register('flarum/initializers/boot', ['flarum/utils/ScrollListener', 'flarum/utils/Drawer', 'flarum/utils/mapRoutes', 'flarum/components/Navigation', 'flarum/components/HeaderPrimary', 'flarum/components/HeaderSecondary', 'flarum/components/AdminNav', 'flarum/components/ModalManager', 'flarum/components/AlertManager'], function (_export, _context) {
"use strict";
var ScrollListener, Drawer, mapRoutes, Navigation, HeaderPrimary, HeaderSecondary, AdminNav, ModalManager, AlertManager;
function boot(app) {
m.startComputation();
m.mount(document.getElementById('app-navigation'), Navigation.component({ className: 'App-backControl', drawer: true }));
m.mount(document.getElementById('header-navigation'), Navigation.component());
m.mount(document.getElementById('header-primary'), HeaderPrimary.component());
m.mount(document.getElementById('header-secondary'), HeaderSecondary.component());
m.mount(document.getElementById('admin-navigation'), AdminNav.component());
app.drawer = new Drawer();
app.modal = m.mount(document.getElementById('modal'), ModalManager.component());
app.alerts = m.mount(document.getElementById('alerts'), AlertManager.component());
app.history = {
canGoBack: function canGoBack() {
return true;
},
getPrevious: function getPrevious() {},
backUrl: function backUrl() {
return app.forum.attribute('baseUrl');
},
back: function back() {
window.location = this.backUrl();
}
};
m.route.mode = 'hash';
m.route(document.getElementById('content'), '/', mapRoutes(app.routes));
m.endComputation();
// Add a class to the body which indicates that the page has been scrolled
// down.
new ScrollListener(function (top) {
var $app = $('#app');
var offset = $app.offset().top;
$app.toggleClass('affix', top >= offset).toggleClass('scrolled', top > offset);
}).start();
app.booted = true;
// If an extension has just been enabled, then we will run its settings
// callback.
var enabled = localStorage.getItem('enabledExtension');
if (enabled && app.extensionSettings[enabled]) {
app.extensionSettings[enabled]();
localStorage.removeItem('enabledExtension');
}
}
_export('default', boot);
return {
setters: [function (_flarumUtilsScrollListener) {
ScrollListener = _flarumUtilsScrollListener.default;
}, function (_flarumUtilsDrawer) {
Drawer = _flarumUtilsDrawer.default;
}, function (_flarumUtilsMapRoutes) {
mapRoutes = _flarumUtilsMapRoutes.default;
}, function (_flarumComponentsNavigation) {
Navigation = _flarumComponentsNavigation.default;
}, function (_flarumComponentsHeaderPrimary) {
HeaderPrimary = _flarumComponentsHeaderPrimary.default;
}, function (_flarumComponentsHeaderSecondary) {
HeaderSecondary = _flarumComponentsHeaderSecondary.default;
}, function (_flarumComponentsAdminNav) {
AdminNav = _flarumComponentsAdminNav.default;
}, function (_flarumComponentsModalManager) {
ModalManager = _flarumComponentsModalManager.default;
}, function (_flarumComponentsAlertManager) {
AlertManager = _flarumComponentsAlertManager.default;
}],
execute: function () {}
};
});;
'use strict';
System.register('flarum/initializers/humanTime', ['flarum/utils/humanTime'], function (_export, _context) {
"use strict";
var humanTimeUtil;
function updateHumanTimes() {
$('[data-humantime]').each(function () {
var $this = $(this);
var ago = humanTimeUtil($this.attr('datetime'));
$this.html(ago);
});
}
/**
* The `humanTime` initializer sets up a loop every 1 second to update
* timestamps rendered with the `humanTime` helper.
*/
function humanTime() {
setInterval(updateHumanTimes, 1000);
}
_export('default', humanTime);
return {
setters: [function (_flarumUtilsHumanTime) {
humanTimeUtil = _flarumUtilsHumanTime.default;
}],
execute: function () {}
};
});;
'use strict';
System.register('flarum/initializers/preload', ['flarum/Session'], function (_export, _context) {
"use strict";
var Session;
function preload(app) {
app.store.pushPayload({ data: app.preload.data });
app.forum = app.store.getById('forums', 1);
app.session = new Session(app.store.getById('users', app.preload.session.userId), app.preload.session.csrfToken);
}
_export('default', preload);
return {
setters: [function (_flarumSession) {
Session = _flarumSession.default;
}],
execute: function () {}
};
});;
'use strict';
System.register('flarum/initializers/routes', ['flarum/components/DashboardPage', 'flarum/components/BasicsPage', 'flarum/components/PermissionsPage', 'flarum/components/AppearancePage', 'flarum/components/ExtensionsPage'], function (_export, _context) {
"use strict";
var DashboardPage, BasicsPage, PermissionsPage, AppearancePage, ExtensionsPage;
_export('default', function (app) {
app.routes = {
'dashboard': { path: '/', component: DashboardPage.component() },
'basics': { path: '/basics', component: BasicsPage.component() },
'permissions': { path: '/permissions', component: PermissionsPage.component() },
'appearance': { path: '/appearance', component: AppearancePage.component() },
'extensions': { path: '/extensions', component: ExtensionsPage.component() }
};
});
return {
setters: [function (_flarumComponentsDashboardPage) {
DashboardPage = _flarumComponentsDashboardPage.default;
}, function (_flarumComponentsBasicsPage) {
BasicsPage = _flarumComponentsBasicsPage.default;
}, function (_flarumComponentsPermissionsPage) {
PermissionsPage = _flarumComponentsPermissionsPage.default;
}, function (_flarumComponentsAppearancePage) {
AppearancePage = _flarumComponentsAppearancePage.default;
}, function (_flarumComponentsExtensionsPage) {
ExtensionsPage = _flarumComponentsExtensionsPage.default;
}],
execute: function () {}
};
});;
'use strict';
System.register('flarum/initializers/store', ['flarum/Store', 'flarum/models/Forum', 'flarum/models/User', 'flarum/models/Discussion', 'flarum/models/Post', 'flarum/models/Group', 'flarum/models/Activity', 'flarum/models/Notification'], function (_export, _context) {
"use strict";
var Store, Forum, User, Discussion, Post, Group, Activity, Notification;
function store(app) {
app.store = new Store({
forums: Forum,
users: User,
discussions: Discussion,
posts: Post,
groups: Group,
activity: Activity,
notifications: Notification
});
}
_export('default', store);
return {
setters: [function (_flarumStore) {
Store = _flarumStore.default;
}, function (_flarumModelsForum) {
Forum = _flarumModelsForum.default;
}, function (_flarumModelsUser) {
User = _flarumModelsUser.default;
}, function (_flarumModelsDiscussion) {
Discussion = _flarumModelsDiscussion.default;
}, function (_flarumModelsPost) {
Post = _flarumModelsPost.default;
}, function (_flarumModelsGroup) {
Group = _flarumModelsGroup.default;
}, function (_flarumModelsActivity) {
Activity = _flarumModelsActivity.default;
}, function (_flarumModelsNotification) {
Notification = _flarumModelsNotification.default;
}],
execute: function () {}
};
});;
'use strict';
System.register('flarum/Model', [], function (_export, _context) {
"use strict";
var Model;
return {
setters: [],
execute: function () {
Model = function () {
/**
* @param {Object} data A resource object from the API.
* @param {Store} store The data store that this model should be persisted to.
* @public
*/
function Model() {
var data = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var store = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
babelHelpers.classCallCheck(this, Model);
/**
* The resource object from the API.
*
* @type {Object}
* @public
*/
this.data = data;
/**
* The time at which the model's data was last updated. Watching the value
* of this property is a fast way to retain/cache a subtree if data hasn't
* changed.
*
* @type {Date}
* @public
*/
this.freshness = new Date();
/**
* Whether or not the resource exists on the server.
*
* @type {Boolean}
* @public
*/
this.exists = false;
/**
* The data store that this resource should be persisted to.
*
* @type {Store}
* @protected
*/
this.store = store;
}
/**
* Get the model's ID.
*
* @return {Integer}
* @public
* @final
*/
babelHelpers.createClass(Model, [{
key: 'id',
value: function id() {
return this.data.id;
}
}, {
key: 'attribute',
value: function attribute(_attribute) {
return this.data.attributes[_attribute];
}
}, {
key: 'pushData',
value: function pushData(data) {
// Since most of the top-level items in a resource object are objects
// (e.g. relationships, attributes), we'll need to check and perform the
// merge at the second level if that's the case.
for (var key in data) {
if (babelHelpers.typeof(data[key]) === 'object') {
this.data[key] = this.data[key] || {};
// For every item in a second-level object, we want to check if we've
// been handed a Model instance. If so, we will convert it to a
// relationship data object.
for (var innerKey in data[key]) {
if (data[key][innerKey] instanceof Model) {
data[key][innerKey] = { data: Model.getIdentifier(data[key][innerKey]) };
}
this.data[key][innerKey] = data[key][innerKey];
}
} else {
this.data[key] = data[key];
}
}
// Now that we've updated the data, we can say that the model is fresh.
// This is an easy way to invalidate retained subtrees etc.
this.freshness = new Date();
}
}, {
key: 'pushAttributes',
value: function pushAttributes(attributes) {
this.pushData({ attributes: attributes });
}
}, {
key: 'save',
value: function save(attributes) {
var _this = this;
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var data = {
type: this.data.type,
id: this.data.id,
attributes: attributes
};
// If a 'relationships' key exists, extract it from the attributes hash and
// set it on the top-level data object instead. We will be sending this data
// object to the API for persistence.
if (attributes.relationships) {
data.relationships = {};
for (var key in attributes.relationships) {
var model = attributes.relationships[key];
data.relationships[key] = {
data: model instanceof Array ? model.map(Model.getIdentifier) : Model.getIdentifier(model)
};
}
delete attributes.relationships;
}
// Before we update the model's data, we should make a copy of the model's
// old data so that we can revert back to it if something goes awry during
// persistence.
var oldData = this.copyData();
this.pushData(data);
var request = { data: data };
if (options.meta) request.meta = options.meta;
return app.request(babelHelpers.extends({
method: this.exists ? 'PATCH' : 'POST',
url: app.forum.attribute('apiUrl') + this.apiEndpoint(),
data: request
}, options)).then(
// If everything went well, we'll make sure the store knows that this
// model exists now (if it didn't already), and we'll push the data that
// the API returned into the store.
function (payload) {
_this.store.data[payload.data.type] = _this.store.data[payload.data.type] || {};
_this.store.data[payload.data.type][payload.data.id] = _this;
return _this.store.pushPayload(payload);
},
// If something went wrong, though... good thing we backed up our model's
// old data! We'll revert to that and let others handle the error.
function (response) {
_this.pushData(oldData);
m.lazyRedraw();
throw response;
});
}
}, {
key: 'delete',
value: function _delete(data) {
var _this2 = this;
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (!this.exists) return m.deferred.resolve().promise;
return app.request(babelHelpers.extends({
method: 'DELETE',
url: app.forum.attribute('apiUrl') + this.apiEndpoint(),
data: data
}, options)).then(function () {
_this2.exists = false;
_this2.store.remove(_this2);
});
}
}, {
key: 'apiEndpoint',
value: function apiEndpoint() {
return '/' + this.data.type + (this.exists ? '/' + this.data.id : '');
}
}, {
key: 'copyData',
value: function copyData() {
return JSON.parse(JSON.stringify(this.data));
}
}], [{
key: 'attribute',
value: function attribute(name, transform) {
return function () {
var value = this.data.attributes && this.data.attributes[name];
return transform ? transform(value) : value;
};
}
}, {
key: 'hasOne',
value: function hasOne(name) {
return function () {
if (this.data.relationships) {
var relationship = this.data.relationships[name];
if (relationship) {
return app.store.getById(relationship.data.type, relationship.data.id);
}
}
return false;
};
}
}, {
key: 'hasMany',
value: function hasMany(name) {
return function () {
if (this.data.relationships) {
var relationship = this.data.relationships[name];
if (relationship) {
return relationship.data.map(function (data) {
return app.store.getById(data.type, data.id);
});
}
}
return false;
};
}
}, {
key: 'transformDate',
value: function transformDate(value) {
return value ? new Date(value) : null;
}
}, {
key: 'getIdentifier',
value: function getIdentifier(model) {
return {
type: model.data.type,
id: model.data.id
};
}
}]);
return Model;
}();
_export('default', Model);
}
};
});;
'use strict';
System.register('flarum/models/Discussion', ['flarum/Model', 'flarum/utils/mixin', 'flarum/utils/computed', 'flarum/utils/ItemList', 'flarum/components/Badge'], function (_export, _context) {
"use strict";
var Model, mixin, computed, ItemList, Badge, Discussion;
return {
setters: [function (_flarumModel) {
Model = _flarumModel.default;
}, function (_flarumUtilsMixin) {
mixin = _flarumUtilsMixin.default;
}, function (_flarumUtilsComputed) {
computed = _flarumUtilsComputed.default;
}, function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}, function (_flarumComponentsBadge) {
Badge = _flarumComponentsBadge.default;
}],
execute: function () {
Discussion = function (_Model) {
babelHelpers.inherits(Discussion, _Model);
function Discussion() {
babelHelpers.classCallCheck(this, Discussion);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Discussion).apply(this, arguments));
}
return Discussion;
}(Model);
_export('default', Discussion);
babelHelpers.extends(Discussion.prototype, {
title: Model.attribute('title'),
slug: Model.attribute('slug'),
startTime: Model.attribute('startTime', Model.transformDate),
startUser: Model.hasOne('startUser'),
startPost: Model.hasOne('startPost'),
lastTime: Model.attribute('lastTime', Model.transformDate),
lastUser: Model.hasOne('lastUser'),
lastPost: Model.hasOne('lastPost'),
lastPostNumber: Model.attribute('lastPostNumber'),
commentsCount: Model.attribute('commentsCount'),
repliesCount: computed('commentsCount', function (commentsCount) {
return Math.max(0, commentsCount - 1);
}),
posts: Model.hasMany('posts'),
relevantPosts: Model.hasMany('relevantPosts'),
readTime: Model.attribute('readTime', Model.transformDate),
readNumber: Model.attribute('readNumber'),
isUnread: computed('unreadCount', function (unreadCount) {
return !!unreadCount;
}),
isRead: computed('unreadCount', function (unreadCount) {
return app.session.user && !unreadCount;
}),
hideTime: Model.attribute('hideTime', Model.transformDate),
hideUser: Model.hasOne('hideUser'),
isHidden: computed('hideTime', 'commentsCount', function (hideTime, commentsCount) {
return !!hideTime || commentsCount === 0;
}),
canReply: Model.attribute('canReply'),
canRename: Model.attribute('canRename'),
canHide: Model.attribute('canHide'),
canDelete: Model.attribute('canDelete'),
removePost: function removePost(id) {
var relationships = this.data.relationships;
var posts = relationships && relationships.posts;
if (posts) {
posts.data.some(function (data, i) {
if (id === data.id) {
posts.data.splice(i, 1);
return true;
}
});
}
},
unreadCount: function unreadCount() {
var user = app.session.user;
if (user && user.readTime() < this.lastTime()) {
return Math.max(0, this.lastPostNumber() - (this.readNumber() || 0));
}
return 0;
},
badges: function badges() {
var items = new ItemList();
if (this.isHidden()) {
items.add('hidden', m(Badge, { type: 'hidden', icon: 'trash', label: app.translator.trans('core.lib.badge.hidden_tooltip') }));
}
return items;
},
postIds: function postIds() {
var posts = this.data.relationships.posts;
return posts ? posts.data.map(function (link) {
return link.id;
}) : [];
}
});
_export('default', Discussion);
}
};
});;
'use strict';
System.register('flarum/models/Forum', ['flarum/Model', 'flarum/utils/mixin'], function (_export, _context) {
"use strict";
var Model, mixin, Forum;
return {
setters: [function (_flarumModel) {
Model = _flarumModel.default;
}, function (_flarumUtilsMixin) {
mixin = _flarumUtilsMixin.default;
}],
execute: function () {
Forum = function (_Model) {
babelHelpers.inherits(Forum, _Model);
function Forum() {
babelHelpers.classCallCheck(this, Forum);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Forum).apply(this, arguments));
}
babelHelpers.createClass(Forum, [{
key: 'apiEndpoint',
value: function apiEndpoint() {
return '/forum';
}
}]);
return Forum;
}(Model);
_export('default', Forum);
}
};
});;
'use strict';
System.register('flarum/models/Group', ['flarum/Model', 'flarum/utils/mixin'], function (_export, _context) {
"use strict";
var Model, mixin, Group;
return {
setters: [function (_flarumModel) {
Model = _flarumModel.default;
}, function (_flarumUtilsMixin) {
mixin = _flarumUtilsMixin.default;
}],
execute: function () {
Group = function (_Model) {
babelHelpers.inherits(Group, _Model);
function Group() {
babelHelpers.classCallCheck(this, Group);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Group).apply(this, arguments));
}
return Group;
}(Model);
babelHelpers.extends(Group.prototype, {
nameSingular: Model.attribute('nameSingular'),
namePlural: Model.attribute('namePlural'),
color: Model.attribute('color'),
icon: Model.attribute('icon')
});
Group.ADMINISTRATOR_ID = '1';
Group.GUEST_ID = '2';
Group.MEMBER_ID = '3';
_export('default', Group);
}
};
});;
'use strict';
System.register('flarum/models/Notification', ['flarum/Model', 'flarum/utils/mixin', 'flarum/utils/computed'], function (_export, _context) {
"use strict";
var Model, mixin, computed, Notification;
return {
setters: [function (_flarumModel) {
Model = _flarumModel.default;
}, function (_flarumUtilsMixin) {
mixin = _flarumUtilsMixin.default;
}, function (_flarumUtilsComputed) {
computed = _flarumUtilsComputed.default;
}],
execute: function () {
Notification = function (_Model) {
babelHelpers.inherits(Notification, _Model);
function Notification() {
babelHelpers.classCallCheck(this, Notification);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Notification).apply(this, arguments));
}
return Notification;
}(Model);
_export('default', Notification);
babelHelpers.extends(Notification.prototype, {
contentType: Model.attribute('contentType'),
subjectId: Model.attribute('subjectId'),
content: Model.attribute('content'),
time: Model.attribute('time', Model.date),
isRead: Model.attribute('isRead'),
unreadCount: Model.attribute('unreadCount'),
additionalUnreadCount: computed('unreadCount', function (unreadCount) {
return Math.max(0, unreadCount - 1);
}),
user: Model.hasOne('user'),
sender: Model.hasOne('sender'),
subject: Model.hasOne('subject')
});
_export('default', Notification);
}
};
});;
'use strict';
System.register('flarum/models/Post', ['flarum/Model', 'flarum/utils/mixin', 'flarum/utils/computed', 'flarum/utils/string'], function (_export, _context) {
"use strict";
var Model, mixin, computed, getPlainContent, Post;
return {
setters: [function (_flarumModel) {
Model = _flarumModel.default;
}, function (_flarumUtilsMixin) {
mixin = _flarumUtilsMixin.default;
}, function (_flarumUtilsComputed) {
computed = _flarumUtilsComputed.default;
}, function (_flarumUtilsString) {
getPlainContent = _flarumUtilsString.getPlainContent;
}],
execute: function () {
Post = function (_Model) {
babelHelpers.inherits(Post, _Model);
function Post() {
babelHelpers.classCallCheck(this, Post);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Post).apply(this, arguments));
}
return Post;
}(Model);
_export('default', Post);
babelHelpers.extends(Post.prototype, {
number: Model.attribute('number'),
discussion: Model.hasOne('discussion'),
time: Model.attribute('time', Model.transformDate),
user: Model.hasOne('user'),
contentType: Model.attribute('contentType'),
content: Model.attribute('content'),
contentHtml: Model.attribute('contentHtml'),
contentPlain: computed('contentHtml', getPlainContent),
editTime: Model.attribute('editTime', Model.transformDate),
editUser: Model.hasOne('editUser'),
isEdited: computed('editTime', function (editTime) {
return !!editTime;
}),
hideTime: Model.attribute('hideTime', Model.transformDate),
hideUser: Model.hasOne('hideUser'),
isHidden: computed('hideTime', function (hideTime) {
return !!hideTime;
}),
canEdit: Model.attribute('canEdit'),
canDelete: Model.attribute('canDelete')
});
_export('default', Post);
}
};
});;
'use strict';
System.register('flarum/models/User', ['flarum/Model', 'flarum/utils/mixin', 'flarum/utils/stringToColor', 'flarum/utils/ItemList', 'flarum/utils/computed', 'flarum/components/GroupBadge'], function (_export, _context) {
"use strict";
var Model, mixin, stringToColor, ItemList, computed, GroupBadge, User;
return {
setters: [function (_flarumModel) {
Model = _flarumModel.default;
}, function (_flarumUtilsMixin) {
mixin = _flarumUtilsMixin.default;
}, function (_flarumUtilsStringToColor) {
stringToColor = _flarumUtilsStringToColor.default;
}, function (_flarumUtilsItemList) {
ItemList = _flarumUtilsItemList.default;
}, function (_flarumUtilsComputed) {
computed = _flarumUtilsComputed.default;
}, function (_flarumComponentsGroupBadge) {
GroupBadge = _flarumComponentsGroupBadge.default;
}],
execute: function () {
User = function (_Model) {
babelHelpers.inherits(User, _Model);
function User() {
babelHelpers.classCallCheck(this, User);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(User).apply(this, arguments));
}
return User;
}(Model);
_export('default', User);
babelHelpers.extends(User.prototype, {
username: Model.attribute('username'),
email: Model.attribute('email'),
isActivated: Model.attribute('isActivated'),
password: Model.attribute('password'),
avatarUrl: Model.attribute('avatarUrl'),
bio: Model.attribute('bio'),
bioHtml: computed('bio', function (bio) {
return bio ? '<p>' + $('<div/>').text(bio).html().replace(/\n/g, '<br>').autoLink({ rel: 'nofollow' }) + '</p>' : '';
}),
preferences: Model.attribute('preferences'),
groups: Model.hasMany('groups'),
joinTime: Model.attribute('joinTime', Model.transformDate),
lastSeenTime: Model.attribute('lastSeenTime', Model.transformDate),
readTime: Model.attribute('readTime', Model.transformDate),
unreadNotificationsCount: Model.attribute('unreadNotificationsCount'),
newNotificationsCount: Model.attribute('newNotificationsCount'),
discussionsCount: Model.attribute('discussionsCount'),
commentsCount: Model.attribute('commentsCount'),
canEdit: Model.attribute('canEdit'),
canDelete: Model.attribute('canDelete'),
avatarColor: null,
color: computed('username', 'avatarUrl', 'avatarColor', function (username, avatarUrl, avatarColor) {
// If we've already calculated and cached the dominant color of the user's
// avatar, then we can return that in RGB format. If we haven't, we'll want
// to calculate it. Unless the user doesn't have an avatar, in which case
// we generate a color from their username.
if (avatarColor) {
return 'rgb(' + avatarColor.join(', ') + ')';
} else if (avatarUrl) {
this.calculateAvatarColor();
return '';
}
return '#' + stringToColor(username);
}),
isOnline: function isOnline() {
return this.lastSeenTime() > moment().subtract(5, 'minutes').toDate();
},
badges: function badges() {
var items = new ItemList();
var groups = this.groups();
if (groups) {
groups.forEach(function (group) {
items.add('group' + group.id(), GroupBadge.component({ group: group }));
});
}
return items;
},
calculateAvatarColor: function calculateAvatarColor() {
var image = new Image();
var user = this;
image.onload = function () {
var colorThief = new ColorThief();
user.avatarColor = colorThief.getColor(this);
user.freshness = new Date();
m.redraw();
};
image.src = this.avatarUrl();
},
savePreferences: function savePreferences(newPreferences) {
var preferences = this.preferences();
babelHelpers.extends(preferences, newPreferences);
return this.save({ preferences: preferences });
}
});
_export('default', User);
}
};
});;
'use strict';
System.register('flarum/Session', [], function (_export, _context) {
"use strict";
var Session;
return {
setters: [],
execute: function () {
Session = function () {
function Session(user, csrfToken) {
babelHelpers.classCallCheck(this, Session);
/**
* The current authenticated user.
*
* @type {User|null}
* @public
*/
this.user = user;
/**
* The CSRF token.
*
* @type {String|null}
* @public
*/
this.csrfToken = csrfToken;
}
/**
* Attempt to log in a user.
*
* @param {String} identification The username/email.
* @param {String} password
* @param {Object} [options]
* @return {Promise}
* @public
*/
babelHelpers.createClass(Session, [{
key: 'login',
value: function login(identification, password) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
return app.request(babelHelpers.extends({
method: 'POST',
url: app.forum.attribute('baseUrl') + '/login',
data: { identification: identification, password: password }
}, options));
}
}, {
key: 'logout',
value: function logout() {
window.location = app.forum.attribute('baseUrl') + '/logout?token=' + this.csrfToken;
}
}]);
return Session;
}();
_export('default', Session);
}
};
});;
'use strict';
System.register('flarum/Store', [], function (_export, _context) {
"use strict";
var Store;
return {
setters: [],
execute: function () {
Store = function () {
function Store(models) {
babelHelpers.classCallCheck(this, Store);
/**
* The local data store. A tree of resource types to IDs, such that
* accessing data[type][id] will return the model for that type/ID.
*
* @type {Object}
* @protected
*/
this.data = {};
/**
* The model registry. A map of resource types to the model class that
* should be used to represent resources of that type.
*
* @type {Object}
* @public
*/
this.models = models;
}
/**
* Push resources contained within an API payload into the store.
*
* @param {Object} payload
* @return {Model|Model[]} The model(s) representing the resource(s) contained
* within the 'data' key of the payload.
* @public
*/
babelHelpers.createClass(Store, [{
key: 'pushPayload',
value: function pushPayload(payload) {
if (payload.included) payload.included.map(this.pushObject.bind(this));
var result = payload.data instanceof Array ? payload.data.map(this.pushObject.bind(this)) : this.pushObject(payload.data);
// Attach the original payload to the model that we give back. This is
// useful to consumers as it allows them to access meta information
// associated with their request.
result.payload = payload;
return result;
}
}, {
key: 'pushObject',
value: function pushObject(data) {
if (!this.models[data.type]) return null;
var type = this.data[data.type] = this.data[data.type] || {};
if (type[data.id]) {
type[data.id].pushData(data);
} else {
type[data.id] = this.createRecord(data.type, data);
}
type[data.id].exists = true;
return type[data.id];
}
}, {
key: 'find',
value: function find(type, id) {
var query = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
var data = query;
var url = app.forum.attribute('apiUrl') + '/' + type;
if (id instanceof Array) {
url += '?filter[id]=' + id.join(',');
} else if ((typeof id === 'undefined' ? 'undefined' : babelHelpers.typeof(id)) === 'object') {
data = id;
} else if (id) {
url += '/' + id;
}
return app.request(babelHelpers.extends({
method: 'GET',
url: url,
data: data
}, options)).then(this.pushPayload.bind(this));
}
}, {
key: 'getById',
value: function getById(type, id) {
return this.data[type] && this.data[type][id];
}
}, {
key: 'getBy',
value: function getBy(type, key, value) {
return this.all(type).filter(function (model) {
return model[key]() === value;
})[0];
}
}, {
key: 'all',
value: function all(type) {
var records = this.data[type];
return records ? Object.keys(records).map(function (id) {
return records[id];
}) : [];
}
}, {
key: 'remove',
value: function remove(model) {
delete this.data[model.data.type][model.id()];
}
}, {
key: 'createRecord',
value: function createRecord(type) {
var data = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
data.type = data.type || type;
return new this.models[type](data, this);
}
}]);
return Store;
}();
_export('default', Store);
}
};
});;
'use strict';
System.register('flarum/Translator', ['flarum/models/User', 'flarum/helpers/username', 'flarum/utils/extractText', 'flarum/utils/extract'], function (_export, _context) {
"use strict";
var User, username, extractText, extract, Translator;
return {
setters: [function (_flarumModelsUser) {
User = _flarumModelsUser.default;
}, function (_flarumHelpersUsername) {
username = _flarumHelpersUsername.default;
}, function (_flarumUtilsExtractText) {
extractText = _flarumUtilsExtractText.default;
}, function (_flarumUtilsExtract) {
extract = _flarumUtilsExtract.default;
}],
execute: function () {
Translator = function () {
function Translator() {
babelHelpers.classCallCheck(this, Translator);
/**
* A map of translation keys to their translated values.
*
* @type {Object}
* @public
*/
this.translations = {};
this.locale = null;
}
babelHelpers.createClass(Translator, [{
key: 'trans',
value: function trans(id, parameters) {
var translation = this.translations[id];
if (translation) {
return this.apply(translation, parameters || {});
}
return id;
}
}, {
key: 'transChoice',
value: function transChoice(id, number, parameters) {
var translation = this.translations[id];
if (translation) {
number = parseInt(number, 10);
translation = this.pluralize(translation, number);
return this.apply(translation, parameters || {});
}
return id;
}
}, {
key: 'apply',
value: function apply(translation, input) {
// If we've been given a user model as one of the input parameters, then
// we'll extract the username and use that for the translation. In the
// future there should be a hook here to inspect the user and change the
// translation key. This will allow a gender property to determine which
// translation key is used.
if ('user' in input) {
var user = extract(input, 'user');
if (!input.username) input.username = username(user);
}
translation = translation.split(new RegExp('({[a-z0-9_]+}|</?[a-z0-9_]+>)', 'gi'));
var hydrated = [];
var open = [hydrated];
translation.forEach(function (part) {
var match = part.match(new RegExp('{([a-z0-9_]+)}|<(/?)([a-z0-9_]+)>', 'i'));
if (match) {
if (match[1]) {
open[0].push(input[match[1]]);
} else if (match[3]) {
if (match[2]) {
open.shift();
} else {
var tag = input[match[3]] || [];
open[0].push(tag);
open.unshift(tag.children || tag);
}
}
} else {
open[0].push(part);
}
});
return hydrated.filter(function (part) {
return part;
});
}
}, {
key: 'pluralize',
value: function pluralize(translation, number) {
var _this = this;
var sPluralRegex = new RegExp(/^\w+\: +(.+)$/),
cPluralRegex = new RegExp(/^\s*((\{\s*(\-?\d+[\s*,\s*\-?\d+]*)\s*\})|([\[\]])\s*(-Inf|\-?\d+)\s*,\s*(\+?Inf|\-?\d+)\s*([\[\]]))\s?(.+?)$/),
iPluralRegex = new RegExp(/^\s*(\{\s*(\-?\d+[\s*,\s*\-?\d+]*)\s*\})|([\[\]])\s*(-Inf|\-?\d+)\s*,\s*(\+?Inf|\-?\d+)\s*([\[\]])/),
standardRules = [],
explicitRules = [];
translation.split('|').forEach(function (part) {
if (cPluralRegex.test(part)) {
var matches = part.match(cPluralRegex);
explicitRules[matches[0]] = matches[matches.length - 1];
} else if (sPluralRegex.test(part)) {
var _matches = part.match(sPluralRegex);
standardRules.push(_matches[1]);
} else {
standardRules.push(part);
}
});
explicitRules.forEach(function (rule, e) {
if (iPluralRegex.test(e)) {
var matches = e.match(iPluralRegex);
if (matches[1]) {
var ns = matches[2].split(',');
for (var n in ns) {
if (number == ns[n]) {
return explicitRules[e];
}
}
} else {
var leftNumber = _this.convertNumber(matches[4]);
var rightNumber = _this.convertNumber(matches[5]);
if (('[' === matches[3] ? number >= leftNumber : number > leftNumber) && (']' === matches[6] ? number <= rightNumber : number < rightNumber)) {
return explicitRules[e];
}
}
}
});
return standardRules[this.pluralPosition(number, this.locale)] || standardRules[0] || undefined;
}
}, {
key: 'convertNumber',
value: function convertNumber(number) {
if ('-Inf' === number) {
return Number.NEGATIVE_INFINITY;
} else if ('+Inf' === number || 'Inf' === number) {
return Number.POSITIVE_INFINITY;
}
return parseInt(number, 10);
}
}, {
key: 'pluralPosition',
value: function pluralPosition(number, locale) {
if ('pt_BR' === locale) {
locale = 'xbr';
}
if (locale.length > 3) {
locale = locale.split('_')[0];
}
switch (locale) {
case 'bo':
case 'dz':
case 'id':
case 'ja':
case 'jv':
case 'ka':
case 'km':
case 'kn':
case 'ko':
case 'ms':
case 'th':
case 'tr':
case 'vi':
case 'zh':
return 0;
case 'af':
case 'az':
case 'bn':
case 'bg':
case 'ca':
case 'da':
case 'de':
case 'el':
case 'en':
case 'eo':
case 'es':
case 'et':
case 'eu':
case 'fa':
case 'fi':
case 'fo':
case 'fur':
case 'fy':
case 'gl':
case 'gu':
case 'ha':
case 'he':
case 'hu':
case 'is':
case 'it':
case 'ku':
case 'lb':
case 'ml':
case 'mn':
case 'mr':
case 'nah':
case 'nb':
case 'ne':
case 'nl':
case 'nn':
case 'no':
case 'om':
case 'or':
case 'pa':
case 'pap':
case 'ps':
case 'pt':
case 'so':
case 'sq':
case 'sv':
case 'sw':
case 'ta':
case 'te':
case 'tk':
case 'ur':
case 'zu':
return number == 1 ? 0 : 1;
case 'am':
case 'bh':
case 'fil':
case 'fr':
case 'gun':
case 'hi':
case 'ln':
case 'mg':
case 'nso':
case 'xbr':
case 'ti':
case 'wa':
return number === 0 || number == 1 ? 0 : 1;
case 'be':
case 'bs':
case 'hr':
case 'ru':
case 'sr':
case 'uk':
return number % 10 == 1 && number % 100 != 11 ? 0 : number % 10 >= 2 && number % 10 <= 4 && (number % 100 < 10 || number % 100 >= 20) ? 1 : 2;
case 'cs':
case 'sk':
return number == 1 ? 0 : number >= 2 && number <= 4 ? 1 : 2;
case 'ga':
return number == 1 ? 0 : number == 2 ? 1 : 2;
case 'lt':
return number % 10 == 1 && number % 100 != 11 ? 0 : number % 10 >= 2 && (number % 100 < 10 || number % 100 >= 20) ? 1 : 2;
case 'sl':
return number % 100 == 1 ? 0 : number % 100 == 2 ? 1 : number % 100 == 3 || number % 100 == 4 ? 2 : 3;
case 'mk':
return number % 10 == 1 ? 0 : 1;
case 'mt':
return number == 1 ? 0 : number === 0 || number % 100 > 1 && number % 100 < 11 ? 1 : number % 100 > 10 && number % 100 < 20 ? 2 : 3;
case 'lv':
return number === 0 ? 0 : number % 10 == 1 && number % 100 != 11 ? 1 : 2;
case 'pl':
return number == 1 ? 0 : number % 10 >= 2 && number % 10 <= 4 && (number % 100 < 12 || number % 100 > 14) ? 1 : 2;
case 'cy':
return number == 1 ? 0 : number == 2 ? 1 : number == 8 || number == 11 ? 2 : 3;
case 'ro':
return number == 1 ? 0 : number === 0 || number % 100 > 0 && number % 100 < 20 ? 1 : 2;
case 'ar':
return number === 0 ? 0 : number == 1 ? 1 : number == 2 ? 2 : number >= 3 && number <= 10 ? 3 : number >= 11 && number <= 99 ? 4 : 5;
default:
return 0;
}
}
}]);
return Translator;
}();
_export('default', Translator);
}
};
});;
'use strict';
System.register('flarum/utils/abbreviateNumber', [], function (_export, _context) {
"use strict";
function abbreviateNumber(number) {
// TODO: translation
if (number >= 1000000) {
return Math.floor(number / 1000000) + app.translator.trans('core.lib.number_suffix.mega_text');
} else if (number >= 1000) {
return Math.floor(number / 1000) + app.translator.trans('core.lib.number_suffix.kilo_text');
} else {
return number.toString();
}
}
_export('default', abbreviateNumber);
return {
setters: [],
execute: function () {}
};
});;
"use strict";
System.register("flarum/utils/anchorScroll", [], function (_export, _context) {
"use strict";
function anchorScroll(element, callback) {
var $window = $(window);
var relativeScroll = $(element).offset().top - $window.scrollTop();
callback();
$window.scrollTop($(element).offset().top - relativeScroll);
}
_export("default", anchorScroll);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/utils/classList', [], function (_export, _context) {
"use strict";
function classList(classes) {
var classNames = void 0;
if (classes instanceof Array) {
classNames = classes.filter(function (name) {
return name;
});
} else {
classNames = [];
for (var i in classes) {
if (classes[i]) classNames.push(i);
}
}
return classNames.join(' ');
}
_export('default', classList);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/utils/computed', [], function (_export, _context) {
"use strict";
function computed() {
for (var _len = arguments.length, dependentKeys = Array(_len), _key = 0; _key < _len; _key++) {
dependentKeys[_key] = arguments[_key];
}
var keys = dependentKeys.slice(0, -1);
var compute = dependentKeys.slice(-1)[0];
var dependentValues = {};
var computedValue = void 0;
return function () {
var _this = this;
var recompute = false;
// Read all of the dependent values. If any of them have changed since last
// time, then we'll want to recompute our output.
keys.forEach(function (key) {
var value = typeof _this[key] === 'function' ? _this[key]() : _this[key];
if (dependentValues[key] !== value) {
recompute = true;
dependentValues[key] = value;
}
});
if (recompute) {
computedValue = compute.apply(this, keys.map(function (key) {
return dependentValues[key];
}));
}
return computedValue;
};
}
_export('default', computed);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/utils/Drawer', [], function (_export, _context) {
"use strict";
var Drawer;
return {
setters: [],
execute: function () {
Drawer = function () {
function Drawer() {
var _this = this;
babelHelpers.classCallCheck(this, Drawer);
// Set up an event handler so that whenever the content area is tapped,
// the drawer will close.
$('#content').click(function (e) {
if (_this.isOpen()) {
e.preventDefault();
_this.hide();
}
});
}
/**
* Check whether or not the drawer is currently open.
*
* @return {Boolean}
* @public
*/
babelHelpers.createClass(Drawer, [{
key: 'isOpen',
value: function isOpen() {
return $('#app').hasClass('drawerOpen');
}
}, {
key: 'hide',
value: function hide() {
$('#app').removeClass('drawerOpen');
if (this.$backdrop) this.$backdrop.remove();
}
}, {
key: 'show',
value: function show() {
var _this2 = this;
$('#app').addClass('drawerOpen');
this.$backdrop = $('<div/>').addClass('drawer-backdrop fade').appendTo('body').click(function () {
return _this2.hide();
});
setTimeout(function () {
return _this2.$backdrop.addClass('in');
});
}
}]);
return Drawer;
}();
_export('default', Drawer);
}
};
});;
"use strict";
System.register("flarum/utils/evented", [], function (_export, _context) {
"use strict";
return {
setters: [],
execute: function () {
_export("default", {
/**
* Arrays of registered event handlers, grouped by the event name.
*
* @type {Object}
* @protected
*/
handlers: null,
getHandlers: function getHandlers(event) {
this.handlers = this.handlers || {};
this.handlers[event] = this.handlers[event] || [];
return this.handlers[event];
},
trigger: function trigger(event) {
var _this = this;
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
this.getHandlers(event).forEach(function (handler) {
return handler.apply(_this, args);
});
},
on: function on(event, handler) {
this.getHandlers(event).push(handler);
},
one: function one(event, handler) {
var wrapper = function wrapper() {
handler.apply(this, arguments);
this.off(event, wrapper);
};
this.getHandlers(event).push(wrapper);
},
off: function off(event, handler) {
var handlers = this.getHandlers(event);
var index = handlers.indexOf(handler);
if (index !== -1) {
handlers.splice(index, 1);
}
}
});
}
};
});;
"use strict";
System.register("flarum/utils/extract", [], function (_export, _context) {
"use strict";
function extract(object, property) {
var value = object[property];
delete object[property];
return value;
}
_export("default", extract);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/utils/extractText', [], function (_export, _context) {
"use strict";
function extractText(vdom) {
var text = '';
if (vdom instanceof Array) {
text += vdom.map(function (element) {
return extractText(element);
}).join('');
} else if ((typeof vdom === 'undefined' ? 'undefined' : babelHelpers.typeof(vdom)) === 'object') {
text += extractText(vdom.children);
} else {
text += vdom;
}
return text;
}
_export('default', extractText);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/utils/formatNumber', [], function (_export, _context) {
"use strict";
function formatNumber(number) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
_export('default', formatNumber);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/utils/humanTime', [], function (_export, _context) {
"use strict";
function humanTime(time) {
var m = moment(time);
var day = 864e5;
var diff = m.diff(moment());
var ago = null;
// If this date was more than a month ago, we'll show the name of the month
// in the string. If it wasn't this year, we'll show the year as well.
if (diff < -30 * day) {
if (m.year() === moment().year()) {
ago = m.format('MMM DD' + "日");
} else {
ago = m.format('MMM \'YY');
}
} else {
ago = m.fromNow();
}
return ago;
}
_export('default', humanTime);
return {
setters: [],
execute: function () {
; /**
* The `humanTime` utility converts a date to a localized, human-readable time-
* ago string.
*
* @param {Date} time
* @return {String}
*/
}
};
});;
"use strict";
System.register("flarum/utils/ItemList", [], function (_export, _context) {
"use strict";
var Item, ItemList;
return {
setters: [],
execute: function () {
Item = function Item(content, priority) {
babelHelpers.classCallCheck(this, Item);
this.content = content;
this.priority = priority;
};
ItemList = function () {
function ItemList() {
babelHelpers.classCallCheck(this, ItemList);
/**
* The items in the list.
*
* @type {Object}
* @public
*/
this.items = {};
}
/**
* Check whether an item is present in the list.
*
* @param key
* @returns {boolean}
*/
babelHelpers.createClass(ItemList, [{
key: "has",
value: function has(key) {
return !!this.items[key];
}
}, {
key: "get",
value: function get(key) {
return this.items[key].content;
}
}, {
key: "add",
value: function add(key, content) {
var priority = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2];
this.items[key] = new Item(content, priority);
}
}, {
key: "replace",
value: function replace(key) {
var content = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var priority = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
if (this.items[key]) {
if (content !== null) {
this.items[key].content = content;
}
if (priority !== null) {
this.items[key].priority = priority;
}
}
}
}, {
key: "remove",
value: function remove(key) {
delete this.items[key];
}
}, {
key: "merge",
value: function merge(items) {
for (var i in items.items) {
if (items.items.hasOwnProperty(i) && items.items[i] instanceof Item) {
this.items[i] = items.items[i];
}
}
}
}, {
key: "toArray",
value: function toArray() {
var items = [];
for (var i in this.items) {
if (this.items.hasOwnProperty(i) && this.items[i] instanceof Item) {
this.items[i].content = Object(this.items[i].content);
this.items[i].content.itemName = i;
items.push(this.items[i]);
this.items[i].key = items.length;
}
}
return items.sort(function (a, b) {
if (a.priority === b.priority) {
return a.key - b.key;
} else if (a.priority > b.priority) {
return -1;
}
return 1;
}).map(function (item) {
return item.content;
});
}
}]);
return ItemList;
}();
_export("default", ItemList);
}
};
});;
'use strict';
System.register('flarum/utils/mapRoutes', [], function (_export, _context) {
"use strict";
function mapRoutes(routes) {
var basePath = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
var map = {};
for (var key in routes) {
var route = routes[key];
if (route.component) route.component.props.routeName = key;
map[basePath + route.path] = route.component;
}
return map;
}
_export('default', mapRoutes);
return {
setters: [],
execute: function () {}
};
});;
"use strict";
System.register("flarum/utils/mixin", [], function (_export, _context) {
"use strict";
function mixin(Parent) {
var Mixed = function (_Parent) {
babelHelpers.inherits(Mixed, _Parent);
function Mixed() {
babelHelpers.classCallCheck(this, Mixed);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Mixed).apply(this, arguments));
}
return Mixed;
}(Parent);
for (var _len = arguments.length, mixins = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
mixins[_key - 1] = arguments[_key];
}
mixins.forEach(function (object) {
babelHelpers.extends(Mixed.prototype, object);
});
return Mixed;
}
_export("default", mixin);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/utils/patchMithril', ['../Component'], function (_export, _context) {
"use strict";
var Component;
function patchMithril(global) {
var mo = global.m;
var m = function m(comp) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (comp.prototype && comp.prototype instanceof Component) {
return comp.component.apply(comp, args);
}
var node = mo.apply(this, arguments);
if (node.attrs.bidi) {
m.bidi(node, node.attrs.bidi);
}
if (node.attrs.route) {
node.attrs.href = node.attrs.route;
node.attrs.config = m.route;
delete node.attrs.route;
}
return node;
};
Object.keys(mo).forEach(function (key) {
return m[key] = mo[key];
});
/**
* Redraw only if not in the middle of a computation (e.g. a route change).
*
* @return {void}
*/
m.lazyRedraw = function () {
m.startComputation();
m.endComputation();
};
global.m = m;
}
_export('default', patchMithril);
return {
setters: [function (_Component) {
Component = _Component.default;
}],
execute: function () {}
};
});;
"use strict";
System.register("flarum/utils/RequestError", [], function (_export, _context) {
"use strict";
var RequestError;
return {
setters: [],
execute: function () {
RequestError = function RequestError(status, responseText, options, xhr) {
babelHelpers.classCallCheck(this, RequestError);
this.status = status;
this.responseText = responseText;
this.options = options;
this.xhr = xhr;
try {
this.response = JSON.parse(responseText);
} catch (e) {
this.response = null;
}
this.alert = null;
};
_export("default", RequestError);
}
};
});;
'use strict';
System.register('flarum/utils/saveSettings', [], function (_export, _context) {
"use strict";
function saveSettings(settings) {
var oldSettings = JSON.parse(JSON.stringify(app.settings));
babelHelpers.extends(app.settings, settings);
return app.request({
method: 'POST',
url: app.forum.attribute('apiUrl') + '/settings',
data: settings
}).catch(function (error) {
app.settings = oldSettings;
throw error;
});
}
_export('default', saveSettings);
return {
setters: [],
execute: function () {}
};
});;
"use strict";
System.register("flarum/utils/ScrollListener", [], function (_export, _context) {
"use strict";
var scroll, ScrollListener;
return {
setters: [],
execute: function () {
scroll = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
return window.setTimeout(callback, 1000 / 60);
};
ScrollListener = function () {
/**
* @param {Function} callback The callback to run when the scroll position
* changes.
* @public
*/
function ScrollListener(callback) {
babelHelpers.classCallCheck(this, ScrollListener);
this.callback = callback;
this.lastTop = -1;
}
/**
* On each animation frame, as long as the listener is active, run the
* `update` method.
*
* @protected
*/
babelHelpers.createClass(ScrollListener, [{
key: "loop",
value: function loop() {
if (!this.active) return;
this.update();
scroll(this.loop.bind(this));
}
}, {
key: "update",
value: function update(force) {
var top = window.pageYOffset;
if (this.lastTop !== top || force) {
this.callback(top);
this.lastTop = top;
}
}
}, {
key: "start",
value: function start() {
if (!this.active) {
this.active = true;
this.loop();
}
}
}, {
key: "stop",
value: function stop() {
this.active = false;
}
}]);
return ScrollListener;
}();
_export("default", ScrollListener);
}
};
});;
'use strict';
System.register('flarum/utils/string', [], function (_export, _context) {
"use strict";
return {
setters: [],
execute: function () {
/**
* Truncate a string to the given length, appending ellipses if necessary.
*
* @param {String} string
* @param {Number} length
* @param {Number} [start=0]
* @return {String}
*/
function truncate(string, length) {
var start = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2];
return (start > 0 ? '...' : '') + string.substring(start, start + length) + (string.length > start + length ? '...' : '');
}
/**
* Create a slug out of the given string. Non-alphanumeric characters are
* converted to hyphens.
*
* @param {String} string
* @return {String}
*/
_export('truncate', truncate);
function slug(string) {
return string.toLowerCase().replace(/[^a-z0-9]/gi, '-').replace(/-+/g, '-').replace(/-$|^-/g, '') || '-';
}
/**
* Strip HTML tags and quotes out of the given string, replacing them with
* meaningful punctuation.
*
* @param {String} string
* @return {String}
*/
_export('slug', slug);
function getPlainContent(string) {
var dom = $('<div/>').html(string.replace(/(<\/p>|<br>)/g, '$1 '));
dom.find(getPlainContent.removeSelectors.join(',')).remove();
return dom.text();
}
/**
* An array of DOM selectors to remove when getting plain content.
*
* @type {Array}
*/
_export('getPlainContent', getPlainContent);
getPlainContent.removeSelectors = ['blockquote', 'script'];
/**
* Make a string's first character uppercase.
*
* @param {String} string
* @return {String}
*/
function ucfirst(string) {
return string.substr(0, 1).toUpperCase() + string.substr(1);
}
_export('ucfirst', ucfirst);
}
};
});;
'use strict';
System.register('flarum/utils/stringToColor', [], function (_export, _context) {
"use strict";
function hsvToRgb(h, s, v) {
var r = void 0;
var g = void 0;
var b = void 0;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;g = t;b = p;break;
case 1:
r = q;g = v;b = p;break;
case 2:
r = p;g = v;b = t;break;
case 3:
r = p;g = q;b = v;break;
case 4:
r = t;g = p;b = v;break;
case 5:
r = v;g = p;b = q;break;
}
return {
r: Math.floor(r * 255),
g: Math.floor(g * 255),
b: Math.floor(b * 255)
};
}
/**
* Convert the given string to a unique color.
*
* @param {String} string
* @return {String}
*/
function stringToColor(string) {
var num = 0;
// Convert the username into a number based on the ASCII value of each
// character.
for (var i = 0; i < string.length; i++) {
num += string.charCodeAt(i);
}
// Construct a color using the remainder of that number divided by 360, and
// some predefined saturation and value values.
var hue = num % 360;
var rgb = hsvToRgb(hue / 360, 0.3, 0.9);
return '' + rgb.r.toString(16) + rgb.g.toString(16) + rgb.b.toString(16);
}
_export('default', stringToColor);
return {
setters: [],
execute: function () {}
};
});;
'use strict';
System.register('flarum/utils/SubtreeRetainer', [], function (_export, _context) {
"use strict";
var SubtreeRetainer;
return {
setters: [],
execute: function () {
SubtreeRetainer = function () {
/**
* @param {...callbacks} callbacks Functions returning data to keep track of.
*/
function SubtreeRetainer() {
babelHelpers.classCallCheck(this, SubtreeRetainer);
for (var _len = arguments.length, callbacks = Array(_len), _key = 0; _key < _len; _key++) {
callbacks[_key] = arguments[_key];
}
this.callbacks = callbacks;
this.data = {};
}
/**
* Return a virtual DOM directive that will retain a subtree if no data has
* changed since the last check.
*
* @return {Object|false}
* @public
*/
babelHelpers.createClass(SubtreeRetainer, [{
key: 'retain',
value: function retain() {
var _this = this;
var needsRebuild = false;
this.callbacks.forEach(function (callback, i) {
var result = callback();
if (result !== _this.data[i]) {
_this.data[i] = result;
needsRebuild = true;
}
});
return needsRebuild ? false : { subtree: 'retain' };
}
}, {
key: 'check',
value: function check() {
for (var _len2 = arguments.length, callbacks = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
callbacks[_key2] = arguments[_key2];
}
this.callbacks = this.callbacks.concat(callbacks);
}
}, {
key: 'invalidate',
value: function invalidate() {
this.data = {};
}
}]);
return SubtreeRetainer;
}();
_export('default', SubtreeRetainer);
}
};
});
|
pingpp/community
|
vendor/flarum/core/js/admin/dist/app.js
|
JavaScript
|
mit
| 682,200
|
import { assert, tostring, wipe, LuaArray } from "@wowts/lua";
import { insert, remove } from "@wowts/table";
import { format } from "@wowts/string";
export class OvalePool<T> {
pool:LuaArray<T> = {};
size = 0;
unused = 0;
name: string;
constructor(name: string) {
this.name = name || "OvalePool";
}
Get() {
// OvalePool.StartProfiling(this.name);
assert(this.pool);
let item = remove(this.pool);
if (item) {
this.unused = this.unused - 1;
} else {
this.size = this.size + 1;
item = <T>{}
}
// OvalePool.StopProfiling(this.name);
return item;
}
Release(item:T):void {
// OvalePool.StartProfiling(this.name);
assert(this.pool);
this.Clean(item);
wipe(item);
insert(this.pool, item);
this.unused = this.unused + 1;
// OvalePool.StopProfiling(this.name);
}
Drain():void {
//OvalePool.StartProfiling(this.name);
this.pool = {}
this.size = this.size - this.unused;
this.unused = 0;
//OvalePool.StopProfiling(this.name);
}
DebuggingInfo():string {
return format("Pool %s has size %d with %d item(s).", tostring(this.name), this.size, this.unused);
}
Clean(item: T): void {
}
}
|
Xeltor/ovale
|
src/Pool.ts
|
TypeScript
|
mit
| 1,354
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>pi-agm: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.2 / pi-agm - 1.2.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
pi-agm
<small>
1.2.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2021-11-05 09:57:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-05 09:57:39 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 3 Virtual package relying on a GMP lib system installation
coq 8.13.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.12.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.12.0 Official release 4.12.0
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.1 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
name: "coq-pi-agm"
version: "1.2.0"
maintainer: "yves.bertot@inria.fr"
homepage: "http://www-sop.inria.fr/members/Yves.Bertot/"
bug-reports: "yves.bertot@inria.fr"
license: "CeCILL-B"
build: [["coq_makefile" "-f" "_CoqProject" "-o" "Makefile" ]
[ make "-j" "%{jobs}%" ]]
install: [ make "install" "DEST='%{lib}%/coq/user-contrib/pi_agm'" ]
remove: [ "sh" "-c" "rm -rf '%{lib}%/coq/user-contrib/pi_agm'" ]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
"coq-coquelicot" {>= "3" & < "4~"}
"coq-interval" {>= "3"}
]
tags: [ "keyword:real analysis" "keyword:pi" "category:Mathematics/Real Calculus and Topology" ]
authors: [ "Yves Bertot <yves.bertot@inria.fr>" ]
synopsis:
"Computing thousands or millions of digits of PI with arithmetic-geometric means"
description: """
This is a proof of correctness for two algorithms to compute PI to high
precision using arithmetic-geometric means. A first file contains
the calculus-based proofs for an abstract view of the algorithm, where all
numbers are real numbers. A second file describes how to approximate all
computations using large integers. Other files describe the second algorithm
which is close to the one used in mpfr, for instance.
The whole development can be used to produce mathematically proved and
formally verified approximations of PI."""
url {
src: "https://github.com/ybertot/pi-agm/archive/v1.1.9.tar.gz"
checksum: "md5=59bb22e2081c7f5dd200a4b35726acfe"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-pi-agm.1.2.0 coq.8.13.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.2).
The following dependencies couldn't be met:
- coq-pi-agm -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-pi-agm.1.2.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.12.0-2.0.8/released/8.13.2/pi-agm/1.2.0.html
|
HTML
|
mit
| 7,734
|
import {Target} from '@openmicrostep/msbuildsystem.core';
import {CXXTarget, CXXLinkType} from '../index.priv';
export class CXXExecutable extends CXXTarget {
linkType = CXXLinkType.EXECUTABLE;
}
Target.register(["cxx-executable"], CXXExecutable, {});
|
OpenMicroStep/MSBuildSystem
|
cxx/src/target/executable.ts
|
TypeScript
|
mit
| 255
|
---
layout: post
title: Installing PyLucene 3.x in GNU\Linux
author: jagan
tags: [Python, PyLucene]
comments: true
---
Lucene
=======
"Lucene is a high performance, scalable Information Retrieval (IR) library. It lets you add indexing and searching capabilities to your applications. Lucene is a
mature, free, open-source project implemented in Java; it’s a member of the popular Apache Jakarta family of projects, licensed under the liberal Apache Software License."
PyLucene
========
" PyLucene is a Python extension for accessing Java Lucene. Its goal is to allow you to use Lucene's text indexing and searching capabilities from Python. It is API compatible with the latest version of Java Lucene, version 2.9.0 as of October 13th, 2009."
I downloaded PyLucene 3.X version and tried to install. Initially I got some error. I was trying to follow the instructions given at http://lucene.apache.org/pylucene/documentation/install.html. There was a confusing statement to me "<edit setup.py to match your environment>" :-(. Where to match ?? I scrated my hed for 2 days. Finally I identified the place to edit. Insted of discussinf error I will try to explain how to install PyLucene in GNU\Linux.
Download PyLucene 3.0.0-1 source from [http://www.apache.org/dyn/closer.cgi/lucene/pylucene/](http://www.apache.org/dyn/closer.cgi/lucene/pylucene/) .
Extract the source. Now you will be having 'pylucene-3.0.0-1' directory. Change to the directory. Then execute the command "pushd jcc". Now you will be in the jcc directory inside the PyLucene dir. Open the 'setup.py' file. You have to make some changes in the file to install it properly. In setup.py there will be portion like this
```bash
JDK = {
'darwin': '/System/Library/Frameworks/JavaVM.framework/Versions/Current',
'ipod': '/usr/include/gcc',
'linux2': '/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0',
'sunos5': '/usr/jdk/instances/jdk1.6.0',
'win32': 'o:/Java/jdk1.6.0_02',
}
```
If you are using GNU\Linux you have to change the line "'linux2': '/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0'," . Here you have to specify the path to your Java installation. Here in the example '/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0' is the Java installation path in my system. If you are using M$ windows you have to edit the line "'win32': 'o:/Java/jdk1.6.0_02',".
Now it is time to build and install JCC .
Be superuser and execute the command "python setup.py install".
If everything is ok JCC will be installed.
Then execute the command 'popd'. Now you are in the PyLucene source dir again.
In this directory you gave to some editing . Open the 'Makefile'. There will be a portain like this in the file.
```bash
#Linux (Ubuntu 8.10 64-bit, Python 2.5.2, OpenJDK 1.6, setuptools 0.6c9)
#PREFIX_PYTHON=/usr
#ANT=ant
#PYTHON=$(PREFIX_PYTHON)/bin/python
#JCC=$(PYTHON) -m jcc --shared
#NUM_FILES=2
```
Uncomment the five lines followed by "#Linux (Ubuntu 8.10 64-bit, Python 2.5.2, OpenJDK 1.6, setuptools 0.6c9)".
Now the portain should look like
```bash
#Linux (Ubuntu 8.10 64-bit, Python 2.5.2, OpenJDK 1.6, setuptools 0.6c9)
PREFIX_PYTHON=/usr
ANT=ant
PYTHON=$(PREFIX_PYTHON)/bin/python
JCC=$(PYTHON) -m jcc --shared
NUM_FILES=2
```
If you are using Python 2.6 some more editing to be done. Change the line "JCC=$(PYTHON) -m jcc --shared" to "JCC=$(PYTHON) -m jcc.__main__ --shared".
Run make and make install command. If every setting is PyLucene will be installed in your system. To check your installation rum 'make test' command.
Now enjoy !!!
Happy Hacking!!!!!!!!!!!
Migrated from my [old blog jaganadhg.freeflux.net](https://web.archive.org/web/20160323193721/http://jaganadhg.freeflux.net/blog)
|
jaganadhg/jaganadhg.github.io
|
_posts/2009-12-30-pylucene.md
|
Markdown
|
mit
| 3,803
|
SCHEDULE_NONE = None
SCHEDULE_HOURLY = '0 * * * *'
SCHEDULE_DAILY = '0 0 * * *'
SCHEDULE_WEEKLY = '0 0 * * 0'
SCHEDULE_MONTHLY = '0 0 1 * *'
SCHEDULE_YEARLY = '0 0 1 1 *'
|
frictionlessdata/datapackage-pipelines
|
datapackage_pipelines/generators/schedules.py
|
Python
|
mit
| 171
|
package com.ozodrukh.eclass.entity;
import android.os.Parcel;
import android.os.Parcelable;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Subject implements Parcelable{
private String auth;
private String grcode;
private String subject;
private String year;;
private String sequence;
private String classNumber;
private String name;
public Subject(String auth, String grcode, String subject, String year, String sequence,
String classNumber, String name) {
this.auth = auth;
this.grcode = grcode;
this.subject = subject;
this.year = year;
this.sequence = sequence;
this.classNumber = classNumber;
this.name = name;
}
public Subject() {
}
protected Subject(Parcel in) {
auth = in.readString();
grcode = in.readString();
subject = in.readString();
year = in.readString();
sequence = in.readString();
classNumber = in.readString();
name = in.readString();
}
public static final Creator<Subject> CREATOR = new Creator<Subject>() {
@Override public Subject createFromParcel(Parcel in) {
return new Subject(in);
}
@Override public Subject[] newArray(int size) {
return new Subject[size];
}
};
public String getAuth() {
return auth;
}
public void setAuth(String auth) {
this.auth = auth;
}
public String getGrcode() {
return grcode;
}
public void setGrcode(String grcode) {
this.grcode = grcode;
}
public String getSubject() {
return subject;
}
@JsonProperty("subj")
public void setSubject(String subject) {
this.subject = subject;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getSequence() {
return sequence;
}
@JsonProperty("subjseq")
public void setSequence(String sequence) {
this.sequence = sequence;
}
@JsonProperty("subjclass")
public String getClassNumber() {
return classNumber;
}
public void setClassNumber(String classNumber) {
this.classNumber = classNumber;
}
@JsonProperty("subjnm")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Subject{" +
"auth='" + auth + '\'' +
", grcode='" + grcode + '\'' +
", subject='" + subject + '\'' +
", year='" + year + '\'' +
", sequence=" + sequence +
", classNumber='" + classNumber + '\'' +
", name='" + name + '\'' +
'}';
}
@Override public int describeContents() {
return 0;
}
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeString(auth);
dest.writeString(grcode);
dest.writeString(subject);
dest.writeString(year);
dest.writeString(sequence);
dest.writeString(classNumber);
dest.writeString(name);
}
}
|
ozodrukh/IUT-E-class
|
mylibrary/src/main/java/com/ozodrukh/eclass/entity/Subject.java
|
Java
|
mit
| 2,918
|
---
title: Form validation
---
# Design
Form validation components were designed with following goals in mind:
* To be compatible with any UI library and CSS framework.
* To not force users to follow certain guidelines, let them follow their guidelines instead.
* To be type safe, like the rest of the framework.
* To be flexible.
Validation components are components for the template engine,
therefore they can only be used from HTML templates.
# Usage
To start using validation components, you should first include the corresponding component package in the template.
Additionally, importing the `Converter` interface may be useful:
```html
<?import org.teavm.flavour.validation.Converter?>
<?use v:org.teavm.flavour.validation?>
```
The first component, called `validator`, is used to define validation logic.
It has the following syntax:
```html
<v:validator as="validatorName">
<v:validation of="dataField1" as="fieldName1" convert="converter1">
<v:check rule="validationExpression" as="ruleName"/>
<!-- etc -->
</v:validation>
<v:validation of="dataField2" as="fieldName2" convert="converter2">
<v:check rule="validationExpression" as="ruleName"/>
<!-- etc -->
</v:validation>
<!-- more v:validation entries -->
<!-- body -->
</v:validator>
```
Where:
* `as="validationName""` name of the variable that provides [validator state object](#validator-state).
* `of="dataFieldN"` path to a *mutable* field or property of a view object that stores actual data.
* `as="fieldNameN"` name of the variable that provides [field state object](#field-state)
* `convert="converterN"` expression that yields a `Converter` instance that should be used
to convert data to and from string.
* `rule="validationExpression"` expression that yields a boolean value, `true` if validation passes.
* `as="ruleName"` name of the variable that provides a `boolean` value which indicates whether the rule passes.
The second component, `bind`, is used to bind validations to input fields:
```
v:bind="fieldName"
```
where `fieldName` points to field state object defined by the containing `v:validator`.
# Standard converters
Standard converters are available via static methods of the `Converter` interface:
* `Converter<String> stringFormat()` does not perform any conversion.
* `Converter<Integer> integerFormat()`
* `Converter<Double> doubleFormat(String formatString)`
where *formatString* is a string accepted by `DecimalFormat` class.
* `Converter<Date> dateFormat(String formatString)`
where *formatString* is a string accepted by `SimpleDateFormat` class.
* `Converter<Date> dateFormat()` uses the default locale-specific date format.
* `Converter<Date> mediumDateFormat()` uses the locale-specific medium date format.
* `Converter<Date> shortDateFormat()` uses the locale-specific medium date format.
* `Converter<Date> shortDateFormat()` uses the locale-specific medium date format.
* `Converter<Date> dateFormat(DateFormat dateFormat)` uses a custom date format.
# Validator state
Validator state is available via the `ValidatorState` class which has the following API:
* `boolean isValid()` indicates whether the form passed validation, i.e. all fields are valid.
* `void submit(Runnable action)` validates the form and performs the given action if form is valid.
# Field state
Field state is available via the `Validation` class which has the following API:
* `boolean isValidFormat()` indicates whether the converter could successfully recognize value in a text field.
* `boolean isValid()` indicates whether all validation rules pass.
# Example
```html
<?import org.teavm.flavour.validation.Converter?>
<?use v:org.teavm.flavour.validation?>
<v:validator as="validator">
<v:validation of="title" as="titleField" convert="Converter.stringFormat()">
<v:check rule="!it.empty" as="titleSpecified"/>
</v:validation>
<v:validation of="startDate" as="startDateField" convert="Converter.dateFormat('yyyy-MM-dd')">
<v:check rule="it != null" as="startDateSpecified"/>
<v:check rule="endDate == null or it.before(endDate)" as="startDateConsistent"/>
</v:validation>
<v:validation of="endDate" as="endDateField" convert="Converter.dateFormat('yyyy-MM-dd')">
<v:check rule="it != null" as="endDateSpecified"/>
<v:check rule="startDate == null or startDate.before(it)" as="endDateConsistent"/>
</v:validation>
<div>
<div><label>Title</label></div>
<div attr:class="titleField.valid ? '' : 'error'"><input type="text" v:bind="titleField"/></div>
<std:if condition="!titleSpecified"><div>Please, specify title</div></std:if>
</div>
<div>
<div><label>Start date</label></div>
<div attr:class="startDateField.valid ? '' : 'error'"><input type="text" v:bind="startDateField"/></div>
<std:if condition="!startDateSpecified"><div>Please, specify start date</div></std:if>
</div>
<div>
<div><label>End date</label></div>
<div attr:class="endDateField.valid ? '' : 'error'"><input type="text" v:bind="endDateField"/></div>
<std:if condition="!endDateSpecified"><div>Please, specify end date</div></std:if>
</div>
<std:if condition="!startDateConsistent"><div>Start date must be later than end date</div></std:if>
<button type="button" event:click="validator.submit(() -> save())" html:enabled="validator.valid">Submit</button>
</v:validator>
```
|
konsoletyper/teavm-site
|
_docs/flavour/form-validation.md
|
Markdown
|
mit
| 5,382
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
import urls
from apps.blog import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gigsblog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.Index.as_view(), name='index'),
url(r'^signup', views.SignUp.as_view(), name='signUp'),
url(r'^login', views.Login.as_view(), name='login'),
url(r'^logout', 'django.contrib.auth.views.logout',{'next_page':'/'}, name='logout'),
url(r'^post/', include('urls.blog', namespace='post')),
url(r'^admin/', include('urls.admin')),
)
|
gusaul/gigsblog
|
urls/main.py
|
Python
|
mit
| 683
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/static/img/ruby.ico" />
<title>笨方法学Ruby第二十二天 - LJZN</title>
<meta name="author" content="LJZN" />
<meta name="description" content="笨方法学Ruby第二十二天" />
<meta name="keywords" content="笨方法学Ruby第二十二天, LJZN, LRTHW" />
<link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/static/css/syntax.css">
<!-- Bootstrap core CSS -->
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link rel="stylesheet" href="/static/css/main.css">
</head>
<body>
<div class="container">
<div class="col-sm-3">
<a href="/"><img id="about" src="/static/img/ruby.png" height="75px" width="75px" /></a>
<h1 class="author-name">LJZN</h1>
<div id="about">
每天更新Rails练习项目到Github~
</div>
<hr size=2>
» <a href="/">Home</a> <br />
» <a href="/category/original">Category</a> <br />
» <a class="about" href="/about/">About Me</a><br />
» <a class="about" href="https://github.com/ljzn">Github</a><br />
</div>
<div class="col-sm-8 col-offset-1">
<h1>笨方法学Ruby第二十二天</h1>
<span class="time">28 Jun 2016</span>
<span class="categories">
» <a href="/category/LRTHW">LRTHW</a>
</span>
<div class="content">
<div class="post">
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">puts</span> <span class="s2">"复习之前所学的代码。"</span></code></pre></figure>
</div>
</div>
<div class="panel-body">
<h4>Related Posts</h4>
<ul>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/10/lrhw-50.html">50sinatra建造网站</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/09/lrhw-49.html">49创建句子</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/08/lrhw-48.html">48进阶用户输入</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/08/lrhw-47.html">47自动化测试</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/06/lrhw-46.html">46项目骨架</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/05/lrhw-45.html">45制作一个游戏</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
</ul>
</div>
<div class="PageNavigation">
<a class="prev" href="/lrthw/2016/06/28/lrhw-21.html">« 笨方法学Ruby第二十一天</a>
<a class="next" href="/lrthw/2016/06/28/lrhw-23.html">笨方法学Ruby第二十三天 »</a>
</div>
<div class="disqus-comments">
<div id="disqus_thread"></div>
<script>
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//ljzn.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
</div>
<footer>
© LJZN
- <a href="https://github.com/ljzn">https://github.com/ljzn</a> - Powered by Jekyll.
</footer>
</div><!-- end /.col-sm-8 -->
</div><!-- end /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="//cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script id="dsq-count-scr" src="//ljzn.disqus.com/count.js" async></script>
</body>
</html>
|
Ljzn/ljzn.github.io
|
_site/lrthw/2016/06/28/lrhw-22.html
|
HTML
|
mit
| 9,657
|
/*
Ratings and how they work:
-1: Detrimental
An ability that severely harms the user.
ex. Defeatist, Slow Start
0: Useless
An ability with no overall benefit in a singles battle.
ex. Color Change, Plus
1: Ineffective
An ability that has minimal effect or is only useful in niche situations.
ex. Light Metal, Suction Cups
2: Useful
An ability that can be generally useful.
ex. Flame Body, Overcoat
3: Effective
An ability with a strong effect on the user or foe.
ex. Chlorophyll, Sturdy
4: Very useful
One of the more popular abilities. It requires minimal support to be effective.
ex. Adaptability, Magic Bounce
5: Essential
The sort of ability that defines metagames.
ex. Imposter, Shadow Tag
*/
export const Abilities: {[abilityid: string]: AbilityData} = {
noability: {
isNonstandard: "Past",
name: "No Ability",
rating: 0.1,
num: 0,
},
adaptability: {
onModifyMove(move) {
move.stab = 2;
},
name: "Adaptability",
rating: 4,
num: 91,
},
aerilate: {
onModifyTypePriority: -1,
onModifyType(move, pokemon) {
const noModifyType = [
'judgment', 'multiattack', 'naturalgift', 'revelationdance', 'technoblast', 'terrainpulse', 'weatherball',
];
if (move.type === 'Normal' && !noModifyType.includes(move.id) && !(move.isZ && move.category !== 'Status')) {
move.type = 'Flying';
move.aerilateBoosted = true;
}
},
onBasePowerPriority: 23,
onBasePower(basePower, pokemon, target, move) {
if (move.aerilateBoosted) return this.chainModify([4915, 4096]);
},
name: "Aerilate",
rating: 4,
num: 184,
},
aftermath: {
name: "Aftermath",
onDamagingHitOrder: 1,
onDamagingHit(damage, target, source, move) {
if (!target.hp && this.checkMoveMakesContact(move, source, target, true)) {
this.damage(source.baseMaxhp / 4, source, target);
}
},
rating: 2.5,
num: 106,
},
airlock: {
onSwitchIn(pokemon) {
this.effectState.switchingIn = true;
},
onStart(pokemon) {
// Air Lock does not activate when Skill Swapped or when Neutralizing Gas leaves the field
if (!this.effectState.switchingIn) return;
this.add('-ability', pokemon, 'Air Lock');
this.effectState.switchingIn = false;
},
suppressWeather: true,
name: "Air Lock",
rating: 2,
num: 76,
},
analytic: {
onBasePowerPriority: 21,
onBasePower(basePower, pokemon) {
let boosted = true;
for (const target of this.getAllActive()) {
if (target === pokemon) continue;
if (this.queue.willMove(target)) {
boosted = false;
break;
}
}
if (boosted) {
this.debug('Analytic boost');
return this.chainModify([5325, 4096]);
}
},
name: "Analytic",
rating: 2.5,
num: 148,
},
angerpoint: {
onHit(target, source, move) {
if (!target.hp) return;
if (move?.effectType === 'Move' && target.getMoveHitData(move).crit) {
target.setBoost({atk: 6});
this.add('-setboost', target, 'atk', 12, '[from] ability: Anger Point');
}
},
name: "Anger Point",
rating: 1.5,
num: 83,
},
anticipation: {
onStart(pokemon) {
for (const target of pokemon.foes()) {
for (const moveSlot of target.moveSlots) {
const move = this.dex.moves.get(moveSlot.move);
if (move.category === 'Status') continue;
const moveType = move.id === 'hiddenpower' ? target.hpType : move.type;
if (
this.dex.getImmunity(moveType, pokemon) && this.dex.getEffectiveness(moveType, pokemon) > 0 ||
move.ohko
) {
this.add('-ability', pokemon, 'Anticipation');
return;
}
}
}
},
name: "Anticipation",
rating: 0.5,
num: 107,
},
arenatrap: {
onFoeTrapPokemon(pokemon) {
if (!pokemon.isAdjacent(this.effectState.target)) return;
if (pokemon.isGrounded()) {
pokemon.tryTrap(true);
}
},
onFoeMaybeTrapPokemon(pokemon, source) {
if (!source) source = this.effectState.target;
if (!source || !pokemon.isAdjacent(source)) return;
if (pokemon.isGrounded(!pokemon.knownType)) { // Negate immunity if the type is unknown
pokemon.maybeTrapped = true;
}
},
name: "Arena Trap",
rating: 5,
num: 71,
},
aromaveil: {
onAllyTryAddVolatile(status, target, source, effect) {
if (['attract', 'disable', 'encore', 'healblock', 'taunt', 'torment'].includes(status.id)) {
if (effect.effectType === 'Move') {
const effectHolder = this.effectState.target;
this.add('-block', target, 'ability: Aroma Veil', '[of] ' + effectHolder);
}
return null;
}
},
isBreakable: true,
name: "Aroma Veil",
rating: 2,
num: 165,
},
asoneglastrier: {
onPreStart(pokemon) {
this.add('-ability', pokemon, 'As One');
this.add('-ability', pokemon, 'Unnerve');
this.effectState.unnerved = true;
},
onEnd() {
this.effectState.unnerved = false;
},
onFoeTryEatItem() {
return !this.effectState.unnerved;
},
onSourceAfterFaint(length, target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.boost({atk: length}, source, source, this.dex.abilities.get('chillingneigh'));
}
},
isPermanent: true,
name: "As One (Glastrier)",
rating: 3.5,
num: 266,
},
asonespectrier: {
onPreStart(pokemon) {
this.add('-ability', pokemon, 'As One');
this.add('-ability', pokemon, 'Unnerve');
this.effectState.unnerved = true;
},
onEnd() {
this.effectState.unnerved = false;
},
onFoeTryEatItem() {
return !this.effectState.unnerved;
},
onSourceAfterFaint(length, target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.boost({spa: length}, source, source, this.dex.abilities.get('grimneigh'));
}
},
isPermanent: true,
name: "As One (Spectrier)",
rating: 3.5,
num: 267,
},
aurabreak: {
onStart(pokemon) {
if (this.suppressingAbility(pokemon)) return;
this.add('-ability', pokemon, 'Aura Break');
},
onAnyTryPrimaryHit(target, source, move) {
if (target === source || move.category === 'Status') return;
move.hasAuraBreak = true;
},
isBreakable: true,
name: "Aura Break",
rating: 1,
num: 188,
},
baddreams: {
onResidualOrder: 28,
onResidualSubOrder: 2,
onResidual(pokemon) {
if (!pokemon.hp) return;
for (const target of pokemon.foes()) {
if (target.status === 'slp' || target.hasAbility('comatose')) {
this.damage(target.baseMaxhp / 8, target, pokemon);
}
}
},
name: "Bad Dreams",
rating: 1.5,
num: 123,
},
ballfetch: {
name: "Ball Fetch",
rating: 0,
num: 237,
},
battery: {
onAllyBasePowerPriority: 22,
onAllyBasePower(basePower, attacker, defender, move) {
if (attacker !== this.effectState.target && move.category === 'Special') {
this.debug('Battery boost');
return this.chainModify([5325, 4096]);
}
},
name: "Battery",
rating: 0,
num: 217,
},
battlearmor: {
onCriticalHit: false,
isBreakable: true,
name: "Battle Armor",
rating: 1,
num: 4,
},
battlebond: {
onSourceAfterFaint(length, target, source, effect) {
if (effect?.effectType !== 'Move') {
return;
}
if (source.species.id === 'greninja' && source.hp && !source.transformed && source.side.foePokemonLeft()) {
this.add('-activate', source, 'ability: Battle Bond');
source.formeChange('Greninja-Ash', this.effect, true);
}
},
onModifyMovePriority: -1,
onModifyMove(move, attacker) {
if (move.id === 'watershuriken' && attacker.species.name === 'Greninja-Ash' &&
!attacker.transformed) {
move.multihit = 3;
}
},
isPermanent: true,
name: "Battle Bond",
rating: 4,
num: 210,
},
beastboost: {
onSourceAfterFaint(length, target, source, effect) {
if (effect && effect.effectType === 'Move') {
let statName = 'atk';
let bestStat = 0;
let s: StatIDExceptHP;
for (s in source.storedStats) {
if (source.storedStats[s] > bestStat) {
statName = s;
bestStat = source.storedStats[s];
}
}
this.boost({[statName]: length}, source);
}
},
name: "Beast Boost",
rating: 3.5,
num: 224,
},
berserk: {
onDamage(damage, target, source, effect) {
if (
effect.effectType === "Move" &&
!effect.multihit &&
(!effect.negateSecondary && !(effect.hasSheerForce && source.hasAbility('sheerforce')))
) {
target.abilityState.checkedBerserk = false;
} else {
target.abilityState.checkedBerserk = true;
}
},
onTryEatItem(item, pokemon) {
const healingItems = [
'aguavberry', 'enigmaberry', 'figyberry', 'iapapaberry', 'magoberry', 'sitrusberry', 'wikiberry', 'oranberry', 'berryjuice',
];
if (healingItems.includes(item.id)) {
return pokemon.abilityState.checkedBerserk;
}
return true;
},
onAfterMoveSecondary(target, source, move) {
target.abilityState.checkedBerserk = true;
if (!source || source === target || !target.hp || !move.totalDamage) return;
const lastAttackedBy = target.getLastAttackedBy();
if (!lastAttackedBy) return;
const damage = move.multihit ? move.totalDamage : lastAttackedBy.damage;
if (target.hp <= target.maxhp / 2 && target.hp + damage > target.maxhp / 2) {
this.boost({spa: 1});
}
},
name: "Berserk",
rating: 2,
num: 201,
},
bigpecks: {
onBoost(boost, target, source, effect) {
if (source && target === source) return;
if (boost.def && boost.def < 0) {
delete boost.def;
if (!(effect as ActiveMove).secondaries && effect.id !== 'octolock') {
this.add("-fail", target, "unboost", "Defense", "[from] ability: Big Pecks", "[of] " + target);
}
}
},
isBreakable: true,
name: "Big Pecks",
rating: 0.5,
num: 145,
},
blaze: {
onModifyAtkPriority: 5,
onModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Blaze boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Blaze boost');
return this.chainModify(1.5);
}
},
name: "Blaze",
rating: 2,
num: 66,
},
bulletproof: {
onTryHit(pokemon, target, move) {
if (move.flags['bullet']) {
this.add('-immune', pokemon, '[from] ability: Bulletproof');
return null;
}
},
isBreakable: true,
name: "Bulletproof",
rating: 3,
num: 171,
},
cheekpouch: {
onEatItem(item, pokemon) {
this.heal(pokemon.baseMaxhp / 3);
},
name: "Cheek Pouch",
rating: 2,
num: 167,
},
chillingneigh: {
onSourceAfterFaint(length, target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.boost({atk: length}, source);
}
},
name: "Chilling Neigh",
rating: 3,
num: 264,
},
chlorophyll: {
onModifySpe(spe, pokemon) {
if (['sunnyday', 'desolateland'].includes(pokemon.effectiveWeather())) {
return this.chainModify(2);
}
},
name: "Chlorophyll",
rating: 3,
num: 34,
},
clearbody: {
onBoost(boost, target, source, effect) {
if (source && target === source) return;
let showMsg = false;
let i: BoostID;
for (i in boost) {
if (boost[i]! < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !(effect as ActiveMove).secondaries && effect.id !== 'octolock') {
this.add("-fail", target, "unboost", "[from] ability: Clear Body", "[of] " + target);
}
},
isBreakable: true,
name: "Clear Body",
rating: 2,
num: 29,
},
cloudnine: {
onSwitchIn(pokemon) {
this.effectState.switchingIn = true;
},
onStart(pokemon) {
// Cloud Nine does not activate when Skill Swapped or when Neutralizing Gas leaves the field
if (!this.effectState.switchingIn) return;
this.add('-ability', pokemon, 'Cloud Nine');
this.effectState.switchingIn = false;
},
suppressWeather: true,
name: "Cloud Nine",
rating: 2,
num: 13,
},
colorchange: {
onAfterMoveSecondary(target, source, move) {
if (!target.hp) return;
const type = move.type;
if (
target.isActive && move.effectType === 'Move' && move.category !== 'Status' &&
type !== '???' && !target.hasType(type)
) {
if (!target.setType(type)) return false;
this.add('-start', target, 'typechange', type, '[from] ability: Color Change');
if (target.side.active.length === 2 && target.position === 1) {
// Curse Glitch
const action = this.queue.willMove(target);
if (action && action.move.id === 'curse') {
action.targetLoc = -1;
}
}
}
},
name: "Color Change",
rating: 0,
num: 16,
},
comatose: {
onStart(pokemon) {
this.add('-ability', pokemon, 'Comatose');
},
onSetStatus(status, target, source, effect) {
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Comatose');
}
return false;
},
// Permanent sleep "status" implemented in the relevant sleep-checking effects
isPermanent: true,
name: "Comatose",
rating: 4,
num: 213,
},
competitive: {
onAfterEachBoost(boost, target, source, effect) {
if (!source || target.isAlly(source)) {
if (effect.id === 'stickyweb') {
this.hint("Court Change Sticky Web counts as lowering your own Speed, and Competitive only affects stats lowered by foes.", true, source.side);
}
return;
}
let statsLowered = false;
let i: BoostID;
for (i in boost) {
if (boost[i]! < 0) {
statsLowered = true;
}
}
if (statsLowered) {
this.add('-ability', target, 'Competitive');
this.boost({spa: 2}, target, target, null, true);
}
},
name: "Competitive",
rating: 2.5,
num: 172,
},
compoundeyes: {
onSourceModifyAccuracyPriority: -1,
onSourceModifyAccuracy(accuracy) {
if (typeof accuracy !== 'number') return;
this.debug('compoundeyes - enhancing accuracy');
return this.chainModify([5325, 4096]);
},
name: "Compound Eyes",
rating: 3,
num: 14,
},
contrary: {
onBoost(boost, target, source, effect) {
if (effect && effect.id === 'zpower') return;
let i: BoostID;
for (i in boost) {
boost[i]! *= -1;
}
},
isBreakable: true,
name: "Contrary",
rating: 4.5,
num: 126,
},
corrosion: {
// Implemented in sim/pokemon.js:Pokemon#setStatus
name: "Corrosion",
rating: 2.5,
num: 212,
},
cottondown: {
onDamagingHit(damage, target, source, move) {
let activated = false;
for (const pokemon of this.getAllActive()) {
if (pokemon === target || pokemon.fainted) continue;
if (!activated) {
this.add('-ability', target, 'Cotton Down');
activated = true;
}
this.boost({spe: -1}, pokemon, target, null, true);
}
},
name: "Cotton Down",
rating: 2,
num: 238,
},
curiousmedicine: {
onStart(pokemon) {
for (const ally of pokemon.adjacentAllies()) {
ally.clearBoosts();
this.add('-clearboost', ally, '[from] ability: Curious Medicine', '[of] ' + pokemon);
}
},
name: "Curious Medicine",
rating: 0,
num: 261,
},
cursedbody: {
onDamagingHit(damage, target, source, move) {
if (source.volatiles['disable']) return;
if (!move.isMax && !move.isFutureMove && move.id !== 'struggle') {
if (this.randomChance(3, 10)) {
source.addVolatile('disable', this.effectState.target);
}
}
},
name: "Cursed Body",
rating: 2,
num: 130,
},
cutecharm: {
onDamagingHit(damage, target, source, move) {
if (this.checkMoveMakesContact(move, source, target)) {
if (this.randomChance(3, 10)) {
source.addVolatile('attract', this.effectState.target);
}
}
},
name: "Cute Charm",
rating: 0.5,
num: 56,
},
damp: {
onAnyTryMove(target, source, effect) {
if (['explosion', 'mindblown', 'mistyexplosion', 'selfdestruct'].includes(effect.id)) {
this.attrLastMove('[still]');
this.add('cant', this.effectState.target, 'ability: Damp', effect, '[of] ' + target);
return false;
}
},
onAnyDamage(damage, target, source, effect) {
if (effect && effect.id === 'aftermath') {
return false;
}
},
isBreakable: true,
name: "Damp",
rating: 1,
num: 6,
},
dancer: {
name: "Dancer",
// implemented in runMove in scripts.js
rating: 1.5,
num: 216,
},
darkaura: {
onStart(pokemon) {
if (this.suppressingAbility(pokemon)) return;
this.add('-ability', pokemon, 'Dark Aura');
},
onAnyBasePowerPriority: 20,
onAnyBasePower(basePower, source, target, move) {
if (target === source || move.category === 'Status' || move.type !== 'Dark') return;
if (!move.auraBooster) move.auraBooster = this.effectState.target;
if (move.auraBooster !== this.effectState.target) return;
return this.chainModify([move.hasAuraBreak ? 3072 : 5448, 4096]);
},
isBreakable: true,
name: "Dark Aura",
rating: 3,
num: 186,
},
dauntlessshield: {
onStart(pokemon) {
this.boost({def: 1}, pokemon);
},
name: "Dauntless Shield",
rating: 3.5,
num: 235,
},
dazzling: {
onFoeTryMove(target, source, move) {
const targetAllExceptions = ['perishsong', 'flowershield', 'rototiller'];
if (move.target === 'foeSide' || (move.target === 'all' && !targetAllExceptions.includes(move.id))) {
return;
}
const dazzlingHolder = this.effectState.target;
if ((source.isAlly(dazzlingHolder) || move.target === 'all') && move.priority > 0.1) {
this.attrLastMove('[still]');
this.add('cant', dazzlingHolder, 'ability: Dazzling', move, '[of] ' + target);
return false;
}
},
isBreakable: true,
name: "Dazzling",
rating: 2.5,
num: 219,
},
defeatist: {
onModifyAtkPriority: 5,
onModifyAtk(atk, pokemon) {
if (pokemon.hp <= pokemon.maxhp / 2) {
return this.chainModify(0.5);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, pokemon) {
if (pokemon.hp <= pokemon.maxhp / 2) {
return this.chainModify(0.5);
}
},
name: "Defeatist",
rating: -1,
num: 129,
},
defiant: {
onAfterEachBoost(boost, target, source, effect) {
if (!source || target.isAlly(source)) {
if (effect.id === 'stickyweb') {
this.hint("Court Change Sticky Web counts as lowering your own Speed, and Defiant only affects stats lowered by foes.", true, source.side);
}
return;
}
let statsLowered = false;
let i: BoostID;
for (i in boost) {
if (boost[i]! < 0) {
statsLowered = true;
}
}
if (statsLowered) {
this.add('-ability', target, 'Defiant');
this.boost({atk: 2}, target, target, null, true);
}
},
name: "Defiant",
rating: 2.5,
num: 128,
},
deltastream: {
onStart(source) {
this.field.setWeather('deltastream');
},
onAnySetWeather(target, source, weather) {
const strongWeathers = ['desolateland', 'primordialsea', 'deltastream'];
if (this.field.getWeather().id === 'deltastream' && !strongWeathers.includes(weather.id)) return false;
},
onEnd(pokemon) {
if (this.field.weatherState.source !== pokemon) return;
for (const target of this.getAllActive()) {
if (target === pokemon) continue;
if (target.hasAbility('deltastream')) {
this.field.weatherState.source = target;
return;
}
}
this.field.clearWeather();
},
name: "Delta Stream",
rating: 4,
num: 191,
},
desolateland: {
onStart(source) {
this.field.setWeather('desolateland');
},
onAnySetWeather(target, source, weather) {
const strongWeathers = ['desolateland', 'primordialsea', 'deltastream'];
if (this.field.getWeather().id === 'desolateland' && !strongWeathers.includes(weather.id)) return false;
},
onEnd(pokemon) {
if (this.field.weatherState.source !== pokemon) return;
for (const target of this.getAllActive()) {
if (target === pokemon) continue;
if (target.hasAbility('desolateland')) {
this.field.weatherState.source = target;
return;
}
}
this.field.clearWeather();
},
name: "Desolate Land",
rating: 4.5,
num: 190,
},
disguise: {
onDamagePriority: 1,
onDamage(damage, target, source, effect) {
if (
effect && effect.effectType === 'Move' &&
['mimikyu', 'mimikyutotem'].includes(target.species.id) && !target.transformed
) {
this.add('-activate', target, 'ability: Disguise');
this.effectState.busted = true;
return 0;
}
},
onCriticalHit(target, source, move) {
if (!target) return;
if (!['mimikyu', 'mimikyutotem'].includes(target.species.id) || target.transformed) {
return;
}
const hitSub = target.volatiles['substitute'] && !move.flags['bypasssub'] && !(move.infiltrates && this.gen >= 6);
if (hitSub) return;
if (!target.runImmunity(move.type)) return;
return false;
},
onEffectiveness(typeMod, target, type, move) {
if (!target || move.category === 'Status') return;
if (!['mimikyu', 'mimikyutotem'].includes(target.species.id) || target.transformed) {
return;
}
const hitSub = target.volatiles['substitute'] && !move.flags['bypasssub'] && !(move.infiltrates && this.gen >= 6);
if (hitSub) return;
if (!target.runImmunity(move.type)) return;
return 0;
},
onUpdate(pokemon) {
if (['mimikyu', 'mimikyutotem'].includes(pokemon.species.id) && this.effectState.busted) {
const speciesid = pokemon.species.id === 'mimikyutotem' ? 'Mimikyu-Busted-Totem' : 'Mimikyu-Busted';
pokemon.formeChange(speciesid, this.effect, true);
this.damage(pokemon.baseMaxhp / 8, pokemon, pokemon, this.dex.species.get(speciesid));
}
},
isBreakable: true,
isPermanent: true,
name: "Disguise",
rating: 3.5,
num: 209,
},
download: {
onStart(pokemon) {
let totaldef = 0;
let totalspd = 0;
for (const target of pokemon.foes()) {
totaldef += target.getStat('def', false, true);
totalspd += target.getStat('spd', false, true);
}
if (totaldef && totaldef >= totalspd) {
this.boost({spa: 1});
} else if (totalspd) {
this.boost({atk: 1});
}
},
name: "Download",
rating: 3.5,
num: 88,
},
dragonsmaw: {
onModifyAtkPriority: 5,
onModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Dragon') {
this.debug('Dragon\'s Maw boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, attacker, defender, move) {
if (move.type === 'Dragon') {
this.debug('Dragon\'s Maw boost');
return this.chainModify(1.5);
}
},
name: "Dragon's Maw",
rating: 3.5,
num: 263,
},
drizzle: {
onStart(source) {
for (const action of this.queue) {
if (action.choice === 'runPrimal' && action.pokemon === source && source.species.id === 'kyogre') return;
if (action.choice !== 'runSwitch' && action.choice !== 'runPrimal') break;
}
this.field.setWeather('raindance');
},
name: "Drizzle",
rating: 4,
num: 2,
},
drought: {
onStart(source) {
for (const action of this.queue) {
if (action.choice === 'runPrimal' && action.pokemon === source && source.species.id === 'groudon') return;
if (action.choice !== 'runSwitch' && action.choice !== 'runPrimal') break;
}
this.field.setWeather('sunnyday');
},
name: "Drought",
rating: 4,
num: 70,
},
dryskin: {
onTryHit(target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.heal(target.baseMaxhp / 4)) {
this.add('-immune', target, '[from] ability: Dry Skin');
}
return null;
}
},
onSourceBasePowerPriority: 17,
onSourceBasePower(basePower, attacker, defender, move) {
if (move.type === 'Fire') {
return this.chainModify(1.25);
}
},
onWeather(target, source, effect) {
if (target.hasItem('utilityumbrella')) return;
if (effect.id === 'raindance' || effect.id === 'primordialsea') {
this.heal(target.baseMaxhp / 8);
} else if (effect.id === 'sunnyday' || effect.id === 'desolateland') {
this.damage(target.baseMaxhp / 8, target, target);
}
},
isBreakable: true,
name: "Dry Skin",
rating: 3,
num: 87,
},
earlybird: {
name: "Early Bird",
// Implemented in statuses.js
rating: 1.5,
num: 48,
},
effectspore: {
onDamagingHit(damage, target, source, move) {
if (this.checkMoveMakesContact(move, source, target) && !source.status && source.runStatusImmunity('powder')) {
const r = this.random(100);
if (r < 11) {
source.setStatus('slp', target);
} else if (r < 21) {
source.setStatus('par', target);
} else if (r < 30) {
source.setStatus('psn', target);
}
}
},
name: "Effect Spore",
rating: 2,
num: 27,
},
electricsurge: {
onStart(source) {
this.field.setTerrain('electricterrain');
},
name: "Electric Surge",
rating: 4,
num: 226,
},
emergencyexit: {
onEmergencyExit(target) {
if (!this.canSwitch(target.side) || target.forceSwitchFlag || target.switchFlag) return;
for (const side of this.sides) {
for (const active of side.active) {
active.switchFlag = false;
}
}
target.switchFlag = true;
this.add('-activate', target, 'ability: Emergency Exit');
},
name: "Emergency Exit",
rating: 1,
num: 194,
},
fairyaura: {
onStart(pokemon) {
if (this.suppressingAbility(pokemon)) return;
this.add('-ability', pokemon, 'Fairy Aura');
},
onAnyBasePowerPriority: 20,
onAnyBasePower(basePower, source, target, move) {
if (target === source || move.category === 'Status' || move.type !== 'Fairy') return;
if (!move.auraBooster) move.auraBooster = this.effectState.target;
if (move.auraBooster !== this.effectState.target) return;
return this.chainModify([move.hasAuraBreak ? 3072 : 5448, 4096]);
},
isBreakable: true,
name: "Fairy Aura",
rating: 3,
num: 187,
},
filter: {
onSourceModifyDamage(damage, source, target, move) {
if (target.getMoveHitData(move).typeMod > 0) {
this.debug('Filter neutralize');
return this.chainModify(0.75);
}
},
isBreakable: true,
name: "Filter",
rating: 3,
num: 111,
},
flamebody: {
onDamagingHit(damage, target, source, move) {
if (this.checkMoveMakesContact(move, source, target)) {
if (this.randomChance(3, 10)) {
source.trySetStatus('brn', target);
}
}
},
name: "Flame Body",
rating: 2,
num: 49,
},
flareboost: {
onBasePowerPriority: 19,
onBasePower(basePower, attacker, defender, move) {
if (attacker.status === 'brn' && move.category === 'Special') {
return this.chainModify(1.5);
}
},
name: "Flare Boost",
rating: 2,
num: 138,
},
flashfire: {
onTryHit(target, source, move) {
if (target !== source && move.type === 'Fire') {
move.accuracy = true;
if (!target.addVolatile('flashfire')) {
this.add('-immune', target, '[from] ability: Flash Fire');
}
return null;
}
},
onEnd(pokemon) {
pokemon.removeVolatile('flashfire');
},
condition: {
noCopy: true, // doesn't get copied by Baton Pass
onStart(target) {
this.add('-start', target, 'ability: Flash Fire');
},
onModifyAtkPriority: 5,
onModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hasAbility('flashfire')) {
this.debug('Flash Fire boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hasAbility('flashfire')) {
this.debug('Flash Fire boost');
return this.chainModify(1.5);
}
},
onEnd(target) {
this.add('-end', target, 'ability: Flash Fire', '[silent]');
},
},
isBreakable: true,
name: "Flash Fire",
rating: 3.5,
num: 18,
},
flowergift: {
onStart(pokemon) {
delete this.effectState.forme;
},
onUpdate(pokemon) {
if (!pokemon.isActive || pokemon.baseSpecies.baseSpecies !== 'Cherrim' || pokemon.transformed) return;
if (!pokemon.hp) return;
if (['sunnyday', 'desolateland'].includes(pokemon.effectiveWeather())) {
if (pokemon.species.id !== 'cherrimsunshine') {
pokemon.formeChange('Cherrim-Sunshine', this.effect, false, '[msg]');
}
} else {
if (pokemon.species.id === 'cherrimsunshine') {
pokemon.formeChange('Cherrim', this.effect, false, '[msg]');
}
}
},
onAllyModifyAtkPriority: 3,
onAllyModifyAtk(atk, pokemon) {
if (this.effectState.target.baseSpecies.baseSpecies !== 'Cherrim') return;
if (['sunnyday', 'desolateland'].includes(pokemon.effectiveWeather())) {
return this.chainModify(1.5);
}
},
onAllyModifySpDPriority: 4,
onAllyModifySpD(spd, pokemon) {
if (this.effectState.target.baseSpecies.baseSpecies !== 'Cherrim') return;
if (['sunnyday', 'desolateland'].includes(pokemon.effectiveWeather())) {
return this.chainModify(1.5);
}
},
isBreakable: true,
name: "Flower Gift",
rating: 1,
num: 122,
},
flowerveil: {
onAllyBoost(boost, target, source, effect) {
if ((source && target === source) || !target.hasType('Grass')) return;
let showMsg = false;
let i: BoostID;
for (i in boost) {
if (boost[i]! < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !(effect as ActiveMove).secondaries) {
const effectHolder = this.effectState.target;
this.add('-block', target, 'ability: Flower Veil', '[of] ' + effectHolder);
}
},
onAllySetStatus(status, target, source, effect) {
if (target.hasType('Grass') && source && target !== source && effect && effect.id !== 'yawn') {
this.debug('interrupting setStatus with Flower Veil');
if (effect.id === 'synchronize' || (effect.effectType === 'Move' && !effect.secondaries)) {
const effectHolder = this.effectState.target;
this.add('-block', target, 'ability: Flower Veil', '[of] ' + effectHolder);
}
return null;
}
},
onAllyTryAddVolatile(status, target) {
if (target.hasType('Grass') && status.id === 'yawn') {
this.debug('Flower Veil blocking yawn');
const effectHolder = this.effectState.target;
this.add('-block', target, 'ability: Flower Veil', '[of] ' + effectHolder);
return null;
}
},
isBreakable: true,
name: "Flower Veil",
rating: 0,
num: 166,
},
fluffy: {
onSourceModifyDamage(damage, source, target, move) {
let mod = 1;
if (move.type === 'Fire') mod *= 2;
if (move.flags['contact']) mod /= 2;
return this.chainModify(mod);
},
isBreakable: true,
name: "Fluffy",
rating: 3.5,
num: 218,
},
forecast: {
onUpdate(pokemon) {
if (pokemon.baseSpecies.baseSpecies !== 'Castform' || pokemon.transformed) return;
let forme = null;
switch (pokemon.effectiveWeather()) {
case 'sunnyday':
case 'desolateland':
if (pokemon.species.id !== 'castformsunny') forme = 'Castform-Sunny';
break;
case 'raindance':
case 'primordialsea':
if (pokemon.species.id !== 'castformrainy') forme = 'Castform-Rainy';
break;
case 'hail':
if (pokemon.species.id !== 'castformsnowy') forme = 'Castform-Snowy';
break;
default:
if (pokemon.species.id !== 'castform') forme = 'Castform';
break;
}
if (pokemon.isActive && forme) {
pokemon.formeChange(forme, this.effect, false, '[msg]');
}
},
name: "Forecast",
rating: 2,
num: 59,
},
forewarn: {
onStart(pokemon) {
let warnMoves: (Move | Pokemon)[][] = [];
let warnBp = 1;
for (const target of pokemon.foes()) {
for (const moveSlot of target.moveSlots) {
const move = this.dex.moves.get(moveSlot.move);
let bp = move.basePower;
if (move.ohko) bp = 150;
if (move.id === 'counter' || move.id === 'metalburst' || move.id === 'mirrorcoat') bp = 120;
if (bp === 1) bp = 80;
if (!bp && move.category !== 'Status') bp = 80;
if (bp > warnBp) {
warnMoves = [[move, target]];
warnBp = bp;
} else if (bp === warnBp) {
warnMoves.push([move, target]);
}
}
}
if (!warnMoves.length) return;
const [warnMoveName, warnTarget] = this.sample(warnMoves);
this.add('-activate', pokemon, 'ability: Forewarn', warnMoveName, '[of] ' + warnTarget);
},
name: "Forewarn",
rating: 0.5,
num: 108,
},
friendguard: {
name: "Friend Guard",
onAnyModifyDamage(damage, source, target, move) {
if (target !== this.effectState.target && target.isAlly(this.effectState.target)) {
this.debug('Friend Guard weaken');
return this.chainModify(0.75);
}
},
isBreakable: true,
rating: 0,
num: 132,
},
frisk: {
onStart(pokemon) {
for (const target of pokemon.foes()) {
if (target.item) {
this.add('-item', target, target.getItem().name, '[from] ability: Frisk', '[of] ' + pokemon, '[identify]');
}
}
},
name: "Frisk",
rating: 1.5,
num: 119,
},
fullmetalbody: {
onBoost(boost, target, source, effect) {
if (source && target === source) return;
let showMsg = false;
let i: BoostID;
for (i in boost) {
if (boost[i]! < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !(effect as ActiveMove).secondaries && effect.id !== 'octolock') {
this.add("-fail", target, "unboost", "[from] ability: Full Metal Body", "[of] " + target);
}
},
name: "Full Metal Body",
rating: 2,
num: 230,
},
furcoat: {
onModifyDefPriority: 6,
onModifyDef(def) {
return this.chainModify(2);
},
isBreakable: true,
name: "Fur Coat",
rating: 4,
num: 169,
},
galewings: {
onModifyPriority(priority, pokemon, target, move) {
if (move?.type === 'Flying' && pokemon.hp === pokemon.maxhp) return priority + 1;
},
name: "Gale Wings",
rating: 3,
num: 177,
},
galvanize: {
onModifyTypePriority: -1,
onModifyType(move, pokemon) {
const noModifyType = [
'judgment', 'multiattack', 'naturalgift', 'revelationdance', 'technoblast', 'terrainpulse', 'weatherball',
];
if (move.type === 'Normal' && !noModifyType.includes(move.id) && !(move.isZ && move.category !== 'Status')) {
move.type = 'Electric';
move.galvanizeBoosted = true;
}
},
onBasePowerPriority: 23,
onBasePower(basePower, pokemon, target, move) {
if (move.galvanizeBoosted) return this.chainModify([4915, 4096]);
},
name: "Galvanize",
rating: 4,
num: 206,
},
gluttony: {
name: "Gluttony",
rating: 1.5,
num: 82,
},
gooey: {
onDamagingHit(damage, target, source, move) {
if (this.checkMoveMakesContact(move, source, target, true)) {
this.add('-ability', target, 'Gooey');
this.boost({spe: -1}, source, target, null, true);
}
},
name: "Gooey",
rating: 2,
num: 183,
},
gorillatactics: {
onStart(pokemon) {
pokemon.abilityState.choiceLock = "";
},
onBeforeMove(pokemon, target, move) {
if (move.isZOrMaxPowered || move.id === 'struggle') return;
if (pokemon.abilityState.choiceLock && pokemon.abilityState.choiceLock !== move.id) {
// Fails unless ability is being ignored (these events will not run), no PP lost.
this.addMove('move', pokemon, move.name);
this.attrLastMove('[still]');
this.debug("Disabled by Gorilla Tactics");
this.add('-fail', pokemon);
return false;
}
},
onModifyMove(move, pokemon) {
if (pokemon.abilityState.choiceLock || move.isZOrMaxPowered || move.id === 'struggle') return;
pokemon.abilityState.choiceLock = move.id;
},
onModifyAtkPriority: 1,
onModifyAtk(atk, pokemon) {
if (pokemon.volatiles['dynamax']) return;
// PLACEHOLDER
this.debug('Gorilla Tactics Atk Boost');
return this.chainModify(1.5);
},
onDisableMove(pokemon) {
if (!pokemon.abilityState.choiceLock) return;
if (pokemon.volatiles['dynamax']) return;
for (const moveSlot of pokemon.moveSlots) {
if (moveSlot.id !== pokemon.abilityState.choiceLock) {
pokemon.disableMove(moveSlot.id, false, this.effectState.sourceEffect);
}
}
},
onEnd(pokemon) {
pokemon.abilityState.choiceLock = "";
},
name: "Gorilla Tactics",
rating: 4.5,
num: 255,
},
grasspelt: {
onModifyDefPriority: 6,
onModifyDef(pokemon) {
if (this.field.isTerrain('grassyterrain')) return this.chainModify(1.5);
},
isBreakable: true,
name: "Grass Pelt",
rating: 0.5,
num: 179,
},
grassysurge: {
onStart(source) {
this.field.setTerrain('grassyterrain');
},
name: "Grassy Surge",
rating: 4,
num: 229,
},
grimneigh: {
onSourceAfterFaint(length, target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.boost({spa: length}, source);
}
},
name: "Grim Neigh",
rating: 3,
num: 265,
},
gulpmissile: {
onDamagingHit(damage, target, source, move) {
if (!source.hp || !source.isActive || target.transformed || target.isSemiInvulnerable()) return;
if (['cramorantgulping', 'cramorantgorging'].includes(target.species.id)) {
this.damage(source.baseMaxhp / 4, source, target);
if (target.species.id === 'cramorantgulping') {
this.boost({def: -1}, source, target, null, true);
} else {
source.trySetStatus('par', target, move);
}
target.formeChange('cramorant', move);
}
},
// The Dive part of this mechanic is implemented in Dive's `onTryMove` in moves.ts
onSourceTryPrimaryHit(target, source, effect) {
if (
effect && effect.id === 'surf' && source.hasAbility('gulpmissile') &&
source.species.name === 'Cramorant' && !source.transformed
) {
const forme = source.hp <= source.maxhp / 2 ? 'cramorantgorging' : 'cramorantgulping';
source.formeChange(forme, effect);
}
},
isPermanent: true,
name: "Gulp Missile",
rating: 2.5,
num: 241,
},
guts: {
onModifyAtkPriority: 5,
onModifyAtk(atk, pokemon) {
if (pokemon.status) {
return this.chainModify(1.5);
}
},
name: "Guts",
rating: 3,
num: 62,
},
harvest: {
name: "Harvest",
onResidualOrder: 28,
onResidualSubOrder: 2,
onResidual(pokemon) {
if (this.field.isWeather(['sunnyday', 'desolateland']) || this.randomChance(1, 2)) {
if (pokemon.hp && !pokemon.item && this.dex.items.get(pokemon.lastItem).isBerry) {
pokemon.setItem(pokemon.lastItem);
pokemon.lastItem = '';
this.add('-item', pokemon, pokemon.getItem(), '[from] ability: Harvest');
}
}
},
rating: 2.5,
num: 139,
},
healer: {
name: "Healer",
onResidualOrder: 5,
onResidualSubOrder: 3,
onResidual(pokemon) {
for (const allyActive of pokemon.adjacentAllies()) {
if (allyActive.status && this.randomChance(3, 10)) {
this.add('-activate', pokemon, 'ability: Healer');
allyActive.cureStatus();
}
}
},
rating: 0,
num: 131,
},
heatproof: {
onSourceBasePowerPriority: 18,
onSourceBasePower(basePower, attacker, defender, move) {
if (move.type === 'Fire') {
return this.chainModify(0.5);
}
},
onDamage(damage, target, source, effect) {
if (effect && effect.id === 'brn') {
return damage / 2;
}
},
isBreakable: true,
name: "Heatproof",
rating: 2,
num: 85,
},
heavymetal: {
onModifyWeightPriority: 1,
onModifyWeight(weighthg) {
return weighthg * 2;
},
isBreakable: true,
name: "Heavy Metal",
rating: 0,
num: 134,
},
honeygather: {
name: "Honey Gather",
rating: 0,
num: 118,
},
hugepower: {
onModifyAtkPriority: 5,
onModifyAtk(atk) {
return this.chainModify(2);
},
name: "Huge Power",
rating: 5,
num: 37,
},
hungerswitch: {
onResidualOrder: 29,
onResidual(pokemon) {
if (pokemon.species.baseSpecies !== 'Morpeko' || pokemon.transformed) return;
const targetForme = pokemon.species.name === 'Morpeko' ? 'Morpeko-Hangry' : 'Morpeko';
pokemon.formeChange(targetForme);
},
name: "Hunger Switch",
rating: 1,
num: 258,
},
hustle: {
// This should be applied directly to the stat as opposed to chaining with the others
onModifyAtkPriority: 5,
onModifyAtk(atk) {
return this.modify(atk, 1.5);
},
onSourceModifyAccuracyPriority: -1,
onSourceModifyAccuracy(accuracy, target, source, move) {
if (move.category === 'Physical' && typeof accuracy === 'number') {
return this.chainModify([3277, 4096]);
}
},
name: "Hustle",
rating: 3.5,
num: 55,
},
hydration: {
onResidualOrder: 5,
onResidualSubOrder: 3,
onResidual(pokemon) {
if (pokemon.status && ['raindance', 'primordialsea'].includes(pokemon.effectiveWeather())) {
this.debug('hydration');
this.add('-activate', pokemon, 'ability: Hydration');
pokemon.cureStatus();
}
},
name: "Hydration",
rating: 1.5,
num: 93,
},
hypercutter: {
onBoost(boost, target, source, effect) {
if (source && target === source) return;
if (boost.atk && boost.atk < 0) {
delete boost.atk;
if (!(effect as ActiveMove).secondaries) {
this.add("-fail", target, "unboost", "Attack", "[from] ability: Hyper Cutter", "[of] " + target);
}
}
},
isBreakable: true,
name: "Hyper Cutter",
rating: 1.5,
num: 52,
},
icebody: {
onWeather(target, source, effect) {
if (effect.id === 'hail') {
this.heal(target.baseMaxhp / 16);
}
},
onImmunity(type, pokemon) {
if (type === 'hail') return false;
},
name: "Ice Body",
rating: 1,
num: 115,
},
iceface: {
onStart(pokemon) {
if (this.field.isWeather('hail') && pokemon.species.id === 'eiscuenoice' && !pokemon.transformed) {
this.add('-activate', pokemon, 'ability: Ice Face');
this.effectState.busted = false;
pokemon.formeChange('Eiscue', this.effect, true);
}
},
onDamagePriority: 1,
onDamage(damage, target, source, effect) {
if (
effect && effect.effectType === 'Move' && effect.category === 'Physical' &&
target.species.id === 'eiscue' && !target.transformed
) {
this.add('-activate', target, 'ability: Ice Face');
this.effectState.busted = true;
return 0;
}
},
onCriticalHit(target, type, move) {
if (!target) return;
if (move.category !== 'Physical' || target.species.id !== 'eiscue' || target.transformed) return;
if (target.volatiles['substitute'] && !(move.flags['bypasssub'] || move.infiltrates)) return;
if (!target.runImmunity(move.type)) return;
return false;
},
onEffectiveness(typeMod, target, type, move) {
if (!target) return;
if (move.category !== 'Physical' || target.species.id !== 'eiscue' || target.transformed) return;
const hitSub = target.volatiles['substitute'] && !move.flags['bypasssub'] && !(move.infiltrates && this.gen >= 6);
if (hitSub) return;
if (!target.runImmunity(move.type)) return;
return 0;
},
onUpdate(pokemon) {
if (pokemon.species.id === 'eiscue' && this.effectState.busted) {
pokemon.formeChange('Eiscue-Noice', this.effect, true);
}
},
onAnyWeatherStart() {
const pokemon = this.effectState.target;
if (!pokemon.hp) return;
if (this.field.isWeather('hail') && pokemon.species.id === 'eiscuenoice' && !pokemon.transformed) {
this.add('-activate', pokemon, 'ability: Ice Face');
this.effectState.busted = false;
pokemon.formeChange('Eiscue', this.effect, true);
}
},
isBreakable: true,
isPermanent: true,
name: "Ice Face",
rating: 3,
num: 248,
},
icescales: {
onSourceModifyDamage(damage, source, target, move) {
if (move.category === 'Special') {
return this.chainModify(0.5);
}
},
isBreakable: true,
name: "Ice Scales",
rating: 4,
num: 246,
},
illuminate: {
name: "Illuminate",
rating: 0,
num: 35,
},
illusion: {
onBeforeSwitchIn(pokemon) {
pokemon.illusion = null;
// yes, you can Illusion an active pokemon but only if it's to your right
for (let i = pokemon.side.pokemon.length - 1; i > pokemon.position; i--) {
const possibleTarget = pokemon.side.pokemon[i];
if (!possibleTarget.fainted) {
pokemon.illusion = possibleTarget;
break;
}
}
},
onDamagingHit(damage, target, source, move) {
if (target.illusion) {
this.singleEvent('End', this.dex.abilities.get('Illusion'), target.abilityState, target, source, move);
}
},
onEnd(pokemon) {
if (pokemon.illusion) {
this.debug('illusion cleared');
pokemon.illusion = null;
const details = pokemon.species.name + (pokemon.level === 100 ? '' : ', L' + pokemon.level) +
(pokemon.gender === '' ? '' : ', ' + pokemon.gender) + (pokemon.set.shiny ? ', shiny' : '');
this.add('replace', pokemon, details);
this.add('-end', pokemon, 'Illusion');
}
},
onFaint(pokemon) {
pokemon.illusion = null;
},
name: "Illusion",
rating: 4.5,
num: 149,
},
immunity: {
onUpdate(pokemon) {
if (pokemon.status === 'psn' || pokemon.status === 'tox') {
this.add('-activate', pokemon, 'ability: Immunity');
pokemon.cureStatus();
}
},
onSetStatus(status, target, source, effect) {
if (status.id !== 'psn' && status.id !== 'tox') return;
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Immunity');
}
return false;
},
isBreakable: true,
name: "Immunity",
rating: 2,
num: 17,
},
imposter: {
onSwitchIn(pokemon) {
this.effectState.switchingIn = true;
},
onStart(pokemon) {
// Imposter does not activate when Skill Swapped or when Neutralizing Gas leaves the field
if (!this.effectState.switchingIn) return;
// copies across in doubles/triples
// (also copies across in multibattle and diagonally in free-for-all,
// but side.foe already takes care of those)
const target = pokemon.side.foe.active[pokemon.side.foe.active.length - 1 - pokemon.position];
if (target) {
pokemon.transformInto(target, this.dex.abilities.get('imposter'));
}
this.effectState.switchingIn = false;
},
name: "Imposter",
rating: 5,
num: 150,
},
infiltrator: {
onModifyMove(move) {
move.infiltrates = true;
},
name: "Infiltrator",
rating: 2.5,
num: 151,
},
innardsout: {
name: "Innards Out",
onDamagingHitOrder: 1,
onDamagingHit(damage, target, source, move) {
if (!target.hp) {
this.damage(target.getUndynamaxedHP(damage), source, target);
}
},
rating: 4,
num: 215,
},
innerfocus: {
onTryAddVolatile(status, pokemon) {
if (status.id === 'flinch') return null;
},
onBoost(boost, target, source, effect) {
if (effect.id === 'intimidate') {
delete boost.atk;
this.add('-fail', target, 'unboost', 'Attack', '[from] ability: Inner Focus', '[of] ' + target);
}
},
isBreakable: true,
name: "Inner Focus",
rating: 1.5,
num: 39,
},
insomnia: {
onUpdate(pokemon) {
if (pokemon.status === 'slp') {
this.add('-activate', pokemon, 'ability: Insomnia');
pokemon.cureStatus();
}
},
onSetStatus(status, target, source, effect) {
if (status.id !== 'slp') return;
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Insomnia');
}
return false;
},
isBreakable: true,
name: "Insomnia",
rating: 2,
num: 15,
},
intimidate: {
onStart(pokemon) {
let activated = false;
for (const target of pokemon.adjacentFoes()) {
if (!activated) {
this.add('-ability', pokemon, 'Intimidate', 'boost');
activated = true;
}
if (target.volatiles['substitute']) {
this.add('-immune', target);
} else {
this.boost({atk: -1}, target, pokemon, null, true);
}
}
},
name: "Intimidate",
rating: 3.5,
num: 22,
},
intrepidsword: {
onStart(pokemon) {
this.boost({atk: 1}, pokemon);
},
name: "Intrepid Sword",
rating: 4,
num: 234,
},
ironbarbs: {
onDamagingHitOrder: 1,
onDamagingHit(damage, target, source, move) {
if (this.checkMoveMakesContact(move, source, target, true)) {
this.damage(source.baseMaxhp / 8, source, target);
}
},
name: "Iron Barbs",
rating: 2.5,
num: 160,
},
ironfist: {
onBasePowerPriority: 23,
onBasePower(basePower, attacker, defender, move) {
if (move.flags['punch']) {
this.debug('Iron Fist boost');
return this.chainModify([4915, 4096]);
}
},
name: "Iron Fist",
rating: 3,
num: 89,
},
justified: {
onDamagingHit(damage, target, source, move) {
if (move.type === 'Dark') {
this.boost({atk: 1});
}
},
name: "Justified",
rating: 2.5,
num: 154,
},
keeneye: {
onBoost(boost, target, source, effect) {
if (source && target === source) return;
if (boost.accuracy && boost.accuracy < 0) {
delete boost.accuracy;
if (!(effect as ActiveMove).secondaries) {
this.add("-fail", target, "unboost", "accuracy", "[from] ability: Keen Eye", "[of] " + target);
}
}
},
onModifyMove(move) {
move.ignoreEvasion = true;
},
isBreakable: true,
name: "Keen Eye",
rating: 0.5,
num: 51,
},
klutz: {
// Item suppression implemented in Pokemon.ignoringItem() within sim/pokemon.js
name: "Klutz",
rating: -1,
num: 103,
},
leafguard: {
onSetStatus(status, target, source, effect) {
if (['sunnyday', 'desolateland'].includes(target.effectiveWeather())) {
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Leaf Guard');
}
return false;
}
},
onTryAddVolatile(status, target) {
if (status.id === 'yawn' && ['sunnyday', 'desolateland'].includes(target.effectiveWeather())) {
this.add('-immune', target, '[from] ability: Leaf Guard');
return null;
}
},
isBreakable: true,
name: "Leaf Guard",
rating: 0.5,
num: 102,
},
levitate: {
// airborneness implemented in sim/pokemon.js:Pokemon#isGrounded
isBreakable: true,
name: "Levitate",
rating: 3.5,
num: 26,
},
libero: {
onPrepareHit(source, target, move) {
if (move.hasBounced || move.sourceEffect === 'snatch') return;
const type = move.type;
if (type && type !== '???' && source.getTypes().join() !== type) {
if (!source.setType(type)) return;
this.add('-start', source, 'typechange', type, '[from] ability: Libero');
}
},
name: "Libero",
rating: 4.5,
num: 236,
},
lightmetal: {
onModifyWeight(weighthg) {
return this.trunc(weighthg / 2);
},
isBreakable: true,
name: "Light Metal",
rating: 1,
num: 135,
},
lightningrod: {
onTryHit(target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.boost({spa: 1})) {
this.add('-immune', target, '[from] ability: Lightning Rod');
}
return null;
}
},
onAnyRedirectTarget(target, source, source2, move) {
if (move.type !== 'Electric' || ['firepledge', 'grasspledge', 'waterpledge'].includes(move.id)) return;
const redirectTarget = ['randomNormal', 'adjacentFoe'].includes(move.target) ? 'normal' : move.target;
if (this.validTarget(this.effectState.target, source, redirectTarget)) {
if (move.smartTarget) move.smartTarget = false;
if (this.effectState.target !== target) {
this.add('-activate', this.effectState.target, 'ability: Lightning Rod');
}
return this.effectState.target;
}
},
isBreakable: true,
name: "Lightning Rod",
rating: 3,
num: 31,
},
limber: {
onUpdate(pokemon) {
if (pokemon.status === 'par') {
this.add('-activate', pokemon, 'ability: Limber');
pokemon.cureStatus();
}
},
onSetStatus(status, target, source, effect) {
if (status.id !== 'par') return;
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Limber');
}
return false;
},
isBreakable: true,
name: "Limber",
rating: 2,
num: 7,
},
liquidooze: {
onSourceTryHeal(damage, target, source, effect) {
this.debug("Heal is occurring: " + target + " <- " + source + " :: " + effect.id);
const canOoze = ['drain', 'leechseed', 'strengthsap'];
if (canOoze.includes(effect.id)) {
this.damage(damage);
return 0;
}
},
name: "Liquid Ooze",
rating: 1.5,
num: 64,
},
liquidvoice: {
onModifyTypePriority: -1,
onModifyType(move, pokemon) {
if (move.flags['sound'] && !pokemon.volatiles['dynamax']) { // hardcode
move.type = 'Water';
}
},
name: "Liquid Voice",
rating: 1.5,
num: 204,
},
longreach: {
onModifyMove(move) {
delete move.flags['contact'];
},
name: "Long Reach",
rating: 1,
num: 203,
},
magicbounce: {
name: "Magic Bounce",
onTryHitPriority: 1,
onTryHit(target, source, move) {
if (target === source || move.hasBounced || !move.flags['reflectable']) {
return;
}
const newMove = this.dex.getActiveMove(move.id);
newMove.hasBounced = true;
newMove.pranksterBoosted = false;
this.actions.useMove(newMove, target, source);
return null;
},
onAllyTryHitSide(target, source, move) {
if (target.isAlly(source) || move.hasBounced || !move.flags['reflectable']) {
return;
}
const newMove = this.dex.getActiveMove(move.id);
newMove.hasBounced = true;
newMove.pranksterBoosted = false;
this.actions.useMove(newMove, this.effectState.target, source);
return null;
},
condition: {
duration: 1,
},
isBreakable: true,
rating: 4,
num: 156,
},
magicguard: {
onDamage(damage, target, source, effect) {
if (effect.effectType !== 'Move') {
if (effect.effectType === 'Ability') this.add('-activate', source, 'ability: ' + effect.name);
return false;
}
},
name: "Magic Guard",
rating: 4,
num: 98,
},
magician: {
onAfterMoveSecondarySelf(source, target, move) {
if (!move || !target) return;
if (target !== source && move.category !== 'Status') {
if (source.item || source.volatiles['gem'] || move.id === 'fling') return;
const yourItem = target.takeItem(source);
if (!yourItem) return;
if (!source.setItem(yourItem)) {
target.item = yourItem.id; // bypass setItem so we don't break choicelock or anything
return;
}
this.add('-item', source, yourItem, '[from] ability: Magician', '[of] ' + target);
}
},
name: "Magician",
rating: 1.5,
num: 170,
},
magmaarmor: {
onUpdate(pokemon) {
if (pokemon.status === 'frz') {
this.add('-activate', pokemon, 'ability: Magma Armor');
pokemon.cureStatus();
}
},
onImmunity(type, pokemon) {
if (type === 'frz') return false;
},
isBreakable: true,
name: "Magma Armor",
rating: 1,
num: 40,
},
magnetpull: {
onFoeTrapPokemon(pokemon) {
if (pokemon.hasType('Steel') && pokemon.isAdjacent(this.effectState.target)) {
pokemon.tryTrap(true);
}
},
onFoeMaybeTrapPokemon(pokemon, source) {
if (!source) source = this.effectState.target;
if (!source || !pokemon.isAdjacent(source)) return;
if (!pokemon.knownType || pokemon.hasType('Steel')) {
pokemon.maybeTrapped = true;
}
},
name: "Magnet Pull",
rating: 4,
num: 42,
},
marvelscale: {
onModifyDefPriority: 6,
onModifyDef(def, pokemon) {
if (pokemon.status) {
return this.chainModify(1.5);
}
},
isBreakable: true,
name: "Marvel Scale",
rating: 2.5,
num: 63,
},
megalauncher: {
onBasePowerPriority: 19,
onBasePower(basePower, attacker, defender, move) {
if (move.flags['pulse']) {
return this.chainModify(1.5);
}
},
name: "Mega Launcher",
rating: 3,
num: 178,
},
merciless: {
onModifyCritRatio(critRatio, source, target) {
if (target && ['psn', 'tox'].includes(target.status)) return 5;
},
name: "Merciless",
rating: 1.5,
num: 196,
},
mimicry: {
onStart(pokemon) {
if (this.field.terrain) {
pokemon.addVolatile('mimicry');
} else {
const types = pokemon.baseSpecies.types;
if (pokemon.getTypes().join() === types.join() || !pokemon.setType(types)) return;
this.add('-start', pokemon, 'typechange', types.join('/'), '[from] ability: Mimicry');
this.hint("Transform Mimicry changes you to your original un-transformed types.");
}
},
onAnyTerrainStart() {
const pokemon = this.effectState.target;
delete pokemon.volatiles['mimicry'];
pokemon.addVolatile('mimicry');
},
onEnd(pokemon) {
delete pokemon.volatiles['mimicry'];
},
condition: {
onStart(pokemon) {
let newType;
switch (this.field.terrain) {
case 'electricterrain':
newType = 'Electric';
break;
case 'grassyterrain':
newType = 'Grass';
break;
case 'mistyterrain':
newType = 'Fairy';
break;
case 'psychicterrain':
newType = 'Psychic';
break;
}
if (!newType || pokemon.getTypes().join() === newType || !pokemon.setType(newType)) return;
this.add('-start', pokemon, 'typechange', newType, '[from] ability: Mimicry');
},
onUpdate(pokemon) {
if (!this.field.terrain) {
const types = pokemon.species.types;
if (pokemon.getTypes().join() === types.join() || !pokemon.setType(types)) return;
this.add('-activate', pokemon, 'ability: Mimicry');
this.add('-end', pokemon, 'typechange', '[silent]');
pokemon.removeVolatile('mimicry');
}
},
},
name: "Mimicry",
rating: 0.5,
num: 250,
},
minus: {
onModifySpAPriority: 5,
onModifySpA(spa, pokemon) {
for (const allyActive of pokemon.allies()) {
if (allyActive.hasAbility(['minus', 'plus'])) {
return this.chainModify(1.5);
}
}
},
name: "Minus",
rating: 0,
num: 58,
},
mirrorarmor: {
onBoost(boost, target, source, effect) {
// Don't bounce self stat changes, or boosts that have already bounced
if (target === source || !boost || effect.id === 'mirrorarmor') return;
let b: BoostID;
for (b in boost) {
if (boost[b]! < 0) {
if (target.boosts[b] === -6) continue;
const negativeBoost: SparseBoostsTable = {};
negativeBoost[b] = boost[b];
delete boost[b];
this.add('-ability', target, 'Mirror Armor');
this.boost(negativeBoost, source, target, null, true);
}
}
},
isBreakable: true,
name: "Mirror Armor",
rating: 2,
num: 240,
},
mistysurge: {
onStart(source) {
this.field.setTerrain('mistyterrain');
},
name: "Misty Surge",
rating: 3.5,
num: 228,
},
moldbreaker: {
onStart(pokemon) {
this.add('-ability', pokemon, 'Mold Breaker');
},
onModifyMove(move) {
move.ignoreAbility = true;
},
name: "Mold Breaker",
rating: 3.5,
num: 104,
},
moody: {
onResidualOrder: 28,
onResidualSubOrder: 2,
onResidual(pokemon) {
let stats: BoostID[] = [];
const boost: SparseBoostsTable = {};
let statPlus: BoostID;
for (statPlus in pokemon.boosts) {
if (statPlus === 'accuracy' || statPlus === 'evasion') continue;
if (pokemon.boosts[statPlus] < 6) {
stats.push(statPlus);
}
}
let randomStat: BoostID | undefined = stats.length ? this.sample(stats) : undefined;
if (randomStat) boost[randomStat] = 2;
stats = [];
let statMinus: BoostID;
for (statMinus in pokemon.boosts) {
if (statMinus === 'accuracy' || statMinus === 'evasion') continue;
if (pokemon.boosts[statMinus] > -6 && statMinus !== randomStat) {
stats.push(statMinus);
}
}
randomStat = stats.length ? this.sample(stats) : undefined;
if (randomStat) boost[randomStat] = -1;
this.boost(boost);
},
name: "Moody",
rating: 5,
num: 141,
},
motordrive: {
onTryHit(target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.boost({spe: 1})) {
this.add('-immune', target, '[from] ability: Motor Drive');
}
return null;
}
},
isBreakable: true,
name: "Motor Drive",
rating: 3,
num: 78,
},
moxie: {
onSourceAfterFaint(length, target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.boost({atk: length}, source);
}
},
name: "Moxie",
rating: 3,
num: 153,
},
multiscale: {
onSourceModifyDamage(damage, source, target, move) {
if (target.hp >= target.maxhp) {
this.debug('Multiscale weaken');
return this.chainModify(0.5);
}
},
isBreakable: true,
name: "Multiscale",
rating: 3.5,
num: 136,
},
multitype: {
// Multitype's type-changing itself is implemented in statuses.js
isPermanent: true,
name: "Multitype",
rating: 4,
num: 121,
},
mummy: {
name: "Mummy",
onDamagingHit(damage, target, source, move) {
const sourceAbility = source.getAbility();
if (sourceAbility.isPermanent || sourceAbility.id === 'mummy') {
return;
}
if (this.checkMoveMakesContact(move, source, target, !source.isAlly(target))) {
const oldAbility = source.setAbility('mummy', target);
if (oldAbility) {
this.add('-activate', target, 'ability: Mummy', this.dex.abilities.get(oldAbility).name, '[of] ' + source);
}
}
},
rating: 2,
num: 152,
},
naturalcure: {
onCheckShow(pokemon) {
// This is complicated
// For the most part, in-game, it's obvious whether or not Natural Cure activated,
// since you can see how many of your opponent's pokemon are statused.
// The only ambiguous situation happens in Doubles/Triples, where multiple pokemon
// that could have Natural Cure switch out, but only some of them get cured.
if (pokemon.side.active.length === 1) return;
if (pokemon.showCure === true || pokemon.showCure === false) return;
const cureList = [];
let noCureCount = 0;
for (const curPoke of pokemon.side.active) {
// pokemon not statused
if (!curPoke?.status) {
// this.add('-message', "" + curPoke + " skipped: not statused or doesn't exist");
continue;
}
if (curPoke.showCure) {
// this.add('-message', "" + curPoke + " skipped: Natural Cure already known");
continue;
}
const species = curPoke.species;
// pokemon can't get Natural Cure
if (!Object.values(species.abilities).includes('Natural Cure')) {
// this.add('-message', "" + curPoke + " skipped: no Natural Cure");
continue;
}
// pokemon's ability is known to be Natural Cure
if (!species.abilities['1'] && !species.abilities['H']) {
// this.add('-message', "" + curPoke + " skipped: only one ability");
continue;
}
// pokemon isn't switching this turn
if (curPoke !== pokemon && !this.queue.willSwitch(curPoke)) {
// this.add('-message', "" + curPoke + " skipped: not switching");
continue;
}
if (curPoke.hasAbility('naturalcure')) {
// this.add('-message', "" + curPoke + " confirmed: could be Natural Cure (and is)");
cureList.push(curPoke);
} else {
// this.add('-message', "" + curPoke + " confirmed: could be Natural Cure (but isn't)");
noCureCount++;
}
}
if (!cureList.length || !noCureCount) {
// It's possible to know what pokemon were cured
for (const pkmn of cureList) {
pkmn.showCure = true;
}
} else {
// It's not possible to know what pokemon were cured
// Unlike a -hint, this is real information that battlers need, so we use a -message
this.add('-message', "(" + cureList.length + " of " + pokemon.side.name + "'s pokemon " + (cureList.length === 1 ? "was" : "were") + " cured by Natural Cure.)");
for (const pkmn of cureList) {
pkmn.showCure = false;
}
}
},
onSwitchOut(pokemon) {
if (!pokemon.status) return;
// if pokemon.showCure is undefined, it was skipped because its ability
// is known
if (pokemon.showCure === undefined) pokemon.showCure = true;
if (pokemon.showCure) this.add('-curestatus', pokemon, pokemon.status, '[from] ability: Natural Cure');
pokemon.setStatus('');
// only reset .showCure if it's false
// (once you know a Pokemon has Natural Cure, its cures are always known)
if (!pokemon.showCure) pokemon.showCure = undefined;
},
name: "Natural Cure",
rating: 2.5,
num: 30,
},
neuroforce: {
onModifyDamage(damage, source, target, move) {
if (move && target.getMoveHitData(move).typeMod > 0) {
return this.chainModify([5120, 4096]);
}
},
name: "Neuroforce",
rating: 2.5,
num: 233,
},
neutralizinggas: {
// Ability suppression implemented in sim/pokemon.ts:Pokemon#ignoringAbility
onPreStart(pokemon) {
this.add('-ability', pokemon, 'Neutralizing Gas');
pokemon.abilityState.ending = false;
for (const target of this.getAllActive()) {
if (target.illusion) {
this.singleEvent('End', this.dex.abilities.get('Illusion'), target.abilityState, target, pokemon, 'neutralizinggas');
}
if (target.volatiles['slowstart']) {
delete target.volatiles['slowstart'];
this.add('-end', target, 'Slow Start', '[silent]');
}
}
},
onEnd(source) {
for (const pokemon of this.getAllActive()) {
if (pokemon !== source && pokemon.hasAbility('Neutralizing Gas')) {
return;
}
}
this.add('-end', source, 'ability: Neutralizing Gas');
// FIXME this happens before the pokemon switches out, should be the opposite order.
// Not an easy fix since we cant use a supported event. Would need some kind of special event that
// gathers events to run after the switch and then runs them when the ability is no longer accessible.
// (If you're tackling this, do note extreme weathers have the same issue)
// Mark this pokemon's ability as ending so Pokemon#ignoringAbility skips it
if (source.abilityState.ending) return;
source.abilityState.ending = true;
const sortedActive = this.getAllActive();
this.speedSort(sortedActive);
for (const pokemon of sortedActive) {
if (pokemon !== source) {
if (pokemon.getAbility().isPermanent) continue; // does not interact with e.g Ice Face, Zen Mode
// Will be suppressed by Pokemon#ignoringAbility if needed
this.singleEvent('Start', pokemon.getAbility(), pokemon.abilityState, pokemon);
}
}
},
name: "Neutralizing Gas",
rating: 4,
num: 256,
},
noguard: {
onAnyInvulnerabilityPriority: 1,
onAnyInvulnerability(target, source, move) {
if (move && (source === this.effectState.target || target === this.effectState.target)) return 0;
},
onAnyAccuracy(accuracy, target, source, move) {
if (move && (source === this.effectState.target || target === this.effectState.target)) {
return true;
}
return accuracy;
},
name: "No Guard",
rating: 4,
num: 99,
},
normalize: {
onModifyTypePriority: 1,
onModifyType(move, pokemon) {
const noModifyType = [
'hiddenpower', 'judgment', 'multiattack', 'naturalgift', 'revelationdance', 'struggle', 'technoblast', 'terrainpulse', 'weatherball',
];
if (!(move.isZ && move.category !== 'Status') && !noModifyType.includes(move.id)) {
move.type = 'Normal';
move.normalizeBoosted = true;
}
},
onBasePowerPriority: 23,
onBasePower(basePower, pokemon, target, move) {
if (move.normalizeBoosted) return this.chainModify([4915, 4096]);
},
name: "Normalize",
rating: 0,
num: 96,
},
oblivious: {
onUpdate(pokemon) {
if (pokemon.volatiles['attract']) {
this.add('-activate', pokemon, 'ability: Oblivious');
pokemon.removeVolatile('attract');
this.add('-end', pokemon, 'move: Attract', '[from] ability: Oblivious');
}
if (pokemon.volatiles['taunt']) {
this.add('-activate', pokemon, 'ability: Oblivious');
pokemon.removeVolatile('taunt');
// Taunt's volatile already sends the -end message when removed
}
},
onImmunity(type, pokemon) {
if (type === 'attract') return false;
},
onTryHit(pokemon, target, move) {
if (move.id === 'attract' || move.id === 'captivate' || move.id === 'taunt') {
this.add('-immune', pokemon, '[from] ability: Oblivious');
return null;
}
},
onBoost(boost, target, source, effect) {
if (effect.id === 'intimidate') {
delete boost.atk;
this.add('-fail', target, 'unboost', 'Attack', '[from] ability: Oblivious', '[of] ' + target);
}
},
isBreakable: true,
name: "Oblivious",
rating: 1.5,
num: 12,
},
overcoat: {
onImmunity(type, pokemon) {
if (type === 'sandstorm' || type === 'hail' || type === 'powder') return false;
},
onTryHitPriority: 1,
onTryHit(target, source, move) {
if (move.flags['powder'] && target !== source && this.dex.getImmunity('powder', target)) {
this.add('-immune', target, '[from] ability: Overcoat');
return null;
}
},
isBreakable: true,
name: "Overcoat",
rating: 2,
num: 142,
},
overgrow: {
onModifyAtkPriority: 5,
onModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Overgrow boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, attacker, defender, move) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Overgrow boost');
return this.chainModify(1.5);
}
},
name: "Overgrow",
rating: 2,
num: 65,
},
owntempo: {
onUpdate(pokemon) {
if (pokemon.volatiles['confusion']) {
this.add('-activate', pokemon, 'ability: Own Tempo');
pokemon.removeVolatile('confusion');
}
},
onTryAddVolatile(status, pokemon) {
if (status.id === 'confusion') return null;
},
onHit(target, source, move) {
if (move?.volatileStatus === 'confusion') {
this.add('-immune', target, 'confusion', '[from] ability: Own Tempo');
}
},
onBoost(boost, target, source, effect) {
if (effect.id === 'intimidate') {
delete boost.atk;
this.add('-fail', target, 'unboost', 'Attack', '[from] ability: Own Tempo', '[of] ' + target);
}
},
isBreakable: true,
name: "Own Tempo",
rating: 1.5,
num: 20,
},
parentalbond: {
onPrepareHit(source, target, move) {
if (move.category === 'Status' || move.selfdestruct || move.multihit) return;
if (['endeavor', 'fling', 'iceball', 'rollout'].includes(move.id)) return;
if (!move.flags['charge'] && !move.spreadHit && !move.isZ && !move.isMax) {
move.multihit = 2;
move.multihitType = 'parentalbond';
}
},
// Damage modifier implemented in BattleActions#modifyDamage()
onSourceModifySecondaries(secondaries, target, source, move) {
if (move.multihitType === 'parentalbond' && move.id === 'secretpower' && move.hit < 2) {
// hack to prevent accidentally suppressing King's Rock/Razor Fang
return secondaries.filter(effect => effect.volatileStatus === 'flinch');
}
},
name: "Parental Bond",
rating: 4.5,
num: 185,
},
pastelveil: {
onStart(pokemon) {
for (const ally of pokemon.alliesAndSelf()) {
if (['psn', 'tox'].includes(ally.status)) {
this.add('-activate', pokemon, 'ability: Pastel Veil');
ally.cureStatus();
}
}
},
onUpdate(pokemon) {
if (['psn', 'tox'].includes(pokemon.status)) {
this.add('-activate', pokemon, 'ability: Pastel Veil');
pokemon.cureStatus();
}
},
onAllySwitchIn(pokemon) {
if (['psn', 'tox'].includes(pokemon.status)) {
this.add('-activate', this.effectState.target, 'ability: Pastel Veil');
pokemon.cureStatus();
}
},
onSetStatus(status, target, source, effect) {
if (!['psn', 'tox'].includes(status.id)) return;
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Pastel Veil');
}
return false;
},
onAllySetStatus(status, target, source, effect) {
if (!['psn', 'tox'].includes(status.id)) return;
if ((effect as Move)?.status) {
const effectHolder = this.effectState.target;
this.add('-block', target, 'ability: Pastel Veil', '[of] ' + effectHolder);
}
return false;
},
isBreakable: true,
name: "Pastel Veil",
rating: 2,
num: 257,
},
perishbody: {
onDamagingHit(damage, target, source, move) {
if (!this.checkMoveMakesContact(move, source, target)) return;
let announced = false;
for (const pokemon of [target, source]) {
if (pokemon.volatiles['perishsong']) continue;
if (!announced) {
this.add('-ability', target, 'Perish Body');
announced = true;
}
pokemon.addVolatile('perishsong');
}
},
name: "Perish Body",
rating: 1,
num: 253,
},
pickpocket: {
onAfterMoveSecondary(target, source, move) {
if (source && source !== target && move?.flags['contact']) {
if (target.item || target.switchFlag || target.forceSwitchFlag || source.switchFlag === true) {
return;
}
const yourItem = source.takeItem(target);
if (!yourItem) {
return;
}
if (!target.setItem(yourItem)) {
source.item = yourItem.id;
return;
}
this.add('-enditem', source, yourItem, '[silent]', '[from] ability: Pickpocket', '[of] ' + source);
this.add('-item', target, yourItem, '[from] ability: Pickpocket', '[of] ' + source);
}
},
name: "Pickpocket",
rating: 1,
num: 124,
},
pickup: {
onResidualOrder: 28,
onResidualSubOrder: 2,
onResidual(pokemon) {
if (pokemon.item) return;
const pickupTargets = this.getAllActive().filter(target => (
target.lastItem && target.usedItemThisTurn && pokemon.isAdjacent(target)
));
if (!pickupTargets.length) return;
const randomTarget = this.sample(pickupTargets);
const item = randomTarget.lastItem;
randomTarget.lastItem = '';
this.add('-item', pokemon, this.dex.items.get(item), '[from] ability: Pickup');
pokemon.setItem(item);
},
name: "Pickup",
rating: 0.5,
num: 53,
},
pixilate: {
onModifyTypePriority: -1,
onModifyType(move, pokemon) {
const noModifyType = [
'judgment', 'multiattack', 'naturalgift', 'revelationdance', 'technoblast', 'terrainpulse', 'weatherball',
];
if (move.type === 'Normal' && !noModifyType.includes(move.id) && !(move.isZ && move.category !== 'Status')) {
move.type = 'Fairy';
move.pixilateBoosted = true;
}
},
onBasePowerPriority: 23,
onBasePower(basePower, pokemon, target, move) {
if (move.pixilateBoosted) return this.chainModify([4915, 4096]);
},
name: "Pixilate",
rating: 4,
num: 182,
},
plus: {
onModifySpAPriority: 5,
onModifySpA(spa, pokemon) {
for (const allyActive of pokemon.allies()) {
if (allyActive.hasAbility(['minus', 'plus'])) {
return this.chainModify(1.5);
}
}
},
name: "Plus",
rating: 0,
num: 57,
},
poisonheal: {
onDamagePriority: 1,
onDamage(damage, target, source, effect) {
if (effect.id === 'psn' || effect.id === 'tox') {
this.heal(target.baseMaxhp / 8);
return false;
}
},
name: "Poison Heal",
rating: 4,
num: 90,
},
poisonpoint: {
onDamagingHit(damage, target, source, move) {
if (this.checkMoveMakesContact(move, source, target)) {
if (this.randomChance(3, 10)) {
source.trySetStatus('psn', target);
}
}
},
name: "Poison Point",
rating: 1.5,
num: 38,
},
poisontouch: {
// upokecenter says this is implemented as an added secondary effect
onModifyMove(move) {
if (!move?.flags['contact'] || move.target === 'self') return;
if (!move.secondaries) {
move.secondaries = [];
}
move.secondaries.push({
chance: 30,
status: 'psn',
ability: this.dex.abilities.get('poisontouch'),
});
},
name: "Poison Touch",
rating: 2,
num: 143,
},
powerconstruct: {
onResidualOrder: 29,
onResidual(pokemon) {
if (pokemon.baseSpecies.baseSpecies !== 'Zygarde' || pokemon.transformed || !pokemon.hp) return;
if (pokemon.species.id === 'zygardecomplete' || pokemon.hp > pokemon.maxhp / 2) return;
this.add('-activate', pokemon, 'ability: Power Construct');
pokemon.formeChange('Zygarde-Complete', this.effect, true);
pokemon.baseMaxhp = Math.floor(Math.floor(
2 * pokemon.species.baseStats['hp'] + pokemon.set.ivs['hp'] + Math.floor(pokemon.set.evs['hp'] / 4) + 100
) * pokemon.level / 100 + 10);
const newMaxHP = pokemon.volatiles['dynamax'] ? (2 * pokemon.baseMaxhp) : pokemon.baseMaxhp;
pokemon.hp = newMaxHP - (pokemon.maxhp - pokemon.hp);
pokemon.maxhp = newMaxHP;
this.add('-heal', pokemon, pokemon.getHealth, '[silent]');
},
isPermanent: true,
name: "Power Construct",
rating: 5,
num: 211,
},
powerofalchemy: {
onAllyFaint(target) {
if (!this.effectState.target.hp) return;
const ability = target.getAbility();
const additionalBannedAbilities = [
'noability', 'flowergift', 'forecast', 'hungerswitch', 'illusion', 'imposter', 'neutralizinggas', 'powerofalchemy', 'receiver', 'trace', 'wonderguard',
];
if (target.getAbility().isPermanent || additionalBannedAbilities.includes(target.ability)) return;
this.add('-ability', this.effectState.target, ability, '[from] ability: Power of Alchemy', '[of] ' + target);
this.effectState.target.setAbility(ability);
},
name: "Power of Alchemy",
rating: 0,
num: 223,
},
powerspot: {
onAllyBasePowerPriority: 22,
onAllyBasePower(basePower, attacker, defender, move) {
if (attacker !== this.effectState.target) {
this.debug('Power Spot boost');
return this.chainModify([5325, 4096]);
}
},
name: "Power Spot",
rating: 1,
num: 249,
},
prankster: {
onModifyPriority(priority, pokemon, target, move) {
if (move?.category === 'Status') {
move.pranksterBoosted = true;
return priority + 1;
}
},
name: "Prankster",
rating: 4,
num: 158,
},
pressure: {
onStart(pokemon) {
this.add('-ability', pokemon, 'Pressure');
},
onDeductPP(target, source) {
if (target.isAlly(source)) return;
return 1;
},
name: "Pressure",
rating: 2.5,
num: 46,
},
primordialsea: {
onStart(source) {
this.field.setWeather('primordialsea');
},
onAnySetWeather(target, source, weather) {
const strongWeathers = ['desolateland', 'primordialsea', 'deltastream'];
if (this.field.getWeather().id === 'primordialsea' && !strongWeathers.includes(weather.id)) return false;
},
onEnd(pokemon) {
if (this.field.weatherState.source !== pokemon) return;
for (const target of this.getAllActive()) {
if (target === pokemon) continue;
if (target.hasAbility('primordialsea')) {
this.field.weatherState.source = target;
return;
}
}
this.field.clearWeather();
},
name: "Primordial Sea",
rating: 4.5,
num: 189,
},
prismarmor: {
onSourceModifyDamage(damage, source, target, move) {
if (target.getMoveHitData(move).typeMod > 0) {
this.debug('Prism Armor neutralize');
return this.chainModify(0.75);
}
},
name: "Prism Armor",
rating: 3,
num: 232,
},
propellertail: {
onModifyMovePriority: 1,
onModifyMove(move) {
// most of the implementation is in Battle#getTarget
move.tracksTarget = move.target !== 'scripted';
},
name: "Propeller Tail",
rating: 0,
num: 239,
},
protean: {
onPrepareHit(source, target, move) {
if (move.hasBounced || move.sourceEffect === 'snatch') return;
const type = move.type;
if (type && type !== '???' && source.getTypes().join() !== type) {
if (!source.setType(type)) return;
this.add('-start', source, 'typechange', type, '[from] ability: Protean');
}
},
name: "Protean",
rating: 4.5,
num: 168,
},
psychicsurge: {
onStart(source) {
this.field.setTerrain('psychicterrain');
},
name: "Psychic Surge",
rating: 4,
num: 227,
},
punkrock: {
onBasePowerPriority: 7,
onBasePower(basePower, attacker, defender, move) {
if (move.flags['sound']) {
this.debug('Punk Rock boost');
return this.chainModify([5325, 4096]);
}
},
onSourceModifyDamage(damage, source, target, move) {
if (move.flags['sound']) {
this.debug('Punk Rock weaken');
return this.chainModify(0.5);
}
},
isBreakable: true,
name: "Punk Rock",
rating: 3.5,
num: 244,
},
purepower: {
onModifyAtkPriority: 5,
onModifyAtk(atk) {
return this.chainModify(2);
},
name: "Pure Power",
rating: 5,
num: 74,
},
queenlymajesty: {
onFoeTryMove(target, source, move) {
const targetAllExceptions = ['perishsong', 'flowershield', 'rototiller'];
if (move.target === 'foeSide' || (move.target === 'all' && !targetAllExceptions.includes(move.id))) {
return;
}
const dazzlingHolder = this.effectState.target;
if ((source.isAlly(dazzlingHolder) || move.target === 'all') && move.priority > 0.1) {
this.attrLastMove('[still]');
this.add('cant', dazzlingHolder, 'ability: Queenly Majesty', move, '[of] ' + target);
return false;
}
},
isBreakable: true,
name: "Queenly Majesty",
rating: 2.5,
num: 214,
},
quickdraw: {
onFractionalPriorityPriority: -1,
onFractionalPriority(priority, pokemon, target, move) {
if (move.category !== "Status" && this.randomChance(3, 10)) {
this.add('-activate', pokemon, 'ability: Quick Draw');
return 0.1;
}
},
name: "Quick Draw",
rating: 2.5,
num: 259,
},
quickfeet: {
onModifySpe(spe, pokemon) {
if (pokemon.status) {
return this.chainModify(1.5);
}
},
name: "Quick Feet",
rating: 2.5,
num: 95,
},
raindish: {
onWeather(target, source, effect) {
if (target.hasItem('utilityumbrella')) return;
if (effect.id === 'raindance' || effect.id === 'primordialsea') {
this.heal(target.baseMaxhp / 16);
}
},
name: "Rain Dish",
rating: 1.5,
num: 44,
},
rattled: {
onDamagingHit(damage, target, source, move) {
if (['Dark', 'Bug', 'Ghost'].includes(move.type)) {
this.boost({spe: 1});
}
},
onAfterBoost(boost, target, source, effect) {
if (effect && effect.id === 'intimidate') {
this.boost({spe: 1});
}
},
name: "Rattled",
rating: 1.5,
num: 155,
},
receiver: {
onAllyFaint(target) {
if (!this.effectState.target.hp) return;
const ability = target.getAbility();
const additionalBannedAbilities = [
'noability', 'flowergift', 'forecast', 'hungerswitch', 'illusion', 'imposter', 'neutralizinggas', 'powerofalchemy', 'receiver', 'trace', 'wonderguard',
];
if (target.getAbility().isPermanent || additionalBannedAbilities.includes(target.ability)) return;
this.add('-ability', this.effectState.target, ability, '[from] ability: Receiver', '[of] ' + target);
this.effectState.target.setAbility(ability);
},
name: "Receiver",
rating: 0,
num: 222,
},
reckless: {
onBasePowerPriority: 23,
onBasePower(basePower, attacker, defender, move) {
if (move.recoil || move.hasCrashDamage) {
this.debug('Reckless boost');
return this.chainModify([4915, 4096]);
}
},
name: "Reckless",
rating: 3,
num: 120,
},
refrigerate: {
onModifyTypePriority: -1,
onModifyType(move, pokemon) {
const noModifyType = [
'judgment', 'multiattack', 'naturalgift', 'revelationdance', 'technoblast', 'terrainpulse', 'weatherball',
];
if (move.type === 'Normal' && !noModifyType.includes(move.id) && !(move.isZ && move.category !== 'Status')) {
move.type = 'Ice';
move.refrigerateBoosted = true;
}
},
onBasePowerPriority: 23,
onBasePower(basePower, pokemon, target, move) {
if (move.refrigerateBoosted) return this.chainModify([4915, 4096]);
},
name: "Refrigerate",
rating: 4,
num: 174,
},
regenerator: {
onSwitchOut(pokemon) {
pokemon.heal(pokemon.baseMaxhp / 3);
},
name: "Regenerator",
rating: 4.5,
num: 144,
},
ripen: {
onTryHeal(damage, target, source, effect) {
if (!effect) return;
if (effect.id === 'berryjuice' || effect.id === 'leftovers') {
this.add('-activate', target, 'ability: Ripen');
}
if ((effect as Item).isBerry) return this.chainModify(2);
},
onBoost(boost, target, source, effect) {
if (effect && (effect as Item).isBerry) {
let b: BoostID;
for (b in boost) {
boost[b]! *= 2;
}
}
},
onSourceModifyDamagePriority: -1,
onSourceModifyDamage(damage, source, target, move) {
if (target.abilityState.berryWeaken) {
target.abilityState.berryWeaken = false;
return this.chainModify(0.5);
}
},
onTryEatItemPriority: -1,
onTryEatItem(item, pokemon) {
this.add('-activate', pokemon, 'ability: Ripen');
},
onEatItem(item, pokemon) {
const weakenBerries = [
'Babiri Berry', 'Charti Berry', 'Chilan Berry', 'Chople Berry', 'Coba Berry', 'Colbur Berry', 'Haban Berry', 'Kasib Berry', 'Kebia Berry', 'Occa Berry', 'Passho Berry', 'Payapa Berry', 'Rindo Berry', 'Roseli Berry', 'Shuca Berry', 'Tanga Berry', 'Wacan Berry', 'Yache Berry',
];
// Record if the pokemon ate a berry to resist the attack
pokemon.abilityState.berryWeaken = weakenBerries.includes(item.name);
},
name: "Ripen",
rating: 2,
num: 247,
},
rivalry: {
onBasePowerPriority: 24,
onBasePower(basePower, attacker, defender, move) {
if (attacker.gender && defender.gender) {
if (attacker.gender === defender.gender) {
this.debug('Rivalry boost');
return this.chainModify(1.25);
} else {
this.debug('Rivalry weaken');
return this.chainModify(0.75);
}
}
},
name: "Rivalry",
rating: 0,
num: 79,
},
rkssystem: {
// RKS System's type-changing itself is implemented in statuses.js
isPermanent: true,
name: "RKS System",
rating: 4,
num: 225,
},
rockhead: {
onDamage(damage, target, source, effect) {
if (effect.id === 'recoil') {
if (!this.activeMove) throw new Error("Battle.activeMove is null");
if (this.activeMove.id !== 'struggle') return null;
}
},
name: "Rock Head",
rating: 3,
num: 69,
},
roughskin: {
onDamagingHitOrder: 1,
onDamagingHit(damage, target, source, move) {
if (this.checkMoveMakesContact(move, source, target, true)) {
this.damage(source.baseMaxhp / 8, source, target);
}
},
name: "Rough Skin",
rating: 2.5,
num: 24,
},
runaway: {
name: "Run Away",
rating: 0,
num: 50,
},
sandforce: {
onBasePowerPriority: 21,
onBasePower(basePower, attacker, defender, move) {
if (this.field.isWeather('sandstorm')) {
if (move.type === 'Rock' || move.type === 'Ground' || move.type === 'Steel') {
this.debug('Sand Force boost');
return this.chainModify([5325, 4096]);
}
}
},
onImmunity(type, pokemon) {
if (type === 'sandstorm') return false;
},
name: "Sand Force",
rating: 2,
num: 159,
},
sandrush: {
onModifySpe(spe, pokemon) {
if (this.field.isWeather('sandstorm')) {
return this.chainModify(2);
}
},
onImmunity(type, pokemon) {
if (type === 'sandstorm') return false;
},
name: "Sand Rush",
rating: 3,
num: 146,
},
sandspit: {
onDamagingHit(damage, target, source, move) {
if (this.field.getWeather().id !== 'sandstorm') {
this.field.setWeather('sandstorm');
}
},
name: "Sand Spit",
rating: 2,
num: 245,
},
sandstream: {
onStart(source) {
this.field.setWeather('sandstorm');
},
name: "Sand Stream",
rating: 4,
num: 45,
},
sandveil: {
onImmunity(type, pokemon) {
if (type === 'sandstorm') return false;
},
onModifyAccuracyPriority: -1,
onModifyAccuracy(accuracy) {
if (typeof accuracy !== 'number') return;
if (this.field.isWeather('sandstorm')) {
this.debug('Sand Veil - decreasing accuracy');
return this.chainModify([3277, 4096]);
}
},
isBreakable: true,
name: "Sand Veil",
rating: 1.5,
num: 8,
},
sapsipper: {
onTryHitPriority: 1,
onTryHit(target, source, move) {
if (target !== source && move.type === 'Grass') {
if (!this.boost({atk: 1})) {
this.add('-immune', target, '[from] ability: Sap Sipper');
}
return null;
}
},
onAllyTryHitSide(target, source, move) {
if (source === this.effectState.target || !target.isAlly(source)) return;
if (move.type === 'Grass') {
this.boost({atk: 1}, this.effectState.target);
}
},
isBreakable: true,
name: "Sap Sipper",
rating: 3,
num: 157,
},
schooling: {
onStart(pokemon) {
if (pokemon.baseSpecies.baseSpecies !== 'Wishiwashi' || pokemon.level < 20 || pokemon.transformed) return;
if (pokemon.hp > pokemon.maxhp / 4) {
if (pokemon.species.id === 'wishiwashi') {
pokemon.formeChange('Wishiwashi-School');
}
} else {
if (pokemon.species.id === 'wishiwashischool') {
pokemon.formeChange('Wishiwashi');
}
}
},
onResidualOrder: 29,
onResidual(pokemon) {
if (
pokemon.baseSpecies.baseSpecies !== 'Wishiwashi' || pokemon.level < 20 ||
pokemon.transformed || !pokemon.hp
) return;
if (pokemon.hp > pokemon.maxhp / 4) {
if (pokemon.species.id === 'wishiwashi') {
pokemon.formeChange('Wishiwashi-School');
}
} else {
if (pokemon.species.id === 'wishiwashischool') {
pokemon.formeChange('Wishiwashi');
}
}
},
isPermanent: true,
name: "Schooling",
rating: 3,
num: 208,
},
scrappy: {
onModifyMovePriority: -5,
onModifyMove(move) {
if (!move.ignoreImmunity) move.ignoreImmunity = {};
if (move.ignoreImmunity !== true) {
move.ignoreImmunity['Fighting'] = true;
move.ignoreImmunity['Normal'] = true;
}
},
onBoost(boost, target, source, effect) {
if (effect.id === 'intimidate') {
delete boost.atk;
this.add('-fail', target, 'unboost', 'Attack', '[from] ability: Scrappy', '[of] ' + target);
}
},
name: "Scrappy",
rating: 3,
num: 113,
},
screencleaner: {
onStart(pokemon) {
let activated = false;
for (const sideCondition of ['reflect', 'lightscreen', 'auroraveil']) {
for (const side of [pokemon.side, ...pokemon.side.foeSidesWithConditions()]) {
if (side.getSideCondition(sideCondition)) {
if (!activated) {
this.add('-activate', pokemon, 'ability: Screen Cleaner');
activated = true;
}
side.removeSideCondition(sideCondition);
}
}
}
},
name: "Screen Cleaner",
rating: 2,
num: 251,
},
serenegrace: {
onModifyMovePriority: -2,
onModifyMove(move) {
if (move.secondaries) {
this.debug('doubling secondary chance');
for (const secondary of move.secondaries) {
if (secondary.chance) secondary.chance *= 2;
}
}
if (move.self?.chance) move.self.chance *= 2;
},
name: "Serene Grace",
rating: 3.5,
num: 32,
},
shadowshield: {
onSourceModifyDamage(damage, source, target, move) {
if (target.hp >= target.maxhp) {
this.debug('Shadow Shield weaken');
return this.chainModify(0.5);
}
},
name: "Shadow Shield",
rating: 3.5,
num: 231,
},
shadowtag: {
onFoeTrapPokemon(pokemon) {
if (!pokemon.hasAbility('shadowtag') && pokemon.isAdjacent(this.effectState.target)) {
pokemon.tryTrap(true);
}
},
onFoeMaybeTrapPokemon(pokemon, source) {
if (!source) source = this.effectState.target;
if (!source || !pokemon.isAdjacent(source)) return;
if (!pokemon.hasAbility('shadowtag')) {
pokemon.maybeTrapped = true;
}
},
name: "Shadow Tag",
rating: 5,
num: 23,
},
shedskin: {
onResidualOrder: 5,
onResidualSubOrder: 3,
onResidual(pokemon) {
if (pokemon.hp && pokemon.status && this.randomChance(33, 100)) {
this.debug('shed skin');
this.add('-activate', pokemon, 'ability: Shed Skin');
pokemon.cureStatus();
}
},
name: "Shed Skin",
rating: 3,
num: 61,
},
sheerforce: {
onModifyMove(move, pokemon) {
if (move.secondaries) {
delete move.secondaries;
// Technically not a secondary effect, but it is negated
delete move.self;
if (move.id === 'clangoroussoulblaze') delete move.selfBoost;
// Actual negation of `AfterMoveSecondary` effects implemented in scripts.js
move.hasSheerForce = true;
}
},
onBasePowerPriority: 21,
onBasePower(basePower, pokemon, target, move) {
if (move.hasSheerForce) return this.chainModify([5325, 4096]);
},
name: "Sheer Force",
rating: 3.5,
num: 125,
},
shellarmor: {
onCriticalHit: false,
isBreakable: true,
name: "Shell Armor",
rating: 1,
num: 75,
},
shielddust: {
onModifySecondaries(secondaries) {
this.debug('Shield Dust prevent secondary');
return secondaries.filter(effect => !!(effect.self || effect.dustproof));
},
isBreakable: true,
name: "Shield Dust",
rating: 2,
num: 19,
},
shieldsdown: {
onStart(pokemon) {
if (pokemon.baseSpecies.baseSpecies !== 'Minior' || pokemon.transformed) return;
if (pokemon.hp > pokemon.maxhp / 2) {
if (pokemon.species.forme !== 'Meteor') {
pokemon.formeChange('Minior-Meteor');
}
} else {
if (pokemon.species.forme === 'Meteor') {
pokemon.formeChange(pokemon.set.species);
}
}
},
onResidualOrder: 29,
onResidual(pokemon) {
if (pokemon.baseSpecies.baseSpecies !== 'Minior' || pokemon.transformed || !pokemon.hp) return;
if (pokemon.hp > pokemon.maxhp / 2) {
if (pokemon.species.forme !== 'Meteor') {
pokemon.formeChange('Minior-Meteor');
}
} else {
if (pokemon.species.forme === 'Meteor') {
pokemon.formeChange(pokemon.set.species);
}
}
},
onSetStatus(status, target, source, effect) {
if (target.species.id !== 'miniormeteor' || target.transformed) return;
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Shields Down');
}
return false;
},
onTryAddVolatile(status, target) {
if (target.species.id !== 'miniormeteor' || target.transformed) return;
if (status.id !== 'yawn') return;
this.add('-immune', target, '[from] ability: Shields Down');
return null;
},
isPermanent: true,
name: "Shields Down",
rating: 3,
num: 197,
},
simple: {
onBoost(boost, target, source, effect) {
if (effect && effect.id === 'zpower') return;
let i: BoostID;
for (i in boost) {
boost[i]! *= 2;
}
},
isBreakable: true,
name: "Simple",
rating: 4,
num: 86,
},
skilllink: {
onModifyMove(move) {
if (move.multihit && Array.isArray(move.multihit) && move.multihit.length) {
move.multihit = move.multihit[1];
}
if (move.multiaccuracy) {
delete move.multiaccuracy;
}
},
name: "Skill Link",
rating: 3,
num: 92,
},
slowstart: {
onStart(pokemon) {
pokemon.addVolatile('slowstart');
},
onEnd(pokemon) {
delete pokemon.volatiles['slowstart'];
this.add('-end', pokemon, 'Slow Start', '[silent]');
},
condition: {
duration: 5,
onResidualOrder: 28,
onResidualSubOrder: 2,
onStart(target) {
this.add('-start', target, 'ability: Slow Start');
},
onModifyAtkPriority: 5,
onModifyAtk(atk, pokemon) {
return this.chainModify(0.5);
},
onModifySpe(spe, pokemon) {
return this.chainModify(0.5);
},
onEnd(target) {
this.add('-end', target, 'Slow Start');
},
},
name: "Slow Start",
rating: -1,
num: 112,
},
slushrush: {
onModifySpe(spe, pokemon) {
if (this.field.isWeather('hail')) {
return this.chainModify(2);
}
},
name: "Slush Rush",
rating: 3,
num: 202,
},
sniper: {
onModifyDamage(damage, source, target, move) {
if (target.getMoveHitData(move).crit) {
this.debug('Sniper boost');
return this.chainModify(1.5);
}
},
name: "Sniper",
rating: 2,
num: 97,
},
snowcloak: {
onImmunity(type, pokemon) {
if (type === 'hail') return false;
},
onModifyAccuracyPriority: -1,
onModifyAccuracy(accuracy) {
if (typeof accuracy !== 'number') return;
if (this.field.isWeather('hail')) {
this.debug('Snow Cloak - decreasing accuracy');
return this.chainModify([3277, 4096]);
}
},
isBreakable: true,
name: "Snow Cloak",
rating: 1.5,
num: 81,
},
snowwarning: {
onStart(source) {
this.field.setWeather('hail');
},
name: "Snow Warning",
rating: 4,
num: 117,
},
solarpower: {
onModifySpAPriority: 5,
onModifySpA(spa, pokemon) {
if (['sunnyday', 'desolateland'].includes(pokemon.effectiveWeather())) {
return this.chainModify(1.5);
}
},
onWeather(target, source, effect) {
if (target.hasItem('utilityumbrella')) return;
if (effect.id === 'sunnyday' || effect.id === 'desolateland') {
this.damage(target.baseMaxhp / 8, target, target);
}
},
name: "Solar Power",
rating: 2,
num: 94,
},
solidrock: {
onSourceModifyDamage(damage, source, target, move) {
if (target.getMoveHitData(move).typeMod > 0) {
this.debug('Solid Rock neutralize');
return this.chainModify(0.75);
}
},
isBreakable: true,
name: "Solid Rock",
rating: 3,
num: 116,
},
soulheart: {
onAnyFaintPriority: 1,
onAnyFaint() {
this.boost({spa: 1}, this.effectState.target);
},
name: "Soul-Heart",
rating: 3.5,
num: 220,
},
soundproof: {
onTryHit(target, source, move) {
if (target !== source && move.flags['sound']) {
this.add('-immune', target, '[from] ability: Soundproof');
return null;
}
},
onAllyTryHitSide(target, source, move) {
if (move.flags['sound']) {
this.add('-immune', this.effectState.target, '[from] ability: Soundproof');
}
},
isBreakable: true,
name: "Soundproof",
rating: 1.5,
num: 43,
},
speedboost: {
onResidualOrder: 28,
onResidualSubOrder: 2,
onResidual(pokemon) {
if (pokemon.activeTurns) {
this.boost({spe: 1});
}
},
name: "Speed Boost",
rating: 4.5,
num: 3,
},
stakeout: {
onModifyAtkPriority: 5,
onModifyAtk(atk, attacker, defender) {
if (!defender.activeTurns) {
this.debug('Stakeout boost');
return this.chainModify(2);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, attacker, defender) {
if (!defender.activeTurns) {
this.debug('Stakeout boost');
return this.chainModify(2);
}
},
name: "Stakeout",
rating: 4.5,
num: 198,
},
stall: {
onFractionalPriority: -0.1,
name: "Stall",
rating: -1,
num: 100,
},
stalwart: {
onModifyMovePriority: 1,
onModifyMove(move) {
// most of the implementation is in Battle#getTarget
move.tracksTarget = move.target !== 'scripted';
},
name: "Stalwart",
rating: 0,
num: 242,
},
stamina: {
onDamagingHit(damage, target, source, effect) {
this.boost({def: 1});
},
name: "Stamina",
rating: 3.5,
num: 192,
},
stancechange: {
onModifyMovePriority: 1,
onModifyMove(move, attacker, defender) {
if (attacker.species.baseSpecies !== 'Aegislash' || attacker.transformed) return;
if (move.category === 'Status' && move.id !== 'kingsshield') return;
const targetForme = (move.id === 'kingsshield' ? 'Aegislash' : 'Aegislash-Blade');
if (attacker.species.name !== targetForme) attacker.formeChange(targetForme);
},
isPermanent: true,
name: "Stance Change",
rating: 4,
num: 176,
},
static: {
onDamagingHit(damage, target, source, move) {
if (this.checkMoveMakesContact(move, source, target)) {
if (this.randomChance(3, 10)) {
source.trySetStatus('par', target);
}
}
},
name: "Static",
rating: 2,
num: 9,
},
steadfast: {
onFlinch(pokemon) {
this.boost({spe: 1});
},
name: "Steadfast",
rating: 1,
num: 80,
},
steamengine: {
onDamagingHit(damage, target, source, move) {
if (['Water', 'Fire'].includes(move.type)) {
this.boost({spe: 6});
}
},
name: "Steam Engine",
rating: 2,
num: 243,
},
steelworker: {
onModifyAtkPriority: 5,
onModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Steel') {
this.debug('Steelworker boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, attacker, defender, move) {
if (move.type === 'Steel') {
this.debug('Steelworker boost');
return this.chainModify(1.5);
}
},
name: "Steelworker",
rating: 3.5,
num: 200,
},
steelyspirit: {
onAllyBasePowerPriority: 22,
onAllyBasePower(basePower, attacker, defender, move) {
if (move.type === 'Steel') {
this.debug('Steely Spirit boost');
return this.chainModify(1.5);
}
},
name: "Steely Spirit",
rating: 3.5,
num: 252,
},
stench: {
onModifyMovePriority: -1,
onModifyMove(move) {
if (move.category !== "Status") {
this.debug('Adding Stench flinch');
if (!move.secondaries) move.secondaries = [];
for (const secondary of move.secondaries) {
if (secondary.volatileStatus === 'flinch') return;
}
move.secondaries.push({
chance: 10,
volatileStatus: 'flinch',
});
}
},
name: "Stench",
rating: 0.5,
num: 1,
},
stickyhold: {
onTakeItem(item, pokemon, source) {
if (!this.activeMove) throw new Error("Battle.activeMove is null");
if (!pokemon.hp || pokemon.item === 'stickybarb') return;
if ((source && source !== pokemon) || this.activeMove.id === 'knockoff') {
this.add('-activate', pokemon, 'ability: Sticky Hold');
return false;
}
},
isBreakable: true,
name: "Sticky Hold",
rating: 2,
num: 60,
},
stormdrain: {
onTryHit(target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.boost({spa: 1})) {
this.add('-immune', target, '[from] ability: Storm Drain');
}
return null;
}
},
onAnyRedirectTarget(target, source, source2, move) {
if (move.type !== 'Water' || ['firepledge', 'grasspledge', 'waterpledge'].includes(move.id)) return;
const redirectTarget = ['randomNormal', 'adjacentFoe'].includes(move.target) ? 'normal' : move.target;
if (this.validTarget(this.effectState.target, source, redirectTarget)) {
if (move.smartTarget) move.smartTarget = false;
if (this.effectState.target !== target) {
this.add('-activate', this.effectState.target, 'ability: Storm Drain');
}
return this.effectState.target;
}
},
isBreakable: true,
name: "Storm Drain",
rating: 3,
num: 114,
},
strongjaw: {
onBasePowerPriority: 19,
onBasePower(basePower, attacker, defender, move) {
if (move.flags['bite']) {
return this.chainModify(1.5);
}
},
name: "Strong Jaw",
rating: 3,
num: 173,
},
sturdy: {
onTryHit(pokemon, target, move) {
if (move.ohko) {
this.add('-immune', pokemon, '[from] ability: Sturdy');
return null;
}
},
onDamagePriority: -30,
onDamage(damage, target, source, effect) {
if (target.hp === target.maxhp && damage >= target.hp && effect && effect.effectType === 'Move') {
this.add('-ability', target, 'Sturdy');
return target.hp - 1;
}
},
isBreakable: true,
name: "Sturdy",
rating: 3,
num: 5,
},
suctioncups: {
onDragOutPriority: 1,
onDragOut(pokemon) {
this.add('-activate', pokemon, 'ability: Suction Cups');
return null;
},
isBreakable: true,
name: "Suction Cups",
rating: 1,
num: 21,
},
superluck: {
onModifyCritRatio(critRatio) {
return critRatio + 1;
},
name: "Super Luck",
rating: 1.5,
num: 105,
},
surgesurfer: {
onModifySpe(spe) {
if (this.field.isTerrain('electricterrain')) {
return this.chainModify(2);
}
},
name: "Surge Surfer",
rating: 3,
num: 207,
},
swarm: {
onModifyAtkPriority: 5,
onModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Swarm boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, attacker, defender, move) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Swarm boost');
return this.chainModify(1.5);
}
},
name: "Swarm",
rating: 2,
num: 68,
},
sweetveil: {
name: "Sweet Veil",
onAllySetStatus(status, target, source, effect) {
if (status.id === 'slp') {
this.debug('Sweet Veil interrupts sleep');
const effectHolder = this.effectState.target;
this.add('-block', target, 'ability: Sweet Veil', '[of] ' + effectHolder);
return null;
}
},
onAllyTryAddVolatile(status, target) {
if (status.id === 'yawn') {
this.debug('Sweet Veil blocking yawn');
const effectHolder = this.effectState.target;
this.add('-block', target, 'ability: Sweet Veil', '[of] ' + effectHolder);
return null;
}
},
isBreakable: true,
rating: 2,
num: 175,
},
swiftswim: {
onModifySpe(spe, pokemon) {
if (['raindance', 'primordialsea'].includes(pokemon.effectiveWeather())) {
return this.chainModify(2);
}
},
name: "Swift Swim",
rating: 3,
num: 33,
},
symbiosis: {
onAllyAfterUseItem(item, pokemon) {
if (pokemon.switchFlag) return;
const source = this.effectState.target;
const myItem = source.takeItem();
if (!myItem) return;
if (
!this.singleEvent('TakeItem', myItem, source.itemState, pokemon, source, this.effect, myItem) ||
!pokemon.setItem(myItem)
) {
source.item = myItem.id;
return;
}
this.add('-activate', source, 'ability: Symbiosis', myItem, '[of] ' + pokemon);
},
name: "Symbiosis",
rating: 0,
num: 180,
},
synchronize: {
onAfterSetStatus(status, target, source, effect) {
if (!source || source === target) return;
if (effect && effect.id === 'toxicspikes') return;
if (status.id === 'slp' || status.id === 'frz') return;
this.add('-activate', target, 'ability: Synchronize');
// Hack to make status-prevention abilities think Synchronize is a status move
// and show messages when activating against it.
source.trySetStatus(status, target, {status: status.id, id: 'synchronize'} as Effect);
},
name: "Synchronize",
rating: 2,
num: 28,
},
tangledfeet: {
onModifyAccuracyPriority: -1,
onModifyAccuracy(accuracy, target) {
if (typeof accuracy !== 'number') return;
if (target?.volatiles['confusion']) {
this.debug('Tangled Feet - decreasing accuracy');
return this.chainModify(0.5);
}
},
isBreakable: true,
name: "Tangled Feet",
rating: 1,
num: 77,
},
tanglinghair: {
onDamagingHit(damage, target, source, move) {
if (this.checkMoveMakesContact(move, source, target, true)) {
this.add('-ability', target, 'Tangling Hair');
this.boost({spe: -1}, source, target, null, true);
}
},
name: "Tangling Hair",
rating: 2,
num: 221,
},
technician: {
onBasePowerPriority: 30,
onBasePower(basePower, attacker, defender, move) {
const basePowerAfterMultiplier = this.modify(basePower, this.event.modifier);
this.debug('Base Power: ' + basePowerAfterMultiplier);
if (basePowerAfterMultiplier <= 60) {
this.debug('Technician boost');
return this.chainModify(1.5);
}
},
name: "Technician",
rating: 3.5,
num: 101,
},
telepathy: {
onTryHit(target, source, move) {
if (target !== source && target.isAlly(source) && move.category !== 'Status') {
this.add('-activate', target, 'ability: Telepathy');
return null;
}
},
isBreakable: true,
name: "Telepathy",
rating: 0,
num: 140,
},
teravolt: {
onStart(pokemon) {
this.add('-ability', pokemon, 'Teravolt');
},
onModifyMove(move) {
move.ignoreAbility = true;
},
name: "Teravolt",
rating: 3.5,
num: 164,
},
thickfat: {
onSourceModifyAtkPriority: 6,
onSourceModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Ice' || move.type === 'Fire') {
this.debug('Thick Fat weaken');
return this.chainModify(0.5);
}
},
onSourceModifySpAPriority: 5,
onSourceModifySpA(atk, attacker, defender, move) {
if (move.type === 'Ice' || move.type === 'Fire') {
this.debug('Thick Fat weaken');
return this.chainModify(0.5);
}
},
isBreakable: true,
name: "Thick Fat",
rating: 3.5,
num: 47,
},
tintedlens: {
onModifyDamage(damage, source, target, move) {
if (target.getMoveHitData(move).typeMod < 0) {
this.debug('Tinted Lens boost');
return this.chainModify(2);
}
},
name: "Tinted Lens",
rating: 4,
num: 110,
},
torrent: {
onModifyAtkPriority: 5,
onModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Torrent boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, attacker, defender, move) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Torrent boost');
return this.chainModify(1.5);
}
},
name: "Torrent",
rating: 2,
num: 67,
},
toughclaws: {
onBasePowerPriority: 21,
onBasePower(basePower, attacker, defender, move) {
if (move.flags['contact']) {
return this.chainModify([5325, 4096]);
}
},
name: "Tough Claws",
rating: 3.5,
num: 181,
},
toxicboost: {
onBasePowerPriority: 19,
onBasePower(basePower, attacker, defender, move) {
if ((attacker.status === 'psn' || attacker.status === 'tox') && move.category === 'Physical') {
return this.chainModify(1.5);
}
},
name: "Toxic Boost",
rating: 2.5,
num: 137,
},
trace: {
onStart(pokemon) {
// n.b. only affects Hackmons
// interaction with No Ability is complicated: https://www.smogon.com/forums/threads/pokemon-sun-moon-battle-mechanics-research.3586701/page-76#post-7790209
if (pokemon.adjacentFoes().some(foeActive => foeActive.ability === 'noability')) {
this.effectState.gaveUp = true;
}
},
onUpdate(pokemon) {
if (!pokemon.isStarted || this.effectState.gaveUp) return;
const additionalBannedAbilities = [
// Zen Mode included here for compatability with Gen 5-6
'noability', 'flowergift', 'forecast', 'hungerswitch', 'illusion', 'imposter', 'neutralizinggas', 'powerofalchemy', 'receiver', 'trace', 'zenmode',
];
const possibleTargets = pokemon.adjacentFoes().filter(target => (
!target.getAbility().isPermanent && !additionalBannedAbilities.includes(target.ability)
));
if (!possibleTargets.length) return;
const target = this.sample(possibleTargets);
const ability = target.getAbility();
this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target);
pokemon.setAbility(ability);
},
name: "Trace",
rating: 2.5,
num: 36,
},
transistor: {
onModifyAtkPriority: 5,
onModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Electric') {
this.debug('Transistor boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA(atk, attacker, defender, move) {
if (move.type === 'Electric') {
this.debug('Transistor boost');
return this.chainModify(1.5);
}
},
name: "Transistor",
rating: 3.5,
num: 262,
},
triage: {
onModifyPriority(priority, pokemon, target, move) {
if (move?.flags['heal']) return priority + 3;
},
name: "Triage",
rating: 3.5,
num: 205,
},
truant: {
onStart(pokemon) {
pokemon.removeVolatile('truant');
if (pokemon.activeTurns && (pokemon.moveThisTurnResult !== undefined || !this.queue.willMove(pokemon))) {
pokemon.addVolatile('truant');
}
},
onBeforeMovePriority: 9,
onBeforeMove(pokemon) {
if (pokemon.removeVolatile('truant')) {
this.add('cant', pokemon, 'ability: Truant');
return false;
}
pokemon.addVolatile('truant');
},
condition: {},
name: "Truant",
rating: -1,
num: 54,
},
turboblaze: {
onStart(pokemon) {
this.add('-ability', pokemon, 'Turboblaze');
},
onModifyMove(move) {
move.ignoreAbility = true;
},
name: "Turboblaze",
rating: 3.5,
num: 163,
},
unaware: {
name: "Unaware",
onAnyModifyBoost(boosts, pokemon) {
const unawareUser = this.effectState.target;
if (unawareUser === pokemon) return;
if (unawareUser === this.activePokemon && pokemon === this.activeTarget) {
boosts['def'] = 0;
boosts['spd'] = 0;
boosts['evasion'] = 0;
}
if (pokemon === this.activePokemon && unawareUser === this.activeTarget) {
boosts['atk'] = 0;
boosts['def'] = 0;
boosts['spa'] = 0;
boosts['accuracy'] = 0;
}
},
isBreakable: true,
rating: 4,
num: 109,
},
unburden: {
onAfterUseItem(item, pokemon) {
if (pokemon !== this.effectState.target) return;
pokemon.addVolatile('unburden');
},
onTakeItem(item, pokemon) {
pokemon.addVolatile('unburden');
},
onEnd(pokemon) {
pokemon.removeVolatile('unburden');
},
condition: {
onModifySpe(spe, pokemon) {
if (!pokemon.item && !pokemon.ignoringAbility()) {
return this.chainModify(2);
}
},
},
name: "Unburden",
rating: 3.5,
num: 84,
},
unnerve: {
onPreStart(pokemon) {
this.add('-ability', pokemon, 'Unnerve');
this.effectState.unnerved = true;
},
onStart(pokemon) {
if (this.effectState.unnerved) return;
this.add('-ability', pokemon, 'Unnerve');
this.effectState.unnerved = true;
},
onEnd() {
this.effectState.unnerved = false;
},
onFoeTryEatItem() {
return !this.effectState.unnerved;
},
name: "Unnerve",
rating: 1.5,
num: 127,
},
unseenfist: {
onModifyMove(move) {
if (move.flags['contact']) delete move.flags['protect'];
},
name: "Unseen Fist",
rating: 2,
num: 260,
},
victorystar: {
onAnyModifyAccuracyPriority: -1,
onAnyModifyAccuracy(accuracy, target, source) {
if (source.isAlly(this.effectState.target) && typeof accuracy === 'number') {
return this.chainModify([4506, 4096]);
}
},
name: "Victory Star",
rating: 2,
num: 162,
},
vitalspirit: {
onUpdate(pokemon) {
if (pokemon.status === 'slp') {
this.add('-activate', pokemon, 'ability: Vital Spirit');
pokemon.cureStatus();
}
},
onSetStatus(status, target, source, effect) {
if (status.id !== 'slp') return;
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Vital Spirit');
}
return false;
},
isBreakable: true,
name: "Vital Spirit",
rating: 2,
num: 72,
},
voltabsorb: {
onTryHit(target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.heal(target.baseMaxhp / 4)) {
this.add('-immune', target, '[from] ability: Volt Absorb');
}
return null;
}
},
isBreakable: true,
name: "Volt Absorb",
rating: 3.5,
num: 10,
},
wanderingspirit: {
onDamagingHit(damage, target, source, move) {
const additionalBannedAbilities = ['hungerswitch', 'illusion', 'neutralizinggas', 'wonderguard'];
if (source.getAbility().isPermanent || additionalBannedAbilities.includes(source.ability) ||
target.volatiles['dynamax']
) {
return;
}
if (this.checkMoveMakesContact(move, source, target)) {
const sourceAbility = source.setAbility('wanderingspirit', target);
if (!sourceAbility) return;
if (target.isAlly(source)) {
this.add('-activate', target, 'Skill Swap', '', '', '[of] ' + source);
} else {
this.add('-activate', target, 'ability: Wandering Spirit', this.dex.abilities.get(sourceAbility).name, 'Wandering Spirit', '[of] ' + source);
}
target.setAbility(sourceAbility);
}
},
name: "Wandering Spirit",
rating: 2.5,
num: 254,
},
waterabsorb: {
onTryHit(target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.heal(target.baseMaxhp / 4)) {
this.add('-immune', target, '[from] ability: Water Absorb');
}
return null;
}
},
isBreakable: true,
name: "Water Absorb",
rating: 3.5,
num: 11,
},
waterbubble: {
onSourceModifyAtkPriority: 5,
onSourceModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Fire') {
return this.chainModify(0.5);
}
},
onSourceModifySpAPriority: 5,
onSourceModifySpA(atk, attacker, defender, move) {
if (move.type === 'Fire') {
return this.chainModify(0.5);
}
},
onModifyAtk(atk, attacker, defender, move) {
if (move.type === 'Water') {
return this.chainModify(2);
}
},
onModifySpA(atk, attacker, defender, move) {
if (move.type === 'Water') {
return this.chainModify(2);
}
},
onUpdate(pokemon) {
if (pokemon.status === 'brn') {
this.add('-activate', pokemon, 'ability: Water Bubble');
pokemon.cureStatus();
}
},
onSetStatus(status, target, source, effect) {
if (status.id !== 'brn') return;
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Water Bubble');
}
return false;
},
isBreakable: true,
name: "Water Bubble",
rating: 4.5,
num: 199,
},
watercompaction: {
onDamagingHit(damage, target, source, move) {
if (move.type === 'Water') {
this.boost({def: 2});
}
},
name: "Water Compaction",
rating: 1.5,
num: 195,
},
waterveil: {
onUpdate(pokemon) {
if (pokemon.status === 'brn') {
this.add('-activate', pokemon, 'ability: Water Veil');
pokemon.cureStatus();
}
},
onSetStatus(status, target, source, effect) {
if (status.id !== 'brn') return;
if ((effect as Move)?.status) {
this.add('-immune', target, '[from] ability: Water Veil');
}
return false;
},
isBreakable: true,
name: "Water Veil",
rating: 2,
num: 41,
},
weakarmor: {
onDamagingHit(damage, target, source, move) {
if (move.category === 'Physical') {
this.boost({def: -1, spe: 2}, target, target);
}
},
name: "Weak Armor",
rating: 1,
num: 133,
},
whitesmoke: {
onBoost(boost, target, source, effect) {
if (source && target === source) return;
let showMsg = false;
let i: BoostID;
for (i in boost) {
if (boost[i]! < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !(effect as ActiveMove).secondaries && effect.id !== 'octolock') {
this.add("-fail", target, "unboost", "[from] ability: White Smoke", "[of] " + target);
}
},
isBreakable: true,
name: "White Smoke",
rating: 2,
num: 73,
},
wimpout: {
onEmergencyExit(target) {
if (!this.canSwitch(target.side) || target.forceSwitchFlag || target.switchFlag) return;
for (const side of this.sides) {
for (const active of side.active) {
active.switchFlag = false;
}
}
target.switchFlag = true;
this.add('-activate', target, 'ability: Wimp Out');
},
name: "Wimp Out",
rating: 1,
num: 193,
},
wonderguard: {
onTryHit(target, source, move) {
if (target === source || move.category === 'Status' || move.type === '???' || move.id === 'struggle') return;
if (move.id === 'skydrop' && !source.volatiles['skydrop']) return;
this.debug('Wonder Guard immunity: ' + move.id);
if (target.runEffectiveness(move) <= 0) {
if (move.smartTarget) {
move.smartTarget = false;
} else {
this.add('-immune', target, '[from] ability: Wonder Guard');
}
return null;
}
},
isBreakable: true,
name: "Wonder Guard",
rating: 5,
num: 25,
},
wonderskin: {
onModifyAccuracyPriority: 10,
onModifyAccuracy(accuracy, target, source, move) {
if (move.category === 'Status' && typeof accuracy === 'number') {
this.debug('Wonder Skin - setting accuracy to 50');
return 50;
}
},
isBreakable: true,
name: "Wonder Skin",
rating: 2,
num: 147,
},
zenmode: {
onResidualOrder: 29,
onResidual(pokemon) {
if (pokemon.baseSpecies.baseSpecies !== 'Darmanitan' || pokemon.transformed) {
return;
}
if (pokemon.hp <= pokemon.maxhp / 2 && !['Zen', 'Galar-Zen'].includes(pokemon.species.forme)) {
pokemon.addVolatile('zenmode');
} else if (pokemon.hp > pokemon.maxhp / 2 && ['Zen', 'Galar-Zen'].includes(pokemon.species.forme)) {
pokemon.addVolatile('zenmode'); // in case of base Darmanitan-Zen
pokemon.removeVolatile('zenmode');
}
},
onEnd(pokemon) {
if (!pokemon.volatiles['zenmode'] || !pokemon.hp) return;
pokemon.transformed = false;
delete pokemon.volatiles['zenmode'];
if (pokemon.species.baseSpecies === 'Darmanitan' && pokemon.species.battleOnly) {
pokemon.formeChange(pokemon.species.battleOnly as string, this.effect, false, '[silent]');
}
},
condition: {
onStart(pokemon) {
if (!pokemon.species.name.includes('Galar')) {
if (pokemon.species.id !== 'darmanitanzen') pokemon.formeChange('Darmanitan-Zen');
} else {
if (pokemon.species.id !== 'darmanitangalarzen') pokemon.formeChange('Darmanitan-Galar-Zen');
}
},
onEnd(pokemon) {
if (['Zen', 'Galar-Zen'].includes(pokemon.species.forme)) {
pokemon.formeChange(pokemon.species.battleOnly as string);
}
},
},
isPermanent: true,
name: "Zen Mode",
rating: 0,
num: 161,
},
// CAP
mountaineer: {
onDamage(damage, target, source, effect) {
if (effect && effect.id === 'stealthrock') {
return false;
}
},
onTryHit(target, source, move) {
if (move.type === 'Rock' && !target.activeTurns) {
this.add('-immune', target, '[from] ability: Mountaineer');
return null;
}
},
isNonstandard: "CAP",
isBreakable: true,
name: "Mountaineer",
rating: 3,
num: -2,
},
rebound: {
isNonstandard: "CAP",
name: "Rebound",
onTryHitPriority: 1,
onTryHit(target, source, move) {
if (this.effectState.target.activeTurns) return;
if (target === source || move.hasBounced || !move.flags['reflectable']) {
return;
}
const newMove = this.dex.getActiveMove(move.id);
newMove.hasBounced = true;
this.actions.useMove(newMove, target, source);
return null;
},
onAllyTryHitSide(target, source, move) {
if (this.effectState.target.activeTurns) return;
if (target.isAlly(source) || move.hasBounced || !move.flags['reflectable']) {
return;
}
const newMove = this.dex.getActiveMove(move.id);
newMove.hasBounced = true;
this.actions.useMove(newMove, this.effectState.target, source);
return null;
},
condition: {
duration: 1,
},
isBreakable: true,
rating: 3,
num: -3,
},
persistent: {
isNonstandard: "CAP",
name: "Persistent",
// implemented in the corresponding move
rating: 3,
num: -4,
},
};
|
svivian/Pokemon-Showdown
|
data/abilities.ts
|
TypeScript
|
mit
| 120,065
|
<html><body>
<h4>Windows 10 x64 (18362.329)</h4><br>
<h2>_FAULT_INFORMATION_ARM64_TYPE</h2>
<font face="arial"> UnsupportedUpstreamTransaction = 0n0<br>
AddressSizeFault = 0n1<br>
TlbMatchConflict = 0n2<br>
ExternalFault = 0n3<br>
PermissionFault = 0n4<br>
AccessFlagFault = 0n5<br>
TranslationFault = 0n6<br>
MaxFaultType = 0n7<br>
</font></body></html>
|
epikcraw/ggool
|
public/Windows 10 x64 (18362.329)/_FAULT_INFORMATION_ARM64_TYPE.html
|
HTML
|
mit
| 388
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_05) on Tue Jun 10 20:54:55 BST 2014 -->
<title>ddm.IntegrationTests</title>
<meta name="date" content="2014-06-10">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ddm.IntegrationTests";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../ddm/factory/classifiers/package-summary.html">Prev Package</a></li>
<li><a href="../../ddm/jade/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?ddm/IntegrationTests/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package ddm.IntegrationTests</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../ddm/IntegrationTests/TestClassifierFactory.html" title="class in ddm.IntegrationTests">TestClassifierFactory</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../ddm/IntegrationTests/TestConfiguration.html" title="class in ddm.IntegrationTests">TestConfiguration</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../ddm/IntegrationTests/TestDatasetManager.html" title="class in ddm.IntegrationTests">TestDatasetManager</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../ddm/IntegrationTests/TestDecisionMaker.html" title="class in ddm.IntegrationTests">TestDecisionMaker</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../ddm/factory/classifiers/package-summary.html">Prev Package</a></li>
<li><a href="../../ddm/jade/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?ddm/IntegrationTests/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
JordiCorbilla/DDM
|
doc/ddm/IntegrationTests/package-summary.html
|
HTML
|
mit
| 5,245
|
#!/usr/bin/python
# -*- coding: utf8 -*-
from bs4 import BeautifulSoup as Soup
import urls
import re
import proxy
from datetime import *
import time
from time import mktime
import functions
def materials ( config ):
url = "https://www.lectio.dk/lectio/%s/MaterialOverview.aspx?holdelement_id=%s" % ( str(config["school_id"]), str(config["team_element_id"]) )
cookies = {}
# Insert User-agent headers and the cookie information
headers = {
"User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36",
"Content-Type" : "application/x-www-form-urlencoded",
"Host" : "www.lectio.dk",
"Origin" : "https://www.lectio.dk",
"Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ")
}
response = proxy.session.get(url, headers=headers)
html = response.text
soup = Soup(html)
if soup.find("table", attrs={"id" : "m_Content_MaterialsStudents"}) is None:
return {
"status" : False,
"error" : "Data not found"
}
rows = soup.find("table", attrs={"id" : "m_Content_MaterialsStudents"}).findAll("tr")
materialsList = []
if len(rows) > 1:
rows.pop(0)
titleProg = re.compile(ur"(?P<authors>.*): (?P<title>.*), (?P<publisher>.*)")
for row in rows:
elements = row.findAll("td")
title = unicode(elements[0].text.replace("\n", ""))
titleGroups = titleProg.match(title)
materialsList.append({
"title_text" : title,
"title" : titleGroups.group("title") if not titleGroups is None else title,
"publisher" : titleGroups.group("publisher") if not titleGroups is None else "",
"authors" : titleGroups.group("authors").split(", ") if not titleGroups is None else "",
"type" : "book" if unicode(elements[1].text.replace("\n", "")) == u"Bog" else unicode(elements[1].text.replace("\n", "")),
"book_storage" : True if elements[2].text.replace("\n", "") == "Ja" else False,
"comment" : unicode(elements[3].text.strip("\n").replace("\n", "")),
"ebook" : elements[4].text.strip("\n").replace("\n", "")
})
return {
"status" : "ok",
"materials" : materialsList
}
|
boh1996/LectioAPI
|
scrapers/materials.py
|
Python
|
mit
| 2,102
|
import PageObject from '../../tests/page-object';
const {
value,
//customHelper,
collection,
clickable
} = PageObject;
export default function aupacTypeahead(selector/*, options*/) {
return {
search(search) {
$(selector).val(search).trigger('input');
},
suggestions : collection({
scope: '', //Reset to global scope
itemScope: '.tt-suggestion',
item: {
select: clickable()
}
}),
value : value(selector),
isDisabled: function() {
return $(selector).prop('disabled');
},
isEnabled: function() {
return ! $(selector).prop('disabled');
}
};
}
|
aupac/ember-aupac-typeahead
|
test-support/pages/aupac-typeahead.js
|
JavaScript
|
mit
| 641
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rose</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="./vendor/codemirror/codemirror.css">
<script type="text/javascript" src="./vendor/codemirror/codemirror.js"></script>
<script type="text/javascript" src="./vendor/codemirror/javascript.js"></script>
<script type="text/javascript" src="./vendor/codemirror/closebrackets.js"></script>
<script type="text/javascript" src="./vendor/codemirror/javascript-hint.js"></script>
<script type="text/javascript" src="./vendor/codemirror/javascript-lint.js"></script>
<script type="text/javascript" src="./vendor/codemirror/matchbrackets.js"></script>
<script type="text/javascript" src="./vendor/codemirror/search.js"></script>
<script type="text/javascript" src="./vendor/codemirror/searchcursor.js"></script>
<script type="text/javascript" src="./vendor/codemirror/show-hint.js"></script>
<script type="text/javascript" src="./vendor/codemirror/comment.js"></script>
<script type="text/javascript" src="./vendor/codemirror/sublime.js"></script>
<script type="text/javascript" src="./vendor/codemirror/foldcode.js"></script>
<link rel="stylesheet" href="./vendor/codemirror/foldgutter.css" />
<script src="./vendor/codemirror/foldcode.js"></script>
<script src="./vendor/codemirror/foldgutter.js"></script>
<script src="./vendor/codemirror/brace-fold.js"></script>
<script src="./vendor/codemirror/comment-fold.js"></script>
<link rel="stylesheet" href="./vendor/codemirror/dialog.css">
<link rel="stylesheet" href="./vendor/codemirror/show-hint.css">
<script src="./vendor/codemirror/dialog.js"></script>
<link rel="stylesheet" href="./vendor/codemirror/lint.css">
<script src="./vendor/codemirror/jshint.min.js"></script>
<script src="./vendor/codemirror/lint.js"></script>
<style>
html {
height: 100%;
}
body {
display: flex;
font-size: 16px;
height: 100%;
}
#preview {
border: none;
outline: none;
width: 50%;
height: 100%;
}
</style>
</head>
<body>
<div id="app"></div>
<iframe id="preview"></iframe>
<script src="dist/woof-bundle.js"></script>
</body>
</html>
|
stevekrouse/rose
|
woof.html
|
HTML
|
mit
| 2,518
|
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("Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Core")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("1fde753a-0467-4731-b50c-7d144660b895")]
// 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.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
regiuskornel/dotnettraining
|
Core/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,379
|
#!/usr/bin/env python
# Copyright (c) 2011-2015 SEOmoz, Moz
#
# 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.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='mozscape',
version='0.1.1',
description='Mozscape API Bindings for Python',
author_email='dan@moz.com',
url='http://github.com/seomoz/SEOmozAPISamples',
py_modules=['mozscape'],
license='MIT',
platforms='Posix; MacOS X',
classifiers=[
'License :: OSI Approved :: MIT License',
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Topic :: Internet :: WWW/HTTP'],
)
|
seomoz/SEOmozAPISamples
|
python/setup.py
|
Python
|
mit
| 1,723
|
# ui
这是一个基于requirejs和jquery的UI库,包含数据表格、弹出层、下拉框等常用控件。
目前还在开发中,功能比较简单,变化比较大,暂时不建议使用。
## 基本用法:
第一步,把ui目录复制到项目中。
第二步,引入脚本。
``` html
<input type="button" value="新增" id="btnAdd">
<form action="#" id="loginForm" style="display: none">
<label for="">用户名</label>
<input type="text">
<label for="">邮箱</label>
<input type="text">
<button>保存</button>
</form>
<script src="../ui/lib/require/require.js"></script>
<script src="../ui/config/config.js"></script>
```
第四步,通过require引入要使用的模块,然后初始化。
```html
<script>
require(['jquery', 'layout'], function($, Layout){
// 初始化控件
new Layout('#loginForm', {
trigger: '#btnAdd',
width: 500,
height: 200,
autoClose: false
});
});
</script>
```
以下是目前包含的控件的参数说明:
## grid
数据表格控件。
支持加载本地和远程数据,支持自定义单元格内容。
暂时不支持分页。
```js
//
require('grid', function(Grid){
// 第一个参数:一个<table></table>元素或者它的选择器
// 第二个参数:配置参数
var grid = new Grid('#tb', {
// AJAX获取远程数据的地址;也可以用data属性来显示本地数据,见下文;
url: 'data/grid.js',
// AJAX方法,仅在定义了url时有效
method: 'POST',
// AJAX参数,仅在定义了url时有效
params: {
page: 1,
pageSize: 9999,
},
// 在定义了url的情况下,data可以是一个函数,用于处理AJAX返回的数据
// 在没有定义url的情况下,data可以是直接是一个对象数组;
// 对象数据的格式应该为:[{},{},{},...]
data: function(json){
return json.data;
},
// 列信息
// key是必填的
columns: [
{ key: 'id', label: 'id' },
{ key: 'name', label: '姓名' },
{ key: 'email', label: '邮箱' },
{ key: 'action', label: '操作',
// formatter可以在单元格中显示自定义的内容
// 第一个参数row为当前行的data对象
// 第二个参数col为当前列的配置信息
formatter: function(row, col){
return '<a href="delUser(' + row.id + '):;">删除</a>';
}
}
]
});
});
```
## select
下拉框控件。
支持加载本地和远程数据。
```js
require('select', function(Select){
// 第一个参数:作为弹窗内容的元素或选择器
// 第二个参数:配置参数,可选
var select = new Select('#roleList', {
// AJAX获取远程数据的地址;也可以用data属性来显示本地数据,见下文;
url: 'data/roles.js',
// AJAX方法,可选,且仅在定义了url时有效
method: 'POST',
// AJAX参数,可选,且仅在定义了url时有效
params: {
page: 1,
pageSize: 9999,
},
// 在定义了url的情况下,data可以是一个函数,用于处理AJAX返回的数据
// 在没有定义url的情况下,data可以是直接是一个对象数组;
// 对象数据的格式应该为:
// [{ roleId: '1', roleName: '管理员'},{}, ..]
data: function(json){
return json.data;
},
// 下拉框的值字段
valueField: 'roleId',
// 下拉框的显示字段
textField: 'roleName',
// 插入的数据,可选
insertData: [{
value: '',
text: '请选择'
}]
});
});
```
## layout
弹出层控件。
支持模态窗口。
```js
//
require('layout', function(Layout){
// 第一个参数:作为弹窗内容的元素或选择器
// 第二个参数:配置参数,可选
var layout = new Layout('#loginForm', {
// 触发弹窗显示的元素
trigger: '#btnShowLoginForm',
// 尺寸,默认为自动
width: 500,
height: 400,
// 是否显示为模态框
modal: true,
// 是否点击模态框时自动隐藏
autoClose: true
});
});
```
|
require-ui/ui
|
README.md
|
Markdown
|
mit
| 4,158
|
<?php
namespace UCD\Unicode\Character;
use UCD\Unicode\Character\Repository\AddCharacterException;
use UCD\Unicode\CodepointAssigned;
interface WritableRepository extends Repository, \SplSubject
{
/**
* @param Collection $characters
* @throws AddCharacterException
*/
public function addMany(Collection $characters);
}
|
nick-jones/php-ucd
|
lib/UCD/Unicode/Character/WritableRepository.php
|
PHP
|
mit
| 344
|
class YankeeScore::Game
attr_accessor :home_team,
:away_team,
:start_time,
:status,
:inning,
:inning_state,
:score
PRE_GAME_STATE = ["Pre-Game","Preview", "Warmup"]
END_GAME_STATE = ["Final", "Postponed", "Game Over"]
def initialize(home_team, away_team)
@home_team = home_team
@away_team = away_team
end
@@all ||= []
def self.all
@@all
end
def self.reset_all!
@@all.clear
end
def save
@@all << self
end
def self.create_from_json(game_hash)
game = self.new(YankeeScore::Team.new(game_hash[:home_name_abbrev]), YankeeScore::Team.new(game_hash[:away_name_abbrev]))
game.start_time = game_hash[:time]
game.status = game_hash[:status][:status]
game.inning = game_hash[:status][:inning]
game.inning_state = game_hash[:status][:inning_state]
if game_hash.has_key?(:linescore)
game.home_team.runs = game_hash[:linescore][:r][:home]
game.away_team.runs = game_hash[:linescore][:r][:away]
game.score = "#{game.away_team.runs}-#{game.home_team.runs}"
end
game.save
end
def self.find_team_by_abbrev(team_abbrev)
self.all.select do |team|
team_abbrev == team.home_team.name || team_abbrev == team.away_team.name
end
end
def is_over?
END_GAME_STATE.include?(self.status)
end
def is_active?
self.inning.to_i >= 1 && !is_over? && !PRE_GAME_STATE.include?(status)
end
end
|
Shmuwol/yankee_score
|
lib/yankee_score/game.rb
|
Ruby
|
mit
| 1,521
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Phaser - ES6 - Webpack</title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta http-equiv="cleartype" content="on">
<link rel="stylesheet" type="text/css" href="fonts.css">
<style>
html,
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="content"></div>
<script src="dist/vendor.bundle.js"></script>
<script src="dist/bundle.js"></script>
</body>
</html>
|
KillerKodersKode/captain_slayer
|
index.html
|
HTML
|
mit
| 676
|
@compat function barplot(;x::AbstractVector = Int[],
y::AbstractVector = Int[],
y2::AbstractVector = Int[],
group::AbstractVector = Int[],
stacked::Bool = false,
horizontal::Bool = false,
normalize::Bool = false)
v = VegaVisualization()
default_scales!(v)
v.scales[1]._type = "ordinal"
default_axes!(v)
#If non-zero group is passed, add a legend
if group != Int[]
default_legend!(v)
end
add_data!(v, x = x, y = y, group = group, y2 = y2)
add_rects!(v)
v.marks[1].properties.enter.width = VegaValueRef(scale = "x", band = true, offset = -1)
v.marks[1].properties.enter.y = VegaValueRef(scale = "y", field = "y")
v.marks[1].properties.enter.y2 = VegaValueRef(scale = "y", field = "y2")
v.marks[1].properties.enter.fill = VegaValueRef(scale = "group", field = "group")
if stacked
push!(v.data, VegaData(name = "stats", source = "table",
transform = [VegaTransform(Dict{Any, Any}("type"=> "aggregate", "groupby" => ["x"], "summarize"=>[Dict{Any,Any}("field" => "y", "ops" => ["sum"])]))]))
# bind the y scale to layout start and layout end
v.marks[1].properties.enter.y = VegaValueRef(scale = "y", field = "layout_start")
v.marks[1].properties.enter.y2 = VegaValueRef(scale = "y", field = "layout_end")
v.scales[2].domain = VegaDataRef("stats", "sum_y")
v.marks[1].from = VegaMarkFrom(data = "table",
transform = [VegaTransform(Dict{Any, Any}("type" => "stack", "groupby" => ["x"], "sortby" => ["group"], "field"=>"y", "offset" => normalize == true? "normalize" : "zero"))])
if normalize
ylim!(v, min = 0, max = 1)
end
end
#Return horizontal bar chart
if horizontal
coord_flip!(v)
end
#Default to Paired color scale, 12
colorscheme!(v; palette = ("Paired", 12))
return v
end
|
slowbrain/Vega.jl
|
src/derived/barplot.jl
|
Julia
|
mit
| 2,013
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Shrubbery : MonoBehaviour {
public bool randomizeFuel = false;
public float fuelAmount = 0;
public float flameAmount = 0;
public float waterAmount = 0;
//public float waterThreshold = 3;
public float waterLimit = 7;
//float waterToGrow;
//public float fuelLimitFactor = 10;
//public float resistanceFactor = 1;
public float resistance = 0;
public float burnRate = .1f;
public float absorbRate = 1;
public int state = 0;
public float growRate = .01f;
public float growScaleFactor = 10;
//public List<GameObject> liveModels;
//public List<GameObject> deadModels;
//public List<GameObject> burnModels;
public GameObject liveModel;
public GameObject deadModel;
public GameObject burnModel;
GameObject currentModel;
public ParticleSystem flame;
public Cloud cloudPrefab;
public Vector3 cloudOffset = Vector3.up;
Cloud cloud;
//Vector3 currentScale = Vector3.one;
//public int currentSize = 1;
// Use this for initialization
void Start () {
if(randomizeFuel){
float r = Random.Range (0.0f, 1.0f);
fuelAmount = waterLimit*r;
waterAmount = waterLimit*(1-r);
}
//waterToGrow = waterThreshold;
//if (burnModels.Count != deadModels.Count || deadModels.Count != liveModels.Count){
// Debug.LogWarning ("improper number of tree models");
//}
ModelChange();
}
// Update is called once per frame
void Update () {
//Debug.Log ("state = " + state.ToString ()+ ", wff = "+new Vector3(waterAmount, fuelAmount, flameAmount).ToString());
if(state == 1){
if(waterAmount <= 0){
++state;
waterAmount = 0;
ModelChange();
}
else{
waterAmount -= growRate*Time.deltaTime;
fuelAmount += growRate*Time.deltaTime;
}
}
if(state == 3){
if (fuelAmount <=0){
++state;
ModelChange();
}
else{
flameAmount += burnRate * Time.deltaTime;
fuelAmount -= burnRate * Time.deltaTime;
}
}
if(state == 4){
if(flameAmount<=0){
state = 0;
flameAmount = fuelAmount = waterAmount = 0;
}
}
/*
if(fuel<=0&&flameAmount<=0&&waterAmount<=0){
currentSize = 0;
dead = false;
burning = false;
ModelChange(0);
UnIgnite();
waterToGrow = waterThreshold;
}
if(waterToGrow <=0){
++currentSize;
currentSize = Mathf.Min(currentSize, liveModels.Count-1);
waterToGrow = waterThreshold;
}
if(burning&&fuel<=0){
//UnIgnite();
fuel = 0;
}
else if (burning){
fuel -= burnRate * Time.deltaTime;
flameAmount += burnRate * Time.deltaTime;
//General.pushEnergy (burnRate*Time.deltaTime);
}
if(!dead&¤tSize>0){
waterAmount -= growRate * Time.deltaTime;
fuel += growRate * Time.deltaTime;
//transform.localScale = 1 + (fuel);
//currentModel.transform.localScale = currentScale;
}
if(waterAmount<=0&¤tSize>0){
dead = true;
ModelChange(currentSize);
}
transform.localScale = (1 + fuel) * Vector3.one;
Debug.Log ("wa = "+waterAmount.ToString ()+", fu = "+fuel.ToString ()+", fl = "+flameAmount.ToString()+", dead = "+dead.ToString ()+", burning = "+burning.ToString ()+", size = "+currentSize.ToString()+", wtg = "+waterToGrow.ToString());
*/
}
void ModelChange(){
/*if(burning){
Destroy(currentModel);
currentModel = (GameObject)Instantiate(burnModels[newSize], transform.position, transform.rotation);
}
else if (dead){
Destroy(currentModel);
currentModel = (GameObject)Instantiate(deadModels[newSize],transform.position, transform.rotation);
}
else{
Destroy(currentModel);
currentModel = (GameObject)Instantiate(liveModels[newSize],transform.position, transform.rotation);
}*/
if(state == 0){
Destroy(currentModel);
flame.enableEmission = false;
}
if(state == 1){
Destroy(currentModel);
currentModel = (GameObject)Instantiate(liveModel, transform.position, transform.rotation);
flame.enableEmission = false;
currentModel.transform.parent = transform;
//currentModel.transform.localScale = Vector3.one;
}
if(state == 2){
Destroy(currentModel);
currentModel = (GameObject)Instantiate(deadModel, transform.position, transform.rotation);
flame.enableEmission = false;
currentModel.transform.parent = transform;
//currentModel.transform.localScale = Vector3.one;
}
if(state == 3){
Destroy(currentModel);
currentModel = (GameObject)Instantiate(burnModel, transform.position, transform.rotation);
flame.enableEmission = true;
currentModel.transform.parent = transform;
//currentModel.transform.localScale = Vector3.one;
}
if(state == 4){
Destroy(currentModel);
flame.enableEmission = true;
}
}
void MakeCloud(float s){
if(!cloud){
cloud = (Cloud)Instantiate(cloudPrefab, transform.position+cloudOffset, transform.rotation);
cloud.size = s;
}
else{
cloud.size += s;
}
}
public void AddWater(float w){
if(state == 0){
++state;
ModelChange();
waterAmount += w;
if(waterAmount > waterLimit){
General.pushEnergy (waterAmount - waterLimit);
waterAmount = waterLimit;
}
}
else if(state == 1){
waterAmount += w;
if(waterAmount > waterLimit){
General.pushEnergy (waterAmount - waterLimit);
waterAmount = waterLimit;
}
}
else if(state == 2){
--state;
ModelChange();
waterAmount += w;
if(waterAmount > waterLimit){
General.pushEnergy (waterAmount - waterLimit);
waterAmount = waterLimit;
}
}
else if(state == 3){
if(w > flameAmount){
--state;
ModelChange();
}
else{
flameAmount -= w;
MakeCloud(2*w);
}
}
else if(state == 4){
if(w > flameAmount){
General.pushEnergy (w - flameAmount);
MakeCloud(2*flameAmount);
state = 0;
ModelChange();
}
else{
flameAmount -= w;
MakeCloud(2*w);
}
}
/*if(!burning){
waterAmount += w;
waterToGrow -= w;
waterAmount = Mathf.Min (waterLimit, waterAmount);
}
else{
flameAmount -= w;
MakeCloud (2*w);
}*/
}
public void Ignite(float f){
if(f == -1){
if(state == 0){
}
else if (state == 1){
state = 3;
ModelChange();
General.pushEnergy(waterAmount);
}
else if (state == 2){
state = 3;
ModelChange();
}
else if (state == 3){
}
else if (state == 4){
}
/*General.pushEnergy (waterAmount);
if(state == 2 || state == 1){
state = 3;
ModelChange();
}*/
}
else{
if(state == 0){
}
else if (state == 1){
if(f > waterAmount){
//General.pushEnergy(f-waterAmount);
fuelAmount += waterAmount;
flameAmount += f - waterAmount;
waterAmount = 0;
state = 3;
ModelChange();
}
else{
waterAmount -= f;
fuelAmount += f;
}
}
else if (state == 2){
flameAmount += f;
state = 3;
ModelChange();
}
else if (state == 3){
flameAmount += f;
}
else if (state == 4){
flameAmount += f;
}
/*if(state == 2){
if(f > waterAmount){
//General.pushEnergy(f-waterAmount);
fuelAmount += waterAmount;
flameAmount += f;
}
else{
waterAmount -= f;
fuelAmount += f;
}
}*/
}
/*burning = true;
dead = true;
ModelChange(currentSize);
*/
}
/*public void UnIgnite(){
burning = false;
Destroy(currentModel);
//currentModel = (GameObject)Instantiate (deadModels[currentSize], transform.position, transform.rotation);
currentModel.transform.parent = transform;
ParticleSystem[] ps = currentModel.GetComponentsInChildren<ParticleSystem>();
foreach (ParticleSystem p in ps){
p.enableEmission = false;
}
//if(fuel<0){
// MakeCloud(fuel);
//}
}*/
void OnTriggerEnter (Collider other){
//Debug.Log ("foo");
/*Fire temp = other.GetComponent<Fire>();
if (burning && temp != null && temp.enabled){
General.changeSize(fuel, fuelLimit, 0);
//General.playerSize += fuel;
fuel = 0;
return;
}*/
FireAttack fA = other.GetComponent<FireAttack>();
//if (source != null == true){
if(fA){
//Debug.Log ("firea attack strength: "+fA.strength.ToString ());
//waterAmount -= fA.strength;
//fuel+= fA.strength;
//if (waterAmount<=0){
//Debug.Log("shrub trigger entered");
//Ignite();
//burning = true;
//flame.enableEmission = true;
//}
////else{
// MakeCloud(2*fA.strength);
//}
Ignite(fA.strength);
Destroy(fA.gameObject);
return;
}
WaterAttack wat = other.GetComponent<WaterAttack>();
if (wat){
AddWater(wat.size);
Destroy(wat);
//Debug.Log("wat, new size = " + waterAmount.ToString ());
}
}
void OnTriggerStay(Collider other){
Fire fireElemental = other.GetComponent<Fire>();
//if (burning && fireElemental != null && fireElemental.enabled){
if(fireElemental && fireElemental.enabled){
if(state == 1){
waterAmount -= absorbRate * growRate;
fuelAmount += absorbRate * growRate;
}
else if(state == 2){
Ignite(absorbRate);
}
else if (state > 2){
flameAmount -= absorbRate*Time.deltaTime;
General.changeSize (absorbRate*Time.deltaTime, 100, 0);
}
return;
}
Water waterElemental = other.GetComponent<Water>();
if(waterElemental&&waterElemental.enabled){
//General.changeSize(.5f*flameAmount*Time.deltaTime, 100, 0);
//AddWater(.5f*flameAmount*Time.deltaTime);
AddWater(absorbRate*Time.deltaTime);
General.changeSize (-absorbRate*Time.deltaTime, 100, 0);
}
}
}
|
ludimation/dpas
|
dpas_project/Assets/_Scripts/objectScripts/Shrubbery.cs
|
C#
|
mit
| 9,431
|
@import 'https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz';
/*
.bg-landing{
background: url('../../images/bg/518079-background-hd.jpg') fixed;
background-position: 50% 50%;
background-attachment: fixed;
background-color: rgb(0, 0, 0);
}*/
.icon_part {
width: 30px;
position: relative;
top: 0px;
padding-right:6px;
padding-bottom:6px;
}
.mb1-blog-img{
float: left;
margin-right: 5px;
}
.remove_part {
/* background: url('../../images/icon/cancel_2-icon.png') no-repeat;*/
width: 20px;
height: 20px;
position: absolute;
right: 2px;
top: 6px;
cursor: pointer;
display: none;
z-index: 99;
color:#fff;
}
.remove_padding {
padding: 0px;
}
.padding_left {
padding-left: 0px;
}
.header_new_style .tt a{
color: #fff;
}
.liner_landing {
display: block;
width: 100%;
border-bottom: 1px solid #080808;
box-shadow: 0 1px 0 rgba(34, 34, 34, 0.8);
-webkit-box-shadow: 0 1px 0 rgba(34, 34, 34, 0.8);
margin: -1px 0 15px;
}
.jp-video-270p{
width: 100%;
}
.jp-type-playlist img{
}
.header_new_style{
margin: 8px 0;
overflow: hidden;
}
.jp-type-playlist .jp-jplayer{
width: 100% !important;
text-align: center;
}
.header_new_style .panel-heading .panel-title a {
text-transform: uppercase;
color: #eee;
}
.header_new_style .panel-group .panel, .header_new_style .panel-heading {
border-radius: 0px;
}
.panel-default > .panel-heading{
background: #fb6060;
}
div.jp-type-playlist div.jp-playlist a{
color: #888;
}
div.jp-type-playlist div.jp-playlist a.jp-playlist-current, div.jp-type-playlist div.jp-playlist a:hover{
color: #3b5998;
}
.image_fix_value {
width: 200px;
height: 200px;
background-position: 50% 25% !important;
background-size: cover !important;
transition-duration: 500ms;
transition-property: width, height;
cursor: pointer;
}
.image_fix_value_video{
width: 300px;
height: 300px;
background-position: 50% 25% !important;
background-size: cover !important;
transition-duration: 500ms;
transition-property: width, height;
cursor: pointer;
margin: 0px auto;
}
.image_fix_value_event{
width: 200px;
height: 200px;
background-position: 50% 25% !important;
background-size: cover !important;
transition-duration: 500ms;
transition-property: width, height;
cursor: pointer;
margin: 0px auto;
}
figure.effect-bubba:hover .image_fix_value_event{
opacity: 0.4
}
.text-justify a{
margin: 0px 7px;
}
.text-justify{
text-align: center;
margin-top: 7px;
margin-bottom: 7px;
}
.header_new_style .wp_content_list{
margin-bottom: 10px;
margin-top: 2px;
border-bottom: solid 1px #967219;
color: #ccc;
padding-bottom: 6px;
}
.wp_content_list{
overflow: hidden;
}
.comment_list a img{
width: 100%;
}
.list_member{
margin: 5px 0;
padding: 0px;
}
.bg-lg-ct{
background: none;
}
.background_landing{
}
.header_new_style h2.text_caplock{
margin-left: 0px;
border-bottom: 1px solid #ffb976;
display: inline-block;
margin-bottom: 0px;
}
.header_new_style{
background: rgba(0, 0, 0, 0.78);
border-radius: 6px;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.15), 0 1px 0 rgba(255, 255, 255, 0.04);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .15), 0 1px 0 rgba(255, 255, 255, .04);
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.15), 0 1px 0 rgba(255, 255, 255, 0.04);
padding: 0px 10px 10px 10px;
}
.BorNone {
border-bottom:none !important;
}
/* 31 August */
.ProfilePic {
background:whitesmoke;
height:176px;
width:176px;
border:6px solid #fff;
box-shadow:0px 6px 16px #000;
border-radius:50%;
}
.ProfileGrid {
margin-top:-156px;
}
.ProfileGrid h1 {
font-size:36px;
margin:16px 0px 6px 0px;
text-align:center;
font-weight:bold;
color:#fff;
}
.ProfileGrid span {
font-size:18px;
margin:70px 0px 6px 0px;
text-align:center;
}
.ProfileGrid p {
font-size:18px;
margin:0px 0px 0px 0px;
text-align:center;
color:#fff;
}
.profile-landing2
{
width: 100%;
position: absolute;
bottom: 0px;
left: 0px;
height: 164px;
padding-top: 7px;
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4gPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJncmFkIiBncmFkaWVudFVuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgeDE9IjAuNSIgeTE9IjAuMCIgeDI9IjAuNSIgeTI9IjEuMCI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjAiLz48c3RvcCBvZmZzZXQ9IjQwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjUiLz48c3RvcCBvZmZzZXQ9IjkwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjgiLz48L2xpbmVhckdyYWRpZW50PjwvZGVmcz48cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJ1cmwoI2dyYWQpIiAvPjwvc3ZnPiA=');
}
.sc-pro-img {
height: 500px!important;
}
.PhotoPic img {
border: 3px solid #fb6060;
}
h2.ProfileHed {
font-weight: 400;
font-size:26px;
font-family: sans-serif;
color:#ffb976 !important;
font-family: 'Yanone Kaffeesatz', sans-serif;
}
h2.ProfileHed a {
color:#ffb976 !important;
text-decoration:none;
}
h2.ProfileHed a:hover {
color:#fb6060 !important;
}
.StarBack {
background: hsla(39, 95%, 68%, 0.33);
padding: 6px;
border-radius: 4px;
}
.BtnNew {
background:#ffb976 !important;
color:#000 !important;
}
.ProfileSocial {
margin: 0px auto;
text-align: center;
width:169px;
margin-bottom:66px;
}
.ProfileSocial ul {
padding:0;
margin:16px 0px 0px 0px;
list-style:none;
}
.ProfileSocial ul li {
float: left;
}
.ProfileSocial ul li a.fa {
display: inline-block;
width: 32px;
height: 32px;
line-height: 30px;
color: #fff;
border: 2px solid #b5b5b5;
border-radius: 100%;
margin: 0 10px 0 0;
font-size: 14px;
overflow: hidden;
-webkit-transition-duration: 0.5s;
transition-duration: 0.5s;
-webkit-transition-property: color, background-color;
transition-property: color, background-color;
}
.ProfileSocial a.fa.fb:hover {
color: #fff;
background: #3b5999;
border: solid 2px #3b5999;
}
.ProfileSocial a.fa.tw:hover {
color: #fff;
background: #55acef;
border: solid 2px #55acef;
}
.ProfileSocial a.fa.gp:hover {
color: #fff;
background: #de4b39;
border: solid 2px #de4b39;
}
.ProfileSocial a.fa.in:hover {
color: #fff;
background: #156ea2;
border: solid 2px #156ea2;
}
.ProfileSocial a.fa.pin:hover {
color: #fff;
background: #cf2833;
border: solid 2px #cf2833;
}
.ListData strong {
color:#fb6060;
font-weight:400;
font-size:18px;
margin:8px 0px 0px 6px;
display:block;
}
.ListData p {
color:#fff;
font-weight:400;
font-size:16px;
margin:-24px 0px 0px 0px;
}
.ListData span {
color:#fff !important;
font-weight:400;
font-size:16px;
margin:-24px 0px 0px 0px;
}
.carousel-info img {
border: 1px solid #ffb976;
height: 56px;
padding: 3px;
width: 56px;
}
.carousel-info {
overflow: hidden;
margin-bottom:1em;
border-bottom:1px solid #5a5a5a;
padding-bottom:12px;
}
.carousel-info:last-child {
border-bottom:none !important;
}
.carousel-info img {
margin-right: 15px;
}
.carousel-info span {
display: block;
}
.testimonials-name{
color: #e6400c;
font-size: 16px;
font-weight: 300;
margin: 10px 0px 0px 0px;
line-height:20px;
text-align:left;
}
.testimonials-name a {
color: #ea4335;
}
.testimonials-name a:hover {
text-decoration:none;
color:#e00000;
}
.testimonials-post {
color: #fff;
font-size: 12px;
font-family:Arial, Helvetica, sans-serif;
}
@media (min-width: 767px){
.profile-landing2
{
width: 100%;
position: absolute;
bottom: 0px;
left: 0px;
height: 164px;
padding-top: 7px;
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4gPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJncmFkIiBncmFkaWVudFVuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgeDE9IjAuNSIgeTE9IjAuMCIgeDI9IjAuNSIgeTI9IjEuMCI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjAiLz48c3RvcCBvZmZzZXQ9IjQwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjUiLz48c3RvcCBvZmZzZXQ9IjkwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjgiLz48L2xpbmVhckdyYWRpZW50PjwvZGVmcz48cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJ1cmwoI2dyYWQpIiAvPjwvc3ZnPiA=');
}
}
@media screen and (max-width: 590px){
.sc-pro-img {
height: 400px!important;
}
.profile-landing2
{
width: 100%;
position: absolute;
bottom: 0px;
left: 0px;
height: 164px;
padding-top: 7px;
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4gPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJncmFkIiBncmFkaWVudFVuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgeDE9IjAuNSIgeTE9IjAuMCIgeDI9IjAuNSIgeTI9IjEuMCI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjAiLz48c3RvcCBvZmZzZXQ9IjQwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjUiLz48c3RvcCBvZmZzZXQ9IjkwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjgiLz48L2xpbmVhckdyYWRpZW50PjwvZGVmcz48cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJ1cmwoI2dyYWQpIiAvPjwvc3ZnPiA=');
}
}
|
akashbachhania/jeet99
|
assets/css/landing_page/landing_page10.css
|
CSS
|
mit
| 9,372
|
---
author: robmyers
comments: true
date: 2006-06-24 07:31:49+00:00
layout: post
slug: notes-towards-free-culture-6
title: Notes Towards Free Culture
wordpress_id: 1002
categories:
- Free Culture
---
[The Commoner N.11 - spring/summer 2006 Re(in)fusing the Commons](http://www.commoner.org.uk/)
_After ten issues, The Commoner makes the first timid steps toward changing format and organisation, towards making more explicit and visible the practices of cyber commoning it is grounded on. Watch this space, we are slow, but things will happen. Meanwhile, enjoy the edition that our two guest editors, Nate Holdren and Stevphen Shukaitis, have put together, an edition in which the different contributions are traversed by the problematic of commoning._
[Boing Boing: Royal Society to try open access science publishing](http://www.boingboing.net/2006/06/21/royal_society_to_try.html)
_The UK Royal Society, the oldest "learned society" in the world, will try publishing some of its journals under open access licensing._
[Boing Boing: Wendy Seltzer smokes the MPAA in the Wall St Journal](http://www.boingboing.net/2006/06/20/wendy_seltzer_smokes.html)
_My pal and former EFF attorney Wendy Seltzer conducted a debate with MPPA exec Fritz Attaway in the pages of the Wall Street Journal. In it, Wendy makes mincemeat of Attaway's arguments, which keep coming around to accusing her of wanting to commit piracy and rip off artists, which, as she explains over and over again, isn't what she's trying to do at all_
[Boing Boing: Pete Seeger tribute disc locked down with Dr0](http://www.boingboing.net/2006/06/20/pete_seeger_tribute_.html)
_Such irony: Bruce Springsteen recorded a tribute album for Pete Seeger, anti-property agitator and old-guard leftist. Springsteen's label slapped a super-restrictive DRM on the disc that prevents PC playback, ripping to MP3, and lots of other freedoms that are totally in synch with the poltiical messages in Seeger's music._
[EFF: DeepLinks](http://www.eff.org/deeplinks/archives/004753.php)
_The ad collects a century-worth of fear mongering by an industry focused on legislating to protect out-dated business models, rather than adjusting to changing market opportunities:_
_"I forsee a marked deterioration in American music...and a host of other injuries to music in its artistic manifestations, by virtue”or rather by vice”of the multiplication of the various music-reproducing machines..." -John Philip Sousa on the Player Piano (1906)_
|
robmyers/robmyers.org
|
_posts/2006-06-24-notes-towards-free-culture-6.md
|
Markdown
|
mit
| 2,568
|
# Mataara
An (optionally) dismissable notification bar.
# Change Log
##### 1.2.1 - 1.2.4
- (Unintentional minor bump)
- Adding Lerna publishing management
- Splitting out dev dependencies
##### 1.1.0
- Enumerated types
- Stylesheet composition
##### 1.0.3
- Minor `.gitignore` update
##### 1.0.2
- Implemented Webpack 2.2.1
##### 1.0.1
- Standardized line height.
##### 1.0.0
- Initial commit
|
ksespinola/component-library
|
notifications/mataara/README.md
|
Markdown
|
mit
| 401
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.push = push;
exports.unshift = unshift;
exports.pop = pop;
exports.shift = shift;
exports.sort = sort;
exports.reverse = reverse;
exports.removeAt = removeAt;
exports.setKey = setKey;
exports.setAt = setAt;
exports.assign = assign;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defineProperty(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); }
var _objectAssign = require('object-assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _debug = require('debug');
var _debug2 = _interopRequireDefault(_debug);
var debug = (0, _debug2['default'])('idempotent');
/**
* Returns a copy of the `arr` array, with the specified `element` appended to
* the highest index of the array.
*
* @param {Array[Anything]} arr
* @param {Anything} element
* @return {Array[Anything]}
*/
function push(arr, element) {
return arr.concat([element]);
}
/**
* Returns a copy of the `arr` array, with the specified `element` prepended to
* the 0th index of the array.
*
* @param {Array[Anything]} arr
* @param {Anything} element
* @return {Array[Anything]}
*/
function unshift(arr, element) {
return [element].concat(arr);
}
/**
* Returns a copy of the `arr` array, with the element at the highest index
* removed.
*
* @param {Array[Anything]} arr
* @return {Array[Anything]}
*/
function pop(arr) {
return arr.slice(0, arr.length - 1);
}
/**
* Returns a copy of the `arr` array, with the element at the 0th index removed.
*
* @param {Array[Anything]} arr
* @return {Array[Anything]}
*/
function shift(arr) {
return arr.slice(1, arr.length);
}
/**
* Returns a copy of the `arr` array, with all the elements sorted. Optionally,
* you can supply a function that
*
* @param {Array[Anything]} arr
* @param {Function : (Anything, Anything) -> Number}
* @return {Array[Anything]}
*/
function sort(arr, sorter) {
var copy = arr.slice();
if (sorter) {
return copy.sort(sorter);
}
return copy.sort();
}
/**
* Returns a copy of the `arr` array, with all the elements placed in reverse
* from the original array.
*
* @param {Array[Anything]} arr
* @return {Array[Anything]}
*/
function reverse(arr) {
return arr.slice().reverse();
}
/**
* Returns a copy of the `arr` array, with the element at the specified index
* removed.
*
* @param {Array[Anything]} arr
* @param {Integer} index
*/
function removeAt(arr, index) {
if (isNaN(index) || index < 0 || index % 1 !== 0) {
debug('Was given a non-integer value ' + index);
return arr.slice();
}
return arr.slice(0, index).concat(arr.slice(index + 1, arr.length));
}
/**
* Returns a copy of the `obj` object, with the element associated with the
* specified `key` replaced with the `value`.
*
* @param {Object} obj
* @param {Anything} key
* @param {Anything} value
* @return {Object}
*/
function setKey(obj, key, value) {
return assign(obj, _defineProperty({}, key, value));
}
/**
* Returns a copy of the `arr` array, with element at the specified `index`
* replaced with the `value`.
*
* @param {Array[Anything]} arr
* @param {Number} index
* @param {Array[Anything]} value
*/
function setAt(arr, index, value) {
if (arr.length <= index) {
return arr.concat(Array(index - arr.length)).concat([value]);
}
return arr.slice(0, index).concat([value]).concat(arr.slice(index + 1, arr.length));
}
/**
* Assigns all properties from the source objects, to the specified destination
* object.
*
* @param {Object} destination
* @param {Object} source in sources
* @return {Object}
*/
function assign(destination) {
for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
sources[_key - 1] = arguments[_key];
}
return _objectAssign2['default'].apply(undefined, [{}, destination].concat(sources));
}
|
shovon/idempotent.js
|
index.js
|
JavaScript
|
mit
| 4,054
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.WindowsAzure.Storage.Table;
using Orleans;
using Orleans.AzureUtils;
using Orleans.Providers.Streams.Common;
using Orleans.Providers.Streams.Generator;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.ServiceBus.Providers;
using Orleans.Streams;
using Orleans.TestingHost;
using Orleans.TestingHost.Utils;
using Tester;
using TestExtensions;
using TestGrainInterfaces;
using TestGrains;
using UnitTests.Grains;
using Xunit;
namespace ServiceBus.Tests.StreamingTests
{
[TestCategory("EventHub"), TestCategory("Streaming")]
public class EHStreamProviderCheckpointTests : TestClusterPerTest
{
private static readonly string StreamProviderTypeName = typeof(EventHubStreamProvider).FullName;
private const string StreamProviderName = GeneratedStreamTestConstants.StreamProviderName;
private const string EHPath = "ehorleanstest";
private const string EHConsumerGroup = "orleansnightly";
private const string EHCheckpointTable = "ehcheckpoint";
private static readonly string CheckpointNamespace = Guid.NewGuid().ToString();
private static readonly Lazy<EventHubSettings> EventHubConfig = new Lazy<EventHubSettings>(() =>
new EventHubSettings(
TestDefaultConfiguration.EventHubConnectionString,
EHConsumerGroup, EHPath));
private static readonly EventHubCheckpointerSettings CheckpointerSettings =
new EventHubCheckpointerSettings(TestDefaultConfiguration.DataConnectionString,
EHCheckpointTable, CheckpointNamespace, TimeSpan.FromSeconds(1));
private static readonly EventHubStreamProviderSettings ProviderSettings =
new EventHubStreamProviderSettings(StreamProviderName);
public override TestCluster CreateTestCluster()
{
var options = new TestClusterOptions(2);
AdjustConfig(options.ClusterConfiguration);
AdjustConfig(options.ClientConfiguration);
return new TestCluster(options);
}
[Fact]
public async Task ReloadFromCheckpointTest()
{
logger.Info("************************ EHReloadFromCheckpointTest *********************************");
await this.ReloadFromCheckpointTestRunner(ImplicitSubscription_RecoverableStream_CollectorGrain.StreamNamespace, 1, 256);
}
[Fact]
public async Task RestartSiloAfterCheckpointTest()
{
logger.Info("************************ EHRestartSiloAfterCheckpointTest *********************************");
await this.RestartSiloAfterCheckpointTestRunner(ImplicitSubscription_RecoverableStream_CollectorGrain.StreamNamespace, 8, 32);
}
public override void Dispose()
{
var dataManager = new AzureTableDataManager<TableEntity>(CheckpointerSettings.TableName, CheckpointerSettings.DataConnectionString, NullLoggerFactory.Instance);
dataManager.InitTableAsync().Wait();
dataManager.ClearTableAsync().Wait();
base.Dispose();
}
private async Task ReloadFromCheckpointTestRunner(string streamNamespace, int streamCount, int eventsInStream)
{
List<Guid> streamGuids = Enumerable.Range(0, streamCount).Select(_ => Guid.NewGuid()).ToList();
try
{
await GenerateEvents(streamNamespace, streamGuids, eventsInStream, 4096);
await TestingUtils.WaitUntilAsync(assertIsTrue => CheckCounters(streamNamespace, streamCount, eventsInStream, assertIsTrue), TimeSpan.FromSeconds(60));
await RestartAgents();
await GenerateEvents(streamNamespace, streamGuids, eventsInStream, 4096);
await TestingUtils.WaitUntilAsync(assertIsTrue => CheckCounters(streamNamespace, streamCount, eventsInStream * 2, assertIsTrue), TimeSpan.FromSeconds(90));
}
finally
{
var reporter = this.GrainFactory.GetGrain<IGeneratedEventReporterGrain>(GeneratedStreamTestConstants.ReporterId);
reporter.Reset().Ignore();
}
}
private async Task RestartSiloAfterCheckpointTestRunner(string streamNamespace, int streamCount, int eventsInStream)
{
List<Guid> streamGuids = Enumerable.Range(0, streamCount).Select(_ => Guid.NewGuid()).ToList();
try
{
await GenerateEvents(streamNamespace, streamGuids, eventsInStream, 0);
await TestingUtils.WaitUntilAsync(assertIsTrue => CheckCounters(streamNamespace, streamCount, eventsInStream, assertIsTrue), TimeSpan.FromSeconds(60));
HostedCluster.RestartSilo(HostedCluster.SecondarySilos[0]);
await HostedCluster.WaitForLivenessToStabilizeAsync();
await GenerateEvents(streamNamespace, streamGuids, eventsInStream, 0);
await TestingUtils.WaitUntilAsync(assertIsTrue => CheckCounters(streamNamespace, streamCount, eventsInStream * 2, assertIsTrue), TimeSpan.FromSeconds(90));
}
finally
{
var reporter = this.GrainFactory.GetGrain<IGeneratedEventReporterGrain>(GeneratedStreamTestConstants.ReporterId);
reporter.Reset().Ignore();
}
}
private async Task<bool> CheckCounters(string streamNamespace, int streamCount, int eventsInStream, bool assertIsTrue)
{
var reporter = this.GrainFactory.GetGrain<IGeneratedEventReporterGrain>(GeneratedStreamTestConstants.ReporterId);
var report = await reporter.GetReport(StreamProviderName, streamNamespace);
if (assertIsTrue)
{
// one stream per queue
Assert.Equal(streamCount, report.Count);
foreach (int eventsPerStream in report.Values)
{
Assert.Equal(eventsInStream, eventsPerStream);
}
}
else if (streamCount != report.Count ||
report.Values.Any(count => count != eventsInStream))
{
return false;
}
return true;
}
private async Task RestartAgents()
{
var mgmt = this.GrainFactory.GetGrain<IManagementGrain>(0);
await mgmt.SendControlCommandToProvider(StreamProviderTypeName, StreamProviderName, (int)PersistentStreamProviderCommand.StopAgents);
await mgmt.SendControlCommandToProvider(StreamProviderTypeName, StreamProviderName, (int)PersistentStreamProviderCommand.StartAgents);
}
private async Task GenerateEvents(string streamNamespace, List<Guid> streamGuids, int eventsInStream, int payloadSize)
{
IStreamProvider streamProvider = this.Client.GetStreamProvider(StreamProviderName);
IAsyncStream<GeneratedEvent>[] producers = streamGuids
.Select(streamGuid => streamProvider.GetStream<GeneratedEvent>(streamGuid, streamNamespace))
.ToArray();
for (int i = 0; i < eventsInStream - 1; i++)
{
// send event on each stream
for (int j = 0; j < streamGuids.Count; j++)
{
await producers[j].OnNextAsync(new GeneratedEvent { EventType = GeneratedEvent.GeneratedEventType.Fill, Payload = new int[payloadSize] });
}
}
// send end events
for (int j = 0; j < streamGuids.Count; j++)
{
await producers[j].OnNextAsync(new GeneratedEvent { EventType = GeneratedEvent.GeneratedEventType.Report, Payload = new int[payloadSize] });
}
}
private static void AdjustConfig(ClusterConfiguration config)
{
// register stream provider
config.Globals.RegisterStreamProvider<EventHubStreamProvider>(StreamProviderName, BuildProviderSettings());
config.AddAzureTableStorageProvider(ImplicitSubscription_RecoverableStream_CollectorGrain.StorageProviderName);
}
private static void AdjustConfig(ClientConfiguration config)
{
config.RegisterStreamProvider<EventHubStreamProvider>(StreamProviderName, BuildProviderSettings());
}
private static Dictionary<string, string> BuildProviderSettings()
{
var settings = new Dictionary<string, string>();
// get initial settings from configs
ProviderSettings.WriteProperties(settings);
EventHubConfig.Value.WriteProperties(settings);
CheckpointerSettings.WriteProperties(settings);
// add queue balancer setting
settings.Add(PersistentStreamProviderConfig.QUEUE_BALANCER_TYPE, StreamQueueBalancerType.DynamicClusterConfigDeploymentBalancer.AssemblyQualifiedName);
// add pub/sub settting
settings.Add(PersistentStreamProviderConfig.STREAM_PUBSUB_TYPE, StreamPubSubType.ImplicitOnly.ToString());
return settings;
}
}
}
|
waynemunro/orleans
|
test/ServiceBus.Tests/Streaming/EHStreamProviderCheckpointTests.cs
|
C#
|
mit
| 9,319
|
//
// YYReturnResultModel.h
// BikeRental
//
// Created by yunyuchen on 2017/5/25.
// Copyright © 2017年 xinghu. All rights reserved.
//
#import "YYBaseModel.h"
@interface YYReturnResultModel : YYBaseModel
@property (nonatomic,assign) CGFloat price;
@property (nonatomic,assign) NSInteger keep;
@property (nonatomic,assign) CGFloat extPrice;
@property (nonatomic,assign) CGFloat longitude;
@property (nonatomic,assign) CGFloat latitude;
@property (nonatomic,assign) CGFloat first;
@end
|
yunyuchen/YiZu
|
YiZu/YiZu/Classes/Main/Models/YYReturnResultModel.h
|
C
|
mit
| 501
|
<?php
namespace Wsh\CmsBundle\Controller\Backend;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class DashboardController extends Controller
{
/**
* @Template()
*/
public function indexAction()
{
return array(
'admin_pool' => $this->container->get('sonata.admin.pool')
);
}
}
|
WenigerSH/wsh-cms
|
src/Wsh/CmsBundle/Controller/Backend/DashboardController.php
|
PHP
|
mit
| 465
|
express-handlebars
=======================
Handlebars renderer for express
|
tndev/node-express-handlebars
|
README.md
|
Markdown
|
mit
| 77
|
<?php
/**
* @filenames: GatotKaca/Erp/HumanResourcesBundle/Entity/EmployeeExperience.php
* Author : Muhammad Surya Ikhsanudin
* License : Protected
* Email : mutofiyah@gmail.com
*
* Dilarang merubah, mengganti dan mendistribusikan
* ulang tanpa sepengetahuan Author
*
* Relation Mapping :
* - GatotKaca\Erp\HumanResourcesBundle\Entity\Employee
**/
namespace GatotKaca\Erp\HumanResourcesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name = "trs_employee_experience")
**/
class EmployeeExperience
{
/**
* @ORM\Id
* @ORM\Column(name = "`id`", type = "string", length = 40)
**/
protected $id;
/**
* @ORM\ManyToOne(targetEntity = "Employee", inversedBy = "experience")
* @ORM\JoinColumn(name = "mtr_employee_id", referencedColumnName = "id")
**/
protected $employee;
/**
* @ORM\Column(name = "`company`", type = "string", length = 77, nullable = true)
**/
protected $company;
/**
* @ORM\Column(name = "`jobtitle`", type = "string", length = 77, nullable = true)
**/
protected $job_title;
/**
* @ORM\Column(name = "`reason`", type = "string", length = 77, nullable = true)
**/
protected $reason;
/**
* @ORM\Column(name = "`exp_start`", type = "date", nullable = true)
**/
protected $start;
/**
* @ORM\Column(name = "`exp_end`", type = "date", nullable = true)
**/
protected $end;
/**
* @ORM\Column(name = "`created`", type = "datetime")
**/
protected $created;
/**
* @ORM\Column(name = "`createdby`", type = "string", length = 40)
**/
protected $created_by;
/**
* @ORM\Column(name = "`updated`", type = "datetime")
**/
protected $updated;
/**
* @ORM\Column(name = "`updatedby`", type = "string", length = 40)
**/
protected $updated_by;
public function __construct()
{
$this->reason = '';
$this->created = new \DateTime();
$this->updated = new \DateTime();
}
/**
* Set id
*
* @param string $id
* @return EmployeeExperience
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Set company
*
* @param string $company
* @return EmployeeExperience
*/
public function setCompany($company)
{
$this->company = $company;
return $this;
}
/**
* Get company
*
* @return string
*/
public function getCompany()
{
return $this->company;
}
/**
* Set job_title
*
* @param string $jobTitle
* @return EmployeeExperience
*/
public function setJobTitle($jobTitle)
{
$this->job_title = $jobTitle;
return $this;
}
/**
* Get job_title
*
* @return string
*/
public function getJobTitle()
{
return $this->job_title;
}
/**
* Set reason
*
* @param string $reason
* @return EmployeeExperience
*/
public function setReason($reason)
{
$this->reason = $reason;
return $this;
}
/**
* Get reason
*
* @return string
*/
public function getReason()
{
return $this->reason;
}
/**
* Set start
*
* @param \DateTime $start
* @return EmployeeExperience
*/
public function setStart($start)
{
$this->start = $start;
return $this;
}
/**
* Get start
*
* @return \DateTime
*/
public function getStart()
{
return $this->start;
}
/**
* Set end
*
* @param \DateTime $end
* @return EmployeeExperience
*/
public function setEnd($end)
{
$this->end = $end;
return $this;
}
/**
* Get end
*
* @return \DateTime
*/
public function getEnd()
{
return $this->end;
}
/**
* Set created
*
* @param \DateTime $created
* @return EmployeeExperience
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set created_by
*
* @param string $createdBy
* @return EmployeeExperience
*/
public function setCreatedBy($createdBy)
{
$this->created_by = $createdBy;
return $this;
}
/**
* Get created_by
*
* @return string
*/
public function getCreatedBy()
{
return $this->created_by;
}
/**
* Set updated
*
* @param \DateTime $updated
* @return EmployeeExperience
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* @return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set updated_by
*
* @param string $updatedBy
* @return EmployeeExperience
*/
public function setUpdatedBy($updatedBy)
{
$this->updated_by = $updatedBy;
return $this;
}
/**
* Get updated_by
*
* @return string
*/
public function getUpdatedBy()
{
return $this->updated_by;
}
/**
* Set employee
*
* @param \GatotKaca\Erp\HumanResourcesBundle\Entity\Employee $employee
* @return EmployeeExperience
*/
public function setEmployee(\GatotKaca\Erp\HumanResourcesBundle\Entity\Employee $employee = null)
{
$this->employee = $employee;
return $this;
}
/**
* Get employee
*
* @return \GatotKaca\Erp\HumanResourcesBundle\Entity\Employee
*/
public function getEmployee()
{
return $this->employee;
}
}
|
AdenKejawen/erp
|
src/GatotKaca/Erp/HumanResourcesBundle/Entity/EmployeeExperience.php
|
PHP
|
mit
| 6,271
|
define(["Tone/core/Tone", "Tone/effect/StereoXFeedbackEffect", "Tone/signal/Signal", "Tone/core/Delay"],
function(Tone){
"use strict";
/**
* @class Tone.PingPongDelay is a feedback delay effect where the echo is heard
* first in one channel and next in the opposite channel. In a stereo
* system these are the right and left channels.
* PingPongDelay in more simplified terms is two Tone.FeedbackDelays
* with independent delay values. Each delay is routed to one channel
* (left or right), and the channel triggered second will always
* trigger at the same interval after the first.
*
* @constructor
* @extends {Tone.StereoXFeedbackEffect}
* @param {Time|Object} [delayTime] The delayTime between consecutive echos.
* @param {NormalRange=} feedback The amount of the effected signal which
* is fed back through the delay.
* @example
* var pingPong = new Tone.PingPongDelay("4n", 0.2).toMaster();
* var drum = new Tone.DrumSynth().connect(pingPong);
* drum.triggerAttackRelease("C4", "32n");
*/
Tone.PingPongDelay = function(){
var options = this.optionsObject(arguments, ["delayTime", "feedback"], Tone.PingPongDelay.defaults);
Tone.StereoXFeedbackEffect.call(this, options);
/**
* the delay node on the left side
* @type {Tone.Delay}
* @private
*/
this._leftDelay = new Tone.Delay(0, options.maxDelayTime);
/**
* the delay node on the right side
* @type {Tone.Delay}
* @private
*/
this._rightDelay = new Tone.Delay(0, options.maxDelayTime);
/**
* the predelay on the right side
* @type {Tone.Delay}
* @private
*/
this._rightPreDelay = new Tone.Delay(0, options.maxDelayTime);
/**
* the delay time signal
* @type {Time}
* @signal
*/
this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time);
//connect it up
this.effectSendL.chain(this._leftDelay, this.effectReturnL);
this.effectSendR.chain(this._rightPreDelay, this._rightDelay, this.effectReturnR);
this.delayTime.fan(this._leftDelay.delayTime, this._rightDelay.delayTime, this._rightPreDelay.delayTime);
//rearranged the feedback to be after the rightPreDelay
this._feedbackLR.disconnect();
this._feedbackLR.connect(this._rightDelay);
this._readOnly(["delayTime"]);
};
Tone.extend(Tone.PingPongDelay, Tone.StereoXFeedbackEffect);
/**
* @static
* @type {Object}
*/
Tone.PingPongDelay.defaults = {
"delayTime" : 0.25,
"maxDelayTime" : 1
};
/**
* Clean up.
* @returns {Tone.PingPongDelay} this
*/
Tone.PingPongDelay.prototype.dispose = function(){
Tone.StereoXFeedbackEffect.prototype.dispose.call(this);
this._leftDelay.dispose();
this._leftDelay = null;
this._rightDelay.dispose();
this._rightDelay = null;
this._rightPreDelay.dispose();
this._rightPreDelay = null;
this._writable(["delayTime"]);
this.delayTime.dispose();
this.delayTime = null;
return this;
};
return Tone.PingPongDelay;
});
|
pereamengual/QuadraMat
|
public/javascripts/Tone.js-master/Tone/effect/PingPongDelay.js
|
JavaScript
|
mit
| 3,048
|
dotfiles
========
Some useful configuration files
|
gbahij/dotfiles
|
README.md
|
Markdown
|
mit
| 51
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.